text:
Q: Download/redirect and play audio file from external system in Salesforce lightning component We are trying to access/play audio files stored on external system from Salesforce Lightning Component. Access to file requires a BASIC authentication with GET method and we don't want users to prompt for username/password when they click on the audio file link (Stored as URL field on Salesforce custom  object). We first tried redirecting the user to audio file but no luck. Second option we are trying is, aura component as below which takes Blob from apex controller but it's not working. Any help is greatly appreciated.
<aura:component>
<audio src="{!v.audioFile} type="audio/x-wav">
        autoplay="true">
</audio>
</aura:component>

js controller
    ({
    doInit : function(component, event, helper) {
        var recID = component.get("v.recordId");
        console.log("recordID "+recID);
        var action = component.get("c.makeCallout");

        action.setParams({
            "recID":recID
        })
       action.setCallback(this, function(response) {
            console.log('get state'+response.getState());
            if (response.getState() == 'SUCCESS') {
                debugger;
               var templateData = response.getReturnValue();
                var byteCharacters = atob(templateData);
                console.log(templateData);

                const buf = new Array(byteCharacters.length);

                for (var i = 0; i != byteCharacters.length; ++i)
                buf[i] = byteCharacters.charCodeAt(i);

                debugger;

                const view = new Uint8Array(buf);

                //cast to blob
                const blob = new Blob([view], {
                type: 'audio/x-wav'
                });
               var audio = new Audio(blob);
                audio.play();

                component.set("v.audiofile", blob);
                component.set("v.callOutComplete", true);
            }
        });
        $A.enqueueAction(action);
    },
})


text:
Q: Why my code to link NetBeans and MySQL is not working? I was trying to link MySQL with NetBeans for the first time. To do this, I wrote a suitable code and made a suitable design for JFrame form too. The JFrame file is not showing any error but it is not giving the desired output. It is not able to fetch the data from MySQL.
Please find the attached code and additional information.
Any kind of help will be really appreciated.
I made a JFrame form named 'Connect' having three jButtons and one jTable. The function of jButton1 is to retrieve data from 'DepTbl' table in MySQL and display it on jTable. Unfortunately, it is not giving the desired output.
It is giving the output as written under catch{ statement, which is

'Error in connectivity.' in JOptionPane.
  Please read the code attached.

Coding I did:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;

private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
DefaultTableModel model=(DefaultTableModel) jTable1.getModel();
try
{ Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection
         ("jdbc:mysql://localhost/PracticalExercises","root","tiger");
Statement stmt = con.createStatement();
String query = "SELECT * FROM DepTbl;";
ResultSet rs=stmt.executeQuery(query);
while(rs.next()){
    String DeptNo=rs.getString("DeptNo");
    String Dname=rs.getString("Dname");
    String Location=rs.getString("Location");
    model.addRow(new Object[] {DeptNo,Dname,Location});}
rs.close();
stmt.close();
con.close();}
catch (Exception e){
        JOptionPane.showMessageDialog(null,"Error in connectivity.");
        }
}

