text:
Q: Copying Data From Excel to Word without overwriting existing text I have a report in Excel that I run every day. I pull the report from an email, do some filtering, write down some numbers and copy some of the table info from the Excel report.
The table in Excel, let's say it has data in columns A-Z. I'm trying to copy data from Excel and into Word based on certain filtering criteria. I have most of that down.
When I copy the filtered table from Excel into Word, and the table is being pasted beneath some text, the table overwrites the text in the Word document.
Const olFolderInbox As Integer = 6
'~~> Path for the attachment
Const AttachmentPath As String = "C:\Users\....."

Sub DownloadAttachmentFirstUnreadEmail()
Dim oOlAp As Object, oOlns As Object, oOlInb As Object, LastRow As Long, objDoc As Object, objWord As Object, objSelection As Object, nonProdCount As Integer, nonProdDT As Integer
Dim oOlItm As Object, oOlAtch As Object, fname As String, sFound As String, totalRowCount As Integer, wFound As String, wdRange As Word.Range, str As String, nonProdCopyToWord As Long
Dim wb As Workbook, uRng As Range

'~~> New File Name for the attachment
Dim NewFileName As String
NewFileName = "MorningOpsFile " & Format(Date, "MM-DD-YYYY")
'~~> Get Outlook instance
Set oOlAp = GetObject(, "Outlook.application")
Set oOlns = oOlAp.GetNamespace("MAPI")
Set oOlInb = oOlns.GetDefaultFolder(olFolderInbox).Folders("Folder Name Here")
Set objWord = CreateObject("Word.Application")
Set objDoc = objWord.Documents.Add
objWord.Visible = True
Set objSelection = objWord.Selection

'~~> Check if there are any actual unread emails
If oOlInb.Items.Restrict("[UnRead] = True").Count = 0 Then
    MsgBox "NO Unread Email In Inbox"
    Exit Sub
End If

'~~> Extract the attachment from the 1st unread email
For Each oOlItm In oOlInb.Items.Restrict("[UnRead] = True")
    '~~> Check if the email actually has an attachment
    If oOlItm.Attachments.Count <> 0 Then
        For Each oOlAtch In oOlItm.Attachments
            '~~> Download the attachment
            oOlAtch.SaveAsFile NewFileName & oOlAtch.Filename
            Exit For
        Next
    Else
        MsgBox "The First item doesn't have an attachment"
    End If
    Exit For
Next

'~~> Mark 1st unread email as read
For Each oOlItm In oOlInb.Items.Restrict("[UnRead] = True")
    oOlItm.UnRead = False
    DoEvents
    oOlItm.Save
    Exit For
    Next
'--> Search for downloaded file without knowing exact filename
sFound = Dir(ActiveWorkbook.Path & "\*File Search String*.xlsx")
If sFound <> "" Then
Workbooks.Open Filename:=ActiveWorkbook.Path & "\" & sFound
End If

Set uRng = ActiveSheet.Range("A1:A2")

'--> Set variable for last row in sheet containing data
LastRow = Sheets("Sheet1).Cells(Rows.Count, 1).End(xlUp).Row

'--> Apply filter to look for today's changes
With Sheets("Sheet 1").Select
Range("$A$1:AB" & LastRow).AutoFilter Field:=3, Criteria1:= _
    xlFilterToday, Operator:=xlFilterDynamic
    '--> Get a total row count of today's changes
 totalRowCount = ActiveSheet.AutoFilter.Range.Columns(1).SpecialCells(xlCellTypeVisible).Cells.Count - 1
 '--> Printout total rowcount number
' MsgBox totalRowCount

Set objDoc = objWord.Documents.Open("C:\Users\....docx")
objWord.Visible = True
'objWord.Activate
objDoc.Content.Select
objDoc.Content.Delete
objWord.Selection.TypeText vbNewLine
objWord.Selection.TypeText "Good Morning All" & vbNewLine
objWord.Selection.TypeText "We have " & totalRowCount & " total current day changes" & vbNewLine
End With

'--> Filter for non-Prod changes
ActiveSheet.Range("$A$1:AB" & LastRow).AutoFilter Field:=10, Criteria1:="QA", _
        Operator:=xlOr, Criteria2:="Development"
'-->Count non-Prod changes
nonProdCount = ActiveSheet.AutoFilter.Range.Columns(1).SpecialCells(xlCellTypeVisible).Cells.Count - 1
'--> Put count of non-Prod changes in Word document
objWord.Selection.TypeText "We have " & nonProdCount & " non-production changes" & vbNewLine
'--> Filter for non-Prod changes with downtime
ActiveSheet.Range("$A$1:AB" & LastRow).AutoFilter Field:=11, Criteria1:="<>", _
    Operator:=xlAnd
'--> Count non-Prod changes with downtime
nonProdDT = ActiveSheet.AutoFilter.Range.Columns(1).SpecialCells(xlCellTypeVisible).Cells.Count - 1
'--> Add non-prod downtime count to Word
objWord.Selection.TypeText nonProdDT & " with downtime" & vbNewLine

'--> Copy non-Prod rows with downtime from Excel to Word
'Set uRng = Union(Range("A1:A" & LastRow).SpecialCells(xlCellTypeVisible), (Range("G1:H" & LastRow).SpecialCells(xlCellTypeVisible)))
'uRng.Copy
ActiveSheet.Range("B1:F" & LastRow).EntireColumn.Hidden = True
ActiveSheet.Range("N1:Q" & LastRow).EntireColumn.Hidden = True
ActiveSheet.Range("Z1:AB" & LastRow).EntireColumn.Hidden = True

ActiveSheet.Range("A1:Y" & LastRow).SpecialCells(xlCellTypeVisible).Copy

objWord.Selection.TypeText vbNewLine
objDoc.Content.Paste

End Sub

How can I copy the filtered table in Excel to Word without overwriting what is in the Word document?

A: This is your problem:
objWord.Selection.TypeText vbNewLine
objDoc.Content.Paste

objDoc.Content is the entire main body of the document - the entire "content", excluding headers, footers, any text in objects that have "text wrap" formatting, etc.
You can use objWord.Selection.Paste, analog to the first line, above.
Perferable, from a programmer's perspective, would be to work with Word Range objects. Something like:
Dim wdRange as Object
Set wdRange = objWord.Selection.Range
wdRange.InsertParagraph
wdRange.Collapse 0
wdRange.Paste

The reason this is considered preferable is that not relying on Selection is more reliable. Theoretically, something could change the Selection while your code is running. A Range will remain static. This also makes it easier to understand where things are being inserted/manipulated (the code is more "self-documenting").


text:
Q: Unity: Fatal Execution Engine Error when resolving a TimeSpan I am trying to resolve a TimeSpan using Unity. Executing the container Resolve call results in a FatalExecutionEngineError.

FatalExecutionEngineError was detected
  Message: The runtime has encountered a fatal error. The address of the error was at 0x543c3dc8, on thread 0x1bb8. The error code is 0xc0000005. This error may be a bug in the CLR or in the unsafe or non-verifiable portions of user code. Common sources of this bug include user marshaling errors for COM-interop or PInvoke, which may corrupt the stack.

Running the test in DEBUG causes the following file to be requested by the debugger.

X:\Unity\Src\ObjectBuilder\Strategies\BuildPlan\DynamicMethod\DynamicMethodBuildPlan.cs

And it shows the following ExecutionEngineException on line 38.

System.ExecutionEngineException was unhandled
    Message="Exception of type 'System.ExecutionEngineException' was thrown."
    InnerException:

Test
[TestClass]
public class Example
{
    private readonly IUnityContainer container = new UnityContainer();

    [TestInitialize]
    public void TestInitialize()
    {
        container.Register<TimeSpan>(new ExternallyControlledLifetimeManager());
    }

    [TestMethod]
    public void Test()
    {
        var expected = new TimeSpan();
        var actual = container.Resolve<TimeSpan>();
        Assert.AreEqual(expected, actual);
    }
}

A: I'm not sure why you get the error, but I tried to replace the type configuration (in the configuration file you edited out) with the following it works.
<instances>
   <add name="MyTimeSpan" type="System.TimeSpan" value="1.02:03:04"  />
</instances>

var duration = container.Resolve<TimeSpan>("MyTimeSpan");

The above should return a timespan with a duration of 1 day, 2 hours, 3 minutes and 4 seconds.
(I tried this with Unity 4.1)

A: Fatal Execution Engine Error when resolving a TimeSpan
I posted this issue on the Unity CodePlex site. It has been answered.

In current bits you get the proper "InvalidOperationException". TimeSpan has multiple constructors, and by default it picks the four-argument one, and then doesn't know what ints to supply. Structs don't actually have a zero-argument constructor, the clr "cheats" under the hood.

The solution is to tell Unity which constructor to use.
container.Register<TimeSpan>(new ExternallyControlledLifetimeManager(),
    new InjectionConstructor(0L));

redpajama_set_name: RedPajamaStackExchange


text:
Q: Sharepoint 2010 I need help.
How do I programatically create a list of external links where you can choose if you want to open the link in a new window or not?

A: If i have understood what you are asking then I did something similar for SP2003:

*

*Add a column to the Link list called 'New Window' of type 'Yes/No'

*Using FrontPage (it was a while ago) I modifed the XSLT for the view (it was the only view and accessed via a listview webpart on the homepage): if New Window = Yes then render the link with target="_blank"
I think the theory for SP2010 should be the same.
Or you could just let the users decide.


text:
Q: Spark ML ALS collaborative filtering always fail if the iteration more than 20 My data set's size is about 3G and has 380 million datas. Always wrong if I add iteration steps. And increase memory, increase block or decrease block, decrease checkpoint cannot solve my problem.
Caused by: java.net.ConnectException: Connection refused (Connection refused) at java.net.PlainSocketImpl.socketConnect(Native Method)
The method introduced to set small checkpoint cannot solve my problem.
StackOverflow-error when applying pyspark ALS's "recommendProductsForUsers" (although cluster of >300GB Ram available)
This is the DataFrame for ALS training, which is about 380 million rows.
+---------+-----------+------+
| user_id|item_id|rating|
+---------+-----------+------+
|154317644|      58866|     6|
| 69669214|     601866|     7|
|126094876|     909352|     3|
| 45246613|    1484481|     3|
|123317968|    2101977|     3|
|   375928|    2681933|     1|
|136939309|    3375806|     2|
|  3150751|    4198976|     2|
| 87648646|    1030196|     3|
| 57672425|    5385142|     2|
+---------+-----------+------+

This is the code to train ALS.
val als = new ALS()
  .setMaxIter(setMaxIter)
  .setRegParam(setRegParam)
  .setUserCol("user_id")
  .setItemCol("item_id")
  .setRatingCol("rating")
  .setImplicitPrefs(false)
  .setCheckpointInterval(setCheckpointInterval)
  .setRank(setRank)
  .setNumItemBlocks(setNumItemBlocks)
  .setNumUserBlocks(setNumUserBlocks)

val Array(training, test) = ratings.randomSplit(Array(0.9, 0.1))
val model = als.fit(training)   // wrong in this step

This is the ALS source code where error happens.
val srcOut = srcOutBlocks.join(srcFactorBlocks).flatMap {
  case (srcBlockId, (srcOutBlock, srcFactors)) =>
    srcOutBlock.view.zipWithIndex.map { case (activeIndices, dstBlockId) =>
      (dstBlockId, (srcBlockId, activeIndices.map(idx => srcFactors(idx))))
    }
}

This is the Exception and Error logs.
    18/08/23 15:05:43 WARN metastore.ObjectStore: Failed to get database global_temp, returning NoSuchObjectException
18/08/23 15:13:35 WARN scheduler.TaskSetManager: Lost task 20.0 in stage 56.0 (TID 31322, 6.ai.bjs-datalake.p1staff.com, executor 9): java.lang.StackOverflowError
    at java.io.ObjectInputStream$PeekInputStream.readFully(ObjectInputStream.java:2669)
    at java.io.ObjectInputStream$BlockDataInputStream.readInt(ObjectInputStream.java:3170)
    at java.io.ObjectInputStream.readHandle(ObjectInputStream.java:1678)

18/08/23 15:13:35 WARN server.TransportChannelHandler: Exception in connection from /10.191.161.108:23300
java.io.IOException: Connection reset by peer
    at sun.nio.ch.FileDispatcherImpl.read0(Native Method)
    at sun.nio.ch.SocketDispatcher.read(SocketDispatcher.java:39)
    at sun.nio.ch.IOUtil.readIntoNativeBuffer(IOUtil.java:223)
    at sun.nio.ch.IOUtil.read(IOUtil.java:192)
    at sun.nio.ch.SocketChannelImpl.read(SocketChannelImpl.java:380)

18/08/23 15:13:36 ERROR cluster.YarnClusterScheduler: Lost executor 15 on 2.ai.bjs-datalake.p1staff.com: Container marked as failed: container_e04_1533096025492_4001_01_000016 on host: 2.ai.bjs-datalake.p1staff.com. Exit status: 50. Diagnostics: Exception from container-launch.
Container id: container_e04_1533096025492_4001_01_000016
Exit code: 50
Stack trace: ExitCodeException exitCode=50:
    at org.apache.hadoop.util.Shell.runCommand(Shell.java:585)
    at org.apache.hadoop.util.Shell.run(Shell.java:482)

18/08/23 15:05:43 WARN metastore.ObjectStore: Failed to get database global_temp, returning NoSuchObjectException
18/08/23 15:13:35 WARN scheduler.TaskSetManager: Lost task 20.0 in stage 56.0 (TID 31322, 6.ai.bjs-datalake.p1staff.com, executor 9): java.lang.StackOverflowError
    at java.io.ObjectInputStream$PeekInputStream.readFully(ObjectInputStream.java:2669)
    at java.io.ObjectInputStream$BlockDataInputStream.readInt(ObjectInputStream.java:3170)
    at java.io.ObjectInputStream.readHandle(ObjectInputStream.java:1678)
    at java.io.ObjectInputStream.readClassDesc(ObjectInputStream.java:1739)

18/08/23 15:13:36 ERROR cluster.YarnClusterScheduler: Lost executor 10 on 5.ai.bjs-datalake.p1staff.com: Container marked as failed: container_e04_1533096025492_4001_01_000011 on host: 5.ai.bjs-datalake.p1staff.com. Exit status: 50. Diagnostics: Exception from container-launch.
Container id: container_e04_1533096025492_4001_01_000011
Exit code: 50
Stack trace: ExitCodeException exitCode=50:
    at org.apache.hadoop.util.Shell.runCommand(Shell.java:585)
    at org.apache.hadoop.util.Shell.run(Shell.java:482)
    at org.apache.hadoop.util.Shell$ShellCommandExecutor.execute(Shell.java:776)
    at org.apache.hadoop.yarn.server.nodemanager.DefaultContainerExecutor.launchContainer(DefaultContainerExecutor.java:212)
    at org.apache.hadoop.yarn.server.nodemanager.containermanager.launcher.ContainerLaunch.call(ContainerLaunch.java:302)
    at org.apache.hadoop.yarn.server.nodemanager.containermanager.launcher.ContainerLaunch.call(ContainerLaunch.java:82)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1149)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:624)
    at java.lang.Thread.run(Thread.java:748)

