text:
Q: javax.mail isn't working on Marshmallow or above systems I'm trying to send email from the android app using javax.mail package
and I found this and it's working just fine on premarshmallow OSs but when I'm trying to send the email from mobiles that have Marshmallow or above OSs
the Transport.send(message) hangs and never return
this is my SendEmailTask class
 public static class SendEmailTask extends AsyncTask<Void, Void, Boolean> {

        @Override
        protected Boolean doInBackground(Void... params) {

                int a=5;
            Log.e("ErrorAsync","before out");
            try {
                Log.e("ErrorAsync","before in");
                Transport.send(message);
                Log.e("ErrorAsync","after in");
            } catch (Exception e) {
                e.printStackTrace();
                Log.e("ErrorAsync",e.getMessage());
            }
            Log.e("ErrorAsync","after out");
            return true;
        }

        @Override
        protected void onPostExecute(Boolean result) {

        }

        @Override
        protected void onPreExecute() {
            if(android.os.Debug.isDebuggerConnected())
                android.os.Debug.waitForDebugger();
        }

        @Override
        protected void onProgressUpdate(Void... values) {}
    }

the logcat output is as follow

09-12 08:29:21.872 6498-6542/? E/ErrorAsync: before out
09-12 08:29:21.873 6498-6542/? E/ErrorAsync: before in

my question is:
is there any way to send email programmatically on Marshmallow or above OSs?

A: I have created my implementation using this library and it is working fine since a long time. So try it like below:
JSSEProvider.java
        import java.security.AccessController;
        import java.security.Provider;

        public final class JSSEProvider extends Provider {

            public JSSEProvider() {
                super("HarmonyJSSE", 1.0, "Harmony JSSE Provider");
                AccessController
                        .doPrivileged(new java.security.PrivilegedAction<Void>() {
                            public Void run() {
                                put("SSLContext.TLS",
                                        "org.apache.harmony.xnet.provider.jsse.SSLContextImpl");
                                put("Alg.Alias.SSLContext.TLSv1", "TLS");
                                put("KeyManagerFactory.X509",
                                        "org.apache.harmony.xnet.provider.jsse.KeyManagerFactoryImpl");
                                put("TrustManagerFactory.X509",
                                        "org.apache.harmony.xnet.provider.jsse.TrustManagerFactoryImpl");
                                return null;
                            }
                        });
            }
        }

