text:
Q: CodeIgniter Two tables Left Join does not return Join Condition id of left table when miss in right table I have two tables say Table1 and Table2 and i am Left joining Table1 on Table2 with Table1.PrimaryKey = Table2.ForeignKey. It does return all the rows from both tables but in some rows, due to no record in Table2 for the join condition, the PrimaryKey field value is missing for Table1. Here is my code
$this->db->select('*');
$this->db->from('CI_Articles_Tbl');
$this->db->join('CI_Article_Images_Tbl',
    'CI_Articles_Tbl.roflArticle_ID=CI_Article_Images_Tbl.roflArticle_ID','left');
$this->db->group_by('CI_Articles_Tbl.roflArticle_ID');
$query = $this->db->get();
return $query->result_array();

What is the problem in my query and what is its possible solution.
Any help will be highly appreciated.

A: You have select table.*
Try this code.
$this->db->select('CI_Articles_Tbl.*');

A: My Answer for my own question is this but let me first Thank "Lighter"! His Code helped me corrected my query,
Suppose you have Two Tables Table1 and Table2 and you want to LEFT JOIN Table1 on Table2 or in other sense, You want all rows from both tables Whether or not a reference matches or not matches in both tables Table1 and Table2. For example you want like this
       Table1.P1 = Table2.P1

What i was doing that i went ahead and selected all fields from Table1 and then straight away gave the join condition on Table2 which is Wrong because sometimes Table1.P1 will NOT have a match Table2.P1, in such a case, rows will come but the value Table1.P1 will be missing.
What you have to do is to show specifically what fields you want from what tables EXCEPT THE field of Table2 that you are using in Join condition. Like this
Table1.*
Table2.* except Table2.P1 (NOTE: VERY IMPORTANT)
My Code is here for any reference purposes
$this->db->select('CI_Articles_Tbl.*,CI_Article_Images_Tbl.roflArticleImage_ID,CI_Article_Images_Tbl.roflArticleImage_Ext,CI_Users_Tbl.*');
        $this->db->from('CI_Articles_Tbl','CI_Article_Images_Tbl','CI_Users_Tbl');
        $this->db->join('CI_Article_Images_Tbl','CI_Articles_Tbl.roflArticle_ID=CI_Article_Images_Tbl.roflArticle_ID','left outer');
        $this->db->join('CI_Users_Tbl','CI_Articles_Tbl.roflUser_ID=CI_Users_Tbl.roflUser_ID');
        $this->db->group_by('CI_Articles_Tbl.roflArticle_ID');
        $query = $this->db->get();
        return $query->result_array();


text:
Q: Excel VBA Dictionary Storing and Retrieving How do you go about creating excel VBA dictionaries?
Say I have the following values:

How can I set column A as the key, column B as the value?
Do I loop through every value to store?
How do I go about using the dictionary afterward to get the value of 5 for instance ("Key A")

A: In Excel:
=VLOOKUP("D", A:B, 2,FALSE)

returns 20.
In VBA:
MsgBox WorksheetFunction.VLookup("D", Sheet1.Range("A:B"), 2, False)

pops 20.

A: putting answer here for documentation purposes, from reddit user MRMCMLXXXV
source https://www.reddit.com/r/excel/comments/6u4swi/how_do_you_create_a_dictionary_in_excel_vba_and/
Public Sub DictionaryExamples()

    Dim exampleValues As Variant
    Dim i As Long
    Dim aKey As String
    Dim aValue As Integer
    Dim exampleDict As Object

    'Load values into a variant array
    exampleValues = Range("A1:B10").Value

    'Instantiate a dictionary
    Set exampleDict = CreateObject("scripting.dictionary")

    'Read all keys and values, and add them to the dictionary

    For i = 1 To UBound(exampleValues)
        aKey = CStr(exampleValues(i, 1))
        aValue = CInt(exampleValues(i, 2))
        exampleDict.Add aKey, aValue
    Next i

    'Output the value associated with key A

    MsgBox exampleDict.Item("A")

End Sub

The result looks like this in excel

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to access object inside delegate I have a function delegate returning an object.
I am storing that object in a list.
I want to iterate through that list to get values in object, but in for loop I am not able to do so:
public static class Tracking
{
    public delegate TrackingObject GetTrackObject ();
    public static List<GetTrackObject> TrackedLists = new List<GetTrackObject>();

    public static void Register (GetTrackObject trackobject)
    {
        TrackedLists.Add(trackobject);
    }
}

public class TrackingObject
{
    object collection;
    Type T;
    Type K;
    Type V;

    public TrackingObject (object o, Type t, Type k, Type v)
    {
        collection = o;
        T = t;
        K = k;
        V = v;
    }
}

class TrackList<T> : List<T>
{
    public string Name = null;
    public int ItemCount;
    public int AvgSize;
    public int Size;

    public TrackList (string name, byte avgsize)
    {
        this.Name = name;
        this.AvgSize = avgsize;
        this.ItemCount = this.Count;
        this.Size = this.Count * this.AvgSize;

        Tracking.Register(this.GetTrackObject);
    }

    public TrackingObject GetTrackObject ()
    {
        TrackingObject TO = new TrackingObject(this, typeof(T), null, null);
        return TO;
    }
}

public static void Main ()
{
    foreach (Tracking.GetTrackObject method in Tracking.TrackedLists)
    { }
}

A: You are not storing the object in the list, you're storing the method to invoke (run) in the list.
One option is to invoke your method to get the result.
public static void Main ()
{
    foreach (Tracking.GetTrackObject method in Tracking.TrackedLists)
    {
        object trackedObject = method();
    }
}

Alternatively you could make your list a list of objects, and invoke the method in your Register method (and store the result in your list).


text:
Q: Android Gson Retrofit Expected BEGIN_OBJECT but was NUMBER First let me say, I have searched before posting, just cant find the answer.
I want To Get an api which is Like this
[
1,
2,
3,
4,
5,
6,
7
]
and then add RecylerView  .
Model
Seats.java
////////////////////////////////////////////////
////////////////////////////////
import com.google.gson.annotations.SerializedName;
public class Seats {

    @SerializedName("seatNo")
    private int seatNo;

    public int getSeatNo() {
        return seatNo;
    }

    public void setSeatNo(int seatNo) {
        this.seatNo = seatNo;
    }

    @Override
    public String toString() {

        return
                "seats{" +
                        "unique_id = '" + seatNo + '\'' +

                        "}";
    }
}

SeatsAdapter
public class SeatsAdapter extends RecyclerView.Adapter<SeatsAdapter.SeatsViewHolder> {

    private SeatsActivity seatsActivity;
    private Context context;
    private ArrayList<Seats> seatsList;
    //Context ctx;

    public SeatsAdapter(SeatsActivity seatsActivity, Context context, ArrayList<Seats> seatsList) {
        this.seatsList = seatsList;
        this.seatsActivity = seatsActivity;
        this.context = context;
        //this.ctx = ctx;
    }

    @Override
    public SeatsViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout
                .item_seat, parent, false);

        return new SeatsViewHolder(view);
    }

    @Override
    public void onBindViewHolder(final SeatsViewHolder holder, int position) {

        final Seats seats = seatsList.get(position);
        holder.mTvSeatNo.setText(seats.getSeatNo());

    }

    @Override
    public int getItemCount() {
        return seatsList.size();
    }

        protected class SeatsViewHolder extends RecyclerView.ViewHolder {

        private final ImageView mIvSeatSelected;
        private ImageView mIvSeat, mTvSeatLadies, mIvSeatBooked;
        private TextView mTvSeatNo;

        public SeatsViewHolder(View itemView) {
            super(itemView);

            mIvSeat = itemView.findViewById(R.id.ivSeat);
            mIvSeatSelected = itemView.findViewById(R.id.ivSeatSelected);
            mTvSeatNo = itemView.findViewById(R.id.tvSeatNo);
            mTvSeatLadies = itemView.findViewById(R.id.ivSeatLadies);
            mIvSeatBooked = itemView.findViewById(R.id.ivSeatBooked);

        }

    }
}

And Here is activity.java
  private void initParcelRcv() {
        seatsList = new ArrayList<Seats>();
        rcvSeat= (RecyclerView) findViewById(R.id.rcvSeat);
        rcvSeat.setLayoutManager(new LinearLayoutManager(this));
        SeatsAdapter = new SeatsAdapter(this,this,seatsList);
        rcvSeat.setAdapter(SeatsAdapter);
    }

   private void getSeatsInfo() {

        Utils.showCustomProgressDialog(this, getResources().getString(R.string
                        .msg_waiting_for_get_documents),
                false, null);

        Call<List<Seats>> call =  ApiClient.getClient().create(ApiInterface.class)
                .getSeats(busName,departure,arrival,departuretime);

        call.enqueue(new Callback<List<Seats>>() {
            @Override
            public void onResponse(Call<List<Seats>> call, Response<List<Seats>> response) {

                if (parseContent.isSuccessful(response)) {

                    List<Seats> seats = response.body();
                   seatsList.addAll(Arrays.asList(seats.toArray()));

                    SeatsAdapter.notifyDataSetChanged();
                    Utils.hideCustomProgressDialog();
                }
                else {
                    Utils.showErrorToast(response.body().hashCode(),
                            SeatsActivity.this);
                    Utils.hideCustomProgressDialog();
                }

            }

            @Override
            public void onFailure(Call<List<Seats>> call, Throwable t) {
                AppLog.handleThrowable(SeatsActivity.class.getSimpleName(), t);
                Utils.showToast(SeatsActivity.class.getSimpleName(), SeatsActivity.this
                );
                Utils.hideCustomProgressDialog();

            }
        });
    }

A: Your code expects "{", but found a number instead. You should check your JSON first (please, write a resulting JSON in your question, I think it is [ 1, 2, 3, 4, 5, 6, 7 ]).
I see you use this POJO in Seats.java:
@SerializedName("seatNo")
private int seatNo;