I expect it to retrieve the data from the table in MySQL and display it in jTable1.
But, the result is in JOptionPane as "Error in connectivity." which is taken from statement under catch{.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Avoid choosing previous dates before today, without including today from datapicker on JS and React I am intending to use a datapicker that does not allow the user to choose previous days before today, but I do want that today itself is available. I did this:
 <input
                        name = "availabilityFrom"
                        onChange = {(e) => handleDateIn (e.target.value, e.target.name)}
                        type = "date"
 />

I am working with React so this above is part of a component, that has a state. Then with the value taken, I stored it on a variable to use its valueOf (), and created today´s variable also. Please notice that this.state.filterBy.availabilityFrom holds the value of the target, the selected date on the datapicker.
let today = new Date().valueOf();
let availabilityFromToDate = new Date(this.state.filterBy.availabilityFrom.split("-").join(",")).valueOf();

Then I used a conditional statement to get the desired behavior of the alert:
 if (availabilityFromToDate <today && availabilityFromToDate)
        {
            sweetAlert ("Warning!",
            "The entry date must be after the current date";
            "warning");
}

It works well, I got so happy when it did. But if I choose today's date, I got the alert message anyway, even if I am not using <= for today.
Maybe I am not understanding the proper use of valueOf (). Been having nightmares about this, haha.
Thanks in advance!: D


text:
Q: how to convert minutes into hours, hours into days in my model
$this->db->select('message,TIMESTAMPDIFF(MINUTE,date_added,CURRENT_TIMESTAMP) AS minutes_passed');
    $this->db->from('activity_logs');
    $this->db->order_by('log_id','desc');
    $this->db->limit(20);
    $q = $this->db->get();
    return $q->result_array();

in controller
 $data['logs'] = $this->common_model->get_logs();

    foreach ($data['logs'] as $k) {
      echo 'total minutes'.$k['minutes_passed']."<br>";//output total minutes "21410"
      }

i have total number of minutes and i want to get total hours related to minutes and then hours to convert into total days.
i hope anyone can guide me through this.
Thanks.

A: Try this function,
& Modify it with your requirements
    function con_min_days($mins)
    {

            $hours = str_pad(floor($mins /60),2,"0",STR_PAD_LEFT);
            $mins  = str_pad($mins %60,2,"0",STR_PAD_LEFT);

            if((int)$hours > 24){
            $days = str_pad(floor($hours /24),2,"0",STR_PAD_LEFT);
            $hours = str_pad($hours %24,2,"0",STR_PAD_LEFT);
            }
            if(isset($days)) { $days = $days." Day[s] ";}

            return $days.$hours." Hour[s] ".$mins." Min[s]";
    }

A: I think you should simply get the date from your database, and make the whole thing in php :
$now = new DateTime;
$date_added = new DateTime;
$date_added->setTimestamp(date_added);

$diff = $now->diff($date_added);

Then you can print :
sprintf("Temps écoulé : %d jours, %d minutes et %d seconds"; $diff->d, $diff->h, $diff->s);

PS : you should not store a timestamp in your database, but a date using DATE or DATETIME field type.

A: select field from database like UNIX_TIMESTAMP(date_added) as create_date
add this function
private function time_elapsed_string($ptime)
{
    $etime = time() - $ptime;
    if ($etime < 1){
        return '0 seconds';
    }
    $a = array( 365 * 24 * 60 * 60  =>  'year',
                 30 * 24 * 60 * 60  =>  'month',
                      24 * 60 * 60  =>  'day',
                           60 * 60  =>  'hour',
                                60  =>  'minute',
                                 1  =>  'second'
                );
    $a_plural = array( 'year'   => 'years',
                       'month'  => 'months',
                       'day'    => 'days',
                       'hour'   => 'hours',
                       'minute' => 'minutes',
                       'second' => 'seconds'
                );
    foreach ($a as $secs => $str){
        $d = $etime / $secs;
        if ($d >= 1){
            $r = round($d);
            return $r . ' ' . ($r > 1 ? $a_plural[$str] : $str) . ' ago';
        }
    }
}

and use it like this :
echo $this->time_elapsed_string($item->create_date)

O/P :
2 hour ago
5 days ago

depends on time in millisecond you passed in function


text:
Q: Выдает ошибку Destination array was not long enough при изменении размера массива Выдает ошибку Destination array was not long enough при изменении размера массива.
void ResizeArray<T>(ref T[,] original, int newCoNum, int newRoNum)
{
    var newArray = new T[newCoNum, newRoNum];
    int columnCount = original.GetLength(1);
    int columnCount2 = newRoNum;
    int columns = original.GetUpperBound(0);
    for (int co = 0; co <= columns; co++)
        Array.Copy(original, co * columnCount, newArray, co * columnCount2, columnCount);
    original = newArray;
}

У меня есть таблица, в которой изменяется количество столбцов и строк. Но если таблицу уменьшить, то тогда программа выдает ошибку.

A: Если у вас одномерный массив, можно воспользоваться Array.Resize. Если двумерный, попробуйте повторить логику из ответов по ссылке https://stackoverflow.com/questions/6539571/how-to-resize-multidimensional-2d-array-in-c
T[,] ResizeArray<T>(T[,] original, int rows, int cols)
{
    var newArray = new T[rows,cols];
    int minRows = Math.Min(rows, original.GetLength(0));
    int minCols = Math.Min(cols, original.GetLength(1));
    for(int i = 0; i < minRows; i++)
        for(int j = 0; j < minCols; j++)
           newArray[i, j] = original[i, j];
    return newArray;
}

Пример использования:
var array = new int[5, 7];
array[1, 2] = 50;
var newArray = ResizeArray(array, 7, 8);

Касаемо Array.Resize:
var array = new int[10];
var newArray = array1;
Array.Resize(ref newArray, 20);


text:
Q: yosemite mail remove self from cc list When I select "Reply All" using Apple Mail my email address automatically gets added back in the original field it appeared in the original message; i.e. if I was CC'd on an email, my address will appear in the CC field when selecting "Reply All".
I've already unchecked the setting in preferences to "Automatically CC myself".  How can I prevent receiving a duplicate email in my inbox for every email I send using the "Reply All" option?

A: The default behavior for Mail is that it doesn't cc you when replying unless you've flipped the toggle to cc you on every reply.
But you can get weird mismatches that cause Mail to not identify your own address. This just happened to me with my work Exchange account. I moved to Mail from Outlook and Mail cc'd me on every response.
The resolution for my specific case was that my contact card had my name entered as firstname lastname, while my Exchange account in Mail showed the name as lastname, firstname. When I changed the display name in the Mail account to match how it displayed in my contact card, Mail stopped ccing me.

A: I had the same issue and I managed to solve it by simply editing the Aliases for my account. What I did:
in the Mail > Preferences > Accounts > select account, than in the Alias dropdown select Edit Aliases and than I've added a new alias, practically my email address:
Full name: myemailaddress@whatever.com Alias: myemailaddress@whatever.com
This solved the issue for me. Hope it help.

A: Especially with Microsoft Exchange accounts that have a different alias used for login than is actually seen in a recipients 'from' field, one needs to go to Mail -> Preferences -> Accounts, select such exchange account -> Email addresses, and then add both the 'alias@domain.com' and the other human readable email address that usually contains the owners name.surname@domain.com.
This solved the issue for me.

A: This happens to me only if the address I am replying from is not exactly the same as the address the message came to. For example:
Customer X sends an email to president@company.co and CC's samh@company.co, but that is actually an alias to sh@company.co. When I reply-all, Mail will send a message from: sh@company.co to: Customer X and CC:president@ and samh@company.co.
This makes some sense: How can Mail know that samh@company.co and sh@company.co are the same thing?

A: I don't think there's a "reply all except for myself" function that's been programmed into Apple Mail. I haven't seen any hidden settings mentioning that, but you could ask Apple Support if you felt there would be such a flag. They would be the only ones with access to the Engineers that would have written that code.
Barring that, you can manually remove yourself or deal with the extra copy. Perhaps opening a second thread asking for software recommendations of mail clients that have implemented the algorithm you propose is worth getting opinions of no one suggests an alternative here.

A: For me this started happening when I switched from gmail to me.com. I put a forward on my gmail account so that my mail is redirected to my @me.com account. In spite of the setting not to do that, Mail will cc:myself whenever replying to messages forwarded by gmail (and thus addressed to my @gmail address), not when replying to messages addressed directly to my @me account.
I offer no solution, but I believe this can be a cause of the problem.

A: For me the problem appeared to be in the Account name (under preferences > Account name). In the default exchange settings, my account name is simply FIRST LAST.
However, in the company directory, the format is FIRST LAST | COMPANY.
By adding the "| COMPANY" bit to the account name, both outlook and Mac Mail then recognised my email address and stopped CCing me into reply alls.

A: This was happening to me on El Capitan, even though I already had my address listed on my contact.
I noticed that Mail automatically adds e-mail addresses that you have sent mail to (maybe via "previous recipients"?) to Contacts. They do not have any information other than the e-mail address.
I had a extra contact card containing only my new e-mail address. It is possible that I first hit reply-all before adding my new e-mail address to my real, original contact card, so I deleted the automatically-added contact card. After restarting Mail the problem was fixed.


text:
Q: Use varwidth to make a paragraph center in a table The following code does what I want, except the V acts like the p option, but I want the m option.
\documentclass[12pt]{memoir}
\usepackage{varwidth}
\begin{document}
\begin{tabular}{lV{2in}}\hline
Cat & Animal\newline Cute\newline Very furry\newline Spotted\\
\end{tabular}
\end{document}

If I use m I have to manually figure out the length of the longest item in the second column, but the word "Cat" is vertically centered like I want it.
\documentclass[12pt]{memoir}
\usepackage{varwidth}
\begin{document}
\begin{tabular}{lm{2in}}\hline
Cat & Animal\newline Cute\newline Very furry\newline Spotted\\
\end{tabular}
\end{document}

Here's what they look like:

I only found the V option via an Internet search; the varwidth manual is surprising sparse.
How do I get a table option that combines array's m and varwidth's V? (I'm actually using memoir's implementation of array if that matters.

A: I didn't know that varwidth defines the V column type. Now I know! ;-).
Its definition is
\newcolumntype{V}[1]{%
  >{\begin{varwidth}[t]{#1}\narrowragged\let\\\tabularnewline}%
  l%
  <{\@finalstrut\@arstrutbox\end{varwidth}}}

so you should get what you want by
\documentclass[12pt]{memoir}
\usepackage{varwidth}

\makeatletter
\newcolumntype{M}[1]{%
  >{\begin{varwidth}{#1}\narrowragged\let\\\tabularnewline\strut}%
  l%
  <{\@finalstrut\@arstrutbox\end{varwidth}}}
\makeatother

\begin{document}
\begin{tabular}{lM{2in}}\hline
Cat & Animal\newline Cute\newline Very furry\newline Spotted\\
\end{tabular}
\end{document}

Notice that memoir loads array (actually it has code to that effect); with other classes it will be necessary to add
\usepackage{array}

A: The environment {NiceTabular} of nicematrix (≥ 6.3 of 2021-10-18) supports the V columns of varwidth with an optional argument, between square brackets m, p or b for the vertical position. So, you have directly the expected output.
\documentclass[12pt]{memoir}
\usepackage{varwidth}
\usepackage{nicematrix}

\begin{document}

\begin{NiceTabular}{lV[m]{2in}}\hline
Cat & Animal\newline Cute\newline Very furry\newline Spotted\\
\end{NiceTabular}

\end{document}

Remark: The letter V supports also the keys r, l and c for the horizontal alignment.

A: I'm not sure I fully understand your question, but does this answer give you the desired output?  If so, I guess the question is then whether the syntax works for you.
\documentclass[12pt]{memoir}
\usepackage{stackengine}
\setstackEOL{\newline}
\setstackgap{L}{13pt}
\begin{document}
\begin{tabular}{ll}\hline
Cat & \Centerstack[l]{Animal\newline Cute\newline Very furry\newline Spotted}\\
\end{tabular}
\end{document}


text:
Q: Is it possible to send raw json with IRestClient I love the simplicity of using servicestack's IRestClient to test my api, but I need to replicate a test scenario when someone sends an incomplete object. For instance if my dto looks like this:
public class Todo
    {
        public long? Id { get; set; }
        public string Content { get; set; }
        public int? Order { get; set; }
        public bool? Done { get; set; }
    }

And I want to do a PUT with partial json like this:
{"Id": 99999, "Order":1}

How do I send just the above with the json client. If I use the typed version the client sends the entire object with defaults.

A: I think it might be easier to use ServiceStack's Http Utils (link is to POST but applies to PUT) to PUT the data.
"http://localhost/todo"
    .PutJsonToUrl(@"{""Id"":9999,""Order"":1}");

Also, I'm not sure exactly what you are trying to test. But, if you're testing your Service the request (your json string) will be deserialized (pretty sure using ServiceStack.Text) into the Todo class so it will get the object with defaults for missing fields. See the test below.
    [Test]
    public void TestJson()
    {
        var json = @"{""Id"": 99999, ""Order"":1}";

        var todo = new ServiceStack.Text.JsonSerializer<Todo>().DeserializeFromString(json);

        Assert.IsNull(todo.Done);
        Assert.IsNull(todo.Content);
    }


text:
Q: Heap corruption at program termination I can't figure out what is causing this memory leak (I assume that's what's going on.)
I've got several classes, so I'll post the constructors and destructors of each. The error message says the corruption is caused by the memory allocated at stock.cpp(20) which is the line
symbol(new char[]),

The constructors and destructors are as follows
hashmap.cpp
HashMap::HashMap(int capacity) :
  slots(new Slot[capacity]),
  capacity(capacity),
  nStocks(0),
  isEmpty(true)

HashMap::~HashMap(void)
{
    delete[] slots;
}

stock.cpp
Stock::Stock(char const * const symbol, char const * const name, int sharePrice, Date priceDate):
  symbol(new char[strlen(symbol)+1]),
  name(new char[strlen(name) + 1]),
  sharePrice(sharePrice),
  priceDate(priceDate),
  isEmpty(false)
{
  strcpy(this->symbol, symbol);
  strcpy(this->name, name);
}

Stock::Stock(void) :
  symbol(new char[]),  //this is where the memory allocation that causes the error occurs
  name(new char[]),
  isEmpty(true)

Stock::~Stock(void)
{
  delete[] symbol;
  delete[] name;
}

As you can see, the array that is allocated at stock.cpp(20) is destroyed when the destructor is called. So what's going on?
EDIT: Here is the complete error message
Debug Error!
Program: asnmt03/Debug/asnmt03.ext
HEAP CORRUPTION DETECTED: after Normal block (#168) at 0x004E51F8
CRT detected that the application wrote to memory after end of heap buffer
Memory allocated at stock.cpp(20)


text:
Q: Can this alternative addition operation on ordinals be incremental? Suppose we have two decreasing sequences $A_i=\langle a_1,..,a_i\rangle $, $B_j= \langle b_1,..,b_j\rangle $, now the decreasing union sequence of those would be the decreasing sequence $C_{i+j}=\langle c_1,..,c_{i+j}\rangle $ such that $\forall k[c_k \in rng (C_{i+j}) \leftrightarrow c_k \in rng(A_i) \lor c_k \in rng(B_j)]$, let's denote that as $C_{i+j}=  A_i \cup_\downarrow B_j$. Now lets define  $$ \Sigma \ [A_i] = a_1 + a_2 +...+a_i$$
Now for every ordinal $\alpha$ let $C(\alpha)$ be the decreasing sequence of ordinals in the Cantor normal form of $\alpha$.
Define: $\alpha +^\uparrow \beta = \Sigma \ [C(\alpha) \cup_\downarrow C(\beta)] $
Now I'm not sure if this is the same as Hessenberg natural sum of ordinals, that's why I gave it a different denotation here.
Now the question is: Does the following always follow in ZF?
$\gamma> \delta \to \gamma +^\uparrow \alpha > \delta +^\uparrow \alpha$


text:
Q: Uninstalled my app. And when reinstalled app values don't change My application is a tycoon game in which the user taps a button in order to increase his score and so he buys upgrades to increase the amount of score he has quickly.
Well, just out of curiosity I uninstalled my app and the reinstalled it through Android Studio, when I ran it the app didn't work. I tried tapping the button to increase the score, but still it didn't increase. To save the users score I use SharedPreferences after they close the app. Maybe that has something to do with it?
Android Manifest:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.navjeevenmann.mytycoon">

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:roundIcon="@mipmap/ic_launcher_round"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <activity android:name=".SecondActivity" />
    <activity android:name=".ThirdActivity"></activity>
</application>

Main Activity:
package com.example.navjeevenmann.mytycoon;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ImageButton;
import android.widget.TextView;

import static com.example.navjeevenmann.mytycoon.R.id.textView;

public class MainActivity extends AppCompatActivity {
private ImageButton myButton;
private int Counter;
private ImageButton autoclick;
private TextView myTextView;
Handler handler = new Handler();
private int add;
private TextView myAddView;
private ImageButton singleclick;
private int Singleadd = 1;
private ImageButton money;
private boolean[] array;

@Override
protected void onCreate(Bundle savedInstanceState) {
    setContentView(R.layout.activity_main);
    getSupportActionBar().hide();

    super.onCreate(savedInstanceState);
    Bundle bundle = getIntent().getExtras();
    if (bundle != null) {
        if (bundle.containsKey("Count")) {
            Counter = bundle.getInt("Count");
        }
        if (bundle.containsKey("Add")) {
            add = bundle.getInt("Add");
        }
        if (bundle.containsKey("Single")) {
            Singleadd = bundle.getInt("Single");
        }
        if (bundle.containsKey("array")) {
            array = bundle.getBooleanArray("array");
        }
    }
    add = getaddvalue();
    Counter = getvalue();
    Singleadd = getSinglevalue();

    money = (ImageButton) findViewById(R.id.imageButton2);
    myButton = (ImageButton) findViewById(R.id.button);
    autoclick = (ImageButton) findViewById(R.id.autoclick);
    singleclick = (ImageButton) findViewById(R.id.singleclick);
    myTextView = (TextView) findViewById(textView);
    myAddView = (TextView) findViewById(R.id.textView2);
    myButton.setBackgroundColor(0);
    myButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Counter = ButtonCounter(Counter);
        }
    });
    autoclick.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(getApplicationContext(), SecondActivity.class);
            intent.putExtra("Count", Counter);
            intent.putExtra("Add", add);
            intent.putExtra("Single", Singleadd);
            intent.putExtra("array", array);

            startActivity(intent);
        }

    });

    singleclick.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            Intent intent = new Intent(getApplicationContext(), ThirdActivity.class);
            intent.putExtra("Count", Counter);
            intent.putExtra("Single", Singleadd);
            intent.putExtra("Add", add);
            intent.putExtra("array", array);
            startActivity(intent);
        }
    });

}