MailSender.java
    import android.util.Log;

    import java.io.ByteArrayInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.io.OutputStream;
    import java.security.Security;
    import java.util.Properties;

    import javax.activation.DataHandler;
    import javax.activation.DataSource;
    import javax.activation.FileDataSource;
    import javax.mail.BodyPart;
    import javax.mail.Message;
    import javax.mail.Multipart;
    import javax.mail.PasswordAuthentication;
    import javax.mail.Session;
    import javax.mail.Transport;
    import javax.mail.internet.InternetAddress;
    import javax.mail.internet.MimeBodyPart;
    import javax.mail.internet.MimeMessage;
    import javax.mail.internet.MimeMultipart;

    public class MailSender extends javax.mail.Authenticator {

        private String mailhost = "smtp.zoho.com";
        private String user;
        private String password;
        private Session session;

        private Multipart _multipart = new MimeMultipart();
        static {
            Security.addProvider(new JSSEProvider());
        }

        public MailSender(String user, String password) {
            this.user = user;
            this.password = password;

            Properties props = new Properties();
            props.setProperty("mail.transport.protocol", "smtp");
            props.setProperty("mail.host", mailhost);
            props.put("mail.smtp.auth", "true");
            props.put("mail.smtp.port", "465");
            props.put("mail.smtp.socketFactory.port", "465");
            props.put("mail.smtp.socketFactory.class",
                    "javax.net.ssl.SSLSocketFactory");
            props.put("mail.smtp.socketFactory.fallback", "false");
            props.setProperty("mail.smtp.quitwait", "false");
            session = Session.getDefaultInstance(props, this);
        }

        protected PasswordAuthentication getPasswordAuthentication() {
            return new PasswordAuthentication(user, password);
        }

        public synchronized void sendMail(String subject, String body,
                                          String sender, String recipients) throws Exception {
            try {
                MimeMessage message = new MimeMessage(session);
                DataHandler handler = new DataHandler(new ByteArrayDataSource(
                        body.getBytes(), "text/plain"));
                message.setSender(new InternetAddress(sender));
                message.setSubject(subject);
                message.setDataHandler(handler);
                BodyPart messageBodyPart = new MimeBodyPart();
                messageBodyPart.setText(body);
                _multipart.addBodyPart(messageBodyPart);

                // Put parts in message
                message.setContent(_multipart);
                if (recipients.indexOf(',') > 0)
                    message.setRecipients(Message.RecipientType.TO,
                            InternetAddress.parse(recipients));
                else
                    message.setRecipient(Message.RecipientType.TO,
                            new InternetAddress(recipients));
                Transport.send(message);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        public void addAttachment(String filename) throws Exception {
            BodyPart messageBodyPart = new MimeBodyPart();
            DataSource source = new FileDataSource(filename);
            messageBodyPart.setDataHandler(new DataHandler(source));
            messageBodyPart.setFileName("download image");
            _multipart.addBodyPart(messageBodyPart);
        }

        public class ByteArrayDataSource implements DataSource {
            private byte[] data;
            private String type;

            public ByteArrayDataSource(byte[] data, String type) {
                super();
                this.data = data;
                this.type = type;
            }

            public ByteArrayDataSource(byte[] data) {
                super();
                this.data = data;
            }

            public void setType(String type) {
                this.type = type;
            }

            public String getContentType() {
                if (type == null)
                    return "application/octet-stream";
                else
                    return type;
            }

            public InputStream getInputStream() throws IOException {
                return new ByteArrayInputStream(data);
            }

            public String getName() {
                return "ByteArrayDataSource";
            }

            public OutputStream getOutputStream() throws IOException {
                throw new IOException("Not Supported");
            }
        }
    }

Mail.java
    import android.util.Log;
    public class Mail {
        String senderId,password,receiverId,subject,body;

        public Mail() {
        }

        public void setSenderId(String senderId) {
            this.senderId = senderId;
        }

        public void setPassword(String password) {
            this.password = password;
        }

        public void setReceiverId(String receiverId) {
            this.receiverId = receiverId;
        }

        public void setSubject(String subject) {
            this.subject = subject;
        }

        public void setBody(String body) {
            this.body = body;
        }

        public void sendMail(){
            new Thread(new Runnable() {
                public void run() {
                    try {
                        MailSender sender = new MailSender(
                                senderId,
                                password);
                        sender.sendMail(subject,
                                body,
                                senderId,
                                receiverId);
                    } catch (Exception e) {
                        Log.e("mailError",e.getMessage());
                        e.printStackTrace();
                    }
                }
            }).start();
        }
    }

Keep all these classes in a single package.
You can send email like this:
Mail email = new Mail();
email.setReceiverId("");
email.setSenderId("");
email.setPassword("");
email.setSubject("");
email.setBody("");
email.sendMail();

Note
Change your smtp settings in MailSender class according to your provider. I used zoho mail.


text:
Q: Need proofread: Prove skew hermitian matrix only has complex eigenvalues Let $\textbf{A}^\ast = -\textbf{A}$
Prove $\textbf{A}$ has only complex eigenvalues
Proof:
Let $\lambda \in \mathbb{C}\ and\ \textbf{A}\vec{v} = \lambda\vec{v}\quad \vec{v} \neq \vec{0}$
$$\textbf{A}\vec{v} = \lambda\vec{v}$$
$$\Rightarrow (\textbf{A}\vec{v})^\ast = (\lambda\vec{v})^\ast$$
$$\Rightarrow (\vec{v}^\ast\textbf{A}^\ast)=(\lambda^\ast\vec{v}^\ast) $$
$$\because \vec{v} \neq \vec{0}$$
$$\therefore\vec{v}^\ast\textbf{A}^\ast\vec{v}=\lambda^\ast\vec{v}^\ast\vec{v}$$
$$\because \textbf{A}^\ast = -\textbf{A}$$
$$\therefore \vec{v}^\ast(-\textbf{A})\vec{v} = \lambda^\ast\vec{v}^\ast\vec{v}$$
$$\Rightarrow -\vec{v}^\ast\textbf{A}\vec{v} = \lambda^\ast\vec{v}^\ast\vec{v}$$
$$\because \textbf{A}\vec{v} = \lambda\vec{v}$$
$$\therefore -\vec{v}^\ast\lambda\vec{v}=\lambda^\ast\vec{v}^\ast\vec{v}$$
$$\Rightarrow -\lambda\vec{v}^\ast\vec{v}=\lambda^\ast\vec{v}^\ast\vec{v}$$
$$\Rightarrow \lambda\langle\vec{v}^\ast,\vec{v}^\ast \rangle=\lambda^\ast\langle\vec{v}^\ast,\vec{v}^\ast\rangle$$
$$\because \vec{v} \neq \vec{0}$$
$$\therefore \vec{v}^\ast \neq 0$$
$$\Rightarrow \langle\vec{v}^\ast,\vec{v}^\ast\rangle \gt 0\quad(\because \vec{v}^\ast\vec{v} = \langle\vec{v}^\ast, \vec{v}^\ast\rangle)$$
$$\Rightarrow -\lambda = \lambda^\ast$$
$$\Rightarrow \lambda \in\mathbb{R}$$

A: First of all, I presume you mean to say $\mathbf A$ has only imaginary eigenvalues; what would an eigenvalue of a complex matrix be if not complex?
Second of all, you made the same mistake with the definition of an eigenvector that you did in your previous proof. Namely: $\vec v$ is an eigenvector if $\mathbf{\vec v}$ is non-zero and there is some $\lambda\in\mathbb C$ such that $\mathbf A \vec v = \lambda v$.
That is, we do not deduce $\vec v$ is non-zero from the nature of the matrix; it is supposed under the definition of an eigenvalue. We do not suppose that $\lambda \neq 0$ because for some eigenvectors, even with skew-Hermitian matrices, $\lambda$ can be zero.  So, at the top of your proof, write

"Let $\vec v\neq 0$ and $\mathbf A \vec v=\lambda v$".

Instead. The rest seems fine.
EDIT:
Also, note that $\vec v^*\vec v$ is a matrix of one entry, and so you should write

$\therefore \vec{v}^\ast \vec{v} \neq 0$

rather than

$\therefore \vec{v}^\ast \vec{v} \neq \vec{0}$

redpajama_set_name: RedPajamaStackExchange


text:
Q: Meaning of 'Solution' Meaning of solution
Which one of the following does it mean?

*

*An attempt to solve a problem which may or may not be correct

*Correct attempt which 100% solves the problem

Refer the following context:

I have attached my solution above. Please let me know if there is some mistake in the solution provided.

In this I'm not sure if my attempt to solve a specific problem is correct or not but I have shared it. Can the word 'solution' be used here?

A: I am quite confident it should be close to the second one in most scenarios. A solution is the correct answer to a problem. While an attempt to solution may or may not be correct.
Consider these words/phrases: "method to solve", "finding a solution", "attempting a problem". You might get a reference.
In a small number of cases, the word has a context based meaning.
If a student says, "This is my solution to the given question."
They are giving out their method to reach the 100% correct answer. The ultimate answer has been reached but the path taken may or may not be correct here.
When the student is not 100% confident even about the final answer they might say: "this is how I have solved the question." Or, "this is my attempt to find a solution to the question."

A: A solution to a problem is like an answer to a question. It is simply an element of a pair. A solution may be true or false. It may be good or bad, satisfactory or unsatisfactory.  It may be partial or even irrelevant.
There's a famous quotation from H.L. Mencken: there is always a well-known solution to every human problem—neat, plausible, and wrong.
However, as this page at Quote Investigator shows, many others have embraced the concept of a false solution:  https://quoteinvestigator.com/2016/07/17/solution/
It may be possible in a domain like arithmetic for there to be  correct answers. Some things are genuinely provable in a strict formal sense, although even here this requires some acceptance of unprovable assertions. We can easily agree that 2+2=4, but the answer to "what is two?" is not so simple.
Outside of arithmetic, ordinary English is full of "problems and solutions", like "How do solve a problem like Maria" (from The Sound of Music), or "The answer was an Orange", which remains searchable as a phrase in Sellar and Yeatman's 1066 and All That.  Even here in our little world of EL&U, down-voting and complaints about down-voting suggest that opinions differ - and that some problems may in fact have no solution.
To bring this back to the original question: an "attempt" is probably the better of the two choices offered by the OP, because "attempt" itself may have be qualified, and terms like "insincere attempt" are more comprehensible than "insincere truth".


text:
Q: Getting SUM() on distinct rows in mysql I have a table ("dump") with transactions, and I want to list the total amount, grouped by category, per month, like: Month | Category | Category ID | SUM. The tables involved looks like this:
TABLE dump:
id INT
date DATE
event VARCHAR(100)
amount DECIMAL(10, 2)
TABLE dump_cat:
id INT
did INT (id in dump)
cid INT (id in categories)
TABLE categories:
id INT
name VARCHAR(100)
Now the query I'm trying to use is:
SELECT SUBSTR(d.date,1,7) AS month, c.name, c.id AS catid, SUM(d.amount) AS sum
 FROM dump as d, dump_cat as dc, categories AS c
 WHERE dc.did = d.id AND c.id = dc.cid AND SUBSTR(d.date, 1, 7) >= '2008-08'
 GROUP BY month, c.name ORDER BY month;
But the sum for most categories is twice as big as it should be. My guess is that this is because the join returns multiple rows, but adding "DISTINCT d.id" in the field part doesn't make any difference. An example of what the query returns is:
+---------+--------------------------+-------+-----------+
| month   | name                     | catid | sum       |
+---------+--------------------------+-------+-----------+
| 2008-08 | Cash                     |    21 |  -6200.00 |
| 2008-08 | Gas                      |     8 |  -2936.19 |
| 2008-08 | Rent                     |     1 | -15682.00 |
where as
SELECT DISTINCT d.id, d.amount FROM dump AS d, dump_cat AS dc
 WHERE d.id = dc.did AND SUBSTR(d.date, 1, 7) ='2008-08' AND dc.cid = 21;
returns
+------+----------+
| id   | amount   |
+------+----------+
| 3961 |  -600.00 |
| 2976 |  -200.00 |
| 2967 |  -400.00 |
| 2964 |  -200.00 |
| 2957 |  -300.00 |
| 2962 | -1400.00 |
+------+----------+
That makes a total of 3100, half of the sum listed above. If I remove "DISTINCT d.id" from the last query, every row is listed twice. This I think is the problem, but I need help to figure out how to solve it. Thanks in advance.
Added: If I collect the dump and dump_cat tables into one, with
CREATE table dumpwithcat SELECT DISTINCT d.id, d.date, d.event, d.amount, dc.cid
  FROM dump AS d, dump_cat AS c WHERE c.did = d.id;
and do the query on that table, everything works fine with correct sum. Is there a way to do this in the original query, with a subquery or something like that?

A:
That makes a total of 3100, half of the sum listed above. If I remove "DISTINCT d.id" from the last query, every row is listed twice.

While you may have only one category per dump, you therefore must have multiple rows in dump_cat per dump.  You should consider defining a UNIQUE constraint to ensure only one row exists per pair of did, cid:
ALTER TABLE dump_cat ADD CONSTRAINT UNIQUE (did, cid);

I predict this statement will fail given the current data in your table.  It can't create a unique constraint when these columns already contain duplicates!
You can remove duplicates this way, for instance:
DELETE dc1 FROM dump_cat dc1 JOIN dump_cat dc2 USING (did, cid)
WHERE dc1.id > dc2.id; -- only delete the second duplicate entry

edit: By the way, don't mark my question accepted until you have verified that I'm correct!  :-)
You can verify that there are in fact duplicates as I suggest by using a query like the following:
SELECT did, COUNT(*)
FROM dump_cat
GROUP BY did
HAVING COUNT(*) > 1;

Another possibility:  you have more than one category with the same name?  (sorry my first try at this query was wrong, here's an edited version)
SELECT c.name, GROUP_CONCAT(c.id) AS cat_id_list, COUNT(*) AS c
FROM category c
GROUP BY c.name
HAVING COUNT(*) > 1;

FWIW, I did test the DELETE command I showed:
INSERT INTO dump_cat (did, cid) VALUES (1, 2), (3,4), (3,4); -- duplicates!

DELETE dc1 FROM dump_cat dc1 JOIN dump_cat dc2 USING (did, cid) WHERE dc1.id > dc2.id
Query OK, 1 row affected (0.00 sec)

PS: This is tangential to your question, but the DISTINCT query modifier always applies to the whole row, not just the first column.  This is a common misunderstanding of many SQL programmers.

A: At first examination it looks to me like you might have the Referential integrity constraint bgetween Dump and Dump_Cat backwards.
Can Transactions (in Dump) be in multiple categories?  If not, then shouldn't the Transaction table, (Dump) specify which category each transaction is in, and not the otjher way around?  i.e, should there be a CatId in the Dump table and not a DumpId in the Cat table?
if Transactions can be in Multiple categories, then your data structure is correct, butthen  you will unavoidably be double (or multiply) counting transaction amounts in any aggregate query because the transaction amount is in fact in multiple categories.

A: If dump records can be in multiple categories, they will impact all of their category's rows for that month.
One solution for this is to also pull a COUNT() of categories for each dump record, and use that as a divisor for the individual amounts. Thus, the amount is apportioned automatically in an even way across all categories the dump record belongs to, preserving the integrity of the overall total.
Something like this (sorry, MySQL isn't my daily RDBMS, unsure of the exact syntax):
 SELECT SUBSTR(d.date,1,7) AS month, c.name, c.id AS catid,
   SUM(d.amount / (SELECT COUNT(*) FROM dump_cat dc2 WHERE dc2.did=d.id)) AS sum
 FROM dump as d, dump_cat as dc, categories AS c
 WHERE dc.did = d.id AND c.id = dc.cid AND SUBSTR(d.date, 1, 7) >= '2008-08'
 GROUP BY month, c.name ORDER BY month;

A: You can take just about any query, like the one you used to create the distinct table, and just select off of that. Just give the the query a "table name".
SELECT SUBSTR(d_dc.date,1,7) AS month, c.name, c.id AS catid, SUM(d_dc.amount) AS sum
FROM (SELECT DISTINCT d.id, d.date, d.event, d.amount, dc.cid
    FROM dump AS d, dump_cat AS dc WHERE dc.did = d.id
    WHERE SUBSTR(d.date, 1, 7) >= '2008-08') AS d_dc
JOIN categories AS c ON d_dc.cid=c.id
GROUP BY month, c.name ORDER BY month

That's probably not the most efficient way to do your query, and I may have gotten some of the table aliases wrong, but that should give you an idea of how to do it.


text:
Q: Where does windows store network drive mappings? I am not able to boot my windows 7, but I have access to the drive on which Windows 7 is installed.
Is there anyway I can restore my network drives?

A: Where does windows store network drive mappings?

When we map a network drive persistently in windows 7 an entry
  relating to the drive is created under the following key in registry:
HKEY_CURRENT_USER\Network
For each drive a key with the name as that of the drive letter is
  created. For example if you mapped a network drive with letter W the
  key will be HKEY_CURRENT_USER\Network\W
The key will contain the following values:

Source Mapped network drives in Windows 7 Registry

How do I load the registry from a different Windows Installation?
See this question Edit another Windows install's registry for instructions on how to load the registry for a different windows installation, for example when you have a non-bootable drive.

What about the credentials (Domain, username, Password)? Where do I find them?
Network Password Recovery from NirSoft can be used to recover network credentials, even from another external drive (eg from a dead system that cannot boot anymore).

This utility recovers all network passwords stored on your system for
  the current logged-on user. It can also recover the passwords stored
  in Credentials file of external drive, as long as you know the last
  log-on password.

...

Where the network passwords are stored?
Older versions of Windows (Windows 95,98 and ME) stored the network
  passwords in pwl files located under the main Windows folder.
Starting from Windows XP, the network passwords are encrypted inside
  the Credentials file, located under:
"Documents and Settings\<User Name>\Application Data\Microsoft\Credentials\<User SID>".
Some passwords may also be stored in the Credentials file under:
"Documents and Settings\<User Name>\Local Settings\Application Data\Microsoft\Credentials\<User SID>".
In addition to the passwords of network shares, Windows XP also stores
  the passwords of .NET Passport (MSN Messenger) in the same Credentials
  files
Credentials file in external drive
Starting from version 1.20, you can also read the Credentials from an
  external profile in your current operating system or from another
  external drive (For example: from a dead system that cannot boot
  anymore).
In order to use this feature, you must know the last logged-on
  password used for this profile, because the Credentials file is
  encrypted with the SHA hash of the log-on password, and without that
  hash, the Credentials file cannot be decrypted.
You can use this feature from the UI, by selecting the 'Advanced
  Options' in the File menu, or from command-line, by using /external
  parameter.
The user profile path should be something like "C:\Documents and Settings\admin" in Windows XP/2003 or "C:\users\myuser" in Windows
  Vista/2008.

Source Network Password Recovery v1.34 - Recover Windows XP/Vista network passwords (Credentials file)

Disclaimer
I am not affiliated with NirSoft in any way, I am just an end user of the software.


text:
Q: How to report TFS usage I'm working on implementing TFS for numerous teams and am looking for a way to monitor TFS in terms of how many distinct users, builds ran, work item totals, collections/projects/teams, and more, preferably if I can see daily/weekly/monthly metrics. I've found some solutions by querying the SQL database, but am curious if there are any extensions or solutions others have found to monitor the usage of your TFS instance as well as any GUIs that help visualizations.

A: No such a comprehensive tool or extension to achieve that.
For specific team project, you can add widgets to a dashboard to monitor the status:

Widgets smartly format data to provide access to easily consumable
  data. You add widgets to your team dashboards to gain visibility into
  the status and trends occurring as you develop your software project.
Each widget provides access to a chart, user-configurable information,
  or a set of links that open a feature or function.

For example , with builds just specify the specific build definition, for work items you can create queries and specify the query when configure a widget.
Actually you can retrieve most of the information via REST API.
e.g.: Get Builds - List:
GET http://server:8080/tfs/{project}/_apis/build/builds?api-version=3.2

You can also try to custom your own reports, please see SQL Server Reporting (TFS) and Create and manage Reporting Services reports for details.


text:
Q: change data variable when passed into a method in vue I have the following vue component where I am changing the class of the parent row based on whether or not an input is focused

<template>

            Email address
            <input type="text" class="form__control form__control--textbox" name="email-address" id="login-form-email" @focus="emailEntered = true" @blur="handleBlur($event, emailEntered)">

            Password
            <input type="password" class="form__control form__control--textbox form__control--password" name="password" id="login-form-password" @focus="passwordEntered = true" @blur="handleBlur($event, passwordEntered)">

</template>

but it doesn't seem to change the variable that is passed into the method - how do I pass a data variable into the method and change it's value?   Or should I be doing it in a different way?  I don't really want to be doing an if else statement as I may have a form that has got a lot more inputs on and I think that would be really inefficient to maintain
I also thought that I could do something in the @bur as you can do @blur="passwordEntered = false", but I wasn't sure how to check if the field was empty or not

A: In order to change the variable, you need to refer it using this
 handleBlur(e, enteredBool) {
   if (e.currentTarget.value.trim() === '') {
     this[enteredBool] = false;   //Change added
   }
 },

and the way you pass it should be like
@blur="handleBlur($event, 'emailEntered')" //Added single quotes

and
@blur="handleBlur($event, 'passwordEntered')" //Added single quotes


text:
Q: MSI M2 - Multisource shipping? We are using MSI Multistock (multisource) and want to be able to ship from multiple sources in M2 in one shipment. In short it does the following

*

*sell items from multiple sources as shown in image

*when shipping apply multisource shipping, and deduct 1st as much as possible from source 1, then continue to source 2 (actual just like the column 'deduct' in the screenshot)

Currently we can only select 1 shipping source because it is a dropdown. We would rather like to assign multiple sources just like the deduct from column in the overview.
Amasty has something in their extension for MSI, the problem is that it adds a lot of other features as well. We only need multisource shipping.
Question: HOw could we add multisource shipping as a shipping algoritm that applies per default for all orders /w the logic of 1st deduct from prio 1 source, if not enough continue to next. And Ship all in 1 shipment.

A: Magento Allow only one source assignment per shipment, in case of qty per source you can create multiple shipment. please try once.


text:
Q: Allocating with new and storing in LRU buffer, deletion does not happen? I am implementing a simple cache of unordered maps allocating them with the new keyword, and I would like for the objects to be deleted when they are evicted from the cache. For reference, this is the LRU cache implementation I am using: https://github.com/facebook/hhvm/blob/master/hphp/util/concurrent-lru-cache.h
I am testing my program on Linux, 1 thread. The code is the following:
HPHP::ConcurrentLRUCache<std::string, std::unordered_map<int, int>*> my_cache(10);
for (int i = 0; i < 1000000; i++) {
    auto map = new std::unordered_map<int, int>(1000);
    for (int j = 0; j < 1000; j++)
        map->insert(std::make_pair(j, j));
    my_cache.insert(std::to_string(i), map);
}

template <class TKey, class TValue, class THash>
    bool ConcurrentLRUCache<TKey, TValue, THash>::
    insert(const TKey& key, const TValue& value) {
        // Insert into the CHM
        ListNode* node = new ListNode(key);
        HashMapAccessor hashAccessor;
        HashMapValuePair hashMapValue(key, HashMapValue(value, node));
        if (!m_map.insert(hashAccessor, hashMapValue)) {
            delete node;
            return false;
        }

        // Evict if necessary, now that we know the hashmap insertion was successful.
        size_t size = m_size.load();
        bool evictionDone = false;
        if (size >= m_maxSize) {
            evict();
            evictionDone = true;
        }

        std::unique_lock<ListMutex> lock(m_listMutex);
        pushFront(node);
        lock.unlock();
        if (!evictionDone) {
            size = m_size++;
        }
        if (size > m_maxSize) {
            if (m_size.compare_exchange_strong(size, size - 1)) {
                evict();
            }
        }
        return true;
    }

template <class TKey, class TValue, class THash>
    void ConcurrentLRUCache<TKey, TValue, THash>::
    evict() {
        std::unique_lock<ListMutex> lock(m_listMutex);
        ListNode* moribund = m_tail.m_prev;
        if (moribund == &m_head) {
            // List is empty, can't evict
            return;
        }
        delink(moribund);
        lock.unlock();

        HashMapAccessor hashAccessor;
        if (!m_map.find(hashAccessor, moribund->m_key)) {
            // Presumably unreachable
            return;
        }
        m_map.erase(hashAccessor);
        delete moribund;
    }

When inserting a map, if the cache is full, the last recently used element should get evicted. However, the map itself does not get deleted and the memory usage peaks. What am I doing wrong?
Note: the maps should be retrieved during the execution of my program, so they should be accessible from the cache.


text:
Q: sql session time out recommendation One of my applications uses sql session state, the timeout is currently set to 20 minutes. My question is, since this is stored in the database and not in server memory, I should be able to increase the timeout without any significant performance issues right?
I don't really understand the importance of the timeout for the database session state scenario, since the database should easily be able to handle a lot of sessions.

A: I think the timeout's relevance is more for public-facing websites where you could potentially get a lot of hits and fill up your database fairly quickly.  That being said, infinite isn't exactly what you want either...

A: I was looking for confirmation of your opinion, too-- that if harddrive space is cheap, I should be able to have 8 hour sessions in SqlSessionState without noticable performance issues (beyond what 20 minute sql server session cause), given a medium sized office level intranet application.
Just try to keep in mind that the advice about session deals with how many users you can deal with at once, how likely it is that users will start some work, get interrupted for a long time, and need to continue.
And finally if you are storing authentication tokens or roles in session, then you may want to expire those more often to check the user still is a user and still has those roles.

A: Length of a session should be determined by the functionality (e.g. on-line banking would tend to shorter timeout, while a site like SO instead allows longer period to type up an entry), not by the implementation mechanism.
Using out-of-process mode allows retaining session context in case of IIS re-cycles, and requires less direct (used by IIS itself) memory resources.  But that has no relation to whether a session should last 8 hours or 5 min.


text:
Q: Is there a way to automatically collapse the Script Documents section in solution explorer? While in debug mode, the solution explorer has a Script Documents section.  It is expanded by default.  As the debugger runs, new ScriptDocumentxxx poll.txt files are added to this section.  As I am navigating the explorer files, the adding of these new line items causes the entire contents of the explorer to shift downward.  This is quite annoying if I am trying to find a file or trying to click something.  I can collapse the section manually, but I'd rather not have to do this all of the time.

A: Right click then 'Scope to This' to hide everything but the project in the solution you want to view.
Click on the Home/House icon to reverse it.

A: Right click the projects you are interested in working on and click on 'Scope to this'. This will hide everything (Including the scripts folder) except those projects you selected.

A: Yes there is. One way is to create a visual studio add-in or extension which monitors the solution explorer tree and collapses the "script documents" -item if it is expanded.
If you need code samples and/or a fully functional add-in just let me know. You have Visual Studio 2013, ay? Is it the express edition or what?

A: I got annoyed enough with this that I turned off JavaScript debugging.  If you are willing to go that far, the scripts are gone.
The path for turn of JS debugging is:
Tools -> Options -> Debugging -> General -> Enable JavaScript debugging for ASP.NET (Chrome, Edge and IE) (Visual Studio 2017 and 2019)
Note: This method does not prevent you from stepping though JS in the Chrome inspection tools so you do not lose that ability.  You lose both the scripts (of course) and that new Chrome window that pops up when you launch the debugger.
Visual Studio 2022 has this menu collapsed by default.  Everyone can upgrade and rejoice as this question and it's answers go the way of the dinosaur.

A: Yes, there is.

IIS Express > Script Debugging > Disabled

A: This is confirmed bug in VS 2019. Just Microsoft is not so fast about fixing it.
https://developercommunity.visualstudio.com/content/idea/351537/provide-a-way-to-prevent-the-script-documents-fold.html


text:
Q: Can I show Articles in a tree like structure We would like to show Knowledge Articles in a tree like structure, has anyone done this? I am looking for sample code & steps to accomplish.
Thank You,

A: From this blog
First off, lets grab the static resource and get that uploaded into your org. You can snag it here
https://www.box.com/s/04u0cd8xjtm0z84tbhid
upload that, make it public, call it jsTree
global class CaseSlaController
{
    //constructors for component and visualforce page extension
    public CaseSlaController() {}
    public CaseSlaController(ApexPages.StandardController controller) {}

    //gets category data and returns in JSON format for visualforce pages. Beware that since we end up double JSON encoding the return
    //(once from the JSON.serialize, and another time because that's how data is returned when moved over apex remoting) you have to fix
    //the data on the client side. We have to double encode it because the built in JSON encoder breaks down when trying to serialize
    //the Schema.DescribeDataCategoryGroupStructureResult object, but the explicit call works.
    @remoteAction
    global static string getCategoriesJson(string sObjectType)
    {
        return JSON.serialize(CaseSlaController.getCategories(sObjectType));
    }

    public static  list<Schema.DescribeDataCategoryGroupStructureResult> getCategories(string sObjectType)
    {

        //the describing of categories requires pairs of sObject type, and category name. This holds a list of those pairs.
        list<Schema.DataCategoryGroupSObjectTypePair> pairs = new list<Schema.DataCategoryGroupSObjectTypePair>();

        //list of objects to describe, for this app we only take 1 sObject type at a time, as passed into this function.
        list<string> objects = new list<string>();
        objects.add(sObjectType);

        //describe the categories for this object type (knowledgeArticleVersion)
        List<Schema.DescribeDataCategoryGroupResult> describeCategoryResult =  Schema.describeDataCategoryGroups(objects);

        //add the found categories to the list.
        for(Schema.DescribeDataCategoryGroupResult s : describeCategoryResult)
        {
            Schema.DataCategoryGroupSObjectTypePair thisPair = new Schema.DataCategoryGroupSObjectTypePair();
            thisPair.sObject = sObjectType;
            thisPair.dataCategoryGroupName = s.getName();
            pairs.add(thisPair);
        }

        //describe the categories recursivly
        list<Schema.DescribeDataCategoryGroupStructureResult> results = Schema.describeDataCategoryGroupStructures(pairs,false);

        return results;
    }
    private static DataCategory[] getAllCategories(DataCategory [] categories)
    {
        if(categories.isEmpty())
        {
            return new DataCategory[]{};
        }
        else
        {
            DataCategory [] categoriesClone = categories.clone();
            DataCategory category = categoriesClone[0];
            DataCategory[] allCategories = new DataCategory[]{category};
            categoriesClone.remove(0);
            categoriesClone.addAll(category.getChildCategories());
            allCategories.addAll(getAllCategories(categoriesClone));
            return allCategories;
        }
    }
}

    <apex:component Controller="CaseSlaController">

    <apex:attribute name="sObjectType" type="string" description="the sObject type to get data category tree for" />
    <apex:attribute name="callback" type="string" description="Name of javascript function to call when tree drawing is complete" />

    <link rel="stylesheet" href="{!URLFOR($Resource.jsTree, 'css/jquery.treeview.css')}" />
    <apex:includeScript value="{!URLFOR($Resource.jsTree, 'js/jquery.min.js')}" />
    <apex:includeScript value="{!URLFOR($Resource.jsTree, 'js/jquery.treeview.js')}" />

</apex:component>

<apex:page sidebar="false" standardController="Case" showHeader="false" extensions="CaseSlaController">
    <c:categorySelect callback="knowledgePicker.bindTreeClicks" sObjectType="KnowledgeArticleVersion"/>

</apex:page>


text:
Q: android:how to Reload the ArrayAdapater Class in Check/uncheck event of ListView's Chekbox? How to Reload the ArrayAdapater Class in Check/uncheck event of ListView's Chekbox?
the Event is define in ArrayAdapter Class? notifieddatachage() is not worked..
I want to reload the ArrayAdpater class for reload the View again for user when clicked the Chekbox that time but its not workd so please help me..

A: on check/Uncheck event call refresh();
public void refresh()
        {
            mCursor=db_conn.onQueryGetCursor("tab_book",mItems,null, null, null, null, null);
            mCursor.requery();
            notifyDataSetChanged();

       }


text:
Q: How to solve system of implications and linear inequalities? I have the following system of, erm, implications - what would be the best way to go about solving this system? I would like to solve for $w,x,y,z,\lambda$ in terms of $a,b,c,d,e,f$
$w > 0 => 0.5w + ax + (1-d)y + fz = \lambda$
$w = 0 => 0.5w + ax + (1-d)y + fz < \lambda$
$x > 0 => (1-a)w + 0.5x + ey + bz = \lambda$
$x = 0 => (1-a)w + 0.5x + ey + bz < \lambda$
$y > 0 => dw + (1-e)x + 0.5y + (1-c)z = \lambda$
$y = 0 => dw + (1-e)x + 0.5y + (1-c)z < \lambda$
$z > 0 => (1-f)w + (1-b)x + cy + 0.5z = \lambda$
$z = 0 => (1-f)w + (1-b)x + cy + 0.5z < \lambda$
$w + x + y + z = 1$
$w \ge 0, x \ge 0, y \ge 0, z \ge 0$
Sorry for just dumping a whole system, but I have no idea how to go about this with the implications there!


text:
Q: Store result of Jinja filter The basics of what I am trying to do is to use the 'random' filter to choose a random item from my list but then I want to use that randomly chosen item in multiple locations.
How do I set the result of a filter to a variable that I can use in multiple locations.
If I call the 'random' filter multiple times there is little chance they will be the same.
Essentially what I want to do:
{% set image = {{ images | random }} %}

obviously this doesnt work.

A: Use the filter without {{ }} delimiters.
{% set image = images|random %}

Jinja stores globals and filters in two different namespaces (dictionaries), which prevents them from being used interchangeably.

A: It's not working on loop, I had used this code:
{% set result = result | replace('x','y') %}


text:
Q: Save cursor pos / reload cursor pos doesnt work on mac? C language What this code does is make a timer area and writing area. It updates the timer and then moves the cursor back to the correct location. I am using
printf("\x1b[s"); To save the cursor location
printf("\x1b[u"); To reload the cursor position.
This allows me to take input from the user and update the timer at the same time. It also allows me to return to the correct spot on the line I was on when I was typing, not just the start of the line. This works fine on linux but ive tested it on mac and its like those two escape codes dont work at all. So it just moves the cursor to the time line and then never back again. If there is no simple solution like this does anyone have any other ideas. I cannot use ncurses or conio.h. This is what it looks like when its working properly https://imgur.com/a/TQuqrSh
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <signal.h>
#include <unistd.h>

int time_left = 25;

void moveTo(int row, int col)
{
    printf("\x1b[%d;%df", row, col);
}

void move_cursor_to_input_pos()
{
    moveTo(2, 15);
    fflush(stdout);
}

void update_timer(int signum)
{

    if (time_left >= 0)
    {
        printf("\x1b[s");
        moveTo(0, 15);
        fflush(stdout);
        time_left -= 1;
        if (time_left < 10)
            printf("%d ", time_left + 1);
        else
            printf("%d", time_left + 1);
        printf("\x1b[u");
        fflush(stdout);
        alarm(1);
    }
}

int main()
{
    moveTo(0, 7);
    printf("Time:  ");
    moveTo(2, 7);
    printf("Input: ");
    fflush(stdout);

    signal(SIGALRM, update_timer);
    alarm(1);
    while (time_left > 0)
    {
        while (1)
        {
            char input[100];
            if (fgets(input, 100, stdin))
            {
                moveTo(10, 10);
                printf("You entered: %s", input);
            }
        }
    }

    return 0;
};


text:
Q: Tripadvisor Widget not working in Angular2 app I'm new to Angular 2 and I'm trying to get a Tripadvisor widget working on my page. The widget works great in plain html but as soon as I include it in my component in angular it shows the image for the widget but the javasript does not execute so you don't see the content.
widget code I'm using:

I did try the example from Including tripadvisor widget in angularjs app - here is the code that I tried from that answer:

But this sadly doesn't fix my problem, I get the same results, you can see the widget in the upper right corner of this page:
http://bellamontereybay.com/


text:
Q: Laravel phpunit how to use diffent migrations for tests I am trying to set up tests in Laravel, but I want to run different migrations from those that usually run.
The migrations that I run to initiate the database imports data from a production environment.
For testing I want to use a different database called "test", and I want to fill this test database with test data, not production data.
I added a "testing" connection to config/database.php which uses the "test" database:
'connections' => [

        'mysql' => [
            'database' => env('DB_DATABASE', 'forge'),
            ...
        ],

        'testing' => [
            'database' => 'test',
            ...
        ],
],

And I setup phpunit.xml to use this "testing" connection:
<?xml version="1.0" encoding="UTF-8"?>
<phpunit ...>
    ...
    <php>
        <env name="DB_CONNECTION" value="testing"/>
        ...
    </php>
</phpunit>

Now I want to initialize this "test" database with test data, using migrations from a different folder than the default.
I can use the normal migrations like this:
<?php

namespace Tests;

use Illuminate\Foundation\Testing\TestCase as BaseTestCase;
use Illuminate\Foundation\Testing\DatabaseMigrations;

abstract class TestCase extends BaseTestCase
{
    use DatabaseMigrations;

    public function setUp(): void
    {
        parent::setUp();
        $this->seed();
    }
}

But this uses the default folder database/migrations.
I would like to put the testing migrations in folder tests/database/migrations.
Is there a way to let use DatabaseMigrations; use migrations from another folder?

A: You might need to override runDatabaseMigrations method in DatabaseMigrations trait and set the app's database path from there before your migrations run.
The runDatabaseMigrations method might end up looking like this:
use DatabaseMigrations { runDatabaseMigrations as runMigration; }

    public function runDatabaseMigrations()
    {
        $this->app->useDatabasePath(base_path('tests/database')); //example path
//        dump($this->app->databasePath());
        $this->runMigration();
    }

Or you can set in the boot method of your AppService provider:
    if (config('app.env') === 'testing') { //Laravel automatically set env to 'testing' when running test
        $this->app->useDatabasePath(base_path('tests/database'));
    }

The migration will look for a sub-folder of 'tests/database' called "migrations".

PS: There will be side effect to this if you're have some other code or folder in the default database folder. Example, your factory class there will not be found for this test class.

A: Artisan migrate has a path option, you have to make your own trait to have similar functionality. I'm thinking something like this.
trait PathDatabaseMigrations {

    public function runDatabaseMigrations()
    {
        // optimal
        $path = 'tests/database/migrations';

        $this->artisan('migrate:fresh', ['--path' => $path,]);

        $this->app[Kernel::class]->setArtisan(null);

        $this->beforeApplicationDestroyed(function () {
            $this->artisan('migrate:rollback', ['--path' => $path,]);

            RefreshDatabaseState::$migrated = false;
        });
    }
}

A: The RefreshDatabase trait has a method called migrateUsing which will overload the parameters that it uses when running the migrations. I changed to a specific test migration file for a single test by passing it in as the --path parameter to the migration.
namespace Tests\Unit;

use Tests\TestCase;
use App\Models\Traits\HasUuid;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Foundation\Testing\RefreshDatabase;

class HasUuidTest extends TestCase
{
    use RefreshDatabase;

    protected function migrateUsing()
    {
        return [
            '--path' => 'tests/migrations/2022_03_15_220516_create_test_uuid_table.php'
        ];
    }

    public function test_has_uuid()
    {
        $model = new TestUuid;
        $this->assertEmpty($model->id);
        $model->save();
        $this->assertNotEmpty($model->id);
    }
}

class TestUuid extends Model
{
    use HasUuid;
}


text:
Q: Implement a graph from adjacency list to Edge list using DFS C++ I have a text file that contains an adjacency list of undirected graph,
example:
1 2 3
2 1 3 4
3 1 2 4
4 2 3
I am reading the file and storing it in an adjacency list,
I want to transfer this data to an Edge List,
I am trying to find out all Unique pair of edges,
Using the DFS I am getting the pairs but those are not unique,
I am trying to eliminate the duplicate pairs ( a duplicate pair is <1,2> is same as <2,1>) but it is not happening.......
Here is the outut I am getting:
degree of 1 is : 2
Nember of vertices is :4
Numbe rof edges is : 5
Max degree is : 3
Min degree is : 2
List of edges : ..........
1 2
Edge 1 2 Inserted
 Back : 2 1
Edge 2 1 Inserted
2 3
Edge 2 3 Inserted
 Back : 3 1
Edge 3 1 Inserted
 Back : 3 2
Edge 3 2 Inserted
3 4
Edge 3 4 Inserted
 Back : 4 2
Edge 4 2 Inserted
 Back : 4 3
Edge 4 3 Inserted
 Back : 2 4
Edge 2 4 Inserted
 Back : 1 3
Edge 1 3 Inserted

Thanks...
Sorry for the long code.........
#include <iostream>
#include <fstream>
#include <limits>
#include <vector>
#include <list>
#include <string>
#include <sstream>
#include <cstdlib>
#include <map>

using namespace std;

typedef struct EdgeList
{
    int u;
    int v;
}EdgeList;

class Graph
{
    public:
        vector<list<int> > adj;
        int V;
        int E;

        EdgeList *edges;

        Graph(int N):adj(N+1)
        {
            V = N;
        }
        Graph(int N, int M):adj(N+1)
        {
            V = N;
            E = M;
            int x = E+550;
            edges = new EdgeList[x];
        }

        void addEdgeList(Graph g, int u, int v);
        bool ischeckEdge(Graph g,int u,int v);

        void addEdge(int u, int v);
        void deleteSelfLoops(Graph g);

        int degree(Graph g, int v);
        int maxDegree(Graph g);
        int minDegree(Graph g);
        int edgeCount(Graph g);
        int numberOfSelfLoops(Graph g);

        bool isEdge(Graph g, int u,int v);

        void DFS(Graph g);
        void dfsUtil(Graph g, int v, bool visited[] );
};

int e = 0;
void Graph::addEdgeList(Graph g, int u, int v)
{
    if(ischeckEdge(g,u,v))
    {
        cout<<"Edge "<<u<<" "<<v<<" Inserted "<<endl;
        g.edges[e].u = u;
        g.edges[e].v = v;
        e++;
    }
}

bool Graph::ischeckEdge(Graph g, int u, int v)
{
    bool a,b,c,d;

    for(int i=0;i<=g.E; i++)
    {

        if( ((g.edges[i].u == u || g.edges[i].v == v) && (!g.edges[i].u == u || !g.edges[i].v == v)) )
        {
            cout<<"First block" ;
            return false;

        }
        else if( ((g.edges[i].u == v || g.edges[i].v == u) && (!g.edges[i].u == v || !g.edges[i].v == u)))
        {
            cout<<" sec block";
            return false;
        }
        else
        {
            return true;
        }
    }
}

void Graph::dfsUtil(Graph g, int v, bool visited[])
{
    list<int> temp;
    temp  = g.adj[v];

    if(!visited[v])
    {
         visited[v] = true;
    }

    list<int>::iterator j;
    for(j = temp.begin();j != temp.end(); j++)
    {
        if(!visited[*j])
        {
            cout<<endl<<v<<" "<<*j<<endl;// print edges
            g.addEdgeList(g,v,*j);
            dfsUtil(g, *j, visited);
        }
        else //back edge
        {
            cout<<" Back : "<<v<<" "<<*j<<endl;
            g.addEdgeList(g,v,*j);
        }
    }
}

void Graph::DFS(Graph g)
{
    bool *visited = new bool[g.V+1];
    int *parent = new int[g.V+1];

    for(int i = 0; i <= g.V; i++)
    {
         visited[i] = false;
         parent[i] = -1;
    }

    for(int v = 0; v <= g.V; v++)
    {
        if(!visited[v])
        {
            dfsUtil(g, v , visited);
        }
    }
 }

 bool Graph::isEdge(Graph g, int u, int v)
 {
     for(int w : adj[v])
     {
        if(u == w)
        {
            return true;
        }
     }
    return false;
 }

void Graph::addEdge(int u, int v)
{
    adj[u].push_back(v); //undirected graph
    //adj[v].push_back(u);
}

void Graph::deleteSelfLoops(Graph g)
{
    for(int v = 0; v <= g.V; v++)
   {
        for(int w : g.adj[v])
        {
            if(v == w)
            {
                g,adj[v].remove(w);
            }
       }
    }
}

int Graph::degree(Graph g, int v)
{
     int deg = 0;

    for(int i = 0;i < g.adj[v].size();i++)
    {
        deg++;
    }
    return deg;
}

int Graph::edgeCount(Graph g)
{
    int edge = 0;
    int i;

    if(g.adj[0].empty())
    {
         i = 1;
    }
    else
    {
        i = 0;
    }

    for(i; i <= g.V; i++)
    {
        edge = edge + degree(g,i);
    }

   return edge/2; //handshaking lemma
}

int Graph::maxDegree(Graph g)
{
    int max = 0;

    for(int i = 0; i <= g.V; i++)
    {
        if(degree(g,i) > max)
        {
            max = degree(g,i);
        }
    }
    return max;
 }

int Graph::minDegree(Graph g)
{
    int min = g.V;
    int i;

    if(g.adj[0].empty())
    {
        i = 1;
    }
    else
    {
        i = 0;
    }

    for(i; i <= g.V; i++)
    {
        if(degree(g,i) < min)
        {
            min = degree(g,i);
        }
    }
    return min;
}

int Graph::numberOfSelfLoops(Graph g)
{
    int count = 0;

    for(int v = 0; v <= g.V; v++)
    {
        for(int w : g.adj[v])
        {
            if(v == w)
            {
                count++;
            }
        }
    }

    return count / 2;
 }

int main()
{
    ifstream fin("AdjList.txt");

    int V = 0;

    string str;

    while(getline(fin, str))
    {
    istringstream ss(str);
    int num;

    while(ss >> num)
    {
        // ... you now get a number ...
        int u;
        u = str[0] - '0'; //char can be coverted to int
        if(num != u )
        {
             //cout<<u<< "  "<< num<<endl;

        }
    }
    V++;
}
fin.close();

Graph g1(V);

fin.open("AdjList.txt");
while(getline(fin, str))
{
    istringstream ss(str);
    int num;

    while(ss >> num)
    {
        // ... you now get a number ...
        int u;
        u = str[0] - '0'; //char can be coverted to int
        if(num != u )
        {
             g1.addEdge(u,num);
             //cout<<u<< "  "<< num<<endl;

            }
        }
    }
    fin.close();

    Graph g(V,g1.edgeCount(g1));
    g.adj = g1.adj;

    cout<<"degree of 1 is : "<<g.degree(g,1)<<endl;
    cout<<"Nember of vertices is :"<<g.V<<endl;
    cout<<"Numbe rof edges is : "<< g.edgeCount(g)<<endl;
    cout<<"Max degree is : "<<g.maxDegree(g)<<endl;
    cout<<"Min degree is : "<<g.minDegree(g)<<endl;

    cout<<"List of edges : .........."<<endl;

    cout<< g.edges[4].u;

    for(int i=0; i<=g.E+500;i++)
    {
        g.edges[i].u=0;
        g.edges[i].v =0;
    }

    g.DFS(g);

    return 0;
 }

A: Since you index vertices with integers, the simple trick you can do is to add edge {v, u} if and only if v <= u (if there are no self-loops then v < u is sufficient). In order to do that, just change:
if(!visited[*j])
{
    cout<<endl<<v<<" "<<*j<<endl;// print edges
    g.addEdgeList(g,v,*j);
    dfsUtil(g, *j, visited);
}

to
if(!visited[*j])
{
    cout<<endl<<v<<" "<<*j<<endl;// print edges
    if(v <= *j)
    {
        g.addEdgeList(g,v,*j);
    }
    dfsUtil(g, *j, visited);
}

A: as I was thinking the problem was in ischeckEdge. it was comparing (0,0) as edges as in the input there is no vertex '0',
bool Graph::ischeckEdge(Graph g, int u, int v)
{
    bool a = false;

    swap(u,v);

    for(int i=0;i<=e; i++)
    {

        if(i == 0)
        {
            continue;
        }
        if(i ==1 && g.edges[i].u ==0 && g.edges[i].v ==0)
        {
            return true;
        }

        if(g.edges[i].u == u && g.edges[i].v ==v )
        {
            //cout<<"Same Edge"<<endl;
            a= false;
            break;
        }
        else
        {
            //cout<<"Edge count : "<<e<<endl;
            //cout<<"Iteration : "<<i<<endl;
            //cout<<"edge u v : "<<g.edges[i].u<<" "<<g.edges[i].v<<endl;
            //cout<<"input u v : "<<u<<" "<<v<<endl;
            a= true;
        }
    }
    return a;
}


text:
Q: FileInput when triggered by label "for" event returns no file path I'm attempting to make the file input field in HTML a lot prettier by covering it up. However I still need to be able to trigger the event of selecting a file.
<form action="scripts/upload.php" method="post" enctype="multipart/form-data">
    <input type="file" name="fileToUpload" id="fileToUpload">

Select an Image

    <button class="btn btn-default" type="submit">
Upload Image</button>
</form>

When using the for="fileToUpload" system, it will open the dialog box and the input field does receive a file path value (I've checked with JS). However this seems to be rather superficial. When passing it on from the form, it disappears.
$_FILES["fileToUpload"]["name"]

This line results in an empty string.
If I leave out my attempts to style and instead stick with using the default button, it works just fine.

I've also attempted JS click events on the input field with the same results. Why will it only properly select files when using the default button?


text:
Q: Change width of progress bar with javascript I try  change width of bootstrap progress bar with java script but don't worked.I wrote this code in head section. Please advice.
document.getElementsByClassName("progress-bar").setAttribute("style", "width:50%");
document.getElementsByClassName("progress-bar").style.width = "width:50%";

Html :

A: getElementsByClassName() will return a list of nodes, you should specify the index of the one you want to change :
document.getElementsByClassName("progress-bar")[0].setAttribute("style", "width:50%");
document.getElementsByClassName("progress-bar")[0].style.width = "50%";

Hope this helps.

A: I would suggest you to use document.querySelector - it returns single element
All major browsers support it
And this is incorrect
document.getElementsByClassName("progress-bar").style.width = "width:50%";
//must be
document.getElementsByClassName("progress-bar").style.width = "50%";

checkout demo below

var percent = 10;
document.querySelector(".progress-bar").style.width = percent + "%";
function increase(){
  percent = percent > 90 ? 10 : percent + 10;
  document.querySelector(".progress-bar").style.width = percent + "%";
}
.progress{
  background: red;
  padding: 3px;
}
.progress-bar{
  background: blue;
  height: 10px;
}

<button onclick="increase()">increase</button>


text:
Q: StringBuilder string format scriptValues.AppendFormat("something = {1};", SessionID.ToString());

in the above, I get a R# warning or something that says I need to add a 3rd param.  When I look with intellisense it shows string formatter.  Do I need one here?

A: It should be scriptValues.AppendFormat(@"something = {0}";", SessionID.ToString());


text:
Q: unable to get near protocol transaction status via RPC Given a transaction https://explorer.near.org/transactions/JBb2DDe3i1CtBwESisLuhxXkWVZpCKYL4J1AdYwAQPsQ
When I query NEAR rpc:
http post https://rpc.mainnet.near.org jsonrpc=2.0 method=tx params:='["JBb2DDe3i1CtBwESisLuhxXkWVZpCKYL4J1AdYwAQPsQ","wasmgit.near"]' id=dontcare

Then I expect to get the transaction status
Instead I get the following response:
{
    "error": {
        "code": -32000,
        "data": "Transaction JBb2DDe3i1CtBwESisLuhxXkWVZpCKYL4J1AdYwAQPsQ doesn't exist",
        "message": "Server error"
    },
    "id": "dontcare",
    "jsonrpc": "2.0"
}

A:
source: https://docs.near.org/docs/api/rpc#setup
Querying historical data (older than 5 epochs or ~2.5 days), you may
get responses that the data is not available anymore. In that case,
archival RPC nodes will come to your rescue:

*

*mainnet https://archival-rpc.mainnet.near.org

*testnet https://archival-rpc.testnet.near.org
You can see this interface defined in nearcore here.

via near-cli
near --nodeUrl https://archival-rpc.mainnet.near.org \
tx-status JBb2DDe3i1CtBwESisLuhxXkWVZpCKYL4J1AdYwAQPsQ \
--accountId wasmgit.near

via http
http post https://archival-rpc.mainnet.near.org \
jsonrpc=2.0 method=tx \
params:='["JBb2DDe3i1CtBwESisLuhxXkWVZpCKYL4J1AdYwAQPsQ","wasmgit.near"]' \
id=dontcare


text:
Q: Numpy: Walk along vector within 2d matrix Consider a function A(x(z, y), y(z)). I want to start at arbitrary (x, y), and walk along z. I have

*

*dy/dz = 1

*dx/dz = z y(1-x)/(y(y+z)). For epsilon z, this gives y(1-x)/(yy)
Now, take the following discretization:
import numpy as np
x = np.linspace(0.01, 0.99, 100)
y = np.linspace(0.5, 2, 50)
X, Y = np.meshgrid(x, y, indexing='ij')
A = X*Y
d = Y*(1-X)/(Y*Y)

Now, A is a 2d function in (x, y):
A.shape
Out[25]: (100, 50)

which is increasing in both dimensions by construction.
Now, from each starting point in A, I want to walk along the (d, 1) vector, until I reach a value above 1.5. My resulting matrix R with the same shape as A should contain the number of grid points in y dimension that it took to get there. If I never arrive at that value (that is, the corresponding boundary of A < 1.5), any distinguishable output (eg nan) would be great.
Since this is difficult to do manually, I cannot give an exact expected output. But for example, take the grid point (85, 20). Let's say that in that neighborhood, d=0.1 roughly (it is actually 0.13). That'd mean that I would want to move along the (1, 10) diagonal locally, until I reach A : A >= 1.5. In this case, I want to walk from A[85, 20] up to A[85+2, 20+20], the first point above 1.5, with value of
A[85+2, 20+20]
Out[51]: 1.5023964131106988

So, I walked 20 grid points along z. This means that my resulting matrix R has R[85, 20] == 20.
I'm both interested in high efficiency ways of doing this, as well as worse performing but more precise solutions. In any case, my solution has to build on the given matrices.

To provide some more intuition about what I'm trying to achieve, consider dx/dz = 0. In that case, I could simply
positive = A > 1.5
iX, iY = np.meshgrid(np.arange(100), np.arange(50), indexing='ij')
gridsMove = positive.argmax(axis=1)[:, np.newaxis]
R = np.maximum(gridsMove-iY, 0).astype(float)
# prune those here where we never arrive (argmax yields `0`, non robust test but works here)
R[gridsMove.repeat(50, axis=1) == 0] = np.nan

However, in my example, I cannot argmax(axis=1), since I'm walking on more than one axis. I'd have to do argmax(axis=0.1) or something along those lines...


text:
Q: Using a class/struct/union over multiple cpp files C++ I am trying to create a class in C++ and be able to access elements of that class in more than one C++ file. I have tried over 7 possible senarios to resolve the error but have been unsuccessful. I have looked into class forward declaration which doesen't seem to be the answer (I could be wrong).
//resources.h
class Jam{
public:
int age;
}jam;

//functions.cpp
#include "resources.h"
void printme(){
std::cout << jam.age;
}

//main.cpp
#include "resources.h"
int main(){
printme();
std::cout << jam.age;
}

Error  1   error LNK2005: "class Jam jam" (?jam@@3VJam@@A) already defined in stdafx.obj
Error  2   error LNK1169: one or more multiply defined symbols found
I understand the error is a multiple definiton because I am including resources.h in both CPP files. How can I fix this? I have tried declaring the class Jam in a CPP file and then declaring extern class Jam jam; for each CPP file that needed to access the class. I have also tried declaring pointers to the class, but I have been unsuccessful. Thank you!

A: You're declaring the structure Jam and creating a variable called jam of this type. The linker is complaining that you've got two (or more) things called jam, because your header causes each .cpp file to declare one of its own.
To fix this, change your header declaration to:
class Jam{
public:
int age;
};

extern Jam jam;

And then place the following line in one of your .cpp sources:
Jam jam;

A: You need to separate your definition from your declaration.  Use:
//resources.h
class Jam{
public:
int age;
};
// Declare but don't define jam
extern Jam jam;

//resources.cpp
// Define jam here; linker will link references to this definition:
Jam jam;

A: The variable jam is defined in the H file, and included in multiple CPP classes, which is a problem.
Variables shouldn't be declared in H files, in order to avoid precisely that. Leave the class definition in the H file, but define the variable in one of the CPP files (and if you need to access it globally - define it as extern in all the rest).
For example:
//resources.h
class Jam{
public:
int age;
};
extern Jam jam; // all the files that include this header will know about it

//functions.cpp
#include "resources.h"
Jam jam; // the linker will link all the references to jam to this one
void printme(){
std::cout << jam.age;
}

//main.cpp
#include "resources.h"
int main(){
printme();
std::cout << jam.age;
}

A: As a first step you should separate the definition of the class and declaration of an instance. Then use extern in resources.h and declare the instance in a CPP.
Like this:
//resources.h
class Jam{
public:
    int age;
};

extern Jam jam;

//functions.cpp
#include "resources.h"
void printme(){
    std::cout << jam.age;
}

//main.cpp
#include "resources.h"
Jam jam;

int main(){
    printme();
    std::cout << jam.age;
}

A: Use the pragma once directive, or some defines to make sure a header doesn't get included more than once in your code.
Example using pragma directive (example.h):
#pragma once
// Everything below the pragma once directive will only be parsed once
class Jam { ... } jam;

Example using defines (example.h):
#ifndef _EXAMPLE_H
#define _EXAMPLE_H
// This define makes sure this code only gets parsed once
class Jam { ... } jam;
#endif


text:
Q: Django multiple profiles In what way can a Student submit an assignment to a particular Teacher(teaching a particular course)... What relationship we they have??
models.py
class Student(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
    avatar = models.ImageField(upload_to='media/pictures/', blank=True)
    regex = RegexValidator(r'^\d{2}/\d{4}',
                           message='Required. 7 characters or fewer. This value must contain only numeric and slash.')
    matric_no = models.CharField(validators=[regex], blank=True, null=True, max_length=7, unique=True)
    phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$',
                                 message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.")
    phone_number = models.CharField(validators=[phone_regex], max_length=17, blank=True)  # validators should be a list
    address = models.CharField(max_length=150, blank=True)
    birth_date = models.DateField(null=True, blank=True)

    GENDER_CHOICES = (
            ('M', 'Male'),
            ('F', 'Female'),
        )

class Teacher(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)
    avatar = models.ImageField(upload_to='media/pictures/', blank=True)
    phone_regex = RegexValidator(regex=r'^\+?1?\d{9,15}$',
                                 message="Phone number must be entered in the format: '+999999999'. Up to 15 digits allowed.")
    phone_number = models.CharField(validators=[phone_regex], max_length=17, blank=True)  # validators should be a list
    address = models.CharField(max_length=150, blank=True)
    birth_date = models.DateField(null=True, blank=True)
    GENDER_CHOICES = (
        ('M', 'Male'),
        ('F', 'Female'),
    )
    gender = models.CharField(max_length=1, choices=GENDER_CHOICES, null=False, default='M',)

    def __str__(self):
        return str(self.user)

Maybe something like user messaging or mailing (User to User)?

A: If one Student can only submit a given assignment to only one Teacher (i.e., not to a group of teachers) you can use a model similar to the following:
class Assignment(models.Model):
    student = models.ForeignKey(Student)
    teacher = models.ForeignKey(Teacher)
    ...other fields...

You can also use a ManyToMany relation between Student and Teacher models and create your own through table but semantically the method above makes more sense in this case.


text:
Q: move shape to different directions Task:
I created a shape with 4 buttons, and need it to move to 4 directions depending on the button clicked (pure JS).
This is what I created - check out the snippet.
Problem:
Left/Right directions work great, but Up/Down do not.
Any idea why? Looks like both directions are identical. :/
Thanks a lot for your help, much appreciated!

var shape = document.getElementById("shape"),
  leftBtn = document.getElementById("leftBtn"),
 rightBtn = document.getElementById("rightBtn"),
    upBtn = document.getElementById("upBtn"),
 downBtn  = document.getElementById("downBtn");

 leftBtn.onclick = function(){
  moveLeft();
 }
 rightBtn.onclick = function(){
  moveRight();
 }
 upBtn.onclick = function(){
  moveUp();
 }
 downBtn.onclick = function(){
  moveDown();
 }

function moveLeft() {
    var val = (parseInt(shape.style.left) || 0) - 50;
    shape.style.left = val + "px";
}

function moveUp() {
    var val = (parseInt(shape.style.top) || 0) - 50;
    shape.style.left = val + "px";
}

function moveRight() {
    var val = (parseInt(shape.style.left) || 0) + 50;
    shape.style.left = val + "px";
}

function moveDown() {
    var val = (parseInt(shape.style.top) || 0) + 50;
    shape.style.left = val + "px";
}
body{
 background-color: black;
}

#shape{
 background-color: red;
 width: 100px;
 height: 100px;
 border-radius: 50%;
 position: relative;
}

  <title>JavaScript and the Document Object Model</title>
  <link rel="stylesheet" type="text/css" href="shape.css">

  <button class="button" id="leftBtn" direction="left">left</button>
  <button class="button" id="upBtn" direction="up">up</button>
  <button class="button" id="downBtn" direction="down">down</button>
  <button class="button" id="rightBtn" direction="right">right</button>

A: As pointed by @Temani, in functions moveUp and moveDown, changing shape.style.left to shape.style.top will solve the problem.

var shape = document.getElementById("shape"),
  leftBtn = document.getElementById("leftBtn"),
 rightBtn = document.getElementById("rightBtn"),
    upBtn = document.getElementById("upBtn"),
 downBtn  = document.getElementById("downBtn");

 leftBtn.onclick = function(){
  moveLeft();
 }
 rightBtn.onclick = function(){
  moveRight();
 }
 upBtn.onclick = function(){
  moveUp();
 }
 downBtn.onclick = function(){
  moveDown();
 }

function moveLeft() {
    var val = (parseInt(shape.style.left) || 0) - 50;
    shape.style.left = val + "px";
}

function moveUp() {
    var val = (parseInt(shape.style.top) || 0) - 50;
    shape.style.top = val + "px";
}

function moveRight() {
    var val = (parseInt(shape.style.left) || 0) + 50;
    shape.style.left = val + "px";
}

function moveDown() {
    var val = (parseInt(shape.style.top) || 0) + 50;
    shape.style.top = val + "px";
}
body{
 background-color: black;
}

#shape{
 background-color: red;
 width: 100px;
 height: 100px;
 border-radius: 50%;
 position: relative;
}

  <title>JavaScript and the Document Object Model</title>
  <link rel="stylesheet" type="text/css" href="shape.css">

  <button class="button" id="leftBtn" direction="left">left</button>
  <button class="button" id="upBtn" direction="up">up</button>
  <button class="button" id="downBtn" direction="down">down</button>
  <button class="button" id="rightBtn" direction="right">right</button>


text:
Q: External commands in a controller I have various files of extensions .cpp stored on the server. When user clicks on the compile button, I should run gcc command passing the absolute path of the file to gcc compiler and then show the user the output of the file.
How can i do that???

A: Kernel.system may the command that you are looking for: it calls a system process. For example:
if (system("gcc ..."))
  @output_to_show = %x['./compiled']
end

Assuming that your server is in Linux/UNIX, it would be good to separate the compile&execute process from the website server in order to reduce the security risks (by creating a new user just for this purpose). Or can you trust the content of the cpp-Files?


text:
Q: gnome-keyring error sending email in mutt here is my .msmtprc :
defaults
account gmail
host smtp.gmail.com
from yy@gmail.com
port 587
auth on
tls on
tls_starttls on
tls_trust_file /etc/ssl/certs/ca-certificates.crt

user yy@gmail.com
password xxxxxxxx
logfile ~/.msmtp.log
account default:gmail

here is my  /etc/Muttrc
set sendmail="/usr/bin/msmtp"
set use_from=yes
set realname="xxxx"
set from="yy@gmail.com"
set envelope_from=yes
set charset="utf-8"
set send_charset="utf-8"
set locale="zh_CN.UTF-8"
set content_type="text/html\;charset=utf-8"

When I input:
echo "test" | mutt -s "subject"  xxxxx@163.com
WARNING: gnome-keyring:: couldn't connect to: /home/debian/.cache/keyring-HF6INk/pkcs11: No such file or directory

What is the matter?


text:
Q: Binding Image.Source to String in WPF? I have below XAML code :
<Window x:Class="WpfApplication1.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    DataContext="{Binding RelativeSource={RelativeSource Self}}"
    WindowStartupLocation="CenterScreen"
    Title="Window1" Height="300" Width="300">

    <Grid>
        <Image x:Name="TestImage" Source="{Binding Path=ImageSource}" />
    </Grid>

</Window>

Also, there is a method that makes an Image from a Base64 string :
Image Base64StringToImage(string base64ImageString)
{
    try
    {
        byte[] b;
        b = Convert.FromBase64String(base64ImageString);
        MemoryStream ms = new System.IO.MemoryStream(b);
        System.Drawing.Image img = System.Drawing.Image.FromStream(ms);

        //////////////////////////////////////////////
        //convert System.Drawing.Image to WPF image
        System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(img);
        IntPtr hBitmap = bmp.GetHbitmap();
        System.Windows.Media.ImageSource imageSource = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, Int32Rect.Empty, BitmapSizeOptions.FromEmptyOptions());

        Image wpfImage = new Image();
        wpfImage.Source = imageSource;
        wpfImage.Width = wpfImage.Height = 16;
        //////////////////////////////////////////////

        return wpfImage;
    }
    catch
    {
        Image img1 = new Image();
        img1.Source = new BitmapImage(new Uri(@"/passwordManager;component/images/TreeView/empty-bookmark.png", UriKind.Relative));
        img1.Width = img1.Height = 16;
        return img1;
    }
}

Now, I'm gonna bind TestImage to the output of Base64StringToImage method.
I've used the following way :
public string ImageSource { get; set; }
ImageSource = Base64StringToImage("iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAABGdBTUEAAK/INwWK6QAAABl0RVh0U29mdHdhcmUAQWRvYmUgSW1hZ2VSZWFkeXHJZTwAAABjUExURXK45////6fT8PX6/bTZ8onE643F7Pf7/pDH7PP5/dns+b7e9MPh9Xq86NHo947G7Hm76NTp+PL4/bHY8ojD67rc85bK7b3e9MTh9dLo97vd8/D3/Hy96Xe76Nfr+H+/6f///1bvXooAAAAhdFJOU///////////////////////////////////////////AJ/B0CEAAACHSURBVHjaXI/ZFoMgEEMzLCqg1q37Yv//KxvAlh7zMuQeyAS8d8I2z8PT/AMDShWQfCYJHL0FmlcXSQTGi7NNLSMwR2BQaXE1IfAguPFx5UQmeqwEHSfviz7w0BIMyU86khBDZ8DLfWHOGPJahe66MKe/fIupXKst1VXxW/VgT/3utz99BBgA4P0So6hyl+QAAAAASUVORK5CYIII").Source.ToString();

but nothing happen.
How can I fix it ?
BTW, I'm dead sure that the base64 string is correct

A: Let's break down what you're doing.
<Image Source="{Binding ImageSource}" />

For this to work, the binding source needs to be either an ImageSource, or a string representing a URI to an image file.  So let's take a look at what the ImageSource property actually is.
public string ImageSource { get; set; }

One problem here is that ImageSource isn't raising PropertyChanged events.  So WPF won't update the binding target when you update the property.
But also, ImageSource isn't an ImageSource, it's a string.  That's okay, but WPF is going to interpret that string as a URI.  What is that URI?
ImageSource = Base64StringToImage(BIG_HONKING_STRING).Source.ToString();

This is the nub of your problem.  The ImageSource string isn't actually a URI, because your image isn't an addressable resource.  Base64StringToImage creates an in-memory ImageSource from the base64 string, then return an Image with that as its Source.  Then you take the Image's Source (which is an ImageSource object), and stringise that.  That might work if the ImageSource had come from a file or URL, but it didn't: it came from a HBITMAP.  So the result of ToString() is going to be meaningless.  So ImageSource is being set to something meaningless, and your Image is trying to interpret this meaningless thing as the URL of a bitmap file.
So to fix this you need to do three things:

*

*Raise the PropertyChanged event for the ImageSource property (or make it a dependency property).

*Change the ImageSource property to be of type ImageSource instead of type string (so that it can contain URL-less image sources).

*Change your setter call to set ImageSource to Base64StringToImage(...).Source -- i.e. remove the ToString() call.  Better still, change Base64StringToImage to return an ImageSource rather than an Image: creating an Image element just creates overhead because all you're really interested in is the BitmapSource.

A: As a complement to @itowlson's excellent answer, this is what your code should look like:
// MainWindow.xaml
<Window x:Class="MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        Title="MainWindow" Height="350" Width="525">
    <DockPanel>
        <Image Source="{Binding ImageSource}" />
    </DockPanel>
</Window>

// MainWindow.xaml.cs
using System.ComponentModel;
using System.IO;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();

        var model = new MainModel();
        DataContext = model;

        model.SetImageData(File.ReadAllBytes(@"C:\Users\Public\Pictures\Sample Pictures\Desert.jpg"));
    }
}

class MainModel : INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public void SetImageData(byte[] data) {
        var source = new BitmapImage();
        source.BeginInit();
        source.StreamSource = new MemoryStream(data);
        source.EndInit();

        // use public setter
        ImageSource = source;
    }

    ImageSource imageSource;
    public ImageSource ImageSource
    {
        get { return imageSource; }
        set
        {
            imageSource = value;
            OnPropertyChanged("ImageSource");
        }
    }

    protected void OnPropertyChanged(string name)
    {
        var handler = PropertyChanged;
        if (null != handler)
        {
            handler(this, new PropertyChangedEventArgs(name));
        }
    }
}