Is anybody meet this error?

A: After set the check point directory, it works. Thank @eliasah
spark.sparkContext.setCheckpointDir("hdfs://datalake/check_point_directory/als")
Check point will not work if you do not set the directory.


text:
Q: How is each byte in an integer stored in CPU / memory? i have tried this
char c[4];
int i=89;
memcpy(&c[0],&i,4);
cout<<(int)c[0]<<endl;
cout<<(int)c[1]<<endl;
cout<<(int)c[2]<<endl;
cout<<(int)c[3]<<endl;

the output is like:
89
0
0
0
which pretty trains my stomache cuz i thought the number would be saved in memory like
0x00000059 so how come c[0] is 89 ? i thought it is supposed to be in c[3]...

A: Endian-ness is obviously the answer as Goz has pointed out.
But for those who are unclear of what that means, it's also important to understand that the order of bytes displayed in the example is the same as the order in the original int.  Memcpy doesn't change the byte order, regardless of the edian type of the platform.

A: Because byte order is an arbitrary design decision. Once in a register, there is no byte order1.
Byte order arises when we address smaller units like bytes.  It's an essentially arbitrary decision the CPU designer gets to make: big-endian or little-endian.
It's useful to simplify the situation and realize that it is mainly the connection to peripherals that is byte ordered. Yes, it can be discovered via byte addressing as you have proved, but in general scalar values are loaded and stored as units, into registers, and in this case byte order doesn't change anything. The most significant bits are on "the left", at least, the way we usually write numbers. And that's why the << and >> operators always produce the exact same results on big-endian vs little-endian machines when used according to the language standards.
But in order to read and write data streams to peripheral devices, you are forced to choose a byte order. This is because peripherals are fundamentally byte stream devices. Does the lowest address have the most significant bits or the least?  It's done both ways and the camps used to be rather evenly divided.
Because memory itself is byte addressed, it's certainly possible to derive different behavior without a peripheral, but this typically doesn't happen without a deliberate peek inside like you did.
Imagine a CPU that has no bytes, only 32-bit words, addressed as 0, 1, 2. The C compiler makes char, int, and long all 32-bit objects. (This is allowed by Cx9.)  Wow, no byte order issues! It's both! But .. what happens when we hook up our first peripheral??

1.Well, x86 has registers that alias smaller registers, but that's another story.

A: Because the processor you are running on is little-endian.  The byte order, of a multi-byte fundamental type, is swapped.  On a big-endian machine it would be as you expect.

A: Different machines can have different byte ordering, but take a look at this code and think about what happens, depending on how the bytes are laied out:
long x = 89;
short *p = (short*)&x;
short y = *p;

A: This is because you're running the program on a little endian cpu. See also endianness here and there.

A: If you want your application to be portable or developed within a team, you probably don't want to follow this logic as it would cause hard to catch bugs and prolong development.


text:
Q: Two-stage linear regression If I do regression in two stages:

Stage 1: $y\sim x_1 + 1$
Stage 2: resid_1st_stage $\sim x_2 + 1$

Will the resid_2nd_stage be orthogonal to $x_1$?

A: Suppose that the two models involved are:
$\newcommand{\Cov}{\mathrm{Cov}}$
$y=\alpha_1 + \beta_1 x_1 + \epsilon_1$
and
$\hat\epsilon_1=\alpha_2 + \beta_2 x_2 + \epsilon_2$
The process goes as follows:
1: estimates of $\hat \beta_1$ and $\hat\alpha_1$ (assuming OLS validity)
2: calculate the residuals $\hat\epsilon_1=y-\hat\alpha_1-\hat\beta_1x_1$
3: repeat the above with the second model, thus obtaining $\hat\epsilon_2=\hat\epsilon_1-\hat\alpha_2-\hat\beta_2x_2$
4: check that $\Cov(\hat\epsilon_2,x_1)=0$:
$\Cov(\hat\epsilon_2,x_1)=\Cov(\hat\epsilon_1-\hat\alpha_2-\hat\beta_2x_2,x_1)=
\Cov(y-\hat\alpha_1-\hat\beta_1x_1
-\hat\alpha_2-\hat\beta_2x_2,x_1)=
\Cov(y-\hat\beta_1x_1
-\hat\beta_2x_2,x_1)$
Which is clearly not null, given the presence of $x_1$ itself in the result, by which
$\Cov(\hat\beta_1x_1,x_1)=\hat\beta_1\sigma_{x_1}^2$
not to mention the interaction between $y$ and $x_1$ or $x_1$ and $x_2$.