public void onStop() {
    super.onStop();
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    SharedPreferences.Editor editor = prefs.edit();
    editor.putInt("usermoney", Counter);
    editor.putInt("Auto", add);
    editor.putInt("Single", Singleadd);
    editor.commit();
}

public int getvalue() {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    return prefs.getInt("usermoney",0);
}

public int getaddvalue() {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    return prefs.getInt("Auto", 0);
}

public int getSinglevalue() {
    SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(this);
    return prefs.getInt("Single", 0);
}

public void onResume() {
    super.onResume();

    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            Counter = AutoCounter(Counter, add);
            handler.postDelayed(this, 1000);
        }
    }, 1000);

    handler.postDelayed(new Runnable() {
        @Override
        public void run() {
            Display(Counter, add);
            handler.postDelayed(this, 1);
        }
    }, 50);
}

public int ButtonCounter(int Counter) {
    Counter += Singleadd;
    return Counter;
}

public int AutoCounter(int Counter, int add) {
    Counter = Counter + add;
    return Counter;
}

public void Display(int Counter, int add) {
    String money = String.valueOf(Counter);
    myTextView.setText(":" + money);
    myAddView.setText("$" + add + "/Per Second");

}

}

Thank you


text:
Q: Critical Reminder: Download and install Magento..... how to insure these patches installed successfully? i got this message from Magento
"Critical Reminder: Download and install Magento security patches. Download now."
and after i installed the required patches successfully i still got that message, so my question is how i insure these patches installed successfully? and if should i remove that alert manually?

A: That message is coming from Magento's RSS feed - it's not based on whether or not you have installed the patch, so if you installed the patch you can remove the alert manually.
There is a scanner at https://shoplift.byte.nl/ which checks whether you've installed the SUPEE-5344 patch correctly.

A: One of the main files patched is app/core/Mage/Core/Controller/Request/Http.php
For example in Magento 1.6.2.0, doing a diff between the patched file and the original shows the following added code.
Compare: (<)V:\Magento\Magento 1.6\Changes\20150217 Patches\5346\Http.php (15698 bytes)
   with: (>)V:\Magento\Magento 1.6\Changes\20150217 Patches\5346\Http.php.old (15031 bytes)

79,85d79
<      * Flag for recognizing if request internally forwarded
<      *
<      * @var bool
<      */
<     protected $_internallyForwarded = false;
<
<     /**
540,562d533
<
<     /**
<      * Define that request was forwarded internally
<      *
<      * @param boolean $flag
<      * @return Mage_Core_Controller_Request_Http
<      */
<     public function setInternallyForwarded($flag = true)
<     {
<         $this->_internallyForwarded = (bool)$flag;
<         return $this;
<     }
<
<     /**
<      * Checks if request was forwarded internally
<      *
<      * @return bool
<      */
<     public function getInternallyForwarded()
<     {
<         return $this->_internallyForwarded;
<     }
<

The following command line entry can quickly tell if this file has been patched by looking for the added _internallyForwarded flag. Run it in your Magento root folder:
grep "_internallyForwarded" app/code/core/Mage/Core/Controller/Request/Http.php

The following shows the file has been patched.
public_html$ grep "_internallyForwarded" app/code/core/Mage/Core/Controller/Request/Http.php
     protected $_internallyForwarded = false;
        $this->_internallyForwarded = (bool)$flag;
        return $this->_internallyForwarded;

Other files that may have been patched:
app/code/core/Mage/Admin/Model/Observer.php
app/code/core/Mage/Core/Controller/Request/Http.php
lib/Varien/Db/Adapter/Pdo/Mysql.php

Also check app/etc/applied.patches.list to see what the latest patch applications are at the end of the list.
Watch in case Magento's totally excellent internal quality control identifies the patch as 5346 instead of 5344 as advertised on the download. They got it (something?) in the append message.

A: Reminder
Reminder is implemented in Mage_AdminNotification module.
There is no check if patches were installed or not.
To remove reminder:

*

*Login to backend

*Navigate to System → Notification

*Mark reminder as read or remove it

Patches
To apply patches:

*

*How to Apply and Revert Magento Patches

*Critical Reminder: Download and install Magento security patches
Which patches were applied?

*

*Check file /app/etc/applied.patches.list


text:
Q: What kind of front end/ gui is used with trading applications? I was wondering what kind of front end is used for trading applications. Coming from a quant background, I was always only concerned with research and back end of the application but am at a total loss when it comes to front end/ gui. Most of my coding has been done in c++ and I am using just a config file to pass parameters.
Now it turns out due to regulatory reasons, this might not suffice. I need to have a front end which can start/ stop the strategy, change parameters and fetch order and trade history. So question boils down to this, How can I create a simple ui which can sit on another machine, communicate with the colocated machine and do all this.
Initially I thought of using web/javascript but not much is out there regarding this. Qt is another option but I suspect it will require substantial rewrite of the code and learning.
What is the preferred front end for medium to high frequency trading applications which have the core strategy running in c++?

A: Coming from the industry, I can tell you with certainty: Anything goes. I have worked on trading application frontends using MFC, QT, Forms, WPF. Java is quite popular too, as are homegrown abominations.  One non-obvious way to communicate with the colocated machine is Citrix or Remote Desktop.
You do need to make sure that you have well defined behavior in case the client crashes, server crashes, connection between them freezes/gets lost, connection to the market gets lost, connection comes back, etc. Tell the trader how it will react in these situations, in advance. If it doesn't make sense, the trader won't use your application.
Further details depend on many variables. Are you an ISV, or is it an in-house application? Are you working in an arcade? Which markets are you connecting to? Does your hosted co-lo environment have some special rules in regards to what can run there?


text:
Q: Start SAS session with custom config (ole automation) I want to automate our information system with Python, because its interface (sas af) doesn't satisfy my needs. Local SAS8 system is used to connect to remote SAS to select data from DBs. As I understand this.
I used the SAS SCL language to add my extensions. But this language is a pain for me. Now I've found out that I can use Dispatch('SAS.Application') and Submit statements from Python. Ok. good.
But SAS system is called like
C:\SAS8\V8\sas.exe -autoexec autoexec.sas -config client.cfg

with C:\SAS8\VM-client as working directory. client.cfg sets main config
-config c:\sas8\v8\sasv8.cfg

and additional parameters. If I Dispatch('SAS.Application') it uses c:\sas8\v8\sasv8.cfg as config file and it doesn't find libraries in C:\SAS8\VM-client folder.
I want to start SAS session as usual, create session with remote sas as usual, and then submit sas statements from Python (make select call, download result to sas7bdat table, read it with sas7bdat python module).
It would be awesome to just set working directory and config file on dispatch, but it's impossible, isn't it?


text:
Q: flutter send PDF data to a printer I have succeeded in discovering and connecting to the printer using the wifip2p plugin.
I want to print a PDF file from a URL or Assets by sending it to the printer.
Please tell me how to print by sending PDF data to the printer after connecting the printer. Thanks for answering the question.
serch print
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'package:wifip2p/wifip2p.dart';