text:
Q: iOS Game Player IDs I am going to work on a game project for the first time. I have some thoughts in pieces, but couldn't get all things to make sense.
The Game can only be played if the user is logged in.
Plan to let user has the following options to login:

*

*Game Center ID

*Facebook ID

*registered ID (email/username/password) with my server.

Question: does it make sense? Looks like there is no API to get user's Game Center ID, so that I can post it to my server.
For Facebook ID, I can get it and post to server.
Registered ID surely no programed.
I need those IDs to be posted to server because, I need to keep record in server for a game achievement award system by us, apart from Game Center's Leader Board.
Thanks in advance.

A: You can get a unique player ID for Game Center by playerID property of GKPlayer class. See GKPlayer Class Reference.

A: I was wrong, GameCenter actually does have a playerID API. developer.apple.com
Thanks.


text:
Q: iPhone 4 iOS5 Core Plot and ARC error:"The current deployment target does not support weak references" I've converted my project to iOS 5 and enabled ARC. Now I need to integrate core plot with the project. When I try to instantiate a sample controller included with the Core Plot, I get about 20 errors as follows:

The current deployment target does not support automated __weak references

I've explicitly said fno-objc-arc next to the controller's name in the build settings.
What else do I need to run core plot with ARC enabled?
Thank you!