text:
Q: What is the core of the cubic 3-fold? Let $X$ be a compact, smooth, $1$-connected, orientable $6$-manifold with torsion free homology, then (from Wall's classification) $X$ has a (smooth) connect sum decomposition $X \cong X_{0} \#_{k} S^{3} \times S^3$ (i.e. the connect sum of $X_{0}$ with k copies of $S^{3} \times S^{3}$), where $b_{3}(X_{0}) = 0$ and $2k = b_{3}(X)$.
We refer to $X_{0}$ as the core of $X$ (following section 5 of "Cubic forms and Complex 3-folds" by Okonek and van de Ven).
Question: How to compute the core $X_{0}$ of a smooth cubic hypersurface $X \subset \mathbb{C} \mathbb{P}^{4}$, so that $X \cong X_{0} \#_{5} S^3 \times S^3$?
Is there a general method to find the core of a smooth projective $3$-fold (over $\mathbb{C}$, with $b_{3}(X) \neq 0$ and trivial $\pi_{1}$)?


text:
Q: Can you assign AWS parameter store data source's value to a variable in Terraform? I am trying to read a value from AWS Parameter Store and assign its value to a variable.
# data source
data "aws_ssm_parameter" "environment" {
  name = "environment"
}

# variable
variable "environment" {
  type        = string
  description = "AWS Environment Name"
  default     = data.aws_ssm_parameter.environment.value
}

Is this possible?
I know you can use data.aws_ssm_parameter.environment.value wherever I need to use a variable but is it possible to simplify it by assigning it to a variable.

A: That is not possible. However, you can use local variables [1] for that. For example:
locals {
  environment = data.aws_ssm_parameter.environment.value
}

You would then reference that value elsewhere in the code with local.environment.

[1] https://developer.hashicorp.com/terraform/language/values/locals


text:
Q: Specializing templates in namespaces - is namespace alias really an alias? I'm trying to provide a hash<> specialization for a family of types I've been working on. So far so good, the specialization itself is easy to provide, I've already done similar things for numeric_limits<>. But I'm facing the problem of how to provide the specialization in a way that is portable to C++11 and -pre-11 (C++03 or whatever).
The problem I'm bumping on, of course, is that hash<> can be defined in one of several namespaced, and I'm forced to provide the specialization in the same namespace.
// in c++11
namespace std { struct hash<>...; }
// in c++03 this is one possibility
namespace std { namespace tr1 { struct hash<>...; } }

// my library's specialization
namespace ????_open {
struct hash<mytype>...;
????_close

Of course, one option would be using #defines to reach, open and close the adequate namespaces, or providing N files with N different specializations and conditionally #include the correct one, but that's cumbersome:
#if defined(some_c++11_condition)
  #include "c++11-specialization.h"
#elif defined(some_c++03_condition)
  #include "c++03-specialization.h"
#elif (some_other_condition)
  #oh_dear_who_knows_what_this_include_will_be_like
#else_ad_nauseam
#endif

Of course, I'll be sticking to that strategy if I'm forced to but I wanted to explore some other options before. In particular, I though I could use namespace alias to specialize in the correct place:
#if defined(some_c++11_condition)
  namespace std_specialize = std;
#elif defined(some_c++03_condition)
  namespace std_specialize = std::tr1;
#...
#endif

...

namespace std_specialize {
struct hash<mytype>...;
}

Unfortunately this doesn't work in any of the 3 compilers I have tried (MSVC 2008, GCC 4.7, Clang 3.0) with various errors regarding "declaration of namespace conflicts with..." in the line that reopens the namespace, which shouldn't happen because namespaces can be reopened multiple times, and if an alias is an alias and not something else then this should also apply for them.
So, is a namespace alias really an alias, or a misnomer meaning something else? Or is there other reason why I can not specialize this way? If so, any other method (better than barrages of #defines)?

A: Yes, a namespace alias is really an alias. The error is occurring because you're declaring std_specialize as an alias for either std or std::tr1 and then trying to declare a namespace with the same name. If it were legal, after that declaration, what would std_specialize refer to, std(or std::tr1) or the new namespace containing your hash specialization?
What you probably want to do is
namespace std {
#if __cplusplus < 201103L
namespace tr1 {
#endif

template<>
struct hash<my_type> { ... };

#if __cplusplus < 201103L
}
#endif
}

A: Proper macros:
// Defined before
// #define NOEXCEPT noexcept

#include <iostream>

#if TR1_CONDITION
// tr1
    #define HASH_NAMESPACE std::tr1
    #define HASH_NAMESPACE_BEGIN namespace std { namespace tr1 {
    #define HASH_NAMESPACE_END }}
#else
// std
    #define HASH_NAMESPACE std
    #define HASH_NAMESPACE_BEGIN namespace std {
    #define HASH_NAMESPACE_END }
#endif

namespace X {
    struct Class {};
}

HASH_NAMESPACE_BEGIN
    template<>
    struct hash<X::Class>  {
        size_t operator()(const X::Class&) const NOEXCEPT { return 123; }
    };
HASH_NAMESPACE_END

int main() {
    HASH_NAMESPACE::hash<X::Class> h;
    std::cout << h(X::Class()) << std::endl;
    return 0;
}

(But all of it is not nice)


text:
Q: OutOfMemoryError: unable to create new native thread using ExecutorService I launched my instance overnight to see how it handled things and when I came by this morning, I was facing a
Exception in thread "pool-535-thread-7" java.lang.OutOfMemoryError: unable to create new native thread
    at java.lang.Thread.start0(Native Method)
    at java.lang.Thread.start(Thread.java:691)
    at java.util.concurrent.ThreadPoolExecutor.addWorker(ThreadPoolExecutor.java:943)
    at java.util.concurrent.ThreadPoolExecutor.processWorkerExit(ThreadPoolExecutor.java:992)[info] application - Connecting to server A
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:603)
    at java.lang.Thread.run(Thread.java:722)

The aim of my code is quite simple : Every 5 minutes, I connect to a list of remote server, send a request (via socket) and that's it.
Here's my code :
My "cron" task :
/** will create a new instance of ExecutorService every 5 minutes, loading all the websites in the database to check their status **/
/** Maybe that's where the problem is ? I need to empty (GC ?) this ExecutorService ? **/
Akka.system().scheduler().schedule(
    Duration.create(0, TimeUnit.MILLISECONDS), // Initial delay 0 milliseconds
    Duration.create(5, TimeUnit.MINUTES),     // Frequency 5 minutes
    new Runnable() {
        public void run() {
            // We get the list of websites to check
            Query<Website> query = Ebean.createQuery(Website.class, "WHERE disabled = false AND removed IS NULL");
            query.order("created ASC");
            List<Website> websites = query.findList(); // Can be 1, 10, 100, 1000. In my test case, I had only 9 websites.

            ExecutorService executor = Executors.newFixedThreadPool(NTHREDS);
            for (Website website : websites) {
                CheckWebsite task = new CheckWebsite(website);
                executor.execute(task);
            }

            // This will make the executor accept no new threads
            // and finish all existing threads in the queue
            executor.shutdown();
        }
    },
    Akka.system().dispatcher()
);

My CheckWebsite class :
public class CheckWebsite implements Runnable {
    private Website website;

    public CheckWebsite(Website website) {
        this.website = website;
    }

    @Override
    public void run() {
        WebsiteLog log = website.checkState(); // This is where the request is made, I copy paste the code just after
        if (log == null) {
            Logger.error("OHOH, WebsiteLog should not be null for website.checkState() in CheckWebsite class :s");
            return;
        }

        try {
            log.save();
       catch (Exception e) {
            Logger.info ("An error occured :/");
            Logger.info(e.getMessage());
            e.printStackTrace();
        }
    }
}

My checkState() method in Website.class :
public WebsiteLog checkState() {
    // Since I use Socket and the connection can hang indefinitely, I use an other ExecutorService in order to limit the time spent
    // The duration is defined via Connector.timeout, Which will be the next code.

    ExecutorService executor = Executors.newFixedThreadPool(1);

    Connector connector = new Connector(this);
    try {
        final long startTime = System.nanoTime();

        Future<String> future = executor.submit(connector);
        String response = future.get(Connector.timeout, TimeUnit.MILLISECONDS);

        long duration = System.nanoTime() - startTime;

        return PlatformLog.getLastOccurence(this, response, ((int) duration/ 1000000));
    }
    catch (Exception e) {
        return PlatformLog.getLastOccurence(this, null, null);
    }
}

Here's the Connector.class. I removed useless part here (like Catches) :
public class Connector implements Callable<String> {
    public final static int timeout = 2500; // WE use a timeout of 2.5s, which should be enough

    private Website website;

    public Connector(Website website) {
        this.website = website;
    }

    @Override
    public String call() throws Exception {
        Logger.info ("Connecting to " + website.getAddress() + ":" + website.getPort());
        Socket socket = new Socket();

        try {
            socket.connect(new InetSocketAddress(website.getIp(), website.getPort()), (timeout - 50));
            BufferedReader input = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            String response = input.readLine();
            socket.close();

            return response;
        }
        catch (Exception e) {
            e.printStackTrace();
            throw e;
        }
        finally {
            // I take the precaution to close the socket here in order to avoid a memory leak
            // But if the previous ExecutorService force the close of this thread before
            // I can't guarantee it will be closed :/
            if (socket != null && !socket.isClosed()) {
                socket.close();
            }
        }
    }
}

I'm new to Java multithreading so I probably made big mistake. I suspect some area that could be potentially the reason, but my lack of knowledge requires me to ask for your help :)
As a summary, here's the potentials areas :

*

*Creating a new ExecutorService every 5 minutes. Maybe I can reuse the old one ? Or do I need to close the current one when finished (if so, how ?).

*The fact that I create an ExecutorService that will create an ExecutorService (in the checkstate() method)

*The fact that the Connector class can be (violently) stopped by the ExecutorService running it, if it takes too long, resulting in a socket not closed (and then a memory leak) ?

Also, as you can see, the exception occured for the thread "pool-535-thread-7" which mean it didn't happen soon.
I store the last_occured check in the database, and the creation of the log entry (in WebsiteLog), the delta is around 5 hours (so, for every 5 minutes, the thread crashed after around 60 calls).
Update : Here's the revisited checkState method to include the shutdown call :
public PlatformLog checkState() {
    ExecutorService executor = Executors.newFixedThreadPool(1);

    Connector connector = new Connector(this);
    String response = null;
    Long duration = null;

    try {
        final long startTime = System.nanoTime();

        Future<String> future = executor.submit(connector);
        response = future.get(Connector.timeout, TimeUnit.MILLISECONDS);

        duration = System.nanoTime() - startTime;
    }
    catch (Exception e) {}

    executor.shutdown();
    if (duration != null) {
        return WebsiteLog.getLastOccurence(this, response, (duration.intValue()/ 1000000));
    }
    else {
        return WebsiteLog.getLastOccurence(this, response, null);
    }
}

A: I'm not sure this is the only problem, but you are creating an ExecutorService in your checkState() method but you don't shut it down.
According to the JavaDocs for Executors.newFixedThreadPool():

The threads in the pool will exist until it is explicitly shutdown.

The threads staying alive will cause the ExecutorService not to be garbage collected (which would call shutdown() on your behalf. Hence you are leaking a thread each time this is called.


text:
Q: Getting historical values from higher timeframes I've built a custom indicator and I've plotted them using dots on top of candles. When a dot meets a certain criteria with another dot, I draw a trend line connecting them. That works..
What I would like to do is augment these lines from higher timeframes since I typically trade on the 5m. Meaning, if these dots on the daily timeframe meet the criteria, I'd like the line to be drawn on the daily but I should be able to see as well when I'm on the 5m timeframe.
I've tried leveraging request.security like so..
dots = request.security(syminfo.tickerid, "D", calcDots(high), gaps = barmerge.gaps_on, lookahead = barmerge.lookahead_on)
And when I plot dots I'll get only the single dot from the daily only on the 5m view I'm on.. which is fine. But when I go do dots[1] it's not the actual previous dot from the daily chart. Perhaps my understand of request.security isn't right and there's something else I need to do to access or run my code against that higher timeframe data?

A: You are correct to use the reuqest.security() function. The catch is, the historical values of dots will be filled on your chart's timeframe. So, dots[1] will refer to its previous value on your chart's timeframe.
Let's look at two examples where we request the daily open price while we are on the 6-hour timeframe. So, we will have a new value on every 4th candle.
Example 1 (barmerge.lookahead_on):
[daily_1, daily_2] = request.security(syminfo.tickerid, "D", [open, open[1]], gaps = barmerge.gaps_on, lookahead = barmerge.lookahead_on)

Variable
Bar #1
Bar #2
Bar #3
Bar #4
Bar #5
Bar #6
Bar #7
Bar #8
Bar #9
Bar #10
Bar #11

daily_1
16978.38
na
na
na
17093.53
na
na
na
16886.81
na
na

daily_1[1]
na
16978.38
na
na
na
17093.53
na
na
na
16886.81
na

daily_2
17165.39
na
na
na
16978.38
na
na
na
17093.53
na
na

In this example, daily_1[1] will follow daily_1 on the next bar. So, its value will refer to daily_1's value on the previous bar on your chart's timeframe. daily_2 will refer to the previous day's open price. It is what you think daily_1[1] should do.
Example 2 (barmerge.lookahead_off):
[daily_1, daily_2] = request.security(syminfo.tickerid, "D", [open, open[1]], gaps = barmerge.gaps_off, lookahead = barmerge.lookahead_on)

Variable
Bar #1
Bar #2
Bar #3
Bar #4
Bar #5
Bar #6
Bar #7
Bar #8
Bar #9
Bar #10
Bar #11

daily_1
16978.38
16978.38
16978.38
16978.38
17093.53
17093.53
17093.53
17093.53
16886.81
16886.81
16886.81

daily_1[1]
17165.39
16978.38
16978.38
16978.38
16978.38
17093.53
17093.53
17093.53
17093.53
16886.81
16886.81

daily_2
17165.39
17165.39
17165.39
17165.39
16978.38
16978.38
16978.38
16978.38
17093.53
17093.53
17093.53

This example shows how the historical values are being filled.
Note:
This is a real example.
Ticker: BINANCE:BTCBUSD
Timeframe: 6h
Bar #1: Fri 02 Dec '22 00:00 UTC
Bar #11: Sun 04 Dec '22 12:00 UTC

You can check out the values if you simply add the following:
plotchar(daily_1, "daily_1", "")
plotchar(daily_1[1], "daily_1[1]", "")
plotchar(daily_2, "daily_2", "")


text:
Q: Leaflet map showing blank space while collapsing left panel I'm designing a portal of leaflet. I need to change leaflet div width while collapsing left panel. So by default I have put width of div this
 .map-wrapper {
        width: Calc(100vw - 33vw);
        height: 100vh;
    }

When I collapse my left panel then I'm adding a class in .map-wrapper
.shrink-map {
    width: Calc(100vw - 5vw) !important;
    transition: .6s linear;
}

It's perfectly collapsed but map is not loading proper. It's showing blank space in right side. how to solve this. Kindly check image001 and image 002 for better understanding

A: It looks like you need to refresh the map while or after "flying out" the panel so it calculates the available space for the map and draws it in full width and height of the container. See the API docs for the invalidatesize method.

Checks if the map container size changed and updates the map if so — call it after you've changed the map size dynamically, also animating pan by default.

PS: It would be really helpful to have a "live" demo of this behaviour.


text:
Q: PHP: Trying to come up with a "prev" and "next" link I'm displaying 10 records per page. The variables I have currently that I'm working with are..
$total = total number of records
$page  = whats the current page I'm displaying

I placed this at the top of my page...
if ( $_GET['page'] == '' ) { $page = 1; } //if no page is specified set it to `1`
else { $page = ($_GET['page']); }  // if page is specified set it

Here are my two links...
    if ( $page != 1 ) { echo '
Prev
'; }
    if ( !( ( $total / ( 10 * $page ) ) < $page ) ) { echo '
Next
'; }

Now I guess (unless I'm not thinking of something) that I can display the "Prev" link every time except when the page is '1'. How can make it where the "Next" link doesn't show on the last page though?

A: replace your last line of code with:
if ($page*10 < $total) echo '
Next
';

A: !( ( $total / ( 10 * $page ) ) < $page )

I ... don't think this is correct.
Suppose $total is 1000 - then on page 99, 1000/990 is less than 99, but there's still another page to show.
What you probably want is to check whether 10 * $page is greater than or equal to $total.

A: You need the total divided by the pagecount ($total / 10) with an extra page if there is a remainder.  Use the ceil function.
$page < ceil($total / 10)

A: Pagination is something that comes up so often in web projects, that it's usually best to create some kind of class somewhere, or at least some conveniences functions, that give you everything you need.
Here's a function that would return a dictionary of things that might be useful:
function pagination($numberItems, $perPage, $currentPage) {
    $numPages = ceil($numberItems/$perPage);
    return array(
        'numberPages' => $numPages,
        'start' => ($currentPage - 1) * $perPage + 1,
        'end' => min($currentPage * $perPage, $numberItems),
        'hasNext' => $page != $numPages,
        'hasPrev' => $page != 1
    );
}

A: You have a mistake in the last line:
$totalPages = ceil( $total / 10 );
if ( $page < $totalPages ) ) { echo "
Next
"; }

A:
// lets get total number of pages here
$itemsPerPage = 10;
$totalItems = 105; // just for example
$pagesNo = ceil( $totalItems / $itemsPerPage );

// get the current page here...
$current = ( isset($_GET['page']) ) ? (int)$_GET['page'] : 1;    // if page is defined, use it, instead use 1
$current = ( $current > 0 ) ? $current : 1;                    // if page was -1,-2... for instance, use 1

// show us 'Prev' button
echo ( $current > 1) ? "Prev" : "";

// show current page NO
echo $current;

// show 'Next' button
echo ( $current < $pagesNo) ? "Next" : "";

Should be like this... This is just quick code... Later, work on some page span (set how many pages should be shown before/after current page number...)

A: Sounds like you need to detect if you're on the first or the last page and "guard" the code against those conditions.
if (/* not the first page */) {
  // print the prev link
}

if (/* not the last page */) {
  // print the next link
}

You already have the code to detect if page=1 so now you just need to determine if you're on the last page or not (integer division or ceil() should be the way to go).
For pages of PHP results from SQL, there's a neat article on PHPFreaks http://www.phpfreaks.com/tutorial/basic-pagination


text:
Q: Import SVG vs. Require SVG I'm working on a React project, and creating a component called SVGLogo that simply imports an svg and exports as a component. I noticed that when I use require() to import my svg file, it works fine:
const SVGLogo = require('../../../../../vft-site/src/images/logo.svg');

But my linter suggests I use the import statement. I changed it but now I get the error 'cannot find module... or its corresponding type declarations':
import SVGLogo from '../../../../../vft-site/src/images/logo.svg';

Why are these different?

A: import comes in es6 like a new feature and require can be called from anywhere but import can be called on top of script


text:
Q: kafka connect error Cancelled in-flight API_VERSIONS request with correlation id 0 due to node -1 I have configured Kafka connect for a sink connector. I am used a oracle managed service for producing message stream and want to write that to autonomous database.
following is worker properties:
group.id=test
bootstrap.servers=xxx.oci.oraclecloud.com:9092
key.converter=org.apache.kafka.connect.json.JsonConverter
value.converter=org.apache.kafka.connect.json.JsonConverter
plugin.path=/opt/jdbc/connector/confluentinc-kafka-connect-jdbc-10.5.2
config.storage.topic=xxxx.osd7kemq-config
offset.storage.topic=xxxx.osd7kemq-offset
status.storage.topic=xxxx.osd7kemq-status

following is the connector config:
name=sink-test
connector.class=io.confluent.connect.jdbc.JdbcSinkConnector

tasks.max=3
topics=teststream
"connection.url": "jdbc:oracle:thin:@pxxxhigh?TNS_ADMIN=/opt/jdbc/wallet"
"connection.user": "abc"
"connection.password": "Randompassword"

when I start the worker using
./bin/connect-distributed.sh ./config/connect-distributed.properties sink.json

it gets errored:

    [2022-09-21 14:02:32,328] INFO Kafka startTimeMs: 1663768952327 (org.apache.kafka.common.utils.AppInfoParser:121)
    [2022-09-21 14:02:32,557] INFO [AdminClient clientId=adminclient-1] Node -1 disconnected. (org.apache.kafka.clients.NetworkClient:935)
    [2022-09-21 14:02:32,561] INFO [AdminClient clientId=adminclient-1] Cancelled in-flight API_VERSIONS request with correlation id 0 due to node -1 being disconnected (elapsed time since creation: 213ms, elapsed time since send: 213ms, request timeout: 3600000ms) (org.apache.kafka.clients.NetworkClient:341)
    [2022-09-21 14:02:32,665] INFO [AdminClient clientId=adminclient-1] Node -1 disconnected. (org.apache.kafka.clients.NetworkClient:935)

Also, have a doubt about where to write consumer details (in this case ADB ) like connection details, table name etc.I wrote sink connector properties file. but seems that is also not correct. will be helpful to know.


text:
Q: Is there a way to "Cancel" a stream after the delay operator I am using a polling scheme in my Angular application using NgRx.
To simplify things, I have something like the following:
    public stopPolling$ = createEffect(() => this.actions$.pipe(
        ofType(actions.stopPolling),
        tap(_ => this.isPollingActive = false),
        map(_ => actions.stopPolling())
      ), { dispatch: false });

     public continuePolling$ = createEffect(() => this.actions$.pipe(
        ofType(actions.getData),
        tap(_ => this.logger.debug('continue polling')),
        delay(8000),
        switchMap(_ => this.pollData())
      ), { dispatch: false });

    private pollData() {
       if (!this.isPollingActive)
         return;
    }

In my "StopPolling" I set a flag, but if it is restarted (ie isPollingActive is et back to true) while I am in the delay(8000), the delay will exit and I will end up with the getData being called multiple times.
So, my question is, is there a way to step the switchMap(_ => this.pollData()) being called after the delay - ie is there someway to "force the delay to exit" before the timeout period?
Almost (if you know C#/.net). like a manualResetEvent.WaitOne(8000) which can be cancelled by calling Set() on the manualResetEvent object.

A: You can create an observable that emits after a delay using timer and unsubscribe with takeUntil to exit early:
this.actions$.pipe(
  ofType(actions.getData),
  tap(_ => this.logger.debug('continue polling')),
  switchMap(_ =>
    timer(8000).pipe(
      takeUntil(this.actions$.pipe(ofType(actions.stopPolling))),
      concatMap(() => this.pollData())
    )
)

This might also allow you to remove the side-effect this.isPollingActive = false and ensure that the control flow remains within the observable.


text:
Q: How to create dynamic lambda join query using expression in C#? I am new to dynamic expression query...
I want to create a join query dynamically. Below it the query for which I want the equivalent dynamic query:
var lstNums = new List<int> { 100, 101 };
var getAll = new StudenRepository().GetAll(); //Returns IQuerable<Student>

var query = getAll.Join(lstNums, a => a.StudentId, b => b, (a, b) => a).ToList();

*

*The lstNums can be list of any primitive data types

*The getAll contains IQuerable, this can be IQuerable of any entity

*The query will contain the List<Student> records after doing join with the getAll and list of integers. But the result can be any list of entity. The list i.e. lstNum can be any list of primitive data types.

Below is what I have tried:
public static IQueryable JoinQuery(this IQueryable outer, IEnumerable innerEntities, string firstEntityPropName,
    Type typeSecondEntity, Type typeResultEntity, params object[] values)
{
    LambdaExpression outerSelectorLambda = DynamicLinq.DynamicExpression.ParseLambda(outer.ElementType, null, firstEntityPropName, values);

    ParameterExpression expnInput = Expression.Parameter(typeSecondEntity, "inner");
    ParameterExpression expnResult = Expression.Parameter(typeResultEntity, "outer");

    return outer.Provider.CreateQuery(
       Expression.Call(
           typeof(Queryable), "Join",
           new Type[] { outer.ElementType, innerEntities.AsQueryable().ElementType, outerSelectorLambda.Body.Type, expnResult.Type },
           outer.Expression, innerEntities.AsQueryable().Expression, Expression.Quote(outerSelectorLambda), expnInput,
           expnResult));
}

The extension method:
public static IQueryable<T> JoinQuery<T>(this IQueryable outer, IEnumerable innerEntities, string firstEntityPropName, Type typeSecondEntity, Type typeResultEntity, params object[] values)
{
    return (IQueryable<T>)Extensions.JoinQuery((IQueryable)outer, (IEnumerable)innerEntities, firstEntityPropName, typeSecondEntity, typeResultEntity, values);
}

Note: I have installed System.Linq.Dynamic nuget package version 1.0.7 for dynamic linq expression.

A: The below code worked for me:
using DynamicLinq = System.Linq.Dynamic;
using LinqExpression = System.Linq.Expressions;

public static IQueryable JoinQuery(this IQueryable outer, IEnumerable innerEntities, string firstEntityPropName,
    Type typeSecondEntity, Type typeResultEntity, params object[] values)
{
    if (innerEntities == null) throw new ArgumentNullException(nameof(innerEntities));
    if (firstEntityPropName == null) throw new ArgumentNullException(nameof(firstEntityPropName));
    if (typeSecondEntity == null) throw new ArgumentNullException(nameof(typeSecondEntity));
    if (typeResultEntity == null) throw new ArgumentNullException(nameof(typeResultEntity));

    LambdaExpression outerSelectorLambda = DynamicLinq.DynamicExpression.ParseLambda(outer.ElementType, null, firstEntityPropName, values);

    ParameterExpression expnInput = Expression.Parameter(typeSecondEntity, "inner");

    ParameterExpression[] parameters = new ParameterExpression[] {
    Expression.Parameter(outer.ElementType, "outer"), Expression.Parameter(innerEntities.AsQueryable().ElementType, "inner")
    };

    LambdaExpression selectorSecondEntity = DynamicLinq.DynamicExpression.ParseLambda(new ParameterExpression[] { expnInput }, typeSecondEntity, "inner");
    LambdaExpression selectorResult = DynamicLinq.DynamicExpression.ParseLambda(parameters, typeResultEntity, "outer");

    return outer.Provider.CreateQuery(
       Expression.Call(
           typeof(Queryable), "Join",
           new Type[] { outer.ElementType, innerEntities.AsQueryable().ElementType, outerSelectorLambda.Body.Type, selectorResult.Body.Type },
           outer.Expression, innerEntities.AsQueryable().Expression, Expression.Quote(outerSelectorLambda), Expression.Quote(selectorSecondEntity),
          Expression.Quote(selectorResult)));
}

The extension method is as follows:
public static IQueryable<T> JoinQuery<T>(this IQueryable outer, IEnumerable innerEntities, string firstEntityPropName, Type typeSecondEntity, Type typeResultEntity, params object[] values)
{
    return (IQueryable<T>)Extensions.JoinQuery((IQueryable)outer, (IEnumerable)innerEntities, firstEntityPropName, typeSecondEntity, typeResultEntity, values);
}


text:
Q: Retaining volatile data in orders Lets assume I have tables: customers and orders, I'd like to store order with unchangeable customer information (like address, name etc.) but do not want to copy all this information to orders table. There are three options:
a) Mapping table for base customers
orders
    ....
    customer_id; link to the customers table
    baseCustomer_id; link to the customers_base table
    ....
customers
    id;
    base_id; link to the base customers table;
    ....
customers_base
    id
    ....

b) Versioning: (if new customer, create version 0 for base customer, and version 1 to have permament record)
orders
    ....
    customer_id
    customer_version
    ....
customers
   id
   version
   ....
c) Create a copy of customer info for each order and store it into the same table;
orders
   ....
   customer_id
   ....
customers
   id
   ....
   copy_of; refers to the customers.id if null represents base customer entity

So the question is: what approach is more preferable from different points of view like db design, readability, implementation complexity?

A: I recommend to something similar to what @Jeffrey L Whitledge suggests in database-structure-for-storing-historical-data
Customer
--------
CustomerId (PK)
Name
AddressId (FK)
PhoneNumber
Email

Order
-----
OrderId (PK)
CustomerId (FK)
ShippingAddressId (FK)
BillingAddressId (FK)
TotalAmount

Address
-------
AddressId (PK)
AddressLine1
AddressLine2
City
Region
Country
PostalCode

etc.

Every data that can be changed should be grouped, such as address is here, if anything changes in the address, it's easy to generate a new entity and the order row can continue to refer to the old entity.
In data warehouse terms, this is usually called a  star schema where you differentiate between fact and dimensional tables.


text:
Q: Copy NSTableView row greyed out I would like to add copy (Command + C) functionality to my NSTableView for a row (or multiple rows) that the user has selected. Based on what I read the copy functionality in the Menu Item should be active automatically if you implement copy in your TableView Controller Delegate.
I've tried adding in the NSTableViewController (is the delegate and data source of the table view) the following things with no luck, the copy menu item still appears greyed out:

*

*override func copy() -> AnyObject {
    print("TEST: copytriggered") /Here i would copy to clipboard the selected rows/
    return true
}

2.
Conforming to NSCopying, implementing copyWithZone...
3.
Trying 1 and 2 in the window controller and app delegate.

*Adding func tableView(_ tableView: NSTableView,
pasteboardWriterForRow row: Int) -> NSPasteboardWriting? in the TableView data source.

I have no clue what to do at this point, any help appreciated.
Thanks,
Marc

A: Just got the answer, publishing here for future reference.
You are confusing the Copy edit action method with the methods for making a duplicate of an object.  The NSCopying protocol and the copyWithZone() method are for the latter, enabling an object to create a copy of itself.  Likewise, the copy() method is just a convenience cover method for copyWithZone().
The action method for the Copy edit menu item is subtly different.  It's "func copy(_ sender: AnyObject?)".  That's the general form for all action methods, taking a sender argument and not returning anything.  You need to implement that method.
Finally, tableView(_:pasteboardWriterForRow:) is generally only used for drag-and-drop, when the user drags a row.


text:
Q: Text Field box creation as per Material Design docs I have been trying to create a text field box as mentioned in the Material Design guidelines. I couldn't figure out how to achieve this. This is what I want to achieve.
TextField Box Material Design Screenshot
I am also attaching the link which has the material design guidelines if the image is not clear enough. I just need to create a text field box, but I couldn't figure it out. Here is the link to Material design guidelines page
https://material.io/guidelines/components/text-fields.html#text-fields-text-field-boxes
Also attaching my xml code for the text field which I want to create.
<android.support.design.widget.TextInputLayout
                    android:id="@+id/firstNameTextInputLayout"
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content"
                    android:layout_marginTop="20dp">

                        <android.support.design.widget.TextInputEditText
                            android:id="@+id/firstNameTextInputEditText"
                            android:layout_width="match_parent"
                            android:layout_height="wrap_content"
                            android:hint="@string/firstName"
                            android:inputType="textPersonName"
                            tools:ignore="MissingPrefix" />

                </android.support.design.widget.TextInputLayout>

Thanks in advance. Kindly help.

A: You're welcome to use my library here on Github:
https://github.com/HITGIF/TextFieldBoxes

Note that it requires Android 4.0.3 IceCreamSandwich (API lv 15) or greater.
First add the dependency in your project:
For Gradle:
allprojects {
    repositories {
      ...
      maven { url 'https://jitpack.io' }
    }
}

dependencies {
    compile 'com.github.HITGIF:TextFieldBoxes:1.3.9'
}

For other build tools & instructions, see the Github repo:
README.md
Then add these to your layout:
...
<studio.carbonylgroup.textfieldboxes.TextFieldBoxes
    android:id="@+id/text_field_boxes"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    app:labelText="Label">

    <studio.carbonylgroup.textfieldboxes.ExtendedEditText
        android:id="@+id/extended_edit_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</studio.carbonylgroup.textfieldboxes.TextFieldBoxes>
...

For more information and usage, see the Github repo above.

A: I don't know if it can help but I currently use a drawable like this one (I nammed it test.xml) =>
<?xml version="1.0" encoding="UTF-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="#767676" />
            <padding
                android:bottom="2dp" />
            <corners android:radius="4dp"/>
        </shape>
    </item>
    <item>
        <shape android:shape="rectangle">
            <solid android:color="#ffffff" />
            <corners android:topLeftRadius="4dp"
                android:topRightRadius="4dp"/>
        </shape>
    </item>
</layer-list>

then I attach this drawable to my textView or my TextInputLayout with the background attribute like this :
<android.support.design.widget.TextInputLayout
            android:id="@+id/firstNameTextInputLayout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:background="@drawable/test">

            <android.support.design.widget.TextInputEditText
                android:id="@+id/firstNameTextInputEditText"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:hint="@string/firstName"
                android:inputType="textPersonName"
                tools:ignore="MissingPrefix" />

        </android.support.design.widget.TextInputLayout>


text:
Q: SQL query with max date instance Given the following table:
DATE      |ARRANGMENT_STATUS | CUSTOMER
----------+------------------+-------
2017-01-01|BROKEN            |0001
2017-02-01|OK                |0001
2017-03-01|BROKEN            |0001

How can I query the DB so result will give me the latest broken status( 2017-03-01) - I dont want to get broken status if they are not the latest ( 2017-01-01)
Hope it makes sence,
thanks

A: If you want all information in the row, you can use order by and limit:
select t.*
from t
where t.arrangement_status = 'Broken'
order by t.date desc
limit 1;

If you only want the date, the JNevill's solution is fine.

A: Grab the max(date) for that status:
SELECT max(date) FROM table WHERE arrangement_status = 'Broken'


text:
Q: How should page-specific styling be applied to BEM blocks? Suppose we have a block element named .button which we want to reuse with different margin values on multiple different pages.
Possible solutions:
//1. Nested styles
.page-1 {
    .button { margin: 10px; }
}

.page-2 {
    .button { margin: 20px; }
}

//2. Specific modifier for EACH page
.button {
    &--pg-1-margin { margin: 10px; }
    &--pg-2-margin { margin: 20px; }
}

// 3. Special, page-specific block level element
// which will be COMBINED with an existing block-level
// element (ex: <button class="button page-1-element">...</button>)
.page-1-element { margin: 10px; }
.page-2-element { margin: 20px; }

*

*Which one of these will be considered BEM-friendly way?

*Is the first method acceptable / preferred way if there are too many different margins used?

A: Here's the answer to your question in official docs: https://en.bem.info/methodology/css/#external-geometry-and-positioning


text:
Q: Prism deviation angle for small angles Consider the following scheme for monochromatic light refracting through a prism, with the deviation angle $\delta$:

Let $\theta_1\ \wedge\ \alpha\ll1$ . I'm trying to prove that, under those conditions, the following approximation is valid:
\begin{equation}
\delta=\alpha(\eta-1)
\end{equation}
where $\eta$ is the refractive index of the prism. Using the direction of both $\hat{n}$ and $\hat{n}'$, we could get other two triangles:

                  ]2
From which we get:
\begin{align}
(I)&\ \phi'=\pi-(\theta+\theta')\\
(II)&\ \delta+\phi'=\pi\\
(III) &\ \phi=\pi-(\theta_2+\theta'_2)\\
(IV)&\ \theta_1=\theta_2+\theta\\
(V)&\ \theta'_1=\theta'_2+\theta'.
\end{align}
Using $(I),(II)$, and then $(IV),(V)$:
\begin{equation}
\delta=\theta+\theta'\implies\delta= (\theta_1+\theta'_1)-(\theta_2+\theta'_2).
\end{equation}
Using Snell's law for both refractions, considering that there's air in the prism's surroundings:
\begin{equation}
\frac{\sin\theta'_1}{\sin\theta'_2}=\eta=\frac{\sin\theta_1}{\sin\theta_2}\simeq\frac{\theta_1}{\sin\theta_2}
\end{equation}
where we used the (in)famous approximation $\sin\theta_1\simeq\theta_1$ since $\theta_1\ll1$. Using $(IV)$, we take this into account again to derive:
\begin{equation}
\theta_1\ll1\implies \theta+\theta_2<<1\implies\theta\ \wedge \theta_2\ll1\implies\sin\theta_2\simeq\theta_2\implies\eta\simeq\frac{\theta_1}{\theta_2}
\end{equation}
since both $\theta$ and $\theta_2$ are positive-defined. Let's get a relation for $\alpha$ now. For that, we highlight the quadrilateral:

Therefore:
\begin{equation}
\alpha+\phi=\pi
\end{equation}
because of the normal unit vectors. Using $(II)$:
\begin{equation}
\alpha=\theta_2+\theta'_2\implies \theta_2+\theta'_2<<1\implies\theta_2\ \wedge\ \theta'_2\ll1
\end{equation}
since $\alpha\ll1$. Because of that, we can approximate $\alpha$ to either $\theta_2$ or $\theta'_2$. Note that we can approximate $\theta_2+\theta'_2\simeq\theta_2$ and rewrite $\delta$:
\begin{equation}
\delta=\theta_1+\theta'_1-\theta_2
\end{equation}
And that's where I got stuck. If we could derive that $\theta'_1\ll1$, the approximation would be valid:
\begin{equation}
\theta_1+\theta'_1+\theta_2\simeq\theta_2\implies\delta=\theta_1+\theta_2
\end{equation}
And we would be done. Note that:
\begin{equation}
\delta=\theta_2\left(\frac{\theta_1}{\theta_2}-1\right)\simeq\alpha(\eta-1)
\end{equation}
Where we used $\alpha\simeq\theta_2$. That would conclude the derivation. Thing is, I've not been able to prove that $\theta'_1\ll1$. I've tried using the other approximations I've shown, but you can't really get rid of it.
Any tip, corrections, or help of any kind are welcome. Thanks in advance!


text:
Q: System of equations with with 3 variables Is it possible to find solutions of this system expressed with $a$:
$x^2+y^2+xy=a$
 $x^2+z^2+zx=a$
 $y^2+z^2-yz=a$
Thanks for help.

A: It is not always possible, at least not over the real numbers, to find solutions of this system. We obtain either $y^2=a$ or $x^2=a$, which has both no real solution for $a<0$. We argue as follows: $(2)-(1)$ gives
$$
(z-y)(x+y+z)=0.
$$
For $z=y$ we obtain $y^2=a$ from $(3)$, and this has no solution for $a<0$. For $a\ge 0$ it has a solution, namely $y^2=a$, $x(x+y)=0$.
In the other case, $y\neq z$ we obtain the solution $z=-x-y$, and $y(x+y)=0$, $a=x^2$.


text:
Q: Repull changes in git I made a mistake and i pulled down changes, and i closed my text editor and did save all. So, all the changes got overwritten. Is there anyway to undo my changes or force a repull and overwrite my changes?
Please?

A: You should look into:
git reset --hard

The general idea is to reset your local repository to HEAD. Any tracked files will be replaced with the ones in HEAD.

A: If I understand you correctly, most files are now reflecting the HEAD, whereas some random subset (whichever you had open in your editor) is based on commit $OLD_COMMIT plus your changes.
To throw away all your changes and force your working copy to reflect the HEAD, simply do git reset --hard.  If you want to salvage your edits, here's what you can do:
First, find out which files got changed by your text editor using git status.  Then, run git reflog to figure out the SHA1 of $OLD_COMMIT.  Then, run
git diff $OLD_COMMIT -- enumerate.c every/one.c of/your.c changed/files.c > patch

Check that patch looks OK, and run git reset --hard to throw away all changes in your working copy.  Then carefully try to apply the patch using the patch command on top the HEAD.  Voila!

A: See also How do I discard unstaged changes in Git?;
use git stash to stash the changes. You can delete the stash if you don't need to keep the changes;
git stash save
git stash drop


text:
Q: What will be the equation of motion of driven pendulum for amplitudes beyond the small angle approximation? When finding the period of a pendulum beyond the small angle approximation, we have to use integration for small interval of $\theta$ and elliptical integration.
I was trying to apply this situation for the driven pendulum.
When using small angle approximation, the equation of motion would be like below.
$$I \ddot{x}(t)+b \dot x(t)+m g l x(t)=F\cos(\omega t)$$

*

*$I$ : moment of inertia

*$b$ : damping coefficient

*$m$ : mass

*$g$ : gravity acceleration

*$l$ : distance between CM of the system and the origin of rotation

*$F$ : amplitude of external force

*$\omega$ : angular frequency of external force

*$x$ : angular displacement

*$t$ : time

When not using small angle approximation, above equation would be changed.
$$I \ddot x(t)+b\dot x(t)+m g l\sin(x(t))=F\cos(\omega t)\cos(x(t)).$$
Then, how do I solve this differential equation?
I tried to simulate the result with Mathematica's DSolve, but it didn't show the solution. Although I plotted the graph with NDSolve, I want to know the way to solve that differential equation.

A: The solutions for a forced/driven pendulum can be chaotic, in the sense of chaos theory, so the period may not even exist! For a tutorial on see these course notes for example. What you can do with an forced/driven pendulum is to simulate it and compute the various chaos-theory related parameters: Lyapunov exponents, Poincare map, etc. There are numerous resources on the web for that. Here are a few such resources:

*

*A Mathematica CDF, which has some [foot]notes on the implementaion.

*There also various (more or less annoying) applets on the web with a similar simulation. Essentially they are all based on Runge-Kuta numerical solutions. You can find more concise/intelligible Java source code in Tao Pang An Introduction to Computational Physics, pp. 92-93

*A short paper on a Python scipy implementation.

*A question here about Lyapunov exponents for the driven pendulum equation.

Etc.
If all you want is to compute the period for non-small angles for an unforced pendulum, Wikipedia has some answers, most notably the fairly fast (in practice) Carvalhaes and Suppes approximation.
Addendum for the more mathematically inclined: the perturbation method doesn't always work for the forced pendulum equation. In particular it doesn't work for Hubbard's pendulum equation, which is an instance of the general forced pendulum equation. There's a relatively recent (2008) computer-assited proof of chaotic behavior in that case.

A: As was mentioned in the comments, the differential equation you give is not solvable analytically. What one can do is one can go beyond the small angle approximation in a controlled fashion by Taylor expanding the sine and cosine function and find (e.g. expanding up to order $x^3$)
$$I \ddot x + b\dot x + mgl\left( x - \frac{x^3}{6}\right) = F \cos(\omega t) \left( 1 - \frac{x^2}{2} \right) $$
This still is a non-linear differential equation and might not be solvable either, but it opens the door for Perturbation Theory, which is the major tool to use when going beyong linear approximations.


text:
Q: Java Swing: adding ScrollPane to JPanel Trying to add a vertical scroll bar to one of the panels in my user interface. Nothing is happening. Related segment below:
outputPanel= new JPanel();
outputPanel.setLayout(null);
outputPanel.setBackground(Color.decode("#ecb3ff"));
scrollPane= new JScrollPane(outputPanel);
scrollPane.setVerticalScrollBarPolicy(JScrollPane.VERTICAL_SCROLLBAR_ALWAYS);
scrollPane.setPreferredSize(new Dimension(700,700));
scrollPane.setViewportView(outputPanel);
frame.add(scrollPane);

scrollPane.setVisible(true);

A: outputPanel.setLayout(null);

Don't use a null layout.
The scrollbar will only appear when the preferred size of the component added to the viewport is greater than the size of the scrollpane.
The preferred size is only calculated when you use layout managers. Since you don't use a layout manager the preferred size is (0, 0) so there is no need to display an active scrollbar.
Read the Swing tutorial on Layout Managers.


text:
Q: Unreliable discovery for elasticsearch nodes on ec2 I'm using elasticsearch (0.90.x) with the cloud-aws plugin. Sometimes nodes running on different machines aren't able to discover each other ("waited for 30s and no initial state was set by the discovery"). I've set "discovery.ec2.ping_timeout" to "15s", but this doesn't seem to help. Are there other settings that might make a difference?
discovery:
    type: ec2
    ec2:
        ping_timeout: 15s

A: Not sure if you are aware of this blog post: http://www.elasticsearch.org/tutorials/elasticsearch-on-ec2/. It explains the plugin settings in depth.
Adding cluster name, like so
cluster.name: your_cluster_name
discovery:
    type: ec2
...

might help.


text:
Q: Couldn't get json_encode($resu) in android onPostExecute(String res) I am trying to connect my android app with backend MySQL and I used php as server side language, but the problem is as I am echoing $res array from php, it is not accessed in Android onPoseExecute(String res).
I have tried the same code in other apps and it's working  perfectly fine there.. but this code is not showing proper response, neither the error in creating Json object.
My username is defined in OnCrate() of android code.
Here is my php Code:
session_start();
$con = mysqli_connect("localhost", "root", "", "SWR");

//Function to sanitize values received from the form. Prevents SQL injection
function clean($str) {
    $str = @trim($str);
    if(get_magic_quotes_gpc()) {
        $str = stripslashes($str);
    }
    return $str;
}

$empID = strtoupper(clean($_POST['username']));
$resu = array();
$resu["status"] = true;
$sql3="insert into t_booked_hall values ('','$empID','','','','','','1','','','0','','0','','','','','','','','0','','','0','','')";
$result3 = mysqli_query($con,$sql3);
echo json_encode($resu);

Android Code:
public class SigninActivity  extends AsyncTask<String, Void , String>{
    protected void onPreExecute(){}

    @Override
    protected String doInBackground(String... arg0) {
        try{
            link="https://haripriyag2362.000webhostapp.com/login_php.php";
            String data  = URLEncoder.encode("username", "UTF-8") + "=" +
                    URLEncoder.encode(username, "UTF-8");

            URL url = new URL(link);
            URLConnection conn = url.openConnection();
            conn.setDoOutput(true);
            OutputStreamWriter wr = new OutputStreamWriter(conn.getOutputStream());
            wr.write( data );
            wr.flush();
            BufferedReader reader = new BufferedReader(new
                    InputStreamReader(conn.getInputStream()));
            StringBuilder sb = new StringBuilder();
            String line = null;
            while((line = reader.readLine()) != null) {
                sb.append(line);
                break;
            }
            return sb.toString();
        } catch(Exception e){
            return new String("Exception: " + e.getMessage());
        }
    }

    //final context context = this;
    @Override
    protected void onPostExecute(String result){
        try{
            JSONObject jObj = new JSONObject(result);

            if(jObj.getBoolean("status")) {
                 Toast.makeText(emp_home.this,"Invalid Succesful..",Toast.LENGTH_SHORT);
            }
            else{
                Toast.makeText(emp_home.this,"Invalid Login ! Try Again",Toast.LENGTH_SHORT);
            }
        }catch (JSONException ex) {
            ex.printStackTrace();
        }
    }
}

A: You must just remove break; in while loop
You Can Use getJSONfromURL(url) func to Get Array Response From Server
 public static JSONObject getJSONfromURL(String url) {
    InputStream is = null;
    String result = "";
    JSONObject jArray = null;

    // Download JSON data from URL
    try {
        HttpParams httpParameters = new BasicHttpParams();
        HttpConnectionParams.setConnectionTimeout(httpParameters, 10000);
        HttpConnectionParams.setSoTimeout(httpParameters, 5000);

        HttpClient httpclient = new DefaultHttpClient(httpParameters);
        HttpPost httppost = new HttpPost(url);

        HttpResponse response = httpclient.execute(httppost);
        HttpEntity entity = response.getEntity();
        is = entity.getContent();

    } catch (ConnectTimeoutException e) {
        //Here Connection TimeOut excepion
    } catch (Exception e) {
    }

    // Convert response to string
    try {
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                is, "utf-8"), 8);
        StringBuilder sb = new StringBuilder();
        String line = null;
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
        is.close();
        result = sb.toString();
    } catch (Exception e) {
    }

    try {

        jArray = new JSONObject(result);
    } catch (JSONException e) {
    }

    return jArray;
}


text:
Q: background-image in react component I'm building a page and I want a material-ui element to have a background image using background-image CSS property. I have googled for it of course, and there are solutions but for some reason I can't see that image.
P.S.1: even changing that MUI element to regular  hasn't helped me at all.
P.S.2: when I'm using  inside container it shows, but that's not what I want.
UPDATE1: Tried adding height and width to container, still no luck...
import React from 'react';

import Paper from 'material-ui/Paper';

import IconButton from 'material-ui/IconButton';
import ActionHome from 'material-ui/svg-icons/action/home';

const styles = {
    paperContainer: {
        backgroundImage: `url(${"static/src/img/main.jpg"})`
    }
};

export default class Home extends React.Component{
    render(){
        return(
            <Paper style={styles.paperContainer}>

            </Paper>
        )
    }
}

A: I got this to work for material-ui, where the padding on my parent element was 24px so I added 48px to the width of the background image to make it work...
const styles = {
   heroContainer: {
     height: 800,
     backgroundImage: `url(${"../static/DSC_1037.jpg"})`,
     backgroundSize: 'cover',
     backgroundPosition: 'center',
     width: `calc(100vw + 48px)`,
     margin: -24,
     padding: 24,
   }
  };
<Grid
    container
    direction="column"
    justify="flex-end"
    alignItems="right"
    style={styles.heroContainer} >
    <Grid item>Goes here</Grid>
</Grid>

A: You have to import the image as the following, using the relative path.
import React from 'react';

import Paper from 'material-ui/Paper';

import IconButton from 'material-ui/IconButton';
import ActionHome from 'material-ui/svg-icons/action/home';

import Image from '../img/main.jpg'; // Import using relative path

const styles = {
    paperContainer: {
        backgroundImage: `url(${Image})`
    }
};

export default class Home extends React.Component{
    render(){
        return(
            <Paper style={styles.paperContainer}>
                Some text to fill the Paper Component
            </Paper>
        )
    }
}

A: Had the same issues while working with Material UI React and the Create React App. Here is the solution that worked for me. Note that I set up a webpack alias for the relative path
import BackgroundHeader from "assets/img/BlueDiamondBg.png"

const BackgroundHead = {
  backgroundImage: 'url('+ BackgroundHeader+')'
  }

A: Like Romainwn said, you need to import the image to the file. Make sure you use the relative path to parent, so instead of
static/src/img/main.jpg    #looks for static folder from current file location

Do
/static/src/img/main.jpg #looks for file from host directory:

Another hack to do it would be adding an inline style tag to the component:
import React from 'react';

import Paper from 'material-ui/Paper';

import IconButton from 'material-ui/IconButton';
import ActionHome from 'material-ui/svg-icons/action/home';

import Image from '../img/main.jpg'; // Import using relative path

export default class Home extends React.Component{
    render(){
        return(
            <Paper style="background:path/to/your/image;">

            </Paper>
        )
    }
}

A: I've found a fix for my case. Actually setting container height in pixels have helped.
Here's the code:
import React from 'react';

const styles = {
    paperContainer: {
        height: 1356,
        backgroundImage: `url(${"static/src/img/main.jpg"})`
    }
};

export default class Home extends React.Component {
    render() {
        return (

        )
    }
}

A: You can you sx props in MUI v5
import React from 'react';

import Paper from 'material-ui/Paper';

import Image from '../img/main.jpg';

export default class Home extends React.Component{
    render(){
        return(
            <Paper sx={{ backgroundImage: `url(${Image})` }}>

            </Paper>
        )
    }
}


text:
Q: Exception in thread, function add number to array I am trying to implement a simple function which adds a number to existing array but I am getting an error in the following code, an exception is exactly at function addArrayToNumber in line: "number+= NUMBERS_ARRAY[i]". I don't want to catch the exception, just repair code.
public class Main {

private static final int[] NUMBERS_ARRAY = {1, 2, 3, 4, 5};

public static final void main(String[] args) {
    int x = addArrayToNumber(1);
    System.out.println("X = " + x);

    int y = addArrayToNumber(10);
    System.out.println("Y = " + y);

}

private static int addArrayToNumber(int number) {
    for (int i = 0; i <= NUMBERS_ARRAY.length; i++) {
        number += NUMBERS_ARRAY[i]; /** here it is */
    }

    return number;
}

A: Array of n members has indices 0, 1, ..., n-1. However, in your for loop, you're testing i <= NUMBERS_ARRAY.length, meaning if array has length 5, you're trying to access NUMBERS_ARRAY[5], which obviously doesn't exist. Instead, use i < NUMBERS_ARRAY.length, so loop becomes
for(int i=0; i < NUMBERS_ARRAY.length; i++)

Alternatively, when you're looping over all elements you can use for-each syntax, i.e.
for (int element : NUMBERS_ARRAY) {
    number += element; /* add every element from NUMBERS_ARRAY to number */
}

and not think about indices at all.

A: You get IndexOutOfBoundsException here because array length is bigger than last index by 1 in example array have elements [1,2,3] indexation starts from 0 and for get last element you need index 2, not 3, otherwise you get exception. According to this correct your code by replace <= to <:
 for (int i = 0; i < NUMBERS_ARRAY.length; i++) {
        number += NUMBERS_ARRAY[i];
 }


text:
Q: How to watch cnn go using browser? I have directv and i used to watch cnn live on my browser in windows. since making the switch to ubuntu, i can watch it. I have install flash and extras. I have tried all browsers. It just doesnt work in ubuntu. Help please. I have already tried every suggestion in previous questions asked.

A: You need to use Google Chrome, which I assume you did not try. You may have tried the open-source browser Chromium, but that doesn't have flash etc. that Google Chrome has, which is needed for CNN Go. You can install Google Chrome using these excellent instructionsn:
How to install Google Chrome


text:
Q: In Javascript, what does this underscore mean? var Gallery = Backbone.Controller.extend({
    _index: null,
    _photos: null,
    _album :null,
    _subalbums:null,
    _subphotos:null,
    _data:null,
    _photosview:null,
    _currentsub:null,
    routes: {
        "": "index",
        "subalbum/:id": "subindex",
        "subalbum/:id/" : "directphoto",
        "subalbum/:id/:num" : "hashphoto"
    },
    initialize: function(options) {
        var ws = this;
        if (this._index === null){
            $.ajax({
                url: 'data/album1.json',
                dataType: 'json',
                data: {},
                success: function(data) {
                    ws._data = data;
                    ws._photos =
                    new PhotoCollection(data);
                    ws._index =
                    new IndexView({model: ws._photos});
                    Backbone.history.loadUrl();
                }
            });
            return this;
        }
        return this;
    },
    //Handle rendering the initial view for the
    //application
    index: function() {
        this._index.render();
    },

I'm reading a tutorial on backbone.js here: http://addyosmani.com/blog/building-spas-jquerys-best-friends/
What are the underscores? (_index, _photos, _album)  Why use them?

A: When used like _varname it's just part of the variables name, and has no javascript meaning. Developers use it to signify the meaning or scope of the variable. In this case it looks like it is telling the developer this variable should be a local or private variable.
A few things to note, in this particular example using _.varname would signify a variable or function with the underscore.js library. Also one could use _varname to signify a variable holding an underscore object, similarly at our office, we use $varname to signify a variable containing a Jquery object.

A: It's probably used to mark internal/private properties. Just like in python prefixing a variable with a underscore is an easy way to tell developers that a variable is internal and they better not tamper with it (and if they do so, even a minor update of the involved library may break things).

A: As far as I'm aware, it's generally used to indicate a private variable (but doesn't actually provide any privacy, just a convention).
It's discussed briefly here, though they're advised against:
http://javascript.crockford.com/code.html

A: Usually _ is used to tell the user/programmer that it is a private/protected variable in question.

A: It means private fields or private methods. Methods that are only for internal use.
They should not be invoked outside of the class.
Private fields contain data for internal use.
They should not be read or written into (directly) from outside of the class.
Note: It is very important to note that just adding an underscore to a variable does not make it private, it is only a naming convention.

A: This is a slight addendum. As already answered these are pseudo private variables. But it is then possible to write pseudo public functions that access these private variables.
I got confused by a colleagues code that effectively has this (but buried very deep in a separate library):
class x {
  constructor(id) {this._id = id}
  get id() {return this._id}
}
let y = new x(3)

Now you have both y.id and y._id that work and return the same value. But if you do console.log(y) it only shows up the _id key.

A: As mentioned, it's a practice among many developers, a bad one at that.  If you have to resort to conventions like this in your programming methods then you should learn the language, methods and patterns before attempting to use the language.  If someone can't distinguish between public/private methods in your code with out the use of the "underscore", then your documentation skill are extremely lacking.  Many of the public projects on the web are very poorly documented which is probably why the "underscore" conventions was "accepted" by most under educated developers while others decided to go with the flow rather than keeping the formal design patterns and methods.  There is a reason why "underscore" was not written into ES6/7 versions.
In a blog I recently came across an Software Engineer Manager who stated:  "The underscore naming convention makes it really easy to tell, at a glance, whether a variable function is intended to be public or private.".  My response is: "Comments are like pictures, in this case they are worth a thousand underscores.
There is a free documentation tool called Doxygen.  While it does not specifically support JavaScript, it can generate professional documentation for your JavaScript applications when you use Doxygen prefix's in your comments. It's really simple to create JavaScript applications with documentation, for both developers and users when you put a little effort into your code comments.
Remember, there are tools that can remove comments, and console statements for "Production Releases".  That being said, the use of source maps are a waste of time and resources also.  Don't minify until your ready to publish..  i.e.  Dev Build (no minification, keep comments and console statements), Release Build (remove comments, and console statements and minify the Dev build. No need to recompile the Dev Build when its release quality code, just prepare it for release and deploy it).


text:
Q: ¿Cómo puedo abrir un archivo PDF usando Intent en Android Nougat? Agradeceré su ayuda para poder hacer que mi código pueda abrir un archivo PDF en un Intent, el código que he venido usando para hacerlo es:
String pathFile =
    Environment.getExternalStorageDirectory().toString() +
    FileUtils.PATH_SEPARATOR + "myFolder" +
    FileUtils.PATH_SEPARATOR + "myFile.pdf";
File pdfFile = new File( pathFile );
if ( pdfFile.exists() ) {
    Uri uri = Uri.fromFile( new File( pathFile ) );
    Intent intent = new Intent( Intent.ACTION_VIEW );
    intent.setDataAndType(uri, "application/pdf");
    intent.addFlags( Intent.FLAG_ACTIVITY_NEW_TASK );
    startActivity( intent );
}

Pero entiendo que ahora (desde la versión Android-N) los privilegios se manejan de manera distinta y por eso espero que me puedan ayudar indicándome cuáles son los cambios que debo hacer para que se pueda abrir un archivo PDF en un Intent.
PD: En mi AndroidManifest.xml tengo solicitado permiso para todo el STORAGE:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

A: Verifica la ruta al archivo y añade una exception si no lo puede abrir.
if(file.exists()) {
            Intent intent = Intent.createChooser(target, "Open File");
            try {
                startActivity(intent);
            } catch (ActivityNotFoundException e) {
                Toast.makeText(getApplicationContext(), "ActivityNotFound" , Toast.LENGTH_LONG).show();
            }
        }else{
            Toast.makeText(getApplicationContext(), "El archivo no existe." , Toast.LENGTH_LONG).show();
        }

A: yo hice este método
Primero tienes que consultar la version del SO
if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP_MR1) {
     if (checkPermission("android.permission.WRITE_EXTERNAL_STORAGE")) {

     }else{
       requestPermissions("android.permission.WRITE_EXTERNAL_STORAGE");
     }
}else{
//TODO: Como es menor a la versión N puedes abrir el archivo
}

Con este método verifico si ha aceptado, pasándole como String el permiso
private boolean checkPermission(String permission) {
        int res = this.checkCallingOrSelfPermission(permission);
        return (res == PackageManager.PERMISSION_GRANTED);
}

Con este método realizo la solicitud del Permiso, puedes pasarle varios permisos al mismo tiempo
private void requestPermissions(String... permissions) {
        ActivityCompat.requestPermissions(this, permissions, 0);
}

Lo que te faltaría hacer es consultar en @OnActivityResult

A: A partir de Android 6.0 el permiso WRITE_EXTERNAL_STORAGE debe ser pedido de manera manual, no es suficiente con declararlo en tu AndroidManifest.xml, para esto aquí se tiene como obtenerlos:
Error al mostrar el directorio externo de archivos en un AlertDialog en android 6.0 (READ_EXTERNAL_STORAGE / WRITE_EXTERNAL_STORAGE )
En cuanto al error que estas teniendo, debes recordar que en versiones de sistema operativo iguales o superiores a Android N debes usar Uri.parse() en lugar de Uri.fromFile() :
    Uri uri;
    //Validación de acuerdo al OS.
    if (Build.VERSION.SDK_INT >=  Build.VERSION_CODES.N) {
           uri = Uri.parse(filepath);
    } else{
           uri = Uri.fromFile(new File(filepath));
    }

Si no realizas esta validación, en Android N obtendrías este error: FileUriExposedException:


text:
Q: Distribution of the index of the variable which achieves the minimum of exponential random variables I am reading Exponential distribution from Wiki, and it is said that the index of the variable which achieves the minimum is distributed according to the law
$$P(k|X_k=min\{X_1,X_2,...,X_n\})=\frac{\lambda_k}{\lambda_1+...+\lambda_n}$$
I don't know how to prove this property. I try the case $n=2$ in different ways.
First, I find $P(X_1\le X_2)=\frac{\lambda_1}{\lambda_1+\lambda_2}$, but I can't change this to the conditional probability formally.
Second, I try to prove this through pdf. Let $Y=min\{X_1,X_2\}$, I want to calculate $f_{X_1|Y}(x_1,y)$. However I find that there should be infinite value of $f_{X_1|Y}(x_1,y)$ at $x_1=y$ , since the conditional probability is actually a discrete distribution. I don't know how to obtain the discrete distribution from continuous pdf.
Please tell me how can I continue my proof or give another formal proof, Thanks!!

A:
it is said that the index of the variable which achieves the minimum is distributed according to the law $$P(k\mid X_k=\min\{X_1,X_2,...,X_n\})~=~\frac{\lambda_k}{\lambda_1+...+\lambda_n}$$

Y...eah.   That's a poor way to express it.   That is not actually a conditional probability.
All they are saying is if we let $K$ be the random variable defined as the index of the minimum value of the sample, that is $X_K=\min\{X_1,X_2,\ldots,X_n\}$, then the probability mass function of $K$ is : $$P(K=k) ~=~ \dfrac{\lambda_k}{\lambda_1+\lambda_2+\cdots+\lambda_n}~~\mathbf 1_{k\in\{1,2,\ldots,n\}}$$
So, for $n=2$ you have found $P(X_1\leqslant X_2)~=~ P(K=1) ~=~ \dfrac{\lambda_1}{\lambda_1+\lambda_2}$
In general $$\begin{align}P(K=k) ~&=~ \int_0^\infty f_{X_k}(t) \prod\limits_{j\in\{1..n\}\setminus\{k\}} (1-F_{X_j}(t))\operatorname d t \\[1ex] &\vdots\\[1ex] &=~ \dfrac{\lambda_k}{\sum_{j=1}^n \lambda_j}\end{align}$$

A: The probability density of an exponential random variable with parameter $\lambda$ is $\lambda e^{-\lambda x}$ which is equal to $\lambda$ at $0$. It means that the probability that it will be less than $\delta$ is equal to $\lambda \delta$ for $\delta \rightarrow 0$. So if we have $n$ independent exponential random variables with parameters $\lambda_i$ the probability that any of them will be less than $\delta$ is equal to $\lambda_i\delta$ for $\delta \rightarrow 0$. Now, the probability that two of them are less than $\delta$ is significantly smaller than any of the $\lambda_i\delta$ for $\delta \rightarrow 0$, thus the probability that the $i$-th variable will be smaller than $\delta$ conditioned on the event that one of them is approaches:
$$\frac{\lambda_i\delta}{\lambda_1\delta+\lambda_2\delta+\dots+\lambda_n\delta}=\frac{\lambda_i}{\lambda_1+\lambda_2+\dots+\lambda_n}$$
as $\delta \rightarrow 0$. Therefore, by memoryless property, it is also the probability that the $i$-th variable will be the smallest one.


text:
Q: How do websites feasibly allow users profiles to each have their own URL? For example, a profile on facebook is often: facebook.com/user. What does Facebook do on their backend to make this work?
I want to create a similar experience for a site I'm building but I don't want to make every user their own .html page. I need some way to read the URL to determine which experience to serve

A: They don't serve static pages, instead they forward requests to a web application of some sort, which can handle URLs however it wants. You would also need to do that in order to handle use input, static pages obviously being static they can't handle anything.


text:
Q: Can't get Result to show with HTML Forms and Javascript I'm trying to get my results to show up in the text box inputs as per my assignment but I can't get them to show up at all. The math isn't showing up at all so my big issue is that I can't get the code to show up in the box.

document.querySelector.("#buttonS").addEventListener("click", function(e) {
  if (document.querySelector("#gallons").reportValidity()) {
    let gallons = document.querySelector("#gallons").value;

    if (document.querySelector("#quarts").checked) {
      quartsTotal = gallons * 4;
      document.querySelector("#quartsResult").placeholder = `quartsTotal`);

  } else if (document.querySelector("#pints").checked) {

  } else if (document.querySelector("#cups").checked) {

  }

}

});
<form id="bakimg">
  <input type="number" step=".01" min="0" id="gallons" required>  How many gallons of milk do you have?

  Which conversion would you like?

  <input type="radio" value="quarts" name="gallonsC" checked>Quarts
  <input type="radio" value="pints" name="gallonsC">Pints
  <input type="radio" value="cups" name="gallonsC">Cups
</form>

<button type="button" id="buttonS">Submit</button>

Results

<input type="text" id="quartsResult" placeholder="">Quarts

<input type="text" id="pintsResult">Pints

<input type="text" id="cupsResult">Cups

A: Check your syntax and make the following changes:

*

*Check the browser console for errors and use the appropriate syntax:

document.querySelector.("#buttonS")

should be written like this:
document.querySelector("#buttonS") // No . after querySelector

*

*Check the extra parentheses:

document.querySelector("#quartsResult").placeholder = `quartsTotal`); // <-- Remove the closing parens

*

*Add the proper IDs to the HTML input elements (quarts, pints, cups):

<input type="radio" value="quarts" name="gallonsC" checked id="quarts">
<input type="radio" value="pints" name="gallonsC" id="pints">
<input type="radio" value="cups" name="gallonsC" id="cups">

*

*Remove the backticks in order to use the variable value (otherwise quartsTotal is still a string):

`quartsTotal` -> quartsTotal
// Perhaps this is what you meant:
`${quartsTotal}`

Good luck with the assignment!


text:
Q: How to check if geopoint type set to null in elasticsearch using mvel? How do i check if a geopoint value is set to null (for custom scoring using mvel)? Should the value be '' or null? And if so how do i check if the value is '' or null?
So my document structure is like this
   document 1
   {
   "id" : 100
   "location" : null
   }

   document 2
   {
   "id" : 200
   "location" : "80.230122,80.97629"
   }

Here location is of type geopoint in the mapping.
When scoring using custom scripts I would like to do something like:
distance=doc['location'].distanceInKm(latitude, longitude)

where I pass latitude and longitude. How do I check for document with id 100 which has the null value for location, and make the distance calculated zero? .empty and .Isempty() doesn't seem to be working.
Note: for document id 100 location is null and not string null. Also I'm using MVEL plugin version 1.5 with ES version 1.5


text:
Q: Button active state offset via class I have some buttons in a container. I would like their active state to offset down by 1px or so. Rather than write css for each button, I would rather class them and have their active state relative to their original position.
The css currently looks like below. Or check out this working fiddle. The problem is that the active state offset seems to be greater than 1px for the bottom 2x buttons. Not sure what I am missing.
#buttons {
    position: absolute;
    top: 10px;
    left: 10px;
}

.greenButtClass {
    font-family: 'avenirMedium';
    position: absolute;
    z-index: 10;
    color: #ffffff;
    font-size: 22pt;
    width: 200px;
    background-color: #7ac144;
    -moz-border-radius: 15px;
    -webkit-border-radius: 15px;
    border-radius: 35px;
    padding: 8px;
    cursor: pointer;
    border: 1px solid #7ac144;
}

.greenButtClass:hover {
    background-color: #6DA840;
}

.greenButtClass:active {
    position: relative;
    top: 1px;
}

A: Here what i suggest if i understand right your problem:
html:

    <button id='places' class='greenButtClass' style="top:15px">Button 1</button>

    <button id='nature' class='greenButtClass' style="top:105px">Button 2</button>

    <button id='trails' class='greenButtClass' style="top:205px">Button 3</button>

css:
#buttons{
    position: absolute;
    top:10px;
    left:10px
}
.greenButtClass{
    font-family: 'avenirMedium';
    z-index: 10;
    color: #ffffff;
    font-size: 22pt;
    width:200px;
    background-color:#7ac144;
    -moz-border-radius: 15px;
    -webkit-border-radius: 15px;
    border-radius:35px;
    padding:8px;
    cursor:pointer;
    border:1px solid #7ac144;
}
.greenButtClass:hover {
    background-color:#6DA840;
}
.greenButtClass:active {
    position:relative;
    top:1px;
}

And a working fiddle
And another one with more spaces between button as your example:
fiddle


text:
Q: Using nodejs passport-google-oauth2 without a redirect URI I'm using the nodejs npm module passport-google-oauth2
I'm currently using it exactly the way its example shows, with a redirect URI that the google oauth will callback with, after successful authentication:
Example:
Server side:
var GoogleStrategy = require( 'passport-google-oauth2' ).Strategy;

passport.use(new GoogleStrategy({
    clientID:     GOOGLE_CLIENT_ID,
    clientSecret: GOOGLE_CLIENT_SECRET,
    callbackURL: "http://yourdormain:3000/auth/google/callback",
    passReqToCallback   : true
  },
  function(request, accessToken, refreshToken, profile, done) {
    User.findOrCreate({ googleId: profile.id }, function (err, user) {
      return done(err, user);
    });
  }
));

Client side:
app.get('/auth/google',
  passport.authenticate('google', { scope:
    [ 'https://www.googleapis.com/auth/plus.login',
      'https://www.googleapis.com/auth/plus.profile.emails.read' ] }
));

app.get( '/auth/google/callback',
    passport.authenticate( 'google', {
        successRedirect: '/auth/google/success',
        failureRedirect: '/auth/google/failure'
}));

I know there is a way to use Google OAuth without redirect; it simply somehow stays on the same page (Google SSO). I think you can do it with just a GoogleVerifier, rather than building a new GoogleAuthorizationCodeTokenRequest() (Java examples), but I'm rather lost at this point.
Questions:

*

*How to use google oauth2 without redirect URI ? (I know it can be done  using GoogleVerifier object in Java).

*Am I using the wrong module for Google SSO in NodeJS ?  Is the module above appropriate for Google SSO using OAuth2 ?  It is for Google OAuth2, but is it SSO-able ?
Thanks in advance for any help


text:
Q: Unable to find Butterknife.Action on upgrading the Butterknife version 8.8.1 to version 10.2.0 Unable to find Butterknife.Action and ButterKnife.apply on upgrading the Butterknife version 8.8.1 to version 10.2.0
error: cannot find symbol
public static final ButterKnife.Action<View> GONE = (view, index) -> view.setVisibility(View.GONE);
                               ^
  symbol:   class Action
  location: class ButterKnife

A: *

*Batterknife.aply depricated in AndroidX

If you migrate to AndroidX you must use:
in gradle
dependencies {

implementation "com.jakewharton:butterknife:10.2.0"

annotationProcessor "com.jakewharton:butterknife-compiler:10.2.0"

...}

in class when you have errors
if you use code like this:
- ButterKnife.apply(new View[]{ ivImageId,vgSubscribtionsId,vgSubscribersID},

                    (view, value, index) -> view.setVisibility(value), View.INVISIBLE);

replace to this for work with AndroidX:
- butterknife.Action viewAction = (view, index) -> {

                view.setVisibility(View.INVISIBLE);

            };
            butterknife.ViewCollections.run(new View[]{ ivImageId,vgSubscribtionsId,vgSubscribersID} , viewAction );

A: Those methods are deprecated and no longer available since version 10.0.0: more details here and here.