This is a wrong model, because your JSON consists of a list of integers.
Maybe you should remove Seats.java and rewrite a callback:
call.enqueue(new Callback<List<Integer>>() {

UPDATE
Simply replace Seats with Integer (I didn't check).
Call<List<Integer>> call =  ApiClient.getClient().create(ApiInterface.class)
                .getSeats(busName,departure,arrival,departuretime);

        call.enqueue(new Callback<List<Integer>>() {
            @Override
            public void onResponse(Call<List<Integer>> call, Response<List<Integer>> response) {

                if (parseContent.isSuccessful(response)) {

                    List<Integer> seats = response.body();
                    seatsList.addAll(Arrays.asList(seats.toArray()));

                    SeatsAdapter.notifyDataSetChanged();
                    Utils.hideCustomProgressDialog();
                }
                else {
                    Utils.showErrorToast(response.body().hashCode(),
                            SeatsActivity.this);
                    Utils.hideCustomProgressDialog();
                }
            }

            @Override
            public void onFailure(Call<List<Integer>> call, Throwable t) {
                AppLog.handleThrowable(SeatsActivity.class.getSimpleName(), t);
                Utils.showToast(SeatsActivity.class.getSimpleName(), SeatsActivity.this
                );
                Utils.hideCustomProgressDialog();

            }
        });


text:
Q: composer showing error when i install a plugin on magento 2.2.11 I am doing as below:
/usr/local/lsws/lsphp72/bin/php composer.phar require facebook/php-business-sdk --no-plugins

its showing error as:
Using version ^13.0 for facebook/php-business-sdk
./composer.json has been updated
Running composer update facebook/php-business-sdk
Loading composer repositories with package information
Updating dependencies
Your requirements could not be resolved to an installable set of packages.

  Problem 1
    - magento/magento-composer-installer 0.1.13 requires composer-plugin-api ^1.0 -> found composer-plugin-api[2.2.0] but it does not match the constraint.
    - magento/product-community-edition 2.2.11 requires magento/magento-composer-installer >=0.1.11 -> satisfiable by magento/magento-composer-installer[0.1.13].
    - magento/product-community-edition is locked to version 2.2.11 and an update of this package was not requested.

You can also try re-running composer require with an explicit version constraint, e.g. "composer require facebook/php-business-sdk:*" to figure out if any version is installable, or "composer require facebook/php-business-sdk:^2.1" if you know which you need.

please help

A: Please try with below and check it.
/usr/local/lsws/lsphp72/bin/php composer.phar require facebook/php-business-sdk --no-plugins --ignore-platform-reqs


text:
Q: Mac os X Error unloading plist I'm currently using MacOSX 10.8 and I tried to install the built-in php-fpm.
Moreover I want a plist file to start and stop php-fpm on demand. I found this one
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>KeepAlive</key>
    <true/>
    <key>Label</key>
    <string>net.php.php-fpm</string>
    <key>LaunchOnlyOnce</key>
    <true/>
    <key>NetworkState</key>
    <true/>
    <key>ProgramArguments</key>
    <array>
        <string>/usr/sbin/php-fpm</string>
    </array>
    <key>RunAtLoad</key>
    <true/>
    <key>ServiceDescription</key>
    <string>PHP FastCGI Process Manager</string>
    <key>StandardErrorPath</key>
    <string>/var/log/system.log</string>
</dict>
</plist>

Where the launchctl (with sudo) -w load works find... When I try to unload I get this error:
launchctl: Error unloading: net.php.php-fpm

I don't really understand why?
UPDATE:
$ sudo launchctl load -w /Library/LaunchAgents/net.php.php-fpm.plist
$ ps aux | grep php
nobody          2055   0.0  0.0  2450420    604   ??  S     2:28PM   0:00.00 /usr/sbin/php-fpm
nobody          2054   0.0  0.0  2450420    604   ??  S     2:28PM   0:00.00 /usr/sbin/php-fpm
root            2053   0.0  0.0  2450420    668   ??  Ss    2:28PM   0:00.00 /usr/sbin/php-fpm

$ tail -f /var/log/system.log
Jan 31 14:28:12 XXXXXX sudo[2040]:      t5e : TTY=ttys001 ; PWD=/Volumes/diskE/Users/XXX ; USER=root ; COMMAND=/bin/launchctl load -w /Library/LaunchAgents/net.php.php-fpm.plist

$ sudo launchctl unload -w /Library/LaunchAgents/net.php.php-fpm.plist
launchctl: Error unloading: net.php.php-fpm

$ ps aux | grep php
nobody          2054   0.0  0.0  2450420    604   ??  S     2:28PM   0:00.00 /usr/sbin/php-fpm
root            2053   0.0  0.0  2450420    668   ??  Ss    2:28PM   0:00.00 /usr/sbin/php-fpm
nobody          2055   0.0  0.0  2450420    604   ??  S     2:28PM   0:00.00 /usr/sbin/php-fpm

$ tail -f /var/log/system.log
Jan 31 14:28:30 XXXXXX sudo[2081]:      t5e : TTY=ttys001 ; PWD=/Volumes/diskE/Users/XXX ; USER=root ; COMMAND=/bin/launchctl unload -w /Library/LaunchAgents/net.php.php-fpm.plist

A: I found my response inside Homebrew bug tracking system:
https://github.com/josegonzalez/homebrew-php/issues/370
It's about PHP-FPM configuration, we must put PHP-FPM daemonize to no (default = true)


text:
Q: Full CNN - Is it possible to implement in (nolearn) Lasagne? I am currently working with a very simple CNN and I am trying to figure out a way to make it into a Full CNN. By Full I mean not having any Dense layer and instead implement a deconvnet. The deconvnet part will be used as a localization part of the CNN.
What I am wondering is if there is a way to implement a deconvnet part in nolearn? In detail, a Deconv2dlayer and Unpooling? Has anyone else looked more into it or even done it?
Here is a reference for more details:
https://datascience.stackexchange.com/questions/8999/deconvolutional-network-in-semantic-segmentation


text:
Q: Group of order $143$, counting argument. I am  trying the following exercise (I cannot use Cauchy's theorem, it's not in my course yet) :

Let $G$ be a group of order $143=11\times13$, prove that that $G$ contains an element of order $13$

If $G$ is cyclic, then I know that there exist a unique subgroup of order $d$
where $d$ is a unique positive divisor of $143$.
If $G$ is not cyclic, then I don't know how can I conclude without Cauchy's theorem, perhaps by counting the element of $G$ ?
If $G$ does not contain an element of order $13$, then let $t$ be the order of $g$. By Lagrange's theorem every element of $G$ must have order $13$ or $11$, since the groupe is not trivial, there exist an element of order $11$.
The order of $g^k$ is $11/(k,11).$
Therefore, $g^{13}$ as order $11$ and $g^i$ as order $11$, for any $1\le i\le11.$ How can I continue or proceed ? Thanks

A: If there is no element of order 13, then for all g in G, g non identity, |g| = 11 or 143, but if there exists p in g: |p|=143, |p^11| = 13, contrary to our assumption. If, however all non-identity elements of G are of order 11, there are 142 such elements. However, there is a property that in a finite group, the number of elements of order d is a multiple of phi(d), and since phi(11) =10, 10|142 which is a contradiction, so there must exist an element in G of order 13.


text:
Q: Смена контента без перезагрузки страницы Здравствуйте. Есть cms amxbans как сделать смену контента без перезагрузки страницы, выводом из других файлов.
A: Смотри в сторону - JavaScript, jQuery, Ajax
A: Для этого надо использовать AJAX - запросы.
Код, который я использую для этих целей:
function send_request(r_method, r_path, r_args, r_handler)
{
    var Request = false;
    if(window.XMLHttpRequest)
    {
        Request=new XMLHttpRequest();
    }
    else if (window.ActiveXObject)
    {
        try
        {
            Request = new ActiveXObject("Microsoft.XMLHTTP")
        };
        catch(CatchException)
        {
            Request=new ActiveXObject("Msxml2.XMLHTTP");
        }
    }
    if(!Request)
    {
        return;
    }
    Request.onreadystatechange=function()
    {
        if(Request.readyState==4)
            if(Request.status==200)
                r_handler(Request.responseText);
        if(r_method.toLowerCase() =="get"&&r_args.length>0)
            r_path+="?"+r_args;
        Request.open(r_method,r_path,true);
        if(r_method.toLowerCase()=="post")
        {
            Request.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");
            Request.send(r_args)
        }
        else
        {
            Request.send(null)
        }
    }
}

Коротко об аргументах:
send_request("Тип запроса. get либо post","Путь/к/файлу.php","Аргументы. Например: topic=46764&page=4",function(response){
    //Код, который будет исполняться при успешном окончании запроса
    //response - переменная, содержащая ответ
})

Небольшой пример:
test.html

<html>

<head>
  <script>
    function send_request(r_method, r_path, r_args, r_handler)
    {
        var Request = false;
        if(window.XMLHttpRequest)
        {
            Request=new XMLHttpRequest();
        }
        else if (window.ActiveXObject)
        {
            try
            {
                Request = new ActiveXObject("Microsoft.XMLHTTP")
            }catch(CatchException)
            {
                Request=new ActiveXObject("Msxml2.XMLHTTP");
            }
        }
        if(!Request)
        {
            return;
        }
        Request.onreadystatechange=function()
        {
            if(Request.readyState==4)
                if(Request.status==200)
                    r_handler(Request.responseText);
            if(r_method.toLowerCase() =="get"&&r_args.length>0)
                r_path+="?"+r_args;
            Request.open(r_method,r_path,true);
            if(r_method.toLowerCase()=="post")
            {
                Request.setRequestHeader("Content-Type","application/x-www-form-urlencoded;charset=utf-8");
                Request.send(r_args)
            }
            else
            {
                Request.send(null)
            }
        }
    }
    function request() {
      send_request("GET", "test.php", "testval=test", function(response) {
          document.body.innerHTML+=response
      })
    }
  </script>
</head>

<body>
  <button onclick="request()">Загрузить!</button>
</body>

</html>

test.php
<?PHP
echo "Тестовая переменная: ".$_GET['testvar'];
?>

Переменных можно добавлять неограниченное количество. Смену контента можно сделать, заставив PHP-скрипт отдавать html-код, и позднее изменять innerHTML какого-либо блока на response. Этот вариант самый простой. Есть вариант посложнее, с JSON, но это уже другой вопрос.


text:
Q: Expression for negating every other odd number index Is there a way to have an iterative expression that negates every other odd number index (starting from 3)?
Basically, I am trying to write a generative expression that will give me value, given index number in a sequence that alternates every other odd number and looks like this:

index   value
0       0
1       0
2       0
3       1
4       0
5       -1
6       0
7       1

--
As mentioned by Gerry in comments, $\sin \frac{n \pi}{2}$ and/or $\cos \frac{n \pi}{2}$ work quite well for values where index $\geq$ 2 ... Effectively, my problem is solved, where I just use conditionals to check for index values before applying the nontrivial sinusoidal multiplier.
Might there be a closed-form way that doesn't involve conditionals to have the value be nonzero only when index $\geq$ N (where N in this case is 2) ?

A: Another method to express periodic behaviour are quasi-polynomials.  One way to define quasi-polynomial is a polynomial in floor functions of linear terms.
To get a function that is 1 exactly on each argument that is 3 modulo 4 use $$f: n\mapsto \left\lfloor\frac{n+1}{4}\right\rfloor - \left\lfloor\frac{n}{4}\right\rfloor.$$
Here $\lfloor . \rfloor$ means round down to the next integer. Now you can subtract $$g: n\mapsto \left\lfloor\frac{n+3}{4}\right\rfloor - \left\lfloor\frac{n+2}{4}\right\rfloor$$
which is 1 exactly if $n$ leaves remainder 1 mod 4.  This means that $$n\mapsto f(n)-g(n) = \left\lfloor\frac{n+1}{4}\right\rfloor - \left\lfloor\frac{n}{4}\right\rfloor - \left\lfloor\frac{n+3}{4}\right\rfloor + \left\lfloor\frac{n+2}{4}\right\rfloor $$ gives the sequence $0,-1,0,1,0,-1,0,1,\dots$. There is no quasi-polynomial function that is non-zero at only one integer (you need one to fix the value at $n=1$), but there are non-polynomial ways to do that in the other answers.

A: As I noted in the comments, the sequence $\cos(n\pi/2)$ goes $1,0,-1,0,1,0,-1,0,\dots$ for $n=0,1,2,3,\dots$, so you can do the following: if $n=1$ then $0$, else $\cos((n-3)\pi/2)$.
Eliminating that glitch at $n=1$ is tricky. Basically, you want a function $f$ with $f(1)=1$, $f(n)=0$ for all $n\ne1$, so you can just use $\cos((n-3)\pi/2)+f(n)$. But I think the amount of effort you'd have to put in to construct such a function would be more than what you'd gain by not having to do the $n=1$ check.

A: This is a fun question. Here's something that works if $n$ is restricted to be integer. It's undefined elsewhere. Gerry's trigonometric version has the advantage of accepting any real number. Also, this assumes you're allowing the silly absolute-value hack $\sqrt{n^2}$ and can compute $(-1)^{n}$.
$$\begin{align}
\text{Abs}(n) & = \sqrt{n^2} \\
\text{Min}(a,b) & = \frac{a + b - \text{Abs}(a - b)}{2} \\
\text{Max}(a,b) & = \frac{a + b + \text{Abs}(a - b)}{2} \\
\text{Entry}(n) & = \text{Min}(\text{Max}(0, n-2), 1) \\
\text{ZeroOne}(n) & = (1 - (-1)^n) / 2 \\
\text{LastEvenN}(n) & = n - \text{ZeroOne}(n) \\
\text{PairedAlt}(n) & = (-1)^{\text{LastEvenN}(n)/2\ +\ 1} \\
\end{align}$$
This gives us the final formula: $f(n) = \text{Entry}(n) \cdot \text{ZeroOne}(n) \cdot \text{PairedAlt}(n)$.
$$\begin{array}{c|ccc}
n & \text{Entry($n$)} & \text{ZeroOne($n$)} & \text{LastEvenN($n$)} & \text{PairedAlt($n$)} & f(n) \\
0 & 0 & 0 & 0 & -1 & 0 \\
1 & 0 & 1 & 0 & -1 & 0 \\
2 & 0 & 0 & 2 & 1 & 0 \\
3 & 1 & 1 & 2 & 1 & 1 \\
4 & 1 & 0 & 4 & -1 & 0 \\
5 & 1 & 1 & 4 & -1 & -1 \\
6 & 1 & 0 & 6 & 1 & 0 \\
7 & 1 & 1 & 6 & 1 & 1 \\
8 & 1 & 0 & 8 & -1 & 0 \\
9 & 1 & 1 & 8 & -1 & -1 \\
\dots & \dots & \dots & \dots & \dots & \dots
\end{array}$$

A: Try this:
 $$\frac14 \left(1 + (-1)^{2^{n(n-1)}}\right)
(1-(-1)^n) (-1)^{(n+1)(1-(-1)^n)/4} $$
The purpose of the factor $1 + (-1)^{2^{n(n-1)}}$ is to force the
value to be zero when $n = 1$. The value of $n(n-1)$ is zero for $0$ or $1$,
positive everywhere else, which means that for $0$ or $1$,
$2^{n(n-1)}=1$ and $1 + (-1)^{2^{n(n-1)}} = 0$,
but for any other integer, $2^{n(n-1)}$ is even and $1 + (-1)^{2^{n(n-1)}} = 0$.
In fact if you take any formula that gives you $0$ for every even $n$
and $(-1)^{(n-1)/2}$ for every odd $n$,
you can multiply it by $\frac12\left(1 + (-1)^{2^{n(n-1)}}\right)$
in order to force the formula to evaluate to $0$ for $n = 1$
without changing any of the other results.
So this would work:
$$\frac12\left(1 + (-1)^{2^{n(n-1)}}\right)
 \cos\left(\frac12 (n+1)\pi \right).$$
But personally, the following seems much simpler to me:
$$a_n = \begin{cases}
\phantom{-}0 & \text{if $n$ is even or $n < 3$,} \\
\phantom{-}1 & \text{if $n \equiv 3 \pmod 4$} \\
-1 & \text{if $n \equiv 1 \pmod 4$} \\
\end{cases}$$

A: As already noted, $\sin(\frac{\pi x}2)$ or $\cos(\frac{\pi x}2)$ work well, except for some isolated points near the beginning. However, the function $$f_n(x)=\frac{\sin \pi (x-n)}{\pi (x-n)}$$
for integer $n$ is equal to $1$ for $x=n$ and $0$ on the other integers. You can use this to cancel out the points where you would need conditionals otherwise. For example, your specific function can be represented as
$$a_n=f_1(n)-\sin\left(\frac{\pi n}{2}\right)=\frac{\sin \pi (n-1)}{\pi (n-1)}-\sin\left(\frac{\pi n}{2}\right)$$

A: You can use a step function that is $0$ for input less than $N$ and $1$ for input $\geq N$, and multiply this with the $-\sin\mathopen{}\left(\frac{n\pi}{2}\right)\mathclose{}$.
Such a step function (assuming integer input) can be given by $$s_N(n)=\frac{\left\lvert n+1-N\right\rvert-\left\lvert n-N\right\rvert+1}{2}$$
So all together: $$f_N(n)=-\sin\mathopen{}\left(\frac{n\pi}{2}\right)\mathclose{}\left(\frac{\left\lvert n+1-N\right\rvert-\left\lvert n-N\right\rvert+1}{2}\right)$$

Note: some may say that the absolute value function is secretly using a conditional. But you can either interpret $|x|$ as $\sqrt{x^2}$, or you can interpret $|x|$ as what you get when you replace the sign bit in a binary representation of $x$ in the computer's memory with the bit for positive.


text:
Q: How to make a UILabelView display text with new lines? I have a UILabelView within a RoundedRectView. The UILabelView is supposed to show a dynamically generated text string with new lines in it.
The problem is that the UILabel still shows the text as "blahblahbla..." and does not seem to show the text over multiple lines. The only exception is when I do a "sizeToFit" function call however at that time, the text no longer appears in the center of the parent view. I have the UILabelView number of lines to be 0 and also have increased the frame of the parent view (RoundedRectView)
What can I do to get past this?
Here is my code:
  CGRect frame = [self.messageView frame]; //get the frame size of parent view
    self.messageView.frame = CGRectMake(frame.origin.x, frame.origin.y, frame.size.width, (lineHeight * count)); //increase it to fit the text

         self.messageLabel.text = message;
        [self.messageView setNeedsDisplay];
   //     [self.messageLabel sizeToFit]; this fixes the multiple line issue but now label is not centered in parent view

A: Set numberOfLines to 0, lineBreakMode to UILineBreakModeWordWrap, adjustsFontSizeToFitWidth to NO. Check if your text contains '\n'.

A: [self.messageLabel setNumberOfLines:0];

Source: apple docs


text:
Q: Where does top get its CPU usage data from? I want to write some scripts that will measure the CPU use, but top's output, while pleasant for the user, isn't really feasible for processing in a script.

A: Check $ man proc. /proc has a subdirectory for each pid on the system. Under each of those is a "stat" file, which includes CPU usage information for that specific pid.

A: If you want information about CPU usage across a span of time, take a look at the mpstat command.


text:
Q: there's a problem when dealing with prime factorization I've done this exercise, it was about finding if a number is "ugly" or not. A number is ugly if it has only 2, 3, or 5 as factors. otherwise, it's not ugly.
this is my solution:
include <stdbool.h>
#include <math.h>
bool is_prime(unsigned int num) {
    bool result = false;
    for (unsigned int i = 2; i <= sqrt(num); i++) {
        if (num % i == 0) {
            result = false;
        }
        else {
            result = true;

        }
    }
    return result;
}

bool is_ugly(unsigned int num) {
    bool result = false;
    for (unsigned int i = 1; i <= num; i++) {
        if (num % i == 0) {
            if (is_prime(i)) {
                if (i != 2 || i != 3 || i != 5) {
                    result = false;
                    break;
                }
                else {
                    result = true;
                    break;
                }
            }
        }
    }
    return result;
}

int main(void) {

    bool result = is_ugly(30); // it must return true;
    return 0;
}

is_ugly function works like this:

*

*it finds a factor and then it uses is_prime function to find if it's a prime factor. Then, I've thought that if the final number isn't equal to 2 or 3 or 5 (it's boolean logic), then it's false, because that means there is at least another number and it makes the initial expression (recall, A number is ugly if it has only 2, 3, or 5 as factors.) false. But it doesn't work, because when I run the algorithm with 30 it returns false, when it should've returned true because 30 = 2 * 3 * 5. Why?

A: Your approach is too complicated.
All you need is to check whether a number contains only divisors 2, 3 and 5.
So the function is_prime is just redundant. Moreover it has a bug because for the number 2 it returns false.
The function is_ugly can look very simply. For exampele
bool is_ugly( unsigned int n )
{
    if ( n != 0 )
    {
        n = max_divide( n, 2 );
        n = max_divide( n, 3 );
        n = max_divide( n, 5 );
    }

    return n == 1'
}

In turn the called function max_divide can look the following way
unsigned int max_divide( unsigned int n, unsigned int divisor )
{
    if ( n != 0 )
    {
        while ( n % divisor == 0 )
        {
            n /= divisor;
        }
    }

    return n;
}


text:
Q: Getting response from lambda via callback and letting lambda continue working lets say I have this lambda function:

exports.handler = (event, context, callback) => {
  lambda.invoke({
    FunctionName: 'longCheckout',
    InvocationType: 'Event',
    Payload: JSON.stringify(event, null, 2) // pass params
  }, function(error, data) {

    console.log(error, data)
    callback(null, data);
  });
};

and I want to call the longCheckout lambda that will do some work and send back a response to the invoking lambda and then continue to execute a longer request. So the lambda function I am calling has a callback argument but when I call that passed in function, nothing happens in the invoking lambda. Here is what the lambda I am calling looks like

exports.handler = (event, test, callback) => {
  docClient.update(params, function(err, data) {
    callback(....)
    // continue to execute
  })
}

A: Lambda can be invoked synchronously (the default behavior that you used), or asynchronously.
If you will choose to invoke asynchronously, both lambdas will continue running at the same time, but you won't be able to get any return value.
A possible solution to do what you ask for is:

*

*Lambda 1 invokes synchronously Lambda 2

*Lambda 2 calls docClient.update and invokes asynchronously Lambda 3 (then returns).

*Lambda 3 makes the rest of the needed execution.

Read this about asynchronous invocations.


text:
Q: Skip in SQL Server subquery I want to use left outer join like this:
    SELECT ...
FROM Table1
LEFT OUTER JOIN
(SELECT only e.g. 3rd record... , SomeField FROM Table2) tbl2
  ON Table1.SomeField = tbl2.SomeField

How can I do that, if I need the subquery to select not just the 3rd record from Table2, but the 3rd record among the Table2 records that have SomeField = Table1.SomeField?
Thanks.

A: If this is sql server 2005 or newer, you might use row_number():
LEFT JOIN
(
   select *
     from
     (
       select *,
              row_number() over (order by something) rn
         from Table2
        where Table2.Column = Table1.Column
     ) a
    where a.rn = 3
) a

Unfortunately you need to nest it a level deeper because you cannot use row_number in a condition directly.
EDIT:
My bad - i didn't really notice the join part. If you want to join derived table, use this:
LEFT JOIN
(
   select *,
          row_number() over (partition by SomeField order by something) rn
     from Table2
) tbl2
  ON Table1.SomeField = tbl2.SomeField
 AND tbl2.rn = 3

Note: you need ORDER BY in row_number() to keep things consistent.


text:
Q: J2ME Ticker at custom location on the screen How to get the ticker at the middle or at custom location on the screen?
I think the normal ticker will place a ticker on the top of the screen.

A: You need to write your own implementation, or use something that wraps the LCDUI Ticker such as LWUIT.  If you don't it will be completely implementation dependent where the ticker goes, you have no control over it.


text:
Q: BeautifulSoup to find text inside the table Here's what my HTML looks like:
 ...

Something really cool here

 ... not important

  ...

  ...

  ...

Now there are four occurrences of this div in my html file, each table content is different and each h2 text is different. Everything else is relatively the same. What I've been able to do so far is extract out the parent of each h2 - however, now I am not sure how to extract out each tr where in then, I can extract out the td that I really need.
Here is the code I've written so far...
from bs4 import BeautifulSoup
soup = BeautifulSoup(open('myhtml.html'), 'html.parser')

currently_watching = soup.find('h2', text='Something really cool here')
parent = currently_watching.parent

A: I would suggest finding the parent div, which actually encloses the table, and then search for all td tags. Here's how you'd do it:
from bs4 import BeautifulSoup
soup = BeautifulSoup(open('myhtml.html'), 'lxml')

div = soup.find('div', class_='section mylist')
for td in div.find_all('td'):
    print(td.text)

A: Searched around a bit and realized that it was my parser that was causing the issue. I installed lxml and everything works fine now.
Why is BeautifulSoup not finding a specific table class?


text:
Q: error " cannot execute binary file" I have mibconverter file(mibcomp.exe) and it works fine on Ubuntu 12.04 but it has error on 14.04 and upper version(16).
I have run on same machine so it is not possibly architecture problem.
Error:
cannot execute binary file: Exec format error".
Is it possible I can fix the problem?
Thank you,
Insuk


text:
Q: SOS extension for x64 debugging Is there any posibility to load SOS extension in visual studio 2010/2012 (.Net framework 4) for x64 process?

A: If you install VS2012 and the WDK, you can attach to a 64 bit process via the User Mode Debugger transport protocol (option under the attach to process dialog). If you do that, you can load SOS from the new Debugger Immediate Window. This works for both 32 and 64 bit processes.

A: It's not possible. For debugging 64 bit applications with SOS, you have to use windbg.


text:
Q: Tree shakable icon component I am creating a custom design system on top of ChakraUI and bootstrap icons.
Bootstrap icons contains 1000+ svg icons.
I created an abstract Icon component to have abstraction over the icon name, that seems IMO more convenient.
However, I am not sure this module will be tree-shaked, and I can't figure out how to change the implementation to make it tree-shakable.
Icon.tsx
import React from 'react'
import * as bootstrapIcons from '@emotion-icons/bootstrap'

// Union of all icon names: 'Alarm' | 'Circle' | 'Square' ...
type IconNames = keyof typeof bootstrapIcons

export const Icon: FC<{name: IconNames}> = ({name}) => {
  const Icon = bootstrapIcons[name]

  return (

      <Icon style={{...}} />

  )
}

App.tsx
import React from 'react'
import { Icon } from './Icon'

const App = () => {
  return

    <Icon name="Alarm" />

}

A: Astrix imports cannot be tree shaken.
Generally when it comes to Icons you can have a Sprite Sheet or Tree Shaking but not both.
To make this particular library tree shake out icons you'll have to change your imports and usage to look like this (haven't tested but should work).
import { Alarm } from '@emotion-icons/bootstrap/Alarm';

const Use = () => <Alarm/>

There's definitely a caveat here where it would be possible to build a build-time plugin that changes...
<Icon name="Alarm"/>
 // to.
import { Alarm } from '@emotion-icons/bootstrap/Alarm';
<Alarm/>

and removes the import.
The reason why astrix imports can't be tree shaken is because javascript is a very dynamic language and static analysis of which keys are used is sometimes very difficult.
Consider the following code
import * as bootstrapIcons from '@emotion-icons/bootstrap'

bootstrapIcons["mralA".reverse()] // which icons should be tree shaken?
const Icons = new Proxy(bootstrapIcons) // which icons should be included? using proxy traps.
const SubSet = PullSubset(bootstrapIcons) // which icons should be included? no matter what the implementation of PullSubset is it will be impossible to preform static analysis on it to determine which icons have been used.


text:
Q: TYPE cause ORA-06502: PL/SQL: numeric or value error I have the following PL/SQL package:
CREATE OR REPLACE PACKAGE PKG_JCSJ
AS
TYPE  record_organ_cant  IS RECORD(CANT_CODE VARCHAR2(90),
        ORGAN_ID  VARCHAR2(90) ,
        CANT_NAME VARCHAR2(90),
        SUPP_TYPE VARCHAR2(20));

  --TYPE array_organ_cant IS TABLE of PKG_JCSJ.record_organ_cant;
  TYPE array_organ_cant IS TABLE of pub_organ_cant%ROWTYPE;

  function fn_transe_organ_cant return PKG_JCSJ.array_organ_cant PIPELINED;
 END PKG_JCSJ;

create or replace package body PKG_JCSJ is

function fn_transe_organ_cant return PKG_JCSJ.array_organ_cant PIPELINED
as
   cursor cursor_organ_cant is select * from pub_organ_cant ;
   record_o_c pub_organ_cant%rowtype;
   record_o_c2 pub_organ_cant%rowtype;
   cant_code VARCHAR2(90);

   TYPE ref_cursor IS REF CURSOR;
   array_column_value ref_cursor;
   sp_cant_code VARCHAR2(90);

begin
   open cursor_organ_cant;
   loop
        fetch cursor_organ_cant into record_o_c;
        exit when cursor_organ_cant%notfound;
        cant_code := record_o_c.cant_code;
        if instr(cant_code, ',')>0 then
           open array_column_value for select * from  table(fn_split(cant_code));
           loop
                fetch array_column_value into sp_cant_code;
                exit when array_column_value%notfound;
                --DBMS_OUTPUT.put_line('---' || sp_cant_code);
                record_o_c2.CANT_CODE := sp_cant_code;
                record_o_c2.ORGAN_ID := record_o_c.ORGAN_ID;
                record_o_c2.CANT_NAME := record_o_c.CANT_NAME;
                record_o_c2.SUPP_TYPE := record_o_c.SUPP_TYPE;
                --DBMS_OUTPUT.put_line('++++++' || record_o_c2.CANT_CODE);

                PIPE ROW (record_o_c2);
           end loop;
           close array_column_value;
        else
           PIPE ROW (record_o_c);
        end if;
   end loop;
   close cursor_organ_cant;
   return;
end fn_transe_organ_cant;
begin
   null;
end PKG_JCSJ;

Why is this statement failing?
TYPE array_organ_cant IS TABLE of PKG_JCSJ.record_organ_cant;

error info is ORA-06502: PL/SQL: numeric or value error. However, when I use the following statement, success!
TYPE array_organ_cant IS TABLE of pub_organ_cant%ROWTYPE;

record_organ_cant is same structure with TABLE pub_organ_cant, I have no idea why the former fails and the latter is successful, what's the difference?
then, package body as follow,

A: First of all, in your package body you don't have to use PKG_JCSJ. because its declared within the pacakge and should be accessible to any of its function like
create or replace package body PKG_JCSJ is
function fn_transe_organ_cant return array_organ_cant PIPELINED
....

Next, when you declare again you don't need PKG_JCSJ. like
CREATE OR REPLACE PACKAGE PKG_JCSJ
AS
  TYPE  record_organ_cant  IS RECORD(CANT_CODE VARCHAR2(90),
        ORGAN_ID  VARCHAR2(90) ,
        CANT_NAME VARCHAR2(90),
        SUPP_TYPE VARCHAR2(20));

  TYPE array_organ_cant IS TABLE of record_organ_cant;

  function fn_transe_organ_cant return array_organ_cant PIPELINED;
 END PKG_JCSJ;


text:
Q: JqueryUI resized div not dropping to correct location I have a 'box' that can be dragged and dropped onto a column of droppable divs. The draggable box snaps to the droppable div using the JqueryUI position function, but when I resize the draggable box to 3x the original height or more, I can no longer move the box a single 'droppable div' lower.
$( ".ru" ).droppable({
  activeClass: "active",
  hoverClass: "hover",
  drop: function(event, ui) {
    ui.draggable.position({
      of: $(this),
      my: 'top left',
      at: 'top left'
    });
  }
});

I hope that makes sense, basically to recreate the problem, resize the draggable box to 3x the height and try to drag it 1 div down.
jsfiddle: link
Thanks for any help.

A: The my and at options take values in the order of 'horizontal-alignment vertical-alignment'. Default value is 'center', which is why the mistake in syntax has the result you describe in your comment. Simply switch the order from 'top left' to 'left top'.
UPDATED: I've also added a custom tolerance option for .droppable() so that hovering is activated on a droppable when the top of #box is over it.
$.ui.intersect = function(draggable, droppable, toleranceMode) {

  var draggableLeft, draggableTop,
    x1 = (draggable.positionAbs || draggable.position.absolute).left,
    y1 = (draggable.positionAbs || draggable.position.absolute).top + 15,
    x2 = x1 + draggable.helperProportions.width,
    y2 = y1 + draggable.helperProportions.height,
    l = droppable.offset.left,
    t = droppable.offset.top,
    r = l + droppable.proportions.width,
    b = t + droppable.proportions.height;

  return (l < x1 + (draggable.helperProportions.width) &&
    x2 - (draggable.helperProportions.width) < r &&
    t < y1 + 1 &&
    b > y1 - 1);
};

$( "#box" ).draggable({
  revert: "invalid",
});

$( ".ru" ).droppable({
  hoverClass: "hover",
  tolerance: "custom", //added this line
  drop: function(event, ui) {
    ui.draggable.position({
      of: $(this),
      my: 'left top', //edited this line
      at: 'left top' //edited this line
    });
  }
});

Check out this UPDATED working fiddle: https://jsfiddle.net/joL53wkq/5/


text:
Q: How to create layer group in geoserver with gsconfig? How can I create layer groups using python gsconfig ?

A: 1. Connect to Catalog
 cat = Catalog("http://localhost:8080/geoserver/rest","admin", "geoserver")

2. Get some layers and styles
lyrs = [list of layers]

stls = [list of styles]

3. Create the group layer
lg = cat.create_layergroup(groupname)

4. Add the layers and styles to the group layer
lg.layers = lyrs

lg.styles = stls

5. Save the group layer
cat.save(lg)

To specify a workspace I think you need to create a resource and then use that to create the group layer in step 3.
myResource = cat.get_resources(workspace='workspaceName') lg =

cat.create_layergroup(myResource,groupname


text:
Q: LINQ to DataSet Group By Multiple Columns - Method Syntax My question is identical to two previously asked questions
LINQ TO DataSet: Multiple group by on a data table, the only difference with this question is that I need to do that with Method Syntax.
and
LINQ Group By Multiple fields -Syntax help - the difference with this question is that I need to do this using LINQ-to-DataSet.
I'm trying to group the Customers by Country, with the result (expected) as below:
   COUNTRYCODE     CUSTOMERNAME
   USA             Microsoft
   USA             IBM
   CAN             RIM
   CAN             Tim Horton
   GER             BMW

How do we do this?  Thank you.
EDIT:
Here's the messy code I'm struggling with.
   var query = orders.AsEnumerable()
                    .GroupBy(t => new {CountryCode= t.Field<string>("CountryCode"),
                                       CustomerName = t.Field<string>("CustomerName"),
                                    (key, group)=> new {Key1 = key.CountryCode, Key2=key.CustomerName})
                    .Select(t => new {t.Key1, t.Key2});

A: var uniqueCountryCustomer =
         tblCustomer.AsEnumerable()
        .GroupBy(row => new
        {
            Country = (string)row["COUNTRYCODE"],
            Customer = (string)row["CUSTOMERNAME"]
        });

For the sake of completeness, here is the query-syntax:
var uniqueCountryCustomer =
            from row in tblCustomer.AsEnumerable()
            group row by new{
                Country=(string)row["COUNTRYCODE"],
                Customer=(string)row["CUSTOMERNAME"]
            };

// display result
var summary = from cc in uniqueCountryCustomer
              select string.Format("Country:{0} Customer:{1} Count:{2}",
              cc.Key.Country,
              cc.Key.Customer,
              cc.Count());
MessageBox.Show(string.Join(Environment.NewLine,summary));

A: The code in my EDIT worked:
 var query = orders.AsEnumerable()
              .GroupBy(t => new {CountryCode= t.Field<string>("CountryCode"),
                                 CustomerName=t.Field<string>("CustomerName"),
                           (key, group)=> new {CountryCode = key.CountryCode,CustomerName=key.CustomerName})
.Select(t => new {t.CountryCode, t.CustomerName});


text:
Q: Get queryset with only selecting one object in related to foreign key I have a model named Answer
class Answer(models.Model):
   survey = models.ForeignKey(Survey)

I want to return a queryset of Answer according to Survey foreign Key, Means if there are 3 objects ,
answers = [
    {"survey": 1},
    {"survey": 2},
    {"survey": 1},
  ]

then queryset should return
[
    {"survey": 2},
    {"survey": 1},
  ]

Means that will check if there is Answer with a foreign key then it should not select other Answer with same foreignkey.
So how to do that. I'm trying this way but this doesn't have any affect
def get_queryset(self, request):
        qs = super().get_queryset(request)
        idx = list(qs.values_list("survey_id", flat=True).distinct())

        return qs.filter(survey_id__in=idx).distinct()

Edit:
I'm now able to do it this way, but I'm not sure if that is optimal solution. your suggestions are welcome to improve it.
 def get_queryset(self, request):
        qs = super().get_queryset(request)
        idx = list(qs.values_list("survey_id", flat=True).distinct())

        data = []
        for i in qs:
            if i.survey_id in idx:
                data.append(i)
                idx.remove(i.survey_id)

        # modify the data to queryset
        return qs.filter(pk__in=[i.pk for i in data])

A: you could do it like this with less for loops as possible (always rely on database not in the for loops):
for id in idx:
   new_value = qs.filter(survey_id=id).first()
   data.append(new_value)


text:
Q: Why do we use "be" with "will", instead of "is" and "are"? I want to know from a grammatical point of view why do we use be with will instead of using is and are. For example:

*

*Jack will be skydiving tomorrow. Correct

*Jack will is skydiving tomorrow. Incorrect
I also want to know why do we use is, are, was, and were instead of be in the present and past tenses. For example:
Present Tense

*

*Jack is skydiving today. Correct

*Jack be skydiving today. Incorrect
Past Tense

*

*Jack was skydiving yesterday. Correct

*Jack be skydiving yesterday. Incorrect

A: Every verb requires its own unique complementation. For example, "make" only takes a bare-infinitive: eg. "He made me cry"; "Keep" only takes a participle: eg. "He keeps crying"; etc.
"Will" belongs to a special category of verb, the modal verbs. Modal verbs (except "ought") allow only a bare-infinitive as a complement. Since the bare infinitive form of "is" and "are" is "be", it should be "will be", not "will is".
Present tense and past tense clauses are sometimes called finite clauses. Finite clauses require a main verb that is inflected for tense. So the bare-infintive (be), the past participle (been) and the present participle (being) are not possible.

A: I'm not sure how one could answer that except to say, "because that's how the verb tenses are formed in English". Why do we say "is" instead of "fwacbar"? I suppose one could study the history of the language and say when the various words were invented, but that still wouldn't really tell you why. It would just tell you when.
Other languages that I know anything about have words or endings used to indicate verb tense and other grammatical constructions. Why does Latin use "-ba-" to indicate imperfect and "-bi-" to indicate future, and not the other way around? It just ... does.


text:
Q: Implementing System.Web.Http.WebHost.WebHostBufferPolicySelector.IHostBufferPolicySelector I am trying to following this web blog on uploading large files using the Web Api class via Asp.Net Web Forms. If you look through the post you will notice that in order to avoid an out of memory because of buffering of larges files, they recommend overriding the IHostBufferPolicySelector interface. Where do I implement the interface? Do I do it in the Web Api class, in the Global.asax or am I completely off track and need to do the implementation somewhere else?

A: You don't need to implement this interface, I only listed it as a reference - that code is already part of Web API source (under System.Web.Http/Hosting/IHostBufferPolicySelector.cs)
What you need to do is override the base class System.Web.Http.WebHost.WebHostBufferPolicySelector
This is enough:
public class NoBufferPolicySelector : WebHostBufferPolicySelector
{
   public override bool UseBufferedInputStream(object hostContext)
   {
      var context = hostContext as HttpContextBase;

      if (context != null)
      {
         if (string.Equals(context.Request.RequestContext.RouteData.Values["controller"].ToString(), "uploading", StringComparison.InvariantCultureIgnoreCase))
            return false;
      }

      return true;
   }

   public override bool UseBufferedOutputStream(HttpResponseMessage response)
   {
      return base.UseBufferedOutputStream(response);
   }
}

and then registering your new class in either Global.asax or WebApiConfig.cs (whichever you prefer):
GlobalConfiguration.Configuration.Services.Replace(typeof(IHostBufferPolicySelector), new NoBufferPolicySelector());


text:
Q: How to start a transaction in another thread? Spring 4.
I'm working on implementing updatable cache through ScheduledThreadPoolExecutor. It currently looks as follows:
public class MyService {

    @Setter
    private MyDao myDao;
    //Immutable
    private volatile Cache cache;

    //Static factory method
    public static MyService create(){
        MyService retVal = new MyService();
        cache = Cache.emptyCache();
        updateCache();
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public int get(){
         //Retrieving from cache
         return cache.getNext();
    }

    private void updateCache() {
        try{
            ScheduledExecutorService ses = Executors.newScheduledThreadPool(1);
            //The runnable should be in a transaction.
            Runnable updateCache;
            //the runnable queries the MyDao,
            //which in turn currently implemented as a DB-dao
            //The cache is assigned after computation
            ses.scheduleWithFixedDelay(updateCache, 0, 60, TimeUnit.SECONDS);
        } catch (Throwable t){ }
    }
}

My question is how can I run the runnable job in a transaction?
Annotating the updateCache() as @Transactional won't work as long as transactions are thread bound.

A: Don't schedule like that, use the scheduling support of Spring.
public class MyService {

    @Setter
    private MyDao myDao;
    //Immutable
    private volatile Cache cache;

    //Static factory method
    public static MyService create(){
        MyService retVal = new MyService();
        cache = Cache.emptyCache();
        updateCache();
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    public int get(){
         //Retrieving from cache
         return cache.getNext();
    }

    @Transactional
    @Scheduled(fixedDelay=60000)
    public void updateCache() {
            //the runnable queries the MyDao,
            //which in turn currently implemented as a DB-dao
            //The cache is assigned after computation
    }
}

Then either add @EnableScheduling or <task:annotation-driven />. See also the earlier mentioned link for more configuration options.


text:
Q: Can't format the fat32 sd card, Bad FAT: unterminated chain I'm trying to format this SD Card, and gParted says all operations successful but when the devices refresh the data is still there hence the disk is unformatted.
When I perform the "Check" operation on the partition it gives me Bad FAT: unterminated chain error so I suppose it is the reason why I can't format the drive.
I can't delete the partition can't resize the partition and can't perform any of the such operations.
Below is the screenshot of the exact error.


text:
Q: How to find which key triggered the form submit event I have a form with multiple fields, But only have one required field. The issue is when the required field is filled and Enter key is pressed the form get submitted.
If Enter key is pressed inside a Text area there is no problem, But for Text box the form get submitted.
I was thinking the following as a solution.

*

*subscribe the podio form submit event.

*find which key caused the form submit

*if form submit is triggered by Enter key prevent the default action.
Right now i'm using the following method.
$("form").bind("keypress", function (e) {
    if (e.keyCode == 13) {
      e.preventDefault();
    }
});

It is working fine. But is there a way that i can do this in form submit event?

A: After seeing your comment in previous answer, you could validate your form as like this fiddle
HTML:

<form>

    First Name:

    <input type='text' id='txtFName'/ >

    Last Name:

    <input type='text' id='txtLName'/ >

    Age:

    <input type='text' id='txtAge'/ >

    Email:

    <input type='text' id='txtEmail'/ >

    <input type="submit" id="btnSubmit" value=" Submit ">

</form>

JS:
    $(document).ready(function() {
    $('form').submit(function(e) {
        var isValid = true;
        var allow = false;
        $('input[type="text"]').each(function() {
            if ($.trim($(this).val()) == '') {
                isValid = false;
                $(this).css({
                    "border": "1px solid red",
                    "background": "#FFCECE"
                });
            }
            else {
                $(this).css({
                    "border": "",
                    "background": ""
                });
            }
        });
        if (isValid == false){
            if(!confirm('Few Fields are empty! Are you sure want to continue?')){
                e.preventDefault();
          } else {
          alert('Thank you for submitting');
          }
        }
        else
           alert('Thank you for submitting');
        });
});

A: Old answer:

var Keys = {
  ENTER: 13
};

$('form').on('submit', function(e) {
  e.preventDefault();

  if (checkIfAllRequiredFieldsAreFilled()) {
    $(this)[0].submit(); //call native event, since calling the jquery event will let you end up in the same function over and over again
  }
});

function checkIfAllRequiredFieldsAreFilled() {
  //do your checkings here, if they are complex. Otherwise just do them in the if-clause
  return true;
}

If you just want to prevent and accidental submit, on pressing enter:

    var Keys = {
        ENTER: 13
    };

    $('form input').on('keypress', function (event) {
        if (event.keyCode == Keys.ENTER) {
           event.preventDefault();
           console.log('Prevented Form-submit from: ', this);
        }
    });

<form>

        Text: <input type="text"/>

        Number: <input type="number"/>

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

Don't use .bind(), use .on():

As of jQuery 3.0, .bind() has been deprecated. It was superseded by
  the .on() method for attaching event handlers to a document since
  jQuery 1.7 [...]


text:
Q: Creating multiple users in Firebase at the same time Well, not exactly at the same time. More like one after the other, in a for-loop.
Problem: So in some instances, the code I used did manage to create multiple accounts but it often gives me the error that the user is null and fails to write to the database.
The code:
Database db = FirebaseDatabase.getInstance().getReference();
String password = "1234567"; // Same password for all accounts
ArrayList emailArray = new ArrayList(); // For example, 20 premade emails

        for (int i = 0; i < emailArray.size(); i++){
            mAuth.createUserWithEmailAndPassword((String) emailArray.get(i), password).addOnCompleteListener(new OnCompleteListener<AuthResult>() {
                @Override
                public void onComplete(@NonNull Task<AuthResult> task) {
                    if (mAuth.getCurrentUser() != null) {

                     String userId = mAuth.getCurrentUser().getUid();  // This value is returning null

                     // Writing a bunch of things to the database for each user
                     db.child(userId).child("name").setValue(...)
                     ...

                     mAuth.signOut();

                    }
                }
            });
        }

I think I may have to use an AuthStateListener but I am unsure and I don't know how to implement it. How would I go about accomplishing this? Please let me know if I should include anything else in my post. Thank you!

A: You should not use the client-side Android SDK to create multiple users like this. There's a significant chance that your app will be flagged for abuse, and locked out of the system.
For administrative use-cases, use the Admin SDK in a trusted environment.

On a code level, the problem occurs because there's only one value for mAuth.getCurrentUser() and you're trying to create all the users in parallel. You'll need to wait for each createUserWithEmailAndPassword to be completed, before starting on the next one. But as said above: this approach is flawed to begin with, so I don't recommend pursuing this path further.


text:
Q: Mapping multiple link tables to a nested JQuery accordion This is my first time asking on Stack Overflow so bear with me.
I have been trying to implement an HTML page using Jquery and Javascript.  Here is a sample JSFiddle of my page: http://jsfiddle.net/R63Hz/2/.  Notice the three tables at the top have elements that map to the nested accordion structure at the bottom.  I would like to use Javascript to map the links in these tables to open the appropriate accordion section. I have tried alot of methods but I think I don't have enough knowledge to figure it out.
Here is my most recent attempt at a solution:
    $(this).on("click", ".linkButton", function () {
            var $tbl = $(this).closest("table");
            var $tr = $(this).closest("tr");
            var row = $tr.index() - 1;
            var table = $tbl.attr("id");
            if(table=="table1") {
                ("#accordion").accordion({ active: 0 });
                ("#accordion2").accordion({ active: row });
            }
            else if(table=="table2") {
                ("#accordion").accordion({ active: 1 });
                ("#accordion3").accordion({ active: row });
            }
            else if(table=="table3") {
                ("#accordion").accordion({ active: 2 });
                ("#accordion4").accordion({ active: row });
            }

        });

I am not sure if the 5th line is working to set up for the conditional statement.

A: You could assign a data value to the individual links then in the on.click handler create an if statement that would expand the relevant accordion section.
Your fiddle is very long/messy which is why I've not edited the Fiddle with an exact solution but I hope that the above makes sense.

A: Here is the solution I found :
I renamed the linkbutton classes to linkbutton1 for the first table, linkbutton2 for the second and linkbutton3 for the third.  Then I created the conditional opening on JQuery based on that. The main thing I had screwed up was I forgot $ signs in front of the commands to open the accordion.
    $(this).on("click", ".linkButton", function () {
            var $tr = $(this).closest("tr");
            var row = $tr.index() - 1;
            $("#accordion").accordion({ active: 0 });
            $("#accordion2").accordion({ active: row });
        });

        $(this).on("click", ".linkButton2", function () {
            var $tr = $(this).closest("tr");
            var row = $tr.index() - 1;
            $("#accordion").accordion({ active: 1 });
            $("#accordion3").accordion({ active: row });
        });

        $(this).on("click", ".linkButton3", function () {
            var $tr = $(this).closest("tr");
            var row = $tr.index() - 1;
            $("#accordion").accordion({ active: 2 });
            $("#accordion4").accordion({ active: row });
        });


text:
Q: subscribe on route.queryParamMap and route.paramMap causes page loads twice As depicted here, I use in my app the url:
http://localhost:8080/rooms/lisbon?roomTypes=1

And in ngOnInit I subscibes both:
this._route.data.subscribe(x => { console.log(1);doCommonBiz(); })

this._route.paramMap.subscribe(param => { console.log(2);doCommonBiz(); })

I need to be notified one one of them occured, if any of below routed:
http://localhost:8080/rooms/lisbon?roomTypes=2
http://localhost:8080/rooms/london?roomTypes=1
http://localhost:8080/rooms/cologne?roomTypes=3

But my subscriptions fire twice.
My question is how can I be notified only once by being aware of two subsciption?

A: After digging some, I found combineLatest is what I am looking for.


text:
Q: FileA has n rows, each row is used to filter rows in FileB in unix I have two csv files
FileA
ID
1
2
3

FileB
name,ID
a,1
a,2
a,4
ab,1
ac,1
bb,3
bd,2
ad,2

What I want to do is to get each value in FileA and compare whether ID in FileB is equal to ID in FileA, if matched, print the entire row in FiLeB and save everything in FileC. Note that the order in FileC is not important
Expected Outcome
FileC
name,ID
a,1
a,2
ab,1
ac,1
bb,3
bd,2
ad,2

My current rough idea:
while read line
do
   helper_function line
done < FileA

helper_function(){
awk -F, '$2==line {print $0}' FileB
... need to implement more...
}

But both FileA and FileB are considerably large, I am not sure whether using for loop here is a good idea since it would be time-consuming. Do we have other ways to solve this? Thank you

A: With awk:
awk -F ',' 'NR==FNR { a[$1]=$1; next}; $2 in a {print $0};' FileA FileB

You can change $2 into $4 for matching field 4.
With grep you shouldn't use grep -f FileA FileB but
grep -f <(sed 's/.*/,&$/' FileA) FileB

The second grep makes sure you will skip the line dontwantthis,123456789.
The sed command will soon grow out-of-control, when you want to add more conditions (the third field,...).


text:
Q: Including Merged Cells When Making Selection of Unknown Size - Excel VBA I am trying to make a selection from a spreadsheet via VBA and paste it to a Word doc. There are merged cells in the selection and I want to include them as is. The selection size may change so I am using .Range.End to get to the end of the selection. Problem is, once my code hits a merged cell, it cannot go further and returns only a part of the selection.
How can I modify this? Preferably I want to achieve this without loops.
Dim rngEnd As Range
Set rngEnd = shDevAvail.Range("C8").End(xlDown)

shDevAvail.Range("A6", rngEnd).Copy
wdDoc.Bookmarks("Device_Avail_Chart").Range.Paste

Here is the data that I am trying to select. The blue rows are the merged cells.
When I tried to get to the bottom the selection, I can only pull up to the row before the next blue rows.

A: If you have any column that doesn't have merged cells, you can you the range.end method on that column for example:
Dim i as Integer

i = shDevAvail.Range("A6").End(xlDown).Row
shDevAvail.Range("A6", "C" & i).Copy

If every column is have mergers in it, then you can come up from the bottom, assuming there is nothing else under the range.
Dim i As Integer

i = shDevAvail.Range("C400000").End(xlUp).Row
shDevAvail.Range("A6", "C" & i).Copy

Finally you can use i = shDevAvail.UsedRange.Rows.Count again assuming that you don't have anything after the range in question. If you use this method, if you have any leading blank rows you have to add the number of leading blanks to number returned, i.e. if you have 5 blank rows at the top of your sheet, you'd need to do i = shDevAvail.UsedRange.Rows.Count+5.


text:
Q: How to fetch data from website using API I have never used API  before and this is the first work that I am going to use API to fetch data from another website to my website. Is there is any such API through which i can fetch data with PHP or Laravel5 etc.?
Actually i need to extract exchange rates from http://www.nrb.org.np/fxmexchangerate.php to my website. I should get the recent data i.e. updated data from this website.
How can i do this?

A:
API: application program interface.

If the site you're trying to collect data from doesn't provide an API then you'd have to find a way to collect the data yourself. If you're using PHP you can check this parser for a simple HTML DOM extractor.
They provide various examples on their site, check these and also check the structure of the site you're trying to get the content from and you should be fine:
// Create DOM from URL or file
$html = file_get_html('http://www.stackoverflow.com/');

// Find all images
foreach($html->find('img') as $element)
   echo $element->src . '
';

// Find all links
foreach($html->find('a') as $element)
   echo $element->href . '
';


text:
Q: Download online video js I don't know if this is the right place to ask such a question, but I want to download an online video of my graduation. I tried to look up the source code and in inspect option in google chrome but I didn't succeed. Is there any way to download the video?

A: This page uses HTTP Live Streaming deploying the M3U8 file format. After obtaining the link to the M3U8 file, it can be downloaded and converted with other software libaries also supporting HLS (e.g. VLC media player or ffmpeg ffmpeg -i "https://….m3u8?…" output.mp4).
You can extract the .m3u8 URL using Chrome Dev Tools, which allow you to browse loaded resources in your browser:

Log network activity
Reload the page. The Network panel logs all network activity in the Network Log.

– Documentation › Chrome DevTools › Network

Once opened with F12, you can press F5 to reload all resources and use the search option to filter for m3u8:


text:
Q: Why are Perl source filters bad and when is it OK to use them? It is "common knowledge" that source filters are bad and should not be used in production code.
When answering a a similar, but more specific question I couldn't find any good references that explain clearly why filters are bad and when they can be safely used.  I think now is time to create one.

*

*Why are source filters bad?

*When is it OK to use a source filter?

A: It's worth mentioning that Devel::Declare keywords (and starting with Perl 5.11.2, pluggable keywords) aren't source filters, and don't run afoul of the "only perl can parse Perl" problem. This is because they're run by the perl parser itself, they take what they need from the input, and then they return control to the very same parser.
For example, when you declare a method in MooseX::Declare like this:
method frob ($bubble, $bobble does coerce) {
  ... # complicated code
}

The word "method" invokes the method keyword parser, which uses its own grammar to get the method name and parse the method signature (which isn't Perl, but it doesn't need to be -- it just needs to be well-defined). Then it leaves perl to parse the method body as the body of a sub. Anything anywhere in your code that isn't between the word "method" and the end of a method signature doesn't get seen by the method parser at all, so it can't break your code, no matter how tricky you get.

A: The problem I see is the same problem you encounter with any C/C++ macro more complex than defining a constant:  It degrades your ability to understand what the code is doing by looking at it, because you're not looking at the code that actually executes.

A: Why source filters are bad:

*

*Nothing but perl can parse Perl. (Source filters are fragile.)

*When a source filter breaks pretty much anything can happen. (They can introduce subtle and very hard to find bugs.)

*Source filters can break tools that work with source code. (PPI, refactoring, static analysis, etc.)

*Source filters are mutually exclusive. (You can't use more than one at a time -- unless you're psychotic).

When they're okay:

*

*You're experimenting.

*You're writing throw-away code.

*Your name is Damian and you must be allowed to program in latin.

*You're programming in Perl 6.

A: In theory, a source filter is no more dangerous than any other module, since you could easily write a module that redefines builtins or other constructs in "unexpected" ways.  In practice however, it is quite hard to write a source filter in a way where you can prove that its not going to make a mistake.  I tried my hand at writing a source filter that implements the perl6 feed operators in perl5 (Perl6::Feeds on cpan).  You can take a look at the regular expressions to see the acrobatics required to simply figure out the boundaries of expression scope.  While the filter works, and provides a test bed to experiment with feeds, I wouldn't consider using it in a production environment without many many more hours of testing.
Filter::Simple certainly comes in handy by dealing with 'the gory details of parsing quoted constructs', so I would be wary of any source filter that doesn't start there.
In all, it really depends on the filter you are using, and how broad a scope it tries to match against.  If it is something simple like a c macro, then its "probably" ok, but if its something complicated then its a judgement call.  I personally can't wait to play around with perl6's macro system.  Finally lisp wont have anything on perl :-)

A: Only perl can parse Perl (see this example):
@result = (dothis $foo, $bar);

# Which of the following is it equivalent to?
@result = (dothis($foo), $bar);
@result = dothis($foo, $bar);

This kind of ambiguity makes it very hard to write source filters that always succeed and do the right thing. When things go wrong, debugging is awkward.
After crashing and burning a few times, I have developed the superstitious approach of never trying to write another source filter.
I do occasionally use Smart::Comments for debugging, though. When I do, I load the module on the command line:
$ perl -MSmart::Comments test.pl

so as to avoid any chance that it might remain enabled in production code.
See also: Perl Cannot Be Parsed: A Formal Proof

A: I don't like source filters because you can't tell what code is going to do just by reading it. Additionally, things that look like they aren't executable, such as comments, might magically be executable with the filter. You (or more likely your coworkers) could delete what you think isn't important and break things.
Having said that, if you are implementing your own little language that you want to turn into Perl, source filters might be the right tool. However, just don't call it Perl. :)

A: There is a nice example here that shows in what trouble you can get with source filters.
http://shadow.cat/blog/matt-s-trout/show-us-the-whole-code/
They used a module called Switch, which is based on source filters. And because of that, they were unable to find the source of an error message for days.


text:
Q: what is the difference with Array.prototype.splice and arr.splice in vuejs? code:(vue2.0, vue-router)
<template>

</template>

and in store/modules
const mutations {
  myMutation(state) {
    state.apis.splice(0, 1) // A
    //Array.prototype.splice.call(state.apis, 0, 1); //B
  }
}
const getter = {
  allApis: (state) => {
    return state.apis
  }
}
export default {
  state,
  getters,
  actions,
  mutations
}

the line A will change the allApis and update the view
but the line B will not change the allApi and update the view;

A: Yes, state.apis.splice(0, 1) will work, as Vue intercept mutating methods and emit events as you can see here in the code.
const arrayProto = Array.prototype
export const arrayMethods = Object.create(arrayProto)
/**
 * Intercept mutating methods and emit events
 */
;[
  'push',
  'pop',
  'shift',
  'unshift',
  'splice',
  'sort',
  'reverse'
]
.forEach(function (method) {
  // cache original method
  const original = arrayProto[method]

As you see in the source code: arrayMethods are original Array prototype methods which are being overwritten to give you reactivity functionality of vue, so using Array.prototype misses the behavior vue defines.
From the documentation:

Vue wraps an observed array's mutation methods so they will also trigger view updates.


text:
Q: Not able to get sorting event from IgniteUI / igniteui-angular grid I need to apply alphanumeric sorting on grid but not able to get sorting event from grid.

A: There are three event emitters that can be used, topic on the subject.

*

*sorting - emitted before sorting expressions are applied

*sortingDone - Emitted after sorting is completed
<igx-grid #grid [data]="localData" [autoGenerate]="true" (sortingDone)="sortingDone($event)">

*sortingExpressionsChange - Emitted before sorting is performed
Sorting is performed using the DefaultSortingStrategy algorithm. Any IgxColumnCOmponent or ISortingExpression can use a custom implementation of the ISortingStrategy.
You can define your own sorting strategy by extending the default one or by implementing ISortingStrategy:

*

*Example with CustomSortingStrategy
export class CustomSortingStrategy extends DefaultSortingStrategy {
...
}

...
const strategy = CustomSortingStrategy.instance();

grid.sort({fieldName: 'Name', dir: SortingDirection.Asc, ignoreCase: true, strategy: CustomSortingStrategy.instance()});

*Example with ISortingStrategy implementation:

export class SortByParityComponent implements ISortingStrategy {
    public sort(data: any[], fieldName: string, dir: SortingDirection) {
        const key = fieldName;
        const reverse = (dir === SortingDirection.Desc ? -1 : 1);
        const cmpFunc = (obj1, obj2) => this.compareObjects(obj1, obj2, key, reverse);
        return data.sort(cmpFunc);
    }
    protected sortByParity(a: any, b: any) {
        return a % 2 === 0 ? -1 : b % 2 === 0 ? 1 : 0;
    }
    protected compareObjects(obj1, obj2, key: string, reverse: number) {
        const a = obj1[key];
        const b = obj2[key];
        return reverse * this.sortByParity(a, b);
    }
}
...

grid.sort({
    fieldName: 'ID',
    dir: SortingDirection.Desc,
    ignoreCase: false,
    strategy: new SortByParityComponent()
});

Here you can find a working sample with CustomSortingStrategy.


text:
Q: Were are the docker Remote API logs stored? I have Docker on OpenSuse Leap 42.1. I have setup Remote API. Where can I see the logs/STDOUT of the Remote API service? Specifically the logs indicating API calls such as GET and POST calls.
I checked the docker service logs using:
journalctl -u docker.service

But this only indicates that API is listening on a port. Doesn't actually show the information about the calls being made.
time="2016-10-31T17:44:07.170795338Z" level=info msg="API listen on /var/run/docker.sock"

When I ran the docker deamon directly I was able to see the REST API information in the STDOUT. I am guessing it is not storing STDOUT to logs.

A: I have Docker Engine 1.13.1 on CentOS 7.3.1611.
I added dockerd option.
/usr/bin/dockerd --log-level=debug (...snip...)

I found API log in journalctl.
Feb 15 10:12:52 xxx dockerd[7596]: time="2017-02-15T10:12:52.456651320+09:00" level=debug msg="Calling POST /containers/create"
Feb 15 10:12:52 xxx dockerd[7596]: time="2017-02-15T10:12:52.456886794+09:00" level=debug msg="form data: {\"AttachStdin\":true,...


text:
Q: Best way to handle live updating of a user alerts panel I would like to build a classic alerts panel using angular and java spring/spring boot  that responds to events and updates in real time so the user wouldn't need to refresh the page to get their newest alerts. Because of the need for it to be live updating it seems like web sockets are my best bet.
After looking through some tutorials it seems that connecting to the backend socket from angular will be pretty easy and the connection can be turned on/off with ease. This will be using stompjs and sock js-client.
However it seems my issues will lie in the backend when creating the various 'topics' that users will subscribe to. All of these tutorials only cover creating a static room on server start that every user is supposed to join (like a chat app). But for my scenario I would need to dynamically create topics on the fly (one separate topic per user) instead of creating all of my topics in the beginning.
Anyone have experience using spring or spring boot to dynamically create the topics for my users to subscribe to?
Main tutorial I have been looking at is:
https://medium.com/oril/spring-boot-websockets-angular-5-f2f4b1c14cee

A: i found that by using this in my controller:
@MessageMapping("/meeting/{roomId}")
private void sendMessageTpPrivateRoom(String message, @DestinationVariable String roomId) throws IOException {
    System.out.println("message sent to: " + roomId);
    this.template.convertAndSend("/meeting/" + roomId, message);
    addToHistory(roomId, message);
}

combined with this in my configuration:
@Override
public void registerStompEndpoints(StompEndpointRegistry registry) {
    registry.addEndpoint("/socket")
            .setAllowedOrigins("*")
            .withSockJS();
}

@Override
public void configureMessageBroker(MessageBrokerRegistry registry) {
    registry.setApplicationDestinationPrefixes("/app")
            .enableSimpleBroker("/chat", "/meeting");
}

I am able to have dynamically created chat rooms where clients in one room do not receive messages from clients in another


text:
Q: Watch extension NSBundle URLForResource always nil In my application i use a static library with resources target, I've connected the resources target to Build Phases -> Copy Bundle Resources and i fetch library resources like this:
 NSUrl *resourcesUrl = [[NSBundle mainBundle] URLForResource:@"MySDKResources" withExtension:@"bundle"]
 NSBundle *bundle = [NSBundle bundleWithURL:resourcesUrl];
 NSString *path = [bundle pathForResource:filename ofType:fileExtension];

Using watch extension, when application receive func session(session: WCSession, didReceiveMessage message: [String : AnyObject], replyHandler: ([String : AnyObject]) -> Void)  delegate I use the same code but this time

*

*resourcesUrl is in different folder, one i cannot find on finder

*bundle is nil

*path is obviously nil

*didReceiveMessage delegate call this code NOT on main thread (so I dispatch on main)

In the same session when one of application classes call this code file path return alright but when watch extension delegate call the same code it returns nil
I've tried to add the static library to Target Dependencies and Compile Sources
and adding the resources target to Copy Bundle Resources but i get No such file or directory error

A: Ok, turns out that when you run watch simulator it kills app on iPhone simulator (but not crash it) so it seems like the app running but actually you cannot instantiate bundle or any other app resource.   this blog post explain how to run application and watch application together on debug.

TL;DR :
while running code on simulator on Xcode menu bar select Debug ->
  Attach to Process -> select the process of your iOS app from the list
  (It'll probably be under Likely Targets)


text:
Q: Writing a apache camel test case but getting this error am writing a camel route test case but am getting this issue,  have also included the camel route. Have debugged looks like the object is flowing through properly but on my assertion it seems to fail...

java.lang.AssertionError:
mock://seda:processMessage?blockWhenFull=true Received message count.
Expected: <1> but was: <0>

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

import org.apache.camel.EndpointInject;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.test.spring.MockEndpoints;
import org.apache.camel.test.spring.junit5.CamelSpringBootTest;
import org.junit.jupiter.api.Test;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.sams.pricing.prism.data.processor.model.CostIQRetail;
import com.sams.pricing.prism.data.processor.service.RulesEngineClient;
import com.sams.pricing.prism.data.processor.util.Endpoints;

@SpringBootTest
@CamelSpringBootTest
@MockEndpoints( Endpoints.SEDA_PROCESS_ENDPOINT)
public class CamelRouteTests3  {

        @Autowired
        private ProducerTemplate template;

        @EndpointInject("mock:"+ Endpoints.SEDA_PROCESS_ENDPOINT)
        private MockEndpoint mock;

        @Mock
        private RulesEngineClient rulesEngineClientMock;

    public CostIQRetail costIQObject() {

        CostIQRetail obj = new CostIQRetail();

        obj.setItemNbr(123);
        obj.setLocationNbr(4931);
        obj.setIsDcFlag(false) ;
        obj.setStatus("SUCCESS");
        obj.setOrderableCost(new BigDecimal((10.0)));
        obj.setWarehousePackCost(new BigDecimal(100.0));
        obj.setOrderablePrepaidCost(null) ;
        obj.setOrderableCollectCost(null) ;
        obj.setReasonCode("Markdown - category funded");
        obj.setEffectiveDate("2022-12-29");
        obj.setIsFutureEffectiveDate(false);
        obj.setCostType("WAREHOUSE PACK COST");
        obj.setSource("COST IQ");
        obj.setCreatedBy("lab1 account");
        obj.setCreatedByUserId("LB-cost-test");
        obj.setCreatedTs("2022-12-29T02:42:25.529Z");
        obj.setCurrentRetailPrice(new BigDecimal(55.0)) ;
        obj.setCurrentOrderableCost(null);
        obj.setCurrentWarehousePackCost(new BigDecimal((0.0)));
        obj.setCurrentOrderablePrepaidCost(null) ;
        obj.setCurrentOrderableCollectCost(null);
        obj.setMarginChange(new BigDecimal((-100.0)));
        obj.setOwedToClub(new BigDecimal((0.0)));
        obj.setItemSourceId(3572924);
        obj.setPriceDestId(701800);
        obj.setCategory(87);
        obj.setOrderableQty(null);
        obj.setOldMargin(new BigDecimal((100.0)));
        obj.setNewMargin(new BigDecimal(0.0));

        return obj;
    }

    private String costIQPayloadString() throws JsonProcessingException
    {

         String key =  "{\"retailTypeReasonCode\":{\"retailTypeReasonCodeId\":{\"retailType\":\"BP\",\"retailReasonCode\":\"CC\"}},\"expirationDate\":null,\"customerRetailAmount\":0.0,\"auditMessage\":null,\"createdTimestamp\":null,\"clientID\":\"COST IQ\",\"rowNumber\":0,\"auditRecordTimestamp\":null,\"clubNumber\":4931,\"itemNumber\":123,\"effectiveDate\":\"2022-12-29\",\"submissionID\":null,\"retailAmount\":55.0,\"createdBy\":\"lab1 account\"}";
    //   String key2 = "{\"retailTypeReasonCode\":{\"retailTypeReasonCodeId\":{\"retailType\":\"BP\",\"retailReasonCode\":\"CC\"}},\"expirationDate\":null,\"customerRetailAmount\":0.0,\"auditMessage\":null,\"createdTimestamp\":null,\"clientID\":\"COST IQ\",\"rowNumber\":0,\"auditRecordTimestamp\":null,\"categoryId\":87,\"subCategoryId\":1,\"clubNumber\":4931,\"itemNumber\":123,\"effectiveDate\":\"2022-12-29\",\"submissionID\":null,\"retailAmount\":10.0,\"createdBy\":\"lab1 account\"}";
         return key;

//      CostIQPayloadTransformer transformer = new CostIQPayloadTransformer();
//      return transformer.payloadTransformer(costIQObject());
    }

    @Test
     void test() throws Exception {
        // Set up the mock endpoints
        mock.expectedBodiesReceived(costIQPayloadString());

        //getMockEndpoint( mock  +  Endpoints.SEDA_PROCESS_ENDPOINT).expectedBodiesReceived(costIQPayloadString());

        //**need to properly mock and return this value
        Mockito.when(rulesEngineClientMock.validateRules((costIQObject()))).thenReturn(costIQObject());  //.thenR

        Map<String, Object> headers = new HashMap<>();
        headers.put("appName", "costIQ");

        //   Send the test message to the SEDA_SEND_ENDPOINT
        template.sendBodyAndHeaders(Endpoints.SEDA_SEND_ENDPOINT, costIQObject(), headers);

        //System.out.println("here " +mock.());
        mock.assertIsSatisfied();

    }

}

(below is the camel route )
 ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(2);
    ExecutorService executorService =
        MoreExecutors.getExitingExecutorService(executor, 100, TimeUnit.MILLISECONDS);

    @SuppressWarnings("resource")
    ThrottlingInflightRoutePolicy throttlingInflightRoutePolicy =
        new ThrottlingInflightRoutePolicy();
    throttlingInflightRoutePolicy.setMaxInflightExchanges(150);
    throttlingInflightRoutePolicy.setResumePercentOfMax(25);

    // Camel's error handler that will attempt to redeliver the message 3 times
    errorHandler(deadLetterChannel("seda:costIqDeadLetterChannel")
                    .maximumRedeliveries(3)
                    .redeliveryDelay(3000)
    );

    // SEDA Endpoint Stage Event Driven Architecture
    from(Endpoints.SEDA_SEND_ENDPOINT)
        .messageHistory()
        // Route Name
        .routeId(Endpoints.SEDA_SEND_ENDPOINT)

        // multicast
        .multicast()
        .parallelProcessing() // create parallel threads

        // thread pool
        .threads()
        .executorService(executorService) // specific thread pool
        .log("Camel Route Started Message Processing : - ${body}")

        .choice()
        .when(PrismUtility.costIQPredicate)
        .circuitBreaker()
        .inheritErrorHandler(true)
        .bean(CostIQService.class, PrismConstants.CALCULATE_PRICE) // rules engine call
        .bean(
            CostIQPayloadTransformer.class,
            PrismConstants.PAYLOAD_TRANSFORMER) // payload transformer
        .to(
            Endpoints.SEDA_PROCESS_ENDPOINT // consumer 1
            )
        .endCircuitBreaker()
        .endChoice()

        .log("Final :- ${body}")
        .end();

Edit :
I modified the class like below by adding "mock:" to my route but  is there a way to go around this? seems like it is not sending to the proper endpoint without me changing and adding the "mock:" value to where it is sending
Edit :
I added in this peice of code - to try to use adviceWith in my test class. I am calling the endpoint like so
    getMockEndpoint("mock:"+Endpoints.SEDA_PROCESS_ENDPOINT).expectedBodiesReceived(costIQPayloadString());

But am getting the error

Cannot advice routes as there are no routes

   @Test
    public void testReplaceFrom() throws Exception {
        AdviceWith.adviceWith(context, Endpoints.SEDA_PROCESS_ENDPOINT, a -> {
            a.mockEndpoints("mock:"+Endpoints.SEDA_PROCESS_ENDPOINT);
        });
        }

A: Here is an example with route advice. Note that you probably will need to do some cleanup after your test to reset the data!
A bit older code in kotlin but should get the idea:
@SpringBootTest
class YourTest {
    @Autowired
    private lateinit var camelContext: CamelContext

    @Autowired
    private lateinit var template: ProducerTemplate

    // No MockEndpoints

    ...

    @Throws(Exception::class)
    private fun configureMockEndpoint() {
        AdviceWith.adviceWith(
            camelContext,
            "yourRouteId"
        ) { adviceWithRouteBuilder: AdviceWithRouteBuilder ->
            adviceWithRouteBuilder.replaceFromWith("direct:test")
        }
    }

    @Test
    fun yourTest() {
        configureMockEndpoint()
        template.sendBodyAndHeader("direct:test", "Your headers", """
            your content
        """.trimIndent())
        // asserts
        // cleanups
    }

}


text:
Q: Using an array as input into a function? X =
[[14.23  3.06  5.64  2.43]
 [13.2   2.76  4.38  2.14]
 [13.16  3.24  5.68  2.67]
 [14.37  3.49  7.8   2.5 ]
 [13.24  2.69  4.32  2.87]
 [14.2   3.39  6.75  2.45]
 [14.39  2.52  5.25  2.45]
 [14.06  2.51  5.05  2.61]
 [14.83  2.98  5.2   2.17]
 [13.86  3.15  7.22  2.27]
 [14.1   3.32  5.75  2.3 ]
 [14.12  2.43  5.    2.32]
 [13.75  2.76  5.6   2.41]
 [14.75  3.69  5.4   2.39]
 [14.38  3.64  7.5   2.38]
 [13.63  2.91  7.3   2.7 ]
 [14.3   3.14  6.2   2.72]
 [13.83  3.4   6.6   2.62]
 [14.19  3.93  8.7   2.48]
 [13.64  3.03  5.1   2.56]]

Here is my dataset. Now I want to calculate the Euclidean distance for 2 of vectors (rows).
Row1 = X[1]
Row2 = X[2]

My function:
def Edistance (v1, v2):
      distance = 0.0
      for i in range(len(v1)-1):
        distance += (v1(i)) - (v2(i))**2
      return sqrt(distance)

Edistance(Row1,Row2)

I then get Typerror: NumPy array is not callable. Can I not use an array in my functions input?

A: You can pass any object as a function argument and so you can pass arrays, but as @xdurch0 mentioned earlier, your syntax is wrong.
def Edistance (v1: dict, v2: dict): # You
      distance = 0.0
      for i in range(len(v1)-1):
        distance += (v1(i)) - (v2(i))**2
      return sqrt(distance)

What you try to do here is to call v1 and v2 as if they were a functions, since () used to execute the commands. But what you want to do, as far as i understand, is to use [] to reference at the element inside the array.
So, basically, you want to do v1[i] and v2[i] (instead of v1(i) and v2(i) respectively).


text:
Q: How to remove first n numeric characters from a string using PHP? I have a string $str = "4sX3yY4mj2DT9gVOOS0x60onT08lwzLLZBqn8".
Now I want to remove the first 5 numeric characters from the string.
How do I do that in php?

A: Use the limit parameter with preg_replace:
$str = preg_replace('~\d~', '', $str, 5);


text:
Q: Create Column from another tables records / Form using labels from one and create records in another table. Dataverse/ canvas app New to power apps, canvas apps & Dataverse
Got a table of categories /groups of items as part of a loans system with the number of quantity in stock. items are cat 5 cables, mice, mouse pads etc
I then have a table that will create a rentals record.
I'd like the records added to the rentals table via a canvas form. I see 2 options.

*

*1 record for each rental of multiple items/from the category table. A record/ row in the rentals I don't want to have to create a new column every time I add a new group/category of items to the category table. Can I automatically create a column in the Rentals table every time a new record is created int the category table?

*2nd option is the form to create a new row for each item rented, each rental in an order having a common Order number to link the individual rentals to 1 order. How would I do this. Id think I would create a form from the above mention category table to give the option of each item available. with I can then add Qty field this would then create an individual record in the rental with the Category? item and quantity, but this would need to run and create multiple records for each item rented?
Hope this makes sense.
Thanks


text:
Q: strtotime outputs nothing I tried the following
echo "Pre order date > $pre_order_close_date";
$pre_order_unix_time = strtotime($pre_order_close_date);
echo "Unix time is > $pre_order_unix_time";

The result is
Pre order date >  31 Jan 2016Unix time is >

I then tried the following to see if my date format is fine
echo "Pre order date > $pre_order_close_date";
$pre_order_unix_time = strtotime("31 Jan 2016");
echo "Unix time is > $pre_order_unix_time";

The result return was
Pre order date >  31 Jan 2016Unix time is > 1454198400

It seems that if I input the string directly its working fine, but if I use a variable in place of 31 Jan 2016, it does not output anything.
What could I have do wrong here.
Thanks for helping!
** How I get my pre_order_close_date **
$get_content is of this value

Retail Price: USD 42

Pre–Order Price: USD 40

Pre–Order Close Date: 31 Jan 2016

Release Date: 1Q 2016

$get_content_explode = explode("\n",$get_content);

foreach($get_content_explode as $gce)
{
if(strstr(strtolower($gce),"close"))
{
$pre_order_close_arr = explode(":",$gce);
$pre_order_close_date = trim($pre_order_close_arr[1]);
}//end if gce
}//end foreach

A: $get_content contains HTML markup. Use strip_tags() to remove it.
$get_content_explode = explode("\n", str_replace(' ', ' ', (strip_tags($get_content))));

DEMO


text:
Q: Use a variable to fill a field with Cucumber It is possible to use a variable to set a value using Selenium - Cucumber?
In my Class.Java :
I tried to create a private variable
( private String username = "x"; )
with Setter
( public void setUsername(String username).. )
But the value doesn't change when i use setUsername from another class.
MyClass myVariable = new MyClass ();
myVariable .setUsername("myUsername");
myVariable .setPassword("myPassword");

myVariable becomes "myUsername" but When " @Before " starts, the value is "x" even if I changed it.
The value of the variable must be dynamic and non-static for the purposes of the project.
Can i use Config.properties to do this ? There is a way to solve this problem?
Thank you so much.

A: "myUsername" is the literal string. If you want to pass the variable, it should be myVariable.setUsername(username); I guess from the code you provided.
Also, I if the space between myVariable and .setUsername is in your code it won't work.


text:
Q: Stable/ unstable w.r.t. perturbations in $L^2(\mathbb{R})$ Suppose we have some travelling wave solution $w(z)$ of a pde. What is then meant by "perturbations in $L^2(\mathbb{R})$?
Does this mean that $w(z)+v(z)$ with $v\in L^2(\mathbb{R}$ behaves like $w(z)$?

A: It means that you look at the behaviour of $w(x + c t) + v(x,t)$ when substituted in the PDE. Since $v(x,t)$ is considered to be 'small', you can then expand the nonlinear terms of the PDE in powers of $v$, and neglect terms of order $v^2$ or higher. In other words, you'll obtain a linear PDE for $v(x,t)$. Now, from standard PDE theory (or Fourier theory, whatever you prefer), it follows that you can write $v(x,t)$ as the product of a function of $t$ and a function of $x$, that is, $v(x,t) = f(t) g(x)$. The description 'perturbations in $L^2(\mathbb{R})$' now means that we take $g \in L^2(\mathbb{R})$, i.e. we assume that the `spatial part' of the perturbation $v$ is square integrable on $\mathbb{R}$.


text:
Q: WordPress if page is X don't check for logged in user id I had a developer write a plugin for registered users to upload videos to their private profile page that would appear in the public video gallery. The developer has gone MIA so I can't get him to modify the code. He gave me a [shortcode] that I placed in the private profile page that gives the users the ability to upload, delete videos, etc.
Now that I need those user videos to display also on their public profile page, they won't because of some code in his plugin that checks if the user is logged in. If any user is logged in, they can see their videos on their public page, but no one else can that's not logged in. Users not logged in see a message saying they must be logged in to have the video functionality. I think I've identified the code below in the plugin that's causing this:
public function videoAdd() {

global $wpdb;

$current_user = wp_get_current_user();

if ($current_user->ID == 0) {

$view = new View(dirname(__FILE__) . '/views/not-logged-in.phtml');

return $view->render(true);

}

My question is (because I can't write php code), can else if statements take care of this by specifying a page name? For instance, if page X, require user to be logged in to upload, but if page Y, only display the user's videos. Here's some example code I found that looks like it can be modified to work, but I'm not savvy enough to do it:
<?php   if ( is_page(123) ) {
?>

my content

<?php } elseif( is_page(124) ) {

?>

abc content

<?php }
else {
echo  '
any content
';
}

?>

Can anyone please help me with a code example to make this work?

A: Yes, you should be able to do this. is_page() accepts both the page ID as well as the page name.
So you could do something like this:
is_page(123)

Where 123 is the ID in the page's URL. For example, in the Admin area: https://your-site.com/wp-admin/post.php?post=123&action=edit, you'd use the string of numbers after post=.
You can also identify a page by URL name. For example, the page https://your-site.com/about-us/ could be identified like this:
is_page('about-us')

Hope that helps!


text:
Q: Как из массива строк сделать массив чисел Есть вложенный массив строк нужно с него сделать массив цифр. Как это возможно реализовать?
$mass2 = array (
Array (
  "9.40",
  "9.55"
),
Array (
  "10.37",
  "10.46"
),

Array (
  "13.45",
  "13.58"
),

Array (
  "14.10",
  "14.30"
)
)

A: $mass3 = array();
foreach($mass2 as $arr) {$mass3[] = array_map('floatval',$arr);}
var_dump($mass3);