A: While Inspire48's answer broadly covers the fact that __weak references are not supported in versions of iOS earlier than 5.0, this particular problem was due to Core Plot's headers not being made completely ARC compatible.
This was fixed in the Mercurial repository a few months ago, so if you want to use Core Plot within an ARC-enabled project, you need to grab the latest code from the repository. The 0.9 snapshot does not interact well with ARC because of items like this in its headers.
The Core Plot framework code in the repository also supports targeting back to iOS 4.0 and Snow Leopard with ARC enabled in your application (I believe 3.0 and Leopard without ARC, as well), so you don't need to target 5.0 to use ARC with Core Plot.

A: __weak references only work on iOS 5 and above. If you have the deployment target set to anything earlier, then you'll get the error. Basically, if you want to deploy to earlier devices you can't use automated __weak references. The substitute would be __unsafe_unretained

A: Change Development Targert 6.0.
Select Your Project > target > development target > change to 6.0


text:
Q: How to disable iframe console.log in React I am building an app that has a section that displays news. Every news item has a preview button, that displays the source of an iframe. All good, until I see that some news pages are console.log a lot. I have successfully turned off console.log for my app, but not for the iframe.
I have tried the following, but it's not working for my case:
const iFrameRef = React.useRef();

React.useEffect(() => {
    if(iFrameRef.current){
      const iframeWindow = iFrameRef.contentDocument;
      iframeWindow.console.log = function() { };
    }
  }, [iFrameRef]);