class SearchIconButton extends StatelessWidget {
  const SearchIconButton({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {

    Size size = MediaQuery.of(context).size;

    return Stack(
      children: <Widget>[
        Positioned(
          right: size.width * 0.02,
          bottom: size.height * 0.02,
          child: FloatingActionButton(
            onPressed: () async{
              try{
                await WifiP2P.discoverDevices();
              }on PlatformException{
                print('Error!');
              }
            },
            child: Icon(Icons.search),
          ),
        ),

      ],
    );
  }
}

write print name
import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'package:wifip2p/wifip2p.dart';

class WritePrintName extends StatelessWidget {
  const WritePrintName({Key? key}) : super(key: key);

  Future<void> conntectToDevice(int position) async{
    CircularProgressIndicator();
    try{
      await WifiP2P.connectToDevice(position);
    }on PlatformException{
      print('Error!');
    }
  }

  @override
  Widget build(BuildContext context) {

    Size size = MediaQuery.of(context).size;

    return Positioned(
      top: size.height * 0.1,
      child: StreamBuilder(
        stream: WifiP2P.peerListChangeEvent,
        builder: (BuildContext context, AsyncSnapshot<List<String>> snapshot){
          if(snapshot.hasData){
            List<Container> list = [];
            for(int nIndex=0; nIndex<snapshot.data!.length; nIndex++){
              list.add(Container(
                width: size.width,
                height: size.height * 0.05,
                alignment: Alignment.center,
                child: TextButton(
                  onPressed: (){
                    conntectToDevice(nIndex);
                  },
                  child: Text(snapshot.data![nIndex], textAlign: TextAlign.center,),
                ),
              ));
            }
            return Column(children: list,);
          }
          return Container(
            width: size.width,
            height: size.height * 0.05,
            alignment: Alignment.center,
            child:Text(
              '검색된 프린터가 없습니다.',
              style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
            ) ,
          );
        },
      ),
    );
  }
}

A: You can do that by installing this package:


text:
Q: How to get a warning in GCC for unsigned integer overflow instead of wrap-around? Test ENV

*

*Linux

*Intel x86-64 GCC 8.2.1

*Flags enabled: -Wextra -Wall -Wfloat-equal -Wundef -Wshadow -Winit-self -Wpointer-arith -Wcast-align -Wstrict-prototypes -Wstrict-overflow=5 -Wwrite-strings -Waggregate-return -Wcast-qual -Wswitch-default -Wswitch-enum -Wconversion -Wunreachable-code -Wformat=2 -pedantic -pedantic-errors -Werror-implicit-function-declaration -Wformat-security -fstrict-overflow

*sizeof(long) is 8.

*sizeof(int) is 4.

Example 1, got a warning, good:
long x = 2147483647 * 3;

Example 2, no warning, not good:
long x = 2147483647U * 3U; // Suffix U

or
unsigned int a = 2147483647;
unsigned int b = 3;
long x = a*b;

Example 3, no warning, but work as expected:
long x = 2147483647L * 3L; // Suffix L

In the example 2, I know that it is a wrap-around instead of integer overflow, but these are those cases that the compiler are unable to warn about?
From the Standard:
(6.3.1.8)

Otherwise, the integer promotions are performed on both operands. Then
  the following rules are applied to the promoted operands:
If both operands have the same type, then no further conversion is needed.
  Otherwise, if both operands have signed integer types or both have unsigned integer types, the operand with the type of lesser integer conversion rank is converted to the type of the operand with greater rank.
Otherwise, if the operand that has unsigned integer type has rank greater or equal to the rank of the type of the other operand, then the operand with signed integer type is converted to the type of the operand with unsigned integer type.
Otherwise, if the type of the operand with signed integer type can represent all of the values of the type of the operand with unsigned integer type, then the operand with unsigned integer type is converted to the type of the operand  with signed integer type.
Otherwise, both operands are converted to the unsigned integer type corresponding to the type of the operand with signed integer type.

(6.5):

If an exceptional condition occurs during the evaluation of an expression (that is, if the result is not mathematically defined or not in the range of representable values for its  (type), the behavior is undefined.

Started using Clang with flag -fsanitize=unsigned-integer-overflow that helps a lot with undesired values from wrap-around. That is not an integer overflow, but not the intended value. Since GCC, until now does not support a warning like this, moving on to Clang.

A: Overflow of signed integers invokes undefined behavior, while unsigned integer overflow is well defined.
For unsigned integers, overflow occurs as if the values were computed modulo one more than the maximum value of the given type.  Put another way, if the type is n bits wide, then only the low order n bits of the result are retained.  This is not actually overflow but is referred to as wraparound.
This is spelled out in section 6.5p9:

The   range   of   nonnegative   values   of   a   signed   integer
  type   is   a   subrange   of   the corresponding  unsigned  integer
  type,  and  the  representation  of  the  same  value  in  each type
  is  the  same.  A  computation  involving  unsigned  operands  can
  never  overflow, because  a  result  that  cannot  be  represented  by
  the  resulting  unsigned  integer  type  is reduced  modulo  the
  number  that  is  one  greater  than  the  largest  value  that  can
  be represented by the resulting type.

Because this behavior is well defined, it doesn't make sense for the compiler to trigger a warning.
In the case of your second example:
long x = 2147483647U * 3U;

The multiplication is done on unsigned types, so the mathematical result 6442450941 wraps around to 2147483645, which is within the range of a long.  There's no overflow (just wraparound) and no out-of-range conversion, so no warning.

A: Not GCC, but some static analyzer rules would warn about such "overflows".
For instance, both examples 1 & 2 would be flagged by MISRA C checker,
because these overflow in expression with constants - which is indicative of programmer mistake.
2012 Rule 12.4: "Evaluation of constant expressions should not lead to unsigned integer wrap-around."
A more generic case is described by INT30-C in SEI CERT C Coding Standard, which advices to avoid any kind of overflow for secure applications and provides a  list of automatic checkers that honor the rule.


text:
Q: Symfony Controller magic method? I am trying to use Symfony to replicate behavior in an existing Framework (zikula). This framework is extensible using modules which are basically extended symphony bundles. The old framework had urls like so
index.php?module=foo&type=bar&func=zip

which in symfony speak roughly translates to
index.php?bundle=foo&controller=bar&method=zip

The framework has an AbstractController which has a magic method like:
public function __call($method, $args)
{
    $event = new \Zikula\Core\Event\GenericEvent($this, array('method' => $method, 'args' => $args));
    $this->eventManager->dispatch('controller.method_not_found', $event);
    if ($event->isPropagationStopped()) {
        return $event->getData();
    }
}

so, if you created a url with a method that didn't exist in the bundle, you could create a listener to capture it and send a response that looks like and behaves like it came from the specified bundle. We use this to call module services that are available to all modules and provided in a separate module but look like they are served by the 'host' module.
Now I am trying to replicates this using symfony and routing.
the first problem is generating a route that doesn't technically exist. Is this possible?
The second problem is capturing the RouteNotFoundException (which I know how to do, we already have listeners for other exceptions).
The last problem is making it appear that the bundle is serving up the response when it is actually being served by an event listener (or something else). This last part is important because other content in the response needs to come from the module/bundle.
I have tried changing the current listener to a controller, and also tried adding a method to our extension of symfony's AbstractController, but haven't yet achieved what I am hoping to achieve. I'm hoping for some suggestions on new ideas or methods to try.

A: I gave up trying to replicate the exact behavior as it seems impossible (it is also pretty difficult to describe). So I have resorted to a normal controller with standard route, but I found a way to make it appear to belong to the original 'host' module. Thanks to Gerry, ggioffreda and DerStoffel for offering ideas.


text:
Q: How to produce multistave music using abc notation in a document? I have been trying to get the package '''abc''' to produce multistave music notation within a document. If possible I'd like to find a solution using this rather than, for instance, LilyPond. After consulting the documentation for the '''abc''' package, I get the impression it should be possible. It reads as follows:

A recent extension of this language,  called ABC Plus,  allows for
setting multiple stavesand polyphony. One of the best programs for
converting these notations into sheet music is '''abcm2ps''', which
can take an ABC or ABC Plus file and transform it intoa
PostScript-file. The purpose of this package is to allow LATEX users
to include in their doc-uments small excerpts of music written
directly in ABC (Plus).

This is what I've tried:
\documentclass{scrartcl}
\usepackage[utf8]{inputenc}
\usepackage[generate,ps2eps]{abc} % I've tried different things within the [], but I still suspect the problem lies here... This works for single-stave stuff.
\begin{ducument}

  Here follows three identical renderings of Brother John:

  \begin{abc}[name=brother1]
    X:1
    T: Brother John
    L: 1/4
    K: F
    M: 4/4
    V:1
    FGAF | FGAF | ABcz | ABcz | c/d/c/B/ AF | c/d/c/B/ AF |
    V:2
    z4   | z4   | FGAF | FGAF | ABcz        | ABcz        |
  \end{abc}

  \begin{abc}[name=brother2]
    X: 1
    T: Brother John
    L: 1/4
    V: 1 clef=treble name="Soprano" sname="S"
    V: 2 clef=treble name="Contralto" sname="C"
    K: F
    %
    [V:1] FGAF | FGAF | ABcz | ABcz | c/d/c/B/ AF | c/d/c/B/ AF |
    [V:2] z4   | z4   | FGAF | FGAF | ABcz        | ABcz        |
  \end{abc}

  \begin{abc}[name=brother3]
    X: 1
    T: Brother John
    L: 1/4
    K: F 0&2
    %
    z4   & FGAF |z4    & FGAF | FGAF & ABcz | FGAF & ABcz | ABcz & c/d/c/B/ AF | ABcz & c/d/c/B/ AF |
  \end{abc}

\end{ducument}

The first two formats follows the suggestions in the documentation of ABC Plus.
The third format follows ABC2MTEX, which I attempted just in case it would work.
I tried to compile this using
latex --shell-escape testfile
dvips -o testfile.ps testfile.dvi
ps2pdf testfile.ps

This works for single-stave music.
Can one of my three examples be improved in some way, or is there some completely different way of producing multistave sheet music?

A: I'm not sure when abcm2ps started to append useless numbers to the generated PostScript files, without even any option to turn this feature off. :-(
Also, if a title is specified in the .abc file, the -O= option will use it. :-(
Here's a temporary fix.
\documentclass{scrartcl}
\usepackage[generate,ps2eps]{abc}
\usepackage{xpatch}

\makeatletter
\renewcommand{\abc@parm}{-O\abc@tempfile.ps\space -c}
\define@key{abc}{name}[]{%
  \if!#1!\stepcounter{abc@count}%
    \edef\abc@tempfile{\normalabcoutputfile-\@arabic\c@abc@count}%
  \else
    \def\abc@tempfile{#1001}%
  \fi
}
\makeatother

\begin{document}

\begin{abc}[name=brother1]
X: 1
T: Brother John
C: Traditional
L: 1/4
K: F
M: 4/4
V:1
FGAF | FGAF | ABcz | ABcz | c/d/c/B/ AF | c/d/c/B/ AF |
V:2
z4 | z4 | FGAF | FGAF | ABcz | ABcz |
V:1
GCFz |GCFz | z4 | z4 |
V:2
c/d/c/B/ AF | c/d/c/B/ AF | GCFz | GCFz|
\end{abc}

\end{document}


text:
Q: Why are user-specific startup items starting for all users? On my Win7 machine I have a number of programs in my user's startup folder (%AppData%\Microsoft\Windows\Start Menu\Programs\Startup). A few of them like ZumoCast and OpenDNSUpdater pop up at logon asking for login info. I've entered that info when logging into my user account so they no longer popup for me. However, every time my kids or wife login to their accounts they get the popups asking for login info and they have to close all of them out. I don't want these programs to run in their accounts!
Checking Process Explorer shows that these processes are indeed running under their individual user accounts, but I have no idea how that's happening.
I tried deleting the shortcuts and creating a task that runs when my user logs in to start all these programs, but the task just hangs and none of them are started.
Does anyone have any idea what's happening here?

A: It is probably starting from the registry.
Try running msconfig and looking at the startup tab.  You'll see all the items that start up and where from.  Uncheck those you don't want.

A: Windows has two Start Menu locations, one for all users and one that's user-specific:

*

*System-wide: %ProgramData%\Microsoft\Windows\Start Menu

*Per-user: %AppData%\Microsoft\Windows\Start Menu
Unless configured otherwise, almost all software will install a startup entry in the system-wide Startup directory, and it's for this reason that even though you've disabled those startup entries for your user account, other users are unaffected.

Create the Disable Startup directory, adding them within it to disable them:

*

*System-wide: %ProgramData%\Microsoft\Windows\Start Menu\Programs\Disable Startup

*Per-user: %AppData%\Microsoft\Windows\Start Menu\Programs\Disable Startup


text:
Q: Why is 'https://www' intermittently hidden in Chrome 69? Whilst browsing the net I have noticed that the URL prefix is mostly always displayed:
https://www

However I have noticed one just one occasion where this has not appeared, i.e. the omnibox has shown:
example.com

This has occurred even on the same domain and without changing any settings in Chrome
There are several articles I have read regarding Chrome's phasing out of the https://www prefix, however, could there be a reason for this intermittently occurring? If it makes a difference, the only time I have noticed this is whilst browsing 'Incognito'
Additionally, the following article on ZDNet titled "Chrome 69 kills off www in URLs: Here's why Google's move has made people angry" explains we should expect not to see the https://www prefix anyway, so why am I still seeing it?

A: This is likely a combination of things at work:

*

*Chrome's default behavior of hiding http:// for non-HTTPS websites.

*Chrome's habit of connecting you to the HTTPS version of a website when using auto-complete in Chrome's Omnibox.

*A website offering both "www" and "non-www" URLs (no redirects)

My guess in how things played out:

*

*You reached the HTTPS, www version of a website (e.g., https://www.example.com/), maybe through Google search.

*In follow-up attempts, you might let Chrome auto-complete the URL, leading you to the HTTPS version.

*In incognito mode, you may have typed out the domain name sans www, leading you to just example.com
Compare the following URLs (typed and auto-completed) for the main website of the well-known brand Toys R Us:
https://www.toysrus.com
http://www.toysrus.com
https://toysrus.com
http://toysrus.com
I believe Google's decision to remove www was temporarily reversed for Chrome 69  as noted by Bleeping Computer. Apparently this change will return with Chrome 70.


text:
Q: CGContextDrawImage inconsistent byte values across devices? I'm trying to compare two images (actually locate a smaller "sub-image" in bigger image) and  I'm loading the images using the method provided below.
The code below now contains a testing for-loop which sums up all the individual byte values. What I discovered is that this sum and therefor bytes, differ, depending on which device it is being run. My question is why is that happening ?
// Black and white configuration:
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceGray();
NSUInteger bytesPerPixel = 1;
NSUInteger bitsPerComponent = 8;
CGBitmapInfo bitmapInfo = kCGBitmapByteOrderDefault;

// Image
CGImageRef imageRef = [[UIImage imageNamed:@"image.jpg"] CGImage];
NSUInteger imageWidth = CGImageGetWidth(imageRef);
NSUInteger imageHeight = CGImageGetHeight(imageRef);
NSUInteger imageSize = imageHeight * imageWidth * bytesPerPixel;
NSUInteger imageBytesPerRow = bytesPerPixel * imageWidth;

unsigned char *imageRawData = calloc(imageSize, sizeof(unsigned char));
CGContextRef imageContext = CGBitmapContextCreate(imageRawData, imageWidth, imageHeight, bitsPerComponent,
                                                  imageBytesPerRow, colorSpace, bitmapInfo);

// Draw the actual image to the bitmap context
CGContextDrawImage(imageContext, CGRectMake(0, 0, imageWidth, imageHeight), imageRef);
CGContextRelease(imageContext);

NSUInteger sum = 0;
for (int byteIndex = 0; byteIndex < imageSize; byteIndex++)
{
    sum += imageRawData[byteIndex];
}

NSLog(@"Sum: %i", sum); // Output on simulator:    Sum: 18492272
                        // Output on iPhone 3GS:   Sum: 18494036
                        // Output on another 3GS:  Sum: 18494015
                        // Output on iPhone 4:     Sum: 18494015

free(imageRawData);
CGColorSpaceRelease(colorSpace);

A: Are the devices all running the same version of the OS? Another possibility (beyond colorspaces, which someone already mentioned) is that the JPG decoding libraries may be subtly different. As JPEG is a lossy image format, it's not inconceivable that different decoders would produce resulting bitmaps that were not bit-equal.  It's seems reasonable to posit that, given the heavy use of images in iOS UI, that the JPG decoder is something that would be undergoing constant tuning for maximum performance.
I'd even believe it conceivable that between the same OS version running on different models of device (i.e. different processors), the results could be not bit-equal if there were multiple versions of the JPG decoder, each heavily optimized for a specific CPU, although that would not explain the difference between 2 devices of the same model, with the same OS.
You might try to re-run the experiment with an image in a lossless format.
It also may be worth pointing out that providing your own backing memory for a CGBitmapContext, but not making special allowances for word alignment is likely to lead to poor performance. For instance, you have:
NSUInteger imageBytesPerRow = bytesPerPixel * imageWidth;

If imageBytesPerRow is not a multiple of the CPU's native word length, you're going to get sub-optimal performance.

A: I assume the "device grey" color space varies by device. Try with a device independent color space.


text:
Q: Mongodb find inside sub array I have a document that's setup like this:
{
  _id : ObjectId(),
  info : [
        [
            1399583281000,
            20.13
        ],
        [
            1399583282000,
            20.13
        ],
        [
            1399583283000,
            20.13
        ],
        [
            1399583285000,
            20.13
        ],
        [
            1399583286000,
            20.13
        ]
    ]
}

This data could be spread across multiple documents.  In general, each document contains data in the info for 59 periods (seconds).
What I would like to do is get all of the info data where the timestamp is greater than a specific time.
Any ideas how I would go about doing this?
Thank you
EDIT:
So, I've found that this seems to return all of the documents:
db.infos.find({
   info:{
      $elemMatch:{
         0:{
            $gt:1399583306000
         }
      }
   }
})

But maybe I need to use this in an aggregate query? so that it will return just all the values?

A: Your on the right track, but there are a few things to note here, aside from the part that nested arrays ( and especially with anonymous keys) are not exactly a great way to store things, but as long as you consistently know the position then that should be reasonably okay.
There is a distinct difference between matching documents and matching "elements of an array". Though your current value would actually not match (your search value is not within the bounds of the document), if the value actually was valid your query correctly matches the "document" here, which contains a matching element in the array.
The "document" contains all of the array elements, even those that do not match, but the condition says the "document" does match, so it is returned. If you just want the matching "elements" then use .aggregate() instead:
    db.infos.aggregate([
        // Still match the document
        { "$match": {
            "info": {
                "$elemMatch": { "0": {"$gte": 1399583285000} }
            }
        }},

        // unwind the array for the matched documents
        { "$unwind": "$info" },

        // Match only the elements
        { "$match": { "info.0": { "$gte": 1399583285000 } } },

        // Group back to the original form if you want
        { "$group": {
            "_id": "$_id",
            "info": { "$push": "$info" }
        }}

    ])

And that returns just the elements that matched the condition:
{
    "_id" : ObjectId("536c1145e99dc11e65ed07ce"),
    "info" : [
            [
                    1399583285000,
                    20.13
            ],
            [
                    1399583286000,
                    20.13
            ]
    ]
}

Or course if you only ever expected one element to match, then you could simply use projection with .find()**:
db.infos.find(
    {
       "info":{
          "$elemMatch":{
             "0": {
                "$gt": 1399583285000
             }
          }
       }
    },
    {
        "info.$": 1
    }
)

But with a term like $gt you are likely to get multiple hits within a document so the aggregate approach is going to be safer considering that the positional $ operator is only going to return the first match.


text:
Q: Why does my caret not return to the beginning of a TRichViewEdit? I'm using a TRichViewEdit for a chat application and after sending the text in the Edit I clear it. The problem is after I clear the Edit the caret appears at the end of the last item. If I click on the Edit or start typing again, the caret returns to the beginning. Why is it not moving back right away?
I've tried calling RichViewEdit.Update and .SelectWordAt(0,0) and neither of those seems to work.
Example:

A: So I found a workaround by calling RVEdit.SetSelectionBounds(0,0,0,0) after the clear, it moves the caret back to the beginning of the edit box.

A: Do this:
RichViewEdit1.Clear;
RichViewEdit1.Format;


text:
Q: Google Calendar API, EventList with MaxResult, is not available in Microsoft Flow I am trying to let my virtual agent to return the searching result of a specific event with its deadline.
But virtual agent couldn't respond under branch:

and I don't want to return a list of events but one specific event since I am going to limited the user input with pre-defined options and there should match exactly.
I looked into the Google AP Documentation:

and seems like I could simply limited the MaxResult to 1 and it should be okay. As you can see, in picture 1, Flow doesn't have that parameter for me, and I could find nowhere I can type anycode to modify that.

A: I finished that project. The way I edit it is also through the agent. I break my flow to a simple flow that will do "search" by looking up the event name instead of time and other details.


text:
Q: Product form of Mobius Inversion formula: $g(n)=\prod_{d|n}f(d)^{a(n/d)}\iff f(n)=\prod_{d|n} g(d)^{b(n/d)}$
Product form of the Möbius inversion formula: If $f(n)>0$ for all $n$ and if $a(n)$ is real, $a(1)\neq 0$, prove that
$$g(n)=\prod_{d|n}f(d)^{a(n/d)}\iff f(n)=\prod_{d|n} g(d)^{b(n/d)}$$
where $b=a^{-1}$ is the Dirichlet inverse of $a$.

So, of course, we have
\begin{align*}
&b(1)=\frac 1{a(1)}\\
&b(n)=\frac {-1}{a(1)}\sum_{d|n}a\left(\frac nd\right)b(d)
\end{align*}
I tried taking logarithms which gave
$$\log g(n)=\sum_{d|n}a(n/d)\log f(d)$$
from which I can't go any further.
On googling Product form of the Möbius inversion formula, Wikipedia gives an alternate statement
$$f(n) = \prod_{d|n}g(d)\iff g(n) = \prod_{d|n} f(d)^{\mu(n/d)}?$$
which can be pretty easily proved by taking logarithms.
But, how does this relate with the original question? Am I missing something trivial?

A: Wikipedia's form is a specific case. Defining the unit function $u(n) = 1$, and defining the product Dirichlet multiplication by
$$\newcommand{\p}{\;\square\;}
(f \p g)(n) := \prod_{d \mid n} f(d)^{g(n/d)}$$
then Wikipedia is claiming that $f = g \p u \iff g = f \p u^{-1}$, where $u^{-1}$ is taken to the usual Dirichlet inverse. One can prove that $\mu \equiv u^{-1}$.
The statement you wish to prove is the more general
$$f = g \p a \iff g = f \p a^{-1}$$

So, taking logs as you have done, we get to
$$f = g \p a \implies \log(f) = \log(g) \ast a$$
for $\ast$ the usual Dirichlet multiplication. $a$ is invertible as $a(1) \ne 0$, so we can multiply by its inverse on both sides and get
$$\log(f) \ast a^{-1} = \log(g)$$
We then convert back to something more expressive:
$$\sum_{d \mid n} \log(f(d)) a(n/d) = \sum_{d \mid n} \log \left( f(d)^{a(n/d)} \right) = \log(g)$$
Now we exponentiate and the result follows.


text:
Q: Doctrine - query returns nested arrays instead of one I'm doing this query
public function getRecommendedVendors($user)
{
    $q = $this->em->createQuery(
        "
          select cat.id
          from Zgh\FEBundle\Entity\Category cat
          inner join cat.users u
          where u = :user
        "
    );

    $q->setParameters(["user" => $user]);

    var_dump($q->execute());
    die;
    return $q->execute();
}

Doing var_dump() returns:
array (size=2)
  0 =>
    array (size=1)
      'id' => string '1' (length=1)
  1 =>
    array (size=1)
      'id' => string '10' (length=2)

Where I want it to return because I use the result inside IN statement:
array (size=2)
  0 =>
    'id' => string '1' (length=1)
  1 =>
    'id' => string '10' (length=2)

A: What you experience is the default query behaviour: The first array "level" are the rows, the second "level" are the columns. Of course, you only have one column, therefore it looks a bit strange.
Instead of execute() you should use getScalarResult(). To learn more about this, read http://docs.doctrine-project.org/en/2.1/reference/dql-doctrine-query-language.html#query-result-formats


text:
Q: How to sign the application for running it on the iPhone device I am new to the iPhone application development.
I have apple developer connection. Please any one here can help i finding the way to get my code sign and run it on the iPhone device?
Thanks,
Pankaj

A: Hotcocoa has made a really nice video tutorial showing how to deploy you app on the iphone

A: Have you enrolled in an iPhone Developer Program? If you have, there's the Developer Program Portal on http://developer.apple.com/iphone. In the portal you will find instructions on certificates and provisioning profiles. I had a little trouble at first myself, but when I read (and followed) their instructions properly it was easy.
If you have not enrolled in an iPhone Developer Program, you're out of luck.


text:
Q: Text alignment *within* bounding box The alignment of a text box can be specified with the horizontalalignment (ha) and verticalalignment (va) arguments, e.g.
import matplotlib.pyplot as plt
fig, ax = plt.subplots(figsize=(8,5))
plt.subplots_adjust(right=0.5)
txt = "Test:\nthis is some text\ninside a bounding box."
fig.text(0.7, 0.5, txt, ha='left', va='center')

Which produces:

Is there anyway to keep the same bounding-box (bbox) alignment, while changing the alignment of the text within that bounding-box?  e.g. for the text to be centered in the bounding-box.
(Obviously in this situation I could just replace the bounding-box, but in more complicated cases I'd like to change the text alignment independently.)

A: The exact bbox depends on the renderer of your specific backend. The following example preserves the x position of the text bbox. It is a bit trickier to exactly preserve both x and y:
import matplotlib
import matplotlib.pyplot as plt

def get_bbox(txt):
    renderer = matplotlib.backend_bases.RendererBase()
    return txt.get_window_extent(renderer)

fig, ax = plt.subplots(figsize=(8,5))
plt.subplots_adjust(right=0.5)
txt = "Test:\nthis is some text\ninside a bounding box."
text_inst = fig.text(0.7, 0.5, txt, ha='left', va='center')

bbox = get_bbox(text_inst)
bbox_fig = bbox.transformed(fig.transFigure.inverted())
print "original bbox (figure system)\t:", bbox.transformed(fig.transFigure.inverted())

# adjust horizontal alignment
text_inst.set_ha('right')
bbox_new = get_bbox(text_inst)
bbox_new_fig = bbox_new.transformed(fig.transFigure.inverted())
print "aligned bbox\t\t\t:", bbox_new_fig

# shift back manually
offset = bbox_fig.x0 - bbox_new_fig.x0
text_inst.set_x(bbox_fig.x0 + offset)
bbox_shifted = get_bbox(text_inst)
print "shifted bbox\t\t\t:", bbox_shifted.transformed(fig.transFigure.inverted())
plt.show()


text:
Q: Cannot use an aggregate or a subquery in an expression I'm trying to display a total and occupation code as columns and the count of dcode inside the rows but it gives me an error:

Cannot use an aggregate or a subquery in an expression used for the
  group by list of a GROUP BY clause.

select count(*) as total

,(select count(dcode) from c122117a_A I where I.dcode = o.dcode and occupation='49' and left(zip,3) between '900' and '934') as 'Doctors-49'

,(select count(dcode) from c122117a_A I where I.dcode = o.dcode and occupation='17' and left(zip,3) between '900' and '934') as 'Health Services-17'

,(select count(dcode) from c122117a_A I where I.dcode = o.dcode and occupation='53' and left(zip,3) between '900' and '934') as '53=Insurance/Underwriters'

,(select count(dcode) from c122117a_A I where I.dcode = o.dcode and occupation='41' and left(zip,3) between '900' and '934') as '41=Occupational Therapy'

,(select count(dcode) from c122117a_A I where I.dcode = o.dcode and occupation='48' and left(zip,3) between '900' and '934') as '48=Nurses'

,(select count(dcode) from c122117a_A I where I.dcode = o.dcode and occupation='43' and left(zip,3) between '900' and '934') as '43=Psychologists'

,(select count(dcode) from c122117a_A I where I.dcode = o.dcode and occupation='21' and left(zip,3) between '900' and '934') as '21=Teacher/Educator'

from c122117a_A o
group by count(*)
order by count(*)

A: Try something like this, complete omitted columns
select count(o.dcode) as total
,sum(case when occupation='49' and left(zip,3) between '900' and '934' then 1 else 0 end) as 'Doctors-49'
,sum(case when occupation='17' and left(zip,3) between '900' and '934' then 1 else 0 end) as 'Health Services-17'
...
from c122117a_A o
group by o.dcode

A: Replace group by count(*) with group by dcode. Because you refer to o.dcode in your subqueries, you have to specify which one. And if you don't group by them, all dcodes are taken together and the database can't determine which one (value) to use.


text:
Q: Select PostgreSQL, выборка без повторов Допустим имеется вот такая таблица
 id |         name         |    date    | id_studio | id_actor | id_seans
----+----------------------+------------+-----------+----------+----------
  1 |  Dark Knight         | 2018-11-20 |         1 |        2 |        1
  1 |  Dark Knight         | 2018-11-20 |         1 |        2 |        2

Мне нужно, чтобы остались обе строчки, но не было повторных значений, то есть чтобы выглядело вот так:
 id |         name         |    date    | id_studio | id_actor | id_seans
----+----------------------+------------+-----------+----------+----------
  1 |  Dark Knight         | 2018-11-20 |         1 |        2 |        1
    |                      |            |           |          |        2


text:
Q: Unable to install package via npm install Error output
npm ERR! code EAI_AGAIN
npm ERR! errno EAI_AGAIN
npm ERR! request to https://registry.npmjs.org/cordova failed, reason: getaddrinfo EAI_AGAIN registry.npmjs.org:443

npm ERR! code EAI_AGAIN
npm ERR! errno EAI_AGAIN
npm ERR! request to https://registry.npmjs.org/cordova failed, reason: getaddrinfo EAI_AGAIN registry.npmjs.org:443

It's stuck for long time and give the above error.
system not behind any proxy.
os version ubuntu 16.04.3 lts
node version 8.11.3
npm version 5.6.0

when I type npm -v, it's showing another error npm update check failed.

A: Update your npm version.

*

*sudo npm cache clean -f

*sudo npm install -g n

*sudo n stable

*npm -v it should print 6.4.0.

Alternatively you ca just type sudo npm install npm@latest -g in terminal

(Note: this will update it to the latest stable version)

Visit this link for more details.


text:
Q: Не могу создать бин 'entityManagerFactory' Я иду полностью по спринговскому гайду.
Но при запуске приложения выдаёт ошибку Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
У меня в коде всё так же как и в гайде. Хотя Я не думаю, что в этой ошибке есть какая-то связь с базой.
 spring.jpa.hibernate.ddl-auto=update
    spring.datasource.url=jdbc:mysql://localhost:3306/demo
    spring.datasource.username=root
    spring.datasource.password=1234

Добавляю к посту свою реализацию класов.
 @Controller
@EnableAutoConfiguration
@RequestMapping("/demo")
public class MainController {

    @Autowired
    private UserRepo userRepo;

    @PostMapping(path = "/add")
    public @ResponseBody String addUser(@RequestParam String name, @RequestParam String email){

        User n = new User();
        n.setName(name);
        n.setEmail(email);
        userRepo.save(n);

        return "saved";
    }

    @GetMapping(path = "/all")
    public @ResponseBody Iterable<User> getAllUsers(){
        return userRepo.findAll();
    }

репозиторий
   public interface UserRepo extends CrudRepository<User, Integer> {
    }

сам клас Юзера
@Entity
public class User {
    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private Integer id;

    private String name;
    private String email;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }
}

В чём моя проблема? Что делаю не так?
[update] полный стэктрейс
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'entityManagerFactory' defined in class path resource [org/springframework/boot/autoconfigure/orm/jpa/HibernateJpaConfiguration.class]: Invocation of init method failed; nested exception is org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1803) ~[spring-beans-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.doCreateBean(AbstractAutowireCapableBeanFactory.java:595) ~[spring-beans-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.createBean(AbstractAutowireCapableBeanFactory.java:517) ~[spring-beans-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.lambda$doGetBean$0(AbstractBeanFactory.java:323) ~[spring-beans-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.beans.factory.support.DefaultSingletonBeanRegistry.getSingleton(DefaultSingletonBeanRegistry.java:222) ~[spring-beans-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.doGetBean(AbstractBeanFactory.java:321) ~[spring-beans-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.beans.factory.support.AbstractBeanFactory.getBean(AbstractBeanFactory.java:202) ~[spring-beans-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.getBean(AbstractApplicationContext.java:1108) ~[spring-context-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishBeanFactoryInitialization(AbstractApplicationContext.java:868) ~[spring-context-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:550) ~[spring-context-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext.refresh(ServletWebServerApplicationContext.java:141) ~[spring-boot-2.2.1.RELEASE.jar:2.2.1.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:747) ~[spring-boot-2.2.1.RELEASE.jar:2.2.1.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) ~[spring-boot-2.2.1.RELEASE.jar:2.2.1.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:315) ~[spring-boot-2.2.1.RELEASE.jar:2.2.1.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1226) ~[spring-boot-2.2.1.RELEASE.jar:2.2.1.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1215) ~[spring-boot-2.2.1.RELEASE.jar:2.2.1.RELEASE]
    at com.example.mysql.MysqlApplication.main(MysqlApplication.java:10) ~[classes/:na]
Caused by: org.hibernate.service.spi.ServiceException: Unable to create requested service [org.hibernate.engine.jdbc.env.spi.JdbcEnvironment]
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:275) ~[hibernate-core-5.4.8.Final.jar:5.4.8.Final]
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:237) ~[hibernate-core-5.4.8.Final.jar:5.4.8.Final]
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214) ~[hibernate-core-5.4.8.Final.jar:5.4.8.Final]
    at org.hibernate.id.factory.internal.DefaultIdentifierGeneratorFactory.injectServices(DefaultIdentifierGeneratorFactory.java:152) ~[hibernate-core-5.4.8.Final.jar:5.4.8.Final]
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.injectDependencies(AbstractServiceRegistryImpl.java:286) ~[hibernate-core-5.4.8.Final.jar:5.4.8.Final]
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.initializeService(AbstractServiceRegistryImpl.java:243) ~[hibernate-core-5.4.8.Final.jar:5.4.8.Final]
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.getService(AbstractServiceRegistryImpl.java:214) ~[hibernate-core-5.4.8.Final.jar:5.4.8.Final]
    at org.hibernate.boot.internal.InFlightMetadataCollectorImpl.<init>(InFlightMetadataCollectorImpl.java:175) ~[hibernate-core-5.4.8.Final.jar:5.4.8.Final]
    at org.hibernate.boot.model.process.spi.MetadataBuildingProcess.complete(MetadataBuildingProcess.java:118) ~[hibernate-core-5.4.8.Final.jar:5.4.8.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.metadata(EntityManagerFactoryBuilderImpl.java:1214) ~[hibernate-core-5.4.8.Final.jar:5.4.8.Final]
    at org.hibernate.jpa.boot.internal.EntityManagerFactoryBuilderImpl.build(EntityManagerFactoryBuilderImpl.java:1245) ~[hibernate-core-5.4.8.Final.jar:5.4.8.Final]
    at org.springframework.orm.jpa.vendor.SpringHibernateJpaPersistenceProvider.createContainerEntityManagerFactory(SpringHibernateJpaPersistenceProvider.java:58) ~[spring-orm-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.createNativeEntityManagerFactory(LocalContainerEntityManagerFactoryBean.java:365) ~[spring-orm-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.buildNativeEntityManagerFactory(AbstractEntityManagerFactoryBean.java:391) ~[spring-orm-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.orm.jpa.AbstractEntityManagerFactoryBean.afterPropertiesSet(AbstractEntityManagerFactoryBean.java:378) ~[spring-orm-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean.afterPropertiesSet(LocalContainerEntityManagerFactoryBean.java:341) ~[spring-orm-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.invokeInitMethods(AbstractAutowireCapableBeanFactory.java:1862) ~[spring-beans-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    at org.springframework.beans.factory.support.AbstractAutowireCapableBeanFactory.initializeBean(AbstractAutowireCapableBeanFactory.java:1799) ~[spring-beans-5.2.1.RELEASE.jar:5.2.1.RELEASE]
    ... 16 common frames omitted
Caused by: org.hibernate.HibernateException: Access to DialectResolutionInfo cannot be null when 'hibernate.dialect' not set
    at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.determineDialect(DialectFactoryImpl.java:100) ~[hibernate-core-5.4.8.Final.jar:5.4.8.Final]
    at org.hibernate.engine.jdbc.dialect.internal.DialectFactoryImpl.buildDialect(DialectFactoryImpl.java:54) ~[hibernate-core-5.4.8.Final.jar:5.4.8.Final]
    at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:137) ~[hibernate-core-5.4.8.Final.jar:5.4.8.Final]
    at org.hibernate.engine.jdbc.env.internal.JdbcEnvironmentInitiator.initiateService(JdbcEnvironmentInitiator.java:35) ~[hibernate-core-5.4.8.Final.jar:5.4.8.Final]
    at org.hibernate.boot.registry.internal.StandardServiceRegistryImpl.initiateService(StandardServiceRegistryImpl.java:101) ~[hibernate-core-5.4.8.Final.jar:5.4.8.Final]
    at org.hibernate.service.internal.AbstractServiceRegistryImpl.createService(AbstractServiceRegistryImpl.java:263) ~[hibernate-core-5.4.8.Final.jar:5.4.8.Final]
    ... 33 common frames omitted

A: Ответ прост (согласно полному стектрейсу):
cannot be null when 'hibernate.dialect' not set
Следовательно нужно установить диалект SQL - добавьте эту строку в файл конфигурации (там где настройки подключения к БД):
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect


text:
Q: I have two TableViews on a single View Controller, how can I pass data to a separate View Controller based upon which TableView was tapped? Firstly, I apologize if this question has been asked before or if it is relatively straightforward to answer. I am relatively new to Swift/programming in general and am still teaching myself as much as I possibly can. I normally check developer documentation/reddit/google for answers to questions I have. If there is a better way of finding answers or support, I would greatly appreciate any general tips or tricks if possible!
In the project I am currently working on, one of my view controllers contains two separate TableViews, each populated by filtered results from a master array. The master array is made up of lessons, each lesson having a name, learning type, and theme. The two filtered arrays are filtered based upon the learning type of the lesson:
var visualArray: [Module] = AllModules.modulesArray.filter { $0.learningType == .visual }
var kinestheticArray: [Module] = AllModules.modulesArray.filter { $0.learningType == .kinesthetic }

What I am trying to accomplish is to pass the name of the module and description of the module to a separate view controller based upon which lesson the user tapped. I have tried to accomplish this in the 'didSelectRowAt' method and the 'prepare(for segue:)' method to no avail. What I would like to happen is the text property of a label on the destination controller to show the name of the selected lesson, what actually happens is the label just stays the same.
Here is my current code for the prepare(for segue:) method mentioned above:
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {

    let tableView = UITableView()

    // Set up indexPath
    guard let visualIndexPath = visualTableView.indexPathForSelectedRow,
        let kinestheticIndexPath = kinestheticTableView.indexPathForSelectedRow else { return }
    let visualModules = visualArray[visualIndexPath.row]
    let kinestheticModules = kinestheticArray[kinestheticIndexPath.row]

    // Set up destination
    guard let destVC = segue.destination as? ModuleVC else { return }
    if tableView == visualTableView {
        print(visualModules.name, visualModules.description)
        destVC.moduleName = visualModules.name
        destVC.moduleDescription = visualModules.description
    } else if tableView == kinestheticTableView {
        destVC.moduleName = kinestheticModules.name
        destVC.moduleDescription = kinestheticModules.description
    }

}

Here is my current code for the destination view controller:
class ModuleVC: UIViewController {

var moduleName: String?
var moduleDescription: String?

override func viewDidLoad() {
    super.viewDidLoad()

    setUI()

    self.navigationItem.largeTitleDisplayMode = .never
    self.navigationController?.navigationBar.prefersLargeTitles = false
}

@IBOutlet var moduleNameLabel: UILabel!
@IBOutlet var moduleDescriptionLabel: UILabel!

func setUI() {

    guard let moduleName = moduleName, let moduleDescription = moduleDescription else {return}
    moduleNameLabel.text = moduleName
    moduleDescriptionLabel.text = moduleDescription

}

}
Any help, even a small step in the right direction, would be immensely appreciated. Thank you for your time!

A: From what I can see, the problem is that you're instantiating a generic tableView in your prepare(for segue:) method, and then doing some sort of check to see if the tableView is equal to your visualTableView or kinestheticTableView. Neither of those conditions will ever be met because you're comparing them to the newly created tableView that has nothing in it, and isn't even laid out in your view.
It sounds like what you're trying to do should be accomplished in the didSelectRow delegate method for the UITableViewDelegate as you hinted at earlier. Sounds like you possibly didn't set it up right.
In the didSelectRowAt method of the UITableViewDelegate, when a tableView row is tapped, the delegate method will fire and it will pass along the tableView which was tapped as a parameter. You can then use that to run a check and it should succeed if one of those two tableViews are tapped. Here is an example of what I think you could do:
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if tableView == visualTableView {
        let visualModules = visualArray[indexPath.row]
        print(visualModules.name, visualModules.description)
        // Now call your segue and pass along the data from those modules
    } else if tableView == kinestheticTableView {
        let kinestheticModules = kinestheticArray[indexPath.row]
        // Now call your segue and pass along the data from those modules
    }
}


text:
Q: Deleting all empty elements from the end of a string array I have the following code:
public static string[] Split(this string me, string splitter, bool remove_empty_elements = false)
{
    return me.Split(new string[] {splitter}, remove_empty_elements ? StringSplitOptions.RemoveEmptyEntries : StringSplitOptions.None);
}

"ABCddcddd".Split("d")

and it generates a string array that looks like:
╭─────┬─────────┬───┬─────────┬─────────┬─────────╮
│ ABC │ <empty> │ c │ <empty> │ <empty> │ <empty> │
╰─────┴─────────┴───┴─────────┴─────────┴─────────╯

What's the best way to remove all empty string elements from end and keep middle ones? Right now I'm doing "ABCddcddd".Split("d").Reverse().SkipWhile(x => x=="").Reverse() and I don't feel very good about it.


text:
Q: Replace Block in Layout for Specific Page At the controller checkout_cart_index with the reference content, I want to replace this:
<block type="checkout/cart_coupon" name="checkout.cart.coupon" as="coupon" template="checkout/cart/coupon.phtml"/>

With this:
<block type="multicoupon/cart_coupon" name="checkout.cart.coupon" as="coupon" template="checkout/cart/coupon.phtml"/>

What happens is instead of replacing the block, it adds a new one. I've spent hours looking into this to no avail. Is there a way to do this with my own module using just the layout or will I have to write the change to a different file?

A: Because unsetChild isn't working in this case, I suggest the nuclear option:
<checkout_cart_index>
    <remove name="checkout.cart.coupon"></remove>
</checkout_cart_index>

This will remove the block entirely. Not such a big deal because you'll immediately re-create it:
<checkout_cart_index>
    <remove name="checkout.cart.coupon"></remove>
    <reference name="checkout.cart">
        <block type="multicoupon/cart_coupon" name="checkout.cart.coupon" as="coupon" template="checkout/cart/coupon.phtml"/>
    </reference>
</checkout_cart_index>


text:
Q: GeoDjango filter by distance from a model field My question is pretty much the same as this. But its quite old and it feels like it must be a fairly common scenario that there might be a better solution to.
I have a model that is something like:
class Person(models.Model):
    location = models.PointField(srid=4326)
    willing_to_travel = models.IntegerField()

If I want all instances of Person who are within a set distance (e.g. 10 miles) of a point p, I can do it like this:
Person.objects.filter(location__distance_lte=(p, D(mi=10)))

But I would like to get all instances of Person who are within their willing_to_travel distance of a particular location.

A: It is possible thanks to Geographic Database Functions introduced in Django 1.9

allow users to access geographic database functions to be used in
  annotations, aggregations, or filters in Django.

The one that interests us the most is Distance, it can be applied in your case as follows:
from django.contrib.gis.db.models.functions import Distance
from django.db.models import F
Person.objects.annotate(distance=Distance('location', p)
       ).filter(distance__lte=F('willing_to_travel'))

Notice that there is subtle difference here, instead of directly using distance_lte here, we have created an annotation that yields us a distance column. Then we are using the standard __lt comparision from the model queryset on it. This translates (roughly) in to
   ... WHERE ST_Distance(app_person.location, ST_GeogFromWKB(...)) <
       app_person.willing_to_travel

Which is similar to the one produced by distance_lte It's not as efficient as one that uses ST_Dwithin but it does the job
you would need to convert location to geography because this query operates on 'units of the field' which means degrees. If you use geography fields the distance will be in meters.


text:
Q: ListView OnClickItems change item color in Android I'm beginner of android studio. I want to know how to change the color if I click again the selected items on listview, Let say I click the first item it turns the background to color red and it will remain same to the other items but then my problem is when I click the red item again I want to change it to color blue. Below is my sample code it only remain the color when I click the item I have no idea to change it to color blue. Thanks in advance.

public class MainActivity extends AppCompatActivity {
ListView list_view;
ArrayList<String> list = new ArrayList<String>();
ArrayAdapter<String> adapter;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    list_view = (ListView) findViewById(R.id.list_views);
    list.add("Data 1");
    list.add("Data 2");
    list.add("Data 3");
    list.add("Data 4");
    list.add("Data 5");

    adapter =new ArrayAdapter<String>(this, R.layout.list_item,list);
    list_view.setAdapter(adapter);

    list_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterView, View v, int i, long l) {
            v.setBackgroundColor(Color.RED);
        }
    });

  }
}

A: Save the currenly applied color in a variable.
int currentColor = Color.white; // make this a class variable
int color = currentColor == white ? Color.RED : Color.Blue;
v.setBackgroundColor(color);

PS this is a pseudo code just to explain the idea

A: There are couple of ways to achieve this, this simplest one is you can check you background color in if condition before apply red color
list_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> adapterView, View v, int i, long l) {
        if (R.color.blue === ((ColorDrawable) v.getBackground()).getColor()) {
            v.setBackgroundColor(Color.RED);
        }else{
           v.setBackgroundColor(Color.BLUE);
         }

    }
});


text:
Q: Calculating magnetic strength required to hold an objects weight + wind speed? Note: I'm a bit new to this subject, so I'm looking for some general answers, ballparks, and direction to continue my research.
Scenario: I have three electromagnets capable of X amount of holding force attached to a surface. There's a small metal object that weighs 10lbs that will be attached to the magnets. The object is rectangular 36"x5"x5". Wind will be blowing and/or the surface will be moving at a particular speed.
Question: How do I go about solving the strength my magnets need to be in order to safely/securely hold an object of a certain weight with windy conditions?

I started researching about MPH to PSF conversions where it reads that 100mph translates to 25.60psf.

*

*Is that accurate, and if so, is that additional force applied to my object?

*Since the object is 36" (3 feet), would that be 25.60psf mean: 10lbs over all / 3 feet = 3.334lbs per foot + 25.60 ... So 28.934lbs of force on each magnet? Is that in the ballpark or am I making this up?

I'm assuming that lift may play a part in this as well, or is that in some ways being accommodated by this MPH->PSF conversion?
I imagine the shape of the object would play a role with regards to lift, so would a rectangular simple object as stated have a minimal, near insignificant, amount of lift for this discussion? Again, I'm not exactly sure what I'm talking about here, so please correct me.
Assuming I can figure out the holding force required per magnet per object per conditions here... is there a safe amount/rule of thumb to add to account for unexpected shocks or gusts? Would a steady wind of 70mph be different than 20mph with a 70mph gust?

Sorry for all the questions. It's something I'm trying to read more about and understand better. Again, it's a bit of an open ended question because I'm trying to learn about it/understand it and don't actually have these materials yet.
Thanks in advance!

A: There are two questions being asked:
1.) How do I calculate how much force my electromagnets can exert
and
2.) How do I calculate the aerodynamic forces acting on an object that will be blowing in the wind, so that I can know how strong my electromagnet needs to be.
I'll answer question 1 first:
Just for future reference, the force exerted by an electromagnet is:
$$F = \frac{\mu^2 N^2 I^2 A}{2\mu_0 L^2}$$
where $N$ is the number of times your wire wraps around your electromagnet, $I$ is the electric current going through it, $A$ is the cross sectional area of your electromagnet, $L$ is the length of the electromagnet.  $\mu$ is the magnetic permeability of whatever your electromagnet core is made of, and $\mu_0$ is the magnetic permeability of free space.  This equation appears about half way down the wikipedia article titled "Electromagnet".
A couple of problems with this are that most electromagnets sold commercially do not state the exact number of turns $N$.  Any number that they place on the packaging (if one is stated at all) is likely a rough estimate.  Furthermore, most electromagnets sold commercially may state something like "iron core" on the packaging, but that doesn't mean it's made of pure iron.  Hence, it is difficult to know for a fact exactly what the core is made of.  This makes is more-or-less impossible to know $\mu$, the magnetic permeability of the material from which the core is made.
The answer to question 2 goes like this.  In principle, the aerodynamic forces acting on your "object" might could be calculated.  But I guarantee you that this is beyond the scope of your project.  Such a feat would require years of work by a team of engineers working full time.  This isn't the direction you want to go.
In all seriousness, the best approach I see is to just trial and error your way through whatever it is you are designing.
Lastly, while doing so, bear in mind that many electromagnets sold in science kits are not very powerful at all.  They are wimpy little things that barely exert any force on anything - it require a delicate touch to determine that they are exerting any force on anything at all.  Be sure that you get something stronger than this.  The strongest electromagnet I've ever encountered outside of a laboratory was the electromagnet that held the back door security gate closed at a restaurant I worked at many years ago.  These electromagnets must be professionally installed and cost many thousands of dollars.  Not to mention the fact that they can be quite dangerous in a wide variety of bizarre ways.
Best of luck with your project.


text:
Q: How to open the two udp client socket with same local port How to open two client socket with the same local port like java.
In Java we can mention the source port while creating DatagramPacket.
I am trying to do UDP hole punching. Correct me if i done anything wrong.
I have added my code here.
void UDPClientConnect ( string IP , string Port )
{
    WSADATA wsa;

if ( WSAStartup(MAKEWORD(2,2),&wsa) != 0 )
{
    printf ( "startup failed %d\n" , WSAGetLastError() ) ;
    return ;
}
int reuse = 1 ;
SOCKET s = socket ( AF_INET , SOCK_DGRAM , IPPROTO_UDP ) ;
setsockopt(s, SOL_SOCKET, SO_REUSEADDR,(char*) &reuse, sizeof(int));

struct sockaddr_in si_other;
int slen=sizeof(si_other);
char buf[BUFLEN];
char message[BUFLEN];

int p = atoi ( Port.c_str() ) ;

memset((char *) &si_other, 0, sizeof(si_other));
si_other.sin_family = AF_INET;

si_other.sin_port = htons(p);
si_other.sin_addr.S_un.S_addr = inet_addr( IP.c_str() );

strcpy_s ( message , "Hello" ) ;

//send the message
if ( sendto ( s , message , strlen(message) , 0 , (struct sockaddr *) &si_other , slen ) == SOCKET_ERROR)
{
    printf ( "sendto() failed with error code : %d" , WSAGetLastError() ) ;
   return ;
}

//receive a reply and print it
memset ( buf , '\0' , BUFLEN ) ;
//try to receive some data, this is a blocking call
if ( recvfrom ( s , buf , BUFLEN , 0 , (struct sockaddr *) &si_other , &slen ) == SOCKET_ERROR )
{
    printf("recvfrom() failed with error code : %d" , WSAGetLastError());
    return ;
}

struct sockaddr_in localAddress;
int addrlen = sizeof(localAddress) ;

getsockname ( s , (struct sockaddr*)&localAddress , &addrlen ) ;

USHORT LocalPort = localAddress.sin_port ;
IN_ADDR localAddr = localAddress.sin_addr ;

printf("local address: %s\n", inet_ntoa( localAddress.sin_addr));
printf("local port: %d\n", (int) ntohs(localAddress.sin_port));

printf ( "\n******************************************\n\n" ) ;

int pos = 1 ;
CStringA CBuff = CStringA ( buf ) ;

string RemortPort = CBuff.Tokenize ( "-" , pos ) ;
string RemortIp = CBuff.Tokenize ( "-" , pos ) ;

reuse = 1 ;

SOCKET Sock_Reuse = socket ( AF_INET , SOCK_DGRAM , IPPROTO_UDP ) ;

setsockopt( Sock_Reuse , SOL_SOCKET, SO_REUSEADDR,(char*) &reuse, sizeof(int)); // optional, but recommended

struct sockaddr_in sin;
memset(&sin,0,sizeof(sin));
sin.sin_family=AF_INET;
sin.sin_port=htons(LocalPort);
sin.sin_addr.s_addr=INADDR_ANY;

if ( SOCKET_ERROR == connect(Sock_Reuse,(struct sockaddr *)&sin,sizeof(struct sockaddr_in)))
{
    printf ( "bind failed %d" , WSAGetLastError() ) ;
}

closesocket ( Sock_Reuse ) ;
closesocket ( s ) ;
WSACleanup ( ) ;

}
In the same method I am trying to open the new socket with same port.
Check this Java Code I am trying to do like this in C/C++. It is not Possible ??
import java.io.* ;
import java.net.* ;

public class UDPHolePunchingClient {

public static void main(String[] args) throws Exception {
    // prepare Socket
    DatagramSocket clientSocket = new DatagramSocket();

    // prepare Data
    byte[] sendData = "Hello".getBytes();

    // send Data to Server with fix IP (X.X.X.X)
    // Client1 uses port 7070, Client2 uses port 7071
    DatagramPacket sendPacket = new DatagramPacket(sendData,
            sendData.length, InetAddress.getByName("172.24.8.110"), 7070);
    clientSocket.send(sendPacket);

    // receive Data ==> Format:"<IP of other Client>-<Port of other Client>"
    DatagramPacket receivePacket = new DatagramPacket(new byte[1024], 1024);
    clientSocket.receive(receivePacket);

    // Convert Response to IP and Port
    String response = new String(receivePacket.getData());
    String[] splitResponse = response.split("-");
    InetAddress ip = InetAddress.getByName(splitResponse[0].substring(1));

    int port = Integer.parseInt(splitResponse[1]);

    // output converted Data for check
    System.out.println("IP: " + ip + " PORT: " + port);

    // close socket and open new socket with SAME localport
    int localPort = clientSocket.getLocalPort();
    clientSocket.close();
    clientSocket = new DatagramSocket(localPort);

    // set Timeout for receiving Data
    clientSocket.setSoTimeout(1000);

    // send 5000 Messages for testing
    for (int i = 0; i < 5000; i++) {

        // send Message to other client
        sendData = ("Datapacket(" + i + ")").getBytes();
        sendPacket = new DatagramPacket(sendData, sendData.length, ip, port);
        clientSocket.send(sendPacket);

        // receive Message from other client
        try {
            receivePacket.setData(new byte[1024]);
            clientSocket.receive(receivePacket);
            System.out.println("REC: "
                    + new String(receivePacket.getData()));

        } catch (Exception e) {
            System.out.println("SERVER TIMED OUT");
        }
    }

    // close connection
    clientSocket.close();
}

}

A: Contrary to all the commentary, all you have to do is set the socket option SO_REUSEPORT prior to the bind().

A: It seems the Java code is not in fact opening two sockets on the same port, but closing the first socket then opening a new one on the same port as the one that was closed.  For a UDP socket not in a connected state, that shouldn't be necessary at all.
If you're not changing the port, your C++ code should be able to continue to use the same socket instead of making a new one.  Assuming you want to mirror what the Java code is doing, you shouldn't need to call connect.  Just use sendto and recvfrom to send data back and forth.


text:
Q: Documenting extension methods with MAML When I refer to a method in my docs, I write something like this: M:MyClass.MyMethod(System.String)
How do I do the same if I need to refer to an extension method?

A: I believe mjd79 is correct in that you'd refer, or link, to the extension methods using same syntax as for normal methods.
Not sure what tool you are using to compile the docs, but the Sandcastle Help File Builder will automatically find and generate an "Extensions" section for any class that has available extension methods at the time of compile.
I realize this only helpful for documenting extensions for class that you own.  When creating extensions for external classes, you do not have many options other than including a blurb in the extension method summary to indicate that the method is intended as an extension method
Attached is a screenshot from some documentation I was playing around with, but you can see the Extensions section:

A: Pretty much the same way - remember that extension methods are just static methods in a static class.  So, for example, if you have something like this (admittedly useless method):
public class StringExtensions
{
  public static string ToSingleQuotedString(this string s)
  {
    return String.Format("'{0}'", s);
  }
}

Your documentation would look like this: M:StringExtensions.ToSingleQuotedString(System.String)
Hope that helps.


text:
Q: How to change the License page default header "License Agreement" in Inno Setup? I want to change the default header "License Agreement" in the license page in Inno Setup.
I am unable to find anything to do so.

A: See Handling and customizing errors and messages in Inno Setup.
This particular message is defined by the WizardLicense message.
You can change it in the [Messages] section:
[Messages]
WizardLicense=Privacy policy