<iframe ref={iFrameRef} src={source} id="iFramePreview" />

What is the method to turn off console.log for an iframe?


text:
Q: What would you like to change about TeX/LaTeX/XeTeX/etc.? Like the title says, is there anything about the system you're using that you would like to change? Some annoyance that should be fixed, some feature that could be improved or added?

A: *

*I'd change the (0,0)-point of the page to be at the top left corner
of the paper, instead of assuming it's one inch from left and top (although note the later --compat).

*Some of the plain macros are defined in terms of points, I'd change
those to use em's and ex's instead (i.e., relative to the used typeface).

*If I were to re-implement TeX (lol!), I'd do it with a multi-paradigm high abstraction level language with a consistent syntax. Although I
do understand why one would seek to achieve efficiency over
everything else; to quote Knuth from TAOCP Vol. 1's Preface:

For example, some combinatorial calculcations need to be repeated a trillion times, and we save about 11.6 days of computation for every
  microsecond we can squeeze out of their inner loop.

That's a nice angle! But maybe not one which fits the nature of TeX,
though. At least not to the point where efficiency goes over
everything else. What with the compiler targeted instruction sets and all.
So I'd be choosing cost of programmer time over the cost of
computation time, and a language which has survived even longer than
TeX itself.
I'd make it backwards compatible with a toggle --compat, but without that option flag, it would handle math much in the same way Philippe describes with some additional exceptions for constants for example.
If I'd choose the other way around, efficiency over everything else, that just would have to be done in MMIX for a custom computer! ;-D
Daydreaming...

A: Transforming boxes to tokens and back
I very often find myself in a situation where I would like to

*

*find out exactly something which is "hidden" in a box (say, is there a hyphenation at a specific line, or how much is glue stretched)

*make a small modification to a box's contents

It is possible up to a degree to analyse box contents with \lastbox, but as the name already says, any kind of box content which is not a box or glue or kern or penalty (like rules, characters or specials) makes the analysis futile.
In particular, it is impossible this way to analyse and recursively reconstruct a box in a modified way, apart from trivial cases.
So I'd basically like two primitives:

*

*Transform a box into a token list

*Transform a token list (which was derived from a box) back into a box.

Needless to say, transforming a box into a token list and transforming that token list back to a box should always reconstruct the same box.
Mind you, I am not talking about transforming a box back into the tokens it was originally generated from (which would mean, say, "undoing" paragraph formatting), because that process is a "trapdoor" function.
All the tokens in the token list could be special just for representing box content, as long as I can analyse and modify the box in all respects by analysing the token list.
If you look into the log listing of a box:
..\vbox(548.5+0.0)x390.0, glue set 505.11273fil
...\write-{}
...\glue(\topskip) 3.66669
...\hbox(8.33331+2.33331)x390.0, glue set 320.08823fil
....\hbox(0.0+0.0)x17.62482
....\OT1/cmr/m/n/12 s
....\OT1/cmr/m/n/12 o

then I would be perfectly content to get everything listed there as a sequence of (nested) tokens, as long as all information and content is there in "parseable" form.

A: "Weak" groups
I've found myself quite a few times trying to temporarily modify a macro, but this method has some very real problems:
\bgroup <stuff> \def\x{\egroup <more stuff>} \x

In particular, if the first "<stuff>" defines any macros, they'll be lost when \x is performed. A certain kind of "weak" group that all \defs "escape" by default except stuff explicitly declared so would be nice. That way you could write stuff like this:
\bwgroup
  \let\a\relax
  % make any subsequent changes to \a local to this weak group:
  \weaken\a % or \weakencsname a\endcsname.
  <do stuff with \a>
  \let\b\relax
\ewgroup % the weak redefinition of \a disappears in a puff of logic.
\a\b % no error. They are both equal to \relax

instead of
\let\a\relax
\let\OLDa\a % and *hope* that \OLDa is not defined already
<do stuff with \a>
\let\a\OLDa
\let\OLDa\undefined % and *hope* that \undefined is actually undefined
\a

Exporting macros out of an enclosing group
If for no other reason than the fact that this would make writing packages safer since you would know that anything you didn't explicitly export could not pollute the global namespace (speaking of which... namespaces would be nice too)
\begingroup
  \begingroup
    \export1{\let\a\relax}
  \endgroup
  \a % no error. The definition of \a was exported 1 group level outwards.
\endgroup
%\a % error. \a is not defined here.

A: I'm missing a paragraph rebreak feature when part of a paragraph is carried to the next page during a page break. When one has to change the page width, e.g., from page 1 to page 2 of a letter, this would be very useful!

A: One area of TeX which needs to be improved is math spacing (starting from 2007, Word does better than TeX in this area). The TeXbook (in chapter 18) recommends quite a few manual adjustments most which could (and thus should) be automated (and the list is not complete). Here are a few examples, with the correct spacing below (the cos²+sin² is a bit subtle as it's a thin space instead of a medium space, but it is an important change since it also changes the shrinking and stretching values):

The problem is that the 8 spacing classes (\mathord, \mathop, \mathbin, \mathrel, \mathopen, \mathclose, \mathpunct and \mathinner) are not enough to cover all the cases. You would need at least the following supplementary classes: \mathnull (no spacing at all, for / and the backslash used as quotient), \mathfact (for factorials), \mathsqrt (for square roots) \mathdiff (for differentials in integrals) and \mathdpunct (for double punctuation like : and ; in French typography, in which you want a thin space both after and before).

A: TeX is a system written by a genius, and it has many great features, but the underlying architecture is flawed. The programming interface, and the programming mechanisms provided within the system contrast the intuition of most computer programmers. The list of idiosyncratic features is too long to enumerate:

*

*Character codes and non standard lexical analysis.

*Clumsy support for imperative programming, including numbered variables of a limited number, no variable names, no control flow, no boolean type, etc.

*Use of Pascal.

*Arbitrary constants and numbers (file numbers, character codes).

In short, if I could do it all over again, I would (a) use a decent modern programming language for the implementation (b) design a clean programming interface, including the usual tools of the trade, block structure, typed named variables, procedures, exceptions, and, yes, even object orientation.
Finally, I would (c) apply a clean design which does not reveal or discuss issues such as mouth, stomach, and \expandafter, and of course, I would write a book without dangerous curves signs...

A: Top 1 on my list: (1) better error messages and (2) better debugging facilities.

*

*I found it notoriously hard to understand LaTeX error messages, especially if "advanced" document classes (such as beamer) or packages (such as biblatex or hyperref) are involved. (For instance, with beamer frames the reported error location is often just the closing brace of the frame.)

*Even more difficult, at least for the beginner to intermediate developer, is the debugging of own macros. Using \show and \meaning is IMHO painful. What I really would like to have is a "symbolic" debugger where I could step through the expansion process to understand what is going on.

A: I think too many parameters and algorithms are "hard-wired" into the TeX engine, in particular when it comes to math typesetting. One example is the algorithm for placing a sub- and superscript combination, which sometimes leads to undesirable results, as I explained in this answer. (Very strange: The distance of a superscript from the baseline is at least 80% of the x-height  only if a subscript is present and by default too close to the superscript, otherwise the superscript is allowed to be lower.)
It would be great if some improvements in this direction could be included in LuaTeX.

A: I hope that the author of XeTeX spends some time and fixes XeTeX bidirectional primitives bugs and also adds few new primitives as already suggested. Doing bidirectional macro programming with various bugs and shortages of XeTeX in terms of bi-directionality, has been a headache for me.

A: Nice automagickal default spacing, alignment and line-breaking in display math mode and in tables, with the user not having to rake his/her brain about whether to split his gathered's or align his multline's or start his tables with {p{\wildguess}|cpr|@{h}lp||pl@{z}}. You should be able to write a really long equation, or a table, and for that to "just work".

A: For me, it's about simplification:
Package integration
Integrate some of the most common packages into LaTeX directly, e.g. array for tabular extensions, geometry for page dimensions, fancyhdr for headers and footers, etc.
I think we could determine a limited number of core packages that implement very common features, iron out whatever incompatibility / instability / missing feature they still exhibit and integrate them into LaTeX.
LaTeX currently require (trained) users to load the same packages over and over to do simple things like produce a right-aligned fixed-width tabular column, and, even worse, forces new users to waste time figuring out how to achieve this.
Package rationalization
Combine / throw out unmaintained or redundant packages. This is probably a very touchy topic, but I think having 5+ packages to achieve the same thing is a waste of resources. For example, shouldn't we agree that biblatex (example!, please don't shoot me...) is the way to go for bibliographies, integrate whatever missing features from natbib, multibib, etc. and slowly depreciate these packages?
It would be very challenging to find the right balance on when this "rationalization" should kick in (we shouldn't discourage anyone from creating new packages), but I believe that sometimes there is too much choice for beginners, and too much work for class / package writers that want to ensure compatibility.
Engine & fonts
This is a long shot, but if we could move everyone over to LuaTeX, integrate fontspec (see first point) and provide a base of great fonts in Open Type (no more Type 1, no more cm-super etc.), I believe TeX would be more attractive to more people.
Or to put it differently, I think that a combination of a simplified font system / handling with a selection of great free fonts (from such foundries as The League of Movable Type, exljbris, etc) would attract a much more broader base of "regular" and "creative" users than today.

A: Surprisingly high on my list: not calling that verbatim-handling macro \next. I think

"file ended while scanning use of
  \next"

(or whatever the phrasing is) is the archetypical meaningless error which you have no chance to fix unless you happen to already know it's caused by the \end{...} of your verbatim-like environment not starting on column 0. I think somebody reading the code would have less problems with a not-quite-appropriately-named \getnextverbatimline or whatnot than the normal user has with \next.


text:
Q: MVC Text Box Validation Greetings, bit of an issue with some validation...
Model:
public class Class1
{
    [Required(AllowEmptyStrings = false, ErrorMessage="Error")]
    public String test { get; set; }
}

Controller:
public class HomeController : Controller
{
    //
    // GET: /Home/

    public ActionResult Index()
    {
        return View();
    }
    public ActionResult TestClick()
    {
        return View();
    }
}

View:

Index

@using (Html.BeginForm())
{
    @Html.ValidationSummary(true);
    @Html.EditorFor(mod => mod.test)
    @Html.ValidationMessageFor(mod => mod.test);
    Test
}

The TestClick() fires and does the post on first load without being validated...if text is changed validation prevents the post...how to validate before the jquery post??


text:
Q: Replace last 4 with asterisks in PHP Hi there i am trying to hide the customers name and i wants to hide only the last 4 with asterisks currently i have this code but it hides the entire name after 4 digits but thats not what i want
$arr[$idx]['consignee']  = $row['consignee'];

i managed to hide the name using this code below but it hides all after 4
            $arr[$idx]['consignee'] = '1' > 0 ?
                                    sub_str($row['consignee'], '5') : $row['consignee'];

Any sample or suggestion please.

A: Like this
 $arr[$idx]['consignee'] = preg_replace('/.{4}$/', '****',  $arr[$idx]['consignee']);

Try it here online
OR substr ( for those that think regx is overkill )
 $arr[$idx]['consignee'] = substr($arr[$idx]['consignee'], 0, -4).'****';

For testing
 $idx = 0;
 $arr = [[
     'consignee' => 'someguy'
 ]];

 $arr[$idx]['consignee'] = substr($arr[$idx]['consignee'], 0, -4).'****';

 echo $arr[$idx]['consignee'];

Try it here online


text:
Q: How to embed "input(id)" into URL in GET request using Python? A'm just a beginner in Python. Please, help me with such problem:
I have API documentation (Server allowed methods):
GET, http://view.example.com/candidates/, shows a
candidate with id=. Returns 200
I write such code:
import requests

url = 'http://view.example.com/candidates/4'
r = requests.get(url)
print r

But I want to now how can I put id of candidate through "input()" builtin-function instead of including it to URL.
There is my efforts to do this:
import requests
cand_id = input('Please, type id of askable candidate: ')
url = ('http://view.example.com/candidates' + 'cand_id')
r = requests.get(url)
print r
dir(r)
r.content

But it's not working...

A: you're using the string 'cand_id' instead of the variable cand_id. The string creates a url of 'http://view.example.com/candidatescand_id'

A: You can do this to construct the url:
url = 'http://view.example.com/candidates'
params = { 'cand_id': 4 }
requests.get(url, params=params)

Result: http://view.example.com/candidates?cand_id=4
--
Or if you want to build the same url as you mentioned in your post:
url = 'http://view.example.com/candidates'
cand_id = input("Enter a candidate id: ")
new_url = "{}/{}".format(url, cand_id)

Result: http://view.example.com/candidates/4


text:
Q: WidgetKit: Can't add custom image to view My error:
The body of the Widget entries' view contains an image of size (512.0, 662.0) which is beyond the maximum of (463.2, 196.79999999999998)
==================================
Error:
|  MessageSendFailure: Message send failure for <ServiceMessage 41: update>

My code:
ZStack {
    VStack {
        Image("man")
            .resizable()
            .frame(width: 100, height: 100)
    }
}

Help me please. Thank you!