text:
Q: What is the Java 7 try-with-resources bytecode equivalent using try-catch-finally? I'm trying to understand how the new try-with-resources statement works by recreating it using regular try-catch-finally statements. Given the following test class using Java 7 try-with-resources:
import java.io.IOException;
import java.util.zip.GZIPOutputStream;

public class TryWithResources {
    public static void main(String[] args) {
        try (GZIPOutputStream gzip = new GZIPOutputStream(System.out)) {
            gzip.write("TEST".getBytes("UTF-8"));
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}

How would you rewrite this class to use try-catch-finally statements which produces exactly the same bytecode as the try-with-resources statement produces? Also, same question when two resources are used, as in the following example:
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;

public class TryWithResources2 {
    public static void main(String[] args) {
        try (ByteArrayOutputStream baos = new ByteArrayOutputStream();
                GZIPOutputStream gzip = new GZIPOutputStream(baos)) {
            gzip.write("TEST".getBytes("UTF-8"));
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}

A: For the TryWithResources class, the following class produces equivalent bytecode as the try-with-resources:
import java.io.IOException;
import java.util.zip.GZIPOutputStream;

public class TryCatchFinally {
    public static void main(String[] args) {
        try {
            final GZIPOutputStream gzip = new GZIPOutputStream(System.out);
            Throwable gzipEx = null;
            try {
                gzip.write("TEST".getBytes("UTF-8"));
            } catch (Throwable t) {
                gzipEx = t;
                throw t;
            } finally {
                if (gzip != null) {
                    if (gzipEx != null) {
                        try {
                            gzip.close();
                        } catch (Throwable t) {
                            gzipEx.addSuppressed(t);
                        }
                    } else {
                        gzip.close();
                    }
                }
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}

Using Sun JDK 1.7.0, the bytecode and exception tables for the main method in both TryWithResources and TryCatchFinally classes is:
  stack=3, locals=6, args_size=1
     0: new           #2                  // class java/util/zip/GZIPOutputStream
     3: dup
     4: getstatic     #3                  // Field java/lang/System.out:Ljava/io/PrintStream;
     7: invokespecial #4                  // Method java/util/zip/GZIPOutputStream."<init>":(Ljava/io/OutputStream;)V
    10: astore_1
    11: aconst_null
    12: astore_2
    13: aload_1
    14: ldc           #5                  // String TEST
    16: ldc           #6                  // String UTF-8
    18: invokevirtual #7                  // Method java/lang/String.getBytes:(Ljava/lang/String;)[B
    21: invokevirtual #8                  // Method java/util/zip/GZIPOutputStream.write:([B)V
    24: aload_1
    25: ifnull        95
    28: aload_2
    29: ifnull        48
    32: aload_1
    33: invokevirtual #9                  // Method java/util/zip/GZIPOutputStream.close:()V
    36: goto          95
    39: astore_3
    40: aload_2
    41: aload_3
    42: invokevirtual #11                 // Method java/lang/Throwable.addSuppressed:(Ljava/lang/Throwable;)V
    45: goto          95
    48: aload_1
    49: invokevirtual #9                  // Method java/util/zip/GZIPOutputStream.close:()V
    52: goto          95
    55: astore_3
    56: aload_3
    57: astore_2
    58: aload_3
    59: athrow
    60: astore        4
    62: aload_1
    63: ifnull        92
    66: aload_2
    67: ifnull        88
    70: aload_1
    71: invokevirtual #9                  // Method java/util/zip/GZIPOutputStream.close:()V
    74: goto          92
    77: astore        5
    79: aload_2
    80: aload         5
    82: invokevirtual #11                 // Method java/lang/Throwable.addSuppressed:(Ljava/lang/Throwable;)V
    85: goto          92
    88: aload_1
    89: invokevirtual #9                  // Method java/util/zip/GZIPOutputStream.close:()V
    92: aload         4
    94: athrow
    95: goto          103
    98: astore_1
    99: aload_1
   100: invokevirtual #13                 // Method java/io/IOException.printStackTrace:()V
   103: return
  Exception table:
     from    to  target type
        32    36    39   Class java/lang/Throwable
        13    24    55   Class java/lang/Throwable
        13    24    60   any
        70    74    77   Class java/lang/Throwable
        55    62    60   any
         0    95    98   Class java/io/IOException

For the TryWithResources2 class, the following class produces equivalent bytecode as the try-with-resources:
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.zip.GZIPOutputStream;

public class TryCatchFinally2 {
    public static void main(String[] args) {
        try {
            final ByteArrayOutputStream baos = new ByteArrayOutputStream();
            Throwable baosEx = null;
            try {
                final GZIPOutputStream gzip = new GZIPOutputStream(baos);
                Throwable gzipEx = null;
                try {
                    gzip.write("TEST".getBytes("UTF-8"));
                } catch (Throwable t) {
                    gzipEx = t;
                    throw t;
                } finally {
                    if (gzip != null) {
                        if (gzipEx != null) {
                            try {
                                gzip.close();
                            } catch (Throwable t) {
                                gzipEx.addSuppressed(t);
                            }
                        } else {
                            gzip.close();
                        }
                    }
                }
            } catch (Throwable t) {
                baosEx = t;
                throw t;
            } finally {
                if (baos != null) {
                    if (baosEx != null) {
                        try {
                            baos.close();
                        } catch (Throwable t) {
                            baosEx.addSuppressed(t);
                        }
                    } else {
                        baos.close();
                    }
                }
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}

The bytecode and exception tables for the main method in both TryWithResources2 and TryCatchFinally2 classes is:
  stack=3, locals=10, args_size=1
     0: new           #2                  // class java/io/ByteArrayOutputStream
     3: dup
     4: invokespecial #3                  // Method java/io/ByteArrayOutputStream."<init>":()V
     7: astore_1
     8: aconst_null
     9: astore_2
    10: new           #4                  // class java/util/zip/GZIPOutputStream
    13: dup
    14: aload_1
    15: invokespecial #5                  // Method java/util/zip/GZIPOutputStream."<init>":(Ljava/io/OutputStream;)V
    18: astore_3
    19: aconst_null
    20: astore        4
    22: aload_3
    23: ldc           #6                  // String TEST
    25: ldc           #7                  // String UTF-8
    27: invokevirtual #8                  // Method java/lang/String.getBytes:(Ljava/lang/String;)[B
    30: invokevirtual #9                  // Method java/util/zip/GZIPOutputStream.write:([B)V
    33: aload_3
    34: ifnull        114
    37: aload         4
    39: ifnull        61
    42: aload_3
    43: invokevirtual #10                 // Method java/util/zip/GZIPOutputStream.close:()V
    46: goto          114
    49: astore        5
    51: aload         4
    53: aload         5
    55: invokevirtual #12                 // Method java/lang/Throwable.addSuppressed:(Ljava/lang/Throwable;)V
    58: goto          114
    61: aload_3
    62: invokevirtual #10                 // Method java/util/zip/GZIPOutputStream.close:()V
    65: goto          114
    68: astore        5
    70: aload         5
    72: astore        4
    74: aload         5
    76: athrow
    77: astore        6
    79: aload_3
    80: ifnull        111
    83: aload         4
    85: ifnull        107
    88: aload_3
    89: invokevirtual #10                 // Method java/util/zip/GZIPOutputStream.close:()V
    92: goto          111
    95: astore        7
    97: aload         4
    99: aload         7
   101: invokevirtual #12                 // Method java/lang/Throwable.addSuppressed:(Ljava/lang/Throwable;)V
   104: goto          111
   107: aload_3
   108: invokevirtual #10                 // Method java/util/zip/GZIPOutputStream.close:()V
   111: aload         6
   113: athrow
   114: aload_1
   115: ifnull        185
   118: aload_2
   119: ifnull        138
   122: aload_1
   123: invokevirtual #13                 // Method java/io/ByteArrayOutputStream.close:()V
   126: goto          185
   129: astore_3
   130: aload_2
   131: aload_3
   132: invokevirtual #12                 // Method java/lang/Throwable.addSuppressed:(Ljava/lang/Throwable;)V
   135: goto          185
   138: aload_1
   139: invokevirtual #13                 // Method java/io/ByteArrayOutputStream.close:()V
   142: goto          185
   145: astore_3
   146: aload_3
   147: astore_2
   148: aload_3
   149: athrow
   150: astore        8
   152: aload_1
   153: ifnull        182
   156: aload_2
   157: ifnull        178
   160: aload_1
   161: invokevirtual #13                 // Method java/io/ByteArrayOutputStream.close:()V
   164: goto          182
   167: astore        9
   169: aload_2
   170: aload         9
   172: invokevirtual #12                 // Method java/lang/Throwable.addSuppressed:(Ljava/lang/Throwable;)V
   175: goto          182
   178: aload_1
   179: invokevirtual #13                 // Method java/io/ByteArrayOutputStream.close:()V
   182: aload         8
   184: athrow
   185: goto          193
   188: astore_1
   189: aload_1
   190: invokevirtual #15                 // Method java/io/IOException.printStackTrace:()V
   193: return
  Exception table:
     from    to  target type
        42    46    49   Class java/lang/Throwable
        22    33    68   Class java/lang/Throwable
        22    33    77   any
        88    92    95   Class java/lang/Throwable
        68    79    77   any
       122   126   129   Class java/lang/Throwable
        10   114   145   Class java/lang/Throwable
        10   114   150   any
       160   164   167   Class java/lang/Throwable
       145   152   150   any
         0   185   188   Class java/io/IOException

A: According to section 14.20.3.1 of the Java Language Specification (JLS) for Java 7:
try (VariableModifiersopt R Identifier = Expression ...)
    Block

is equivalent to
{
    final VariableModifiers_minus_final R Identifier = Expression;
    Throwable #primaryExc = null;
    try ResourceSpecification_tail
        Block
    catch (Throwable #t) {
        #primaryExc = #t;
        throw #t;
    } finally {
        if (Identifier != null) {
            if (#primaryExc != null) {
                try {
                    Identifier.close();
                } catch (Throwable #suppressedExc) {
                    #primaryExc.addSuppressed(#suppressedExc);
                }
            } else {
                Identifier.close();
            }
        }
    }
}

The JLS goes into a lot more detail ... too much to reproduce here.

The Java 7 JLS chapter on try-with-resources is available in HTML form here, and you can get the PDF version of the JLS here.


text:
Q: Access a record, after filtering a list of type sum I have a list of
type my_sum = {a : type_a} / {b : type_b}
mylist = [{field_only_in_a = "test"} : type_a,{haha=3 ; fsd=4} : type_b]

I want to do that :
result = List.find( a -> match a with
                                      | {a = _} -> true
                                      | _ -> false
                                     end,
                                mylist)
 if Option.is_some(result) then
     Option.some(Option.get(result).field_only_in_a)
 else
     Option.none

Like you can see, after the find I'm sure to get something of type_a but on compilation time I get that :
    Record has type
{ a : type_a } / { b : type_b }  but field access expected it to have type
{ field_only_in_a: 'a; 'r.a }
Hint:
  You tried to access a sum type with several cases as a record.

How could I say to the compilator, that I have extract only one type of the sum type and that I have the good type to acces the record... ?

A: Well, you cannot really inform the compiler that only a subtype will exist in the list... but you can explicitly create a list with this subtype only. Actually, what you are looking for is List.find_map which find a first element matching a certain criteria and maps it (you use this mapping to project from my_sum to its case type_a). Below is a fully working code (compiles on its own):
type type_a = {fld_a : string}
type type_b = {fld_b : int}
type my_sum = {a : type_a} / {b : type_b}

mylist = [{a = {fld_a = "test"}}, {b = {fld_b = 10}}] : list(my_sum)

get_first_a(l : list(my_sum)) : option(type_a) =
  List.find_map(
    (el -> match el
           | ~{a} -> some(a)
           | _ -> none
    ), l)

_ = prerr("First a-typed element of {mylist} is {get_first_a(mylist)}\n")

If there was no List.find_map function in the stdlib there would still be a ton of ways to do it. Probably the simplest would be to use List.filter_map to obtain a list(type_a) and then get its head with List.head_opt.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How implement Estimote Beacons in Android? I have checked the developer link of estimote. I have followed all step in that and it's working fine. My concern is that I don't know anything more about that in detail and I am integrating this is for the first time.
Here is a simple flow of my application.
Example:
There are 10-15(or more) beacons in college. When any of student use this android app get notification based on the beacon. What if I found 3-4 beacons in my range (I don't know how to find a list of nearest beacons). I want nearest beacons id. And then I want so send the notification based on beacon type.

A: Use Android Beacon Library: it's super-easy to integrate. You should use the ranging feature. In the samples, look for Ranging Example Code.
Take into account that in background, only monitoring can be done (i.e. detecting if a given beacon is present, without knowing the estimated distance). Then, when your app becomes foreground, you can start ranging to find the distance of the visible beacons, to find the nearest one. Also, notice that this is an estimate.
On this forum it states that you need to add an specific parser for Estimote:
beaconManager.getBeaconParsers().add(
    new BeaconParser().setBeaconLayout("m:2-3=0215,i:4-19,i:20-21,i:22-23,p:24-24"));


text:
Q: Bootstrap list-group menu expands on-click, but does not collapse I've created a sidebar list-group menu in Bootstrap that expands on the first click, but the second click doesn't collapse the menu back, and clicking on other items simply expands them as well without collapsing anything.

        List Header 1

                List Item 1
                list Item 2

        List Header 2

                List Item 1
                list Item 2

I'm using standard bootstrap.min.js and none of my custom JavaScript is touching the .collapse scripts, at least not intentionally.

A: If you have this issue, check and make sure that your CMS isn't duplicating a call to any of the jQuery libraries twice. I found that due to a typo, my header was repeating and the double-call was causing several minor - but annoying - bugs.


text:
Q: Continue scanning a string until it has found the first/last occurrence of a string I have this line of text that I want to scan using regex.
axhaweacb

I want to get the text from "a" to "b". This is my current pattern:
pattern = "a.*?b";

The current output is: axhaweacb (it's taking everything in between a and b), but what I want to receive back is "acb".
Why you may ask? The logic/regex I am trying to apply is:
When you find the first occurrence of the "from" regex ("a"), start scanning. If you find another occurrence of the "from" letter without finding the "last" occurrence of a letter - in this case "b", remove the previous string - which is axh so that the string becomes: aweacb. If you find another occurrence of "from" - in this case a, without finding "to" - b. Remove the previous string so that it becomes acb. Then start scanning again. In this case we have found our pattern - a to b, without another "a" in our way.
I know that I can substring the string to begin with, and strip down everything until the last occurance of "a" - but I want to reuse this for different strings as well. And in that case, it will always substring everything until the last occurance of something - which results in removing a lot of data.
I hope I made my question/problem clear. If not, please tell me and I will do my best to clarify my problem.
Thank you.

A: The regex engine searches for a match from left to right. When it finds a with a.*?b, it is the first a in your string. Then, the first b found and matched  is the last character in your axhaweacb string.
Lazy quantifier matches up to the closest right-most character matching the subsequent subpattern, not the shortest possible substring.
So, what you need is a way to exclude (=fail if found) all occurrences of the leading and trailing subpatterns in between them.
It can be done with the help of a tempered greedy token:
pattern = "a(?:(?!a|b).)*b";
            ^^^^^^^^^^^^^

Here is a demo

A: You can use this negative lookahead based regex:
a(?:(?![ab]).)*b

*

*(?![ab]) is the negative regex to match anything but a and b`

*(?:(?![ab]).)* matches 0 or more of any character that is not a and b, thus giving us shortest match betweenaandb`

RegEx Demo


text:
Q: Drawing on bitmap with mouse is spaced out by the speed of the mouse Im making a Drawing/Editing program. I have made a drawing tool, using this code on the MouseMove event:
If down = True Then
                Using br = New SolidBrush(Color.FromArgb(ColorA, ColorR, ColorG, ColorB))
                    GFX.FillEllipse(br, e.X, e.Y, size, size)
                End Using
            End If

GFX is graphics from a bitmap called IMG.
IMG is projected on a PictureBox.
The color integers are for the color channels, ColorA is for the alpha channel.
The down boolean is to check if the mouse is down.
SolidBrush br is the brush used to render the color of the stroke
e is MouseEventArgs
Now that I explained the code I will head on the problem that im facing:

I tried to draw a cricle with the drawing tool and I've noticed the "dots" were spaced out. It seems its more spaced out if the mouse is moving at a fast speed.
Do I need to get the raw input from the mouse? I really don't know, so how do I fix this?
Thanks.


text:
Q: How to add local account of another computer to sql server? I need to add a user (\network_service) to a different computer's sql server logins.
How can I do this?  I am attempting to search for the account, but it is not finding it.
In SQL Server:
Security >
Right-Click Logins >
Click "Search" >
attempt to find \\<computername>\network_service
attempt to find \\<computername.domainname>\network_service
attempt to find <computername>\network_service

...nothing is working.  I am searching under "all locations".
This is to get a dotnetnuke website running with using a separate server for its sql database.  Supposedly, I need to add the NETWORK_SERVICE account as a sql server login.
Any ideas?

A: http://msdn.microsoft.com/en-us/library/ff647402.aspx
Network Service on one computer is Network Service on all; It is a limited-privilege, authenticatable user account common to all Windows NT machines. So, you should be able to simply grant the DB server's Network Service user access to the DB, and then applications, whether local or remote, that are authenticating themselves as Network Services should get the same access.


text:
Q: Set of products of Number N is countable How can I show that the Set of the products of a number is countable?
For example, if F the set of the products of number 5 (minus 0(zero)) F={5,-5,10,-10,15,-15,...}, how can it be proved that it's a countable set?
EDIT: By countable, I mean that set F with the set N(natural numbers with zero), can be a bijective function.

A: Construct a bijection from $N$ to $F$.
Example: If $F={0,2,4,6,...}$, then $f(n) = 2n$ will do. Just show that it's a bijection.


text:
Q: Is the complement of {(a^nb^n)^m | n>0,m>0} context-free? I've been asked to decide whether a given language is CFL. If yes, I should find the grammar that creates it, and if not, I need to prove it (with the pumping lemma).
The given language is the complement of the next language:
$L=\{(a^{n}b^{n})^{m} \mid n>0, m>0\}$. The alphabet is $\{a,b\}$.
I couldn't find any grammar that can create words of type $abaabb$ and also words of type $aabbb$.
Any suggestions?

A: Let $L=\left\{(a^nb^n)^m:n,m\in\Bbb Z^+\right\}$ and $L'=\{a,b\}^*\setminus\left\{(a^nb^n)^m:n,m\in\Bbb Z^+\right\}$; we're interested in whether $L'$ is context-free.
$L$ consists of those words having alternating blocks of $a$s and $b$s such that

*

*all of the blocks are the same positive length,

*the first block is a block of $a$s, and

*the last block is a block of $b$s.

From this characterization of $L$ it's not hard to devise a test for membership in $L'$.

*

*The empty word $\epsilon$ is in $L'$.

*Every word that begins with $b$ or ends with $a$ is in $L'$.

*Every word that has a block of $a$s either immediately preceded or immediately followed by a block of $b$s of a different length is in $L'$. (By block I mean a maximal block: a string of consecutive $a$s or $b$s that cannot be extended to a longer such string.)

*And finally, every word in $L'$ is in at least one of these three categories.

It's easy to design a context-free grammar that produces every word in the first two categories. The third category is also context-free. Here's a start on it: the grammar fragment
$$\begin{align*}
&S\to XbaaAbaY\mid aaAbaY\mid XbaaAb\mid aaAb\\
&A\to aAb\mid aA\mid\epsilon
\end{align*}$$
generates strings of the following forms, where $n>m$: $Xba^nb^maY$, $a^nb^maY$, $Xba^nb^m$, and $a^nb^m$. Provided that you give $X$ and $Y$ the right productions, these are all of the ways to have a block of $a$s followed by a shorter block of $b$s.


text: Q: Internal App Sharing in Google Play Console shows "An unexpected error occurred " On click on Internal App Sharing in Google Play Console. I get an error message saying "An Unexpected error has occurred. Please try again".  I was able to use this before. Facing this issue for a couple of days now.  Attaching a screenshot of the error message  Please check


text:
Q: How to call the method in watchkit extension from parent ios app We can call the method  openParentApplication:reply: in parent ios app from watch kit extension.
But is there any way to call the method in watchkit extension from parent ios app ?
For example:In my app when user add event in ios app then watchkit event list also should refresh so for that i need to call the refresh method in watchkit extension when user add new event in main app.
Please help.
Thanks.

A: You can't directly call a method from watchkit extension, but you can send a darwin notification (or use MMWormhole library (here), and execute proper method after recieving it.

A: You can use the built-in WatchConnectivity framework to send message from iOS app to the paired Apple Watch.
1) First, activate watch connectivity session both in iOS app and WatchKit extension. On the iOS side it can be done in application didFinishLaunchingWithOptions of the app delegate. On watch side you can run this code in applicationDidFinishLaunching method of the WatchKit extension delegate.
if WCSession.isSupported() {
  let session = WCSession.defaultSession()
  session.delegate = self
  session.activateSession()
}

2) Now send a message from your iOS app.
let session = WCSession.defaultSession()

session.sendMessage(["message from iOS app":""], replyHandler: { reply in
  // Handle reply from watch (optional)
}, errorHandler: nil)

3) Receive the message in your WatchKit extension by implementing the session didReceiveMessage method in your WCSessionDelegate delegate class.
func session(session: WCSession, didReceiveMessage message: [String : AnyObject], replyHandler: ([String : AnyObject]) -> Void) {
  if let message = message["message from iOS app"] {
    NSNotificationCenter.defaultCenter().postNotificationName("myapp.reload", object: self, userInfo: ["data": message])
  }
}

Upon receiving the message from iOS we are sending a notification with postNotificationName method.
4) Subscribe to this notification in your InterfaceController that needs updating (or anywhere else where you want to receive this update notification).
override func awakeWithContext(context: AnyObject?) {
  super.awakeWithContext(context)

  NSNotificationCenter.defaultCenter().addObserver(self, selector: "didReceiveReloadNotification:", name: "myapp.reload", object: nil)
}

deinit {
  NSNotificationCenter.defaultCenter().removeObserver(self,
  name: "myapp.reload", object: nil)
}

5) Finally, implement the notification handler method. This is where you can update your UI.
func didReceiveReloadNotification(notification: NSNotification) {
  let userInfo = notification.userInfo as? [String: String]
  if let userInfo = userInfo, data = userInfo["data"] {
    // Update UI
  }
}

Note: for the sake of readability I am using inline text string for the  notification name "myapp.reload" and the message key "message from iOS app". But in the real app it is better to use properties for these text strings to avoid typos.


text:
Q: Alignment issue with dropdown list Is there anything I can do about this?
<%=Html.DropDownList("MySelectedReport",Model.MyList,new {style="width:220px;"}) %>

alignement issue
P.S. This only happens in IE 9,8. Firefox and Chrome are rendering the dropdown aligned.

A: From what I belive, its an IE only trait Im afraid :(
Another lovely IE problem!

A: From what I see, you probably have something like this in you css select { border: 1px solid #ccc }. If you remove border style of select element, your dropdown will be rendered correctly.


text:
Q: astype('float') changes data, not just data type I download a bunch of csv-files from an aws s3-bucket and put them in a dataframe. Before uploading the dataframe to sql server I would like to change the columns of the dataframe to have the right datatypes.
When I run astype('float64') on a column I want to change it not only changes the datatype but also the data.
Code:
df['testcol'] = df['lineId'].astype('float64')

pycharm image of the result
I attached a picture to visualize the error. As you can see the data in the third column (testcol) is different to the data in the second column (lineId) even though only the datatype should be changed.
A pl_id can have multiple lineId's, that's why I added and sorted by pl_id in the picture.
Am I using astype() wrong or is this a pandas bug?

A: Basically it seems that the float64 is not sufficient to carry that long integer:
np.float64('211052094743748628')
Out[135]: 2.1105209474374864e+17

"The max precision a float 64 can reach is close to 10-16 (unit in the last place (ULP), see en.wikipedia.org/wiki/Floating-point_arithmetic) so the idea of an exact decimal value with significantly more than 16 digits for a floating point is misleading."
Numpy float64 vs Python float
Consider maybe using int64, which can be more suitable for the size of Id in your dataset:
np.int64('211052094743748628')
Out[150]: 211052094743748628


text:
Q: Sort NSMutableArray of objects by date self.objectSet = [NSMutableArray array];

//add objects to set

[self.objectSet sortUsingComparator:^NSComparisonResult(id a, id b) {
    NSDate *firstDate = [(Entity *)a createdAt];
    NSDate *secondDate = [(Entity *)b createdAt];
    return [secondDate compare:firstDate];
}];

I want to sort the nsmutablearray by createdAt date. However the above code has no effect on the displayed table view. The data is unsorted.
Any ideas whats wrong?

A: Did you try to sort with sort descriptors?
Is it the same effect?
NSSortDescriptor *sortDescriptor = [NSSortDescriptor sortDescriptorWithKey:@"createdAt" ascending:YES];
[self.objectSet sortUsingDescriptors:@[sortDescriptor]];


text:
Q: how to get mobile online status of the facebook user using smack? I am developing Facebook chat application using smack.

*

*Here I want to get online user status of both mobile user's  & website user's,
and how can I differentiate both of them.

*If a user send message ,how can I differentiate he is mobile user
(or) website user?

A: Why dont you get it from RosterEntry class
Roster roster = xmppConnection.getRoster();
Collection<RosterEntry> entries = roster.getEntries();
Presence presence;

for(RosterEntry entry : entries) {
    presence = roster.getPresence(entry.getUser());

    System.out.println(entry.getUser());
    System.out.println(presence.getType().name());
    System.out.println(presence.getStatus());//This is what you wanted
}

A: For #2, You may use Mobile EESP library.


text:
Q: Sql nao retorna nome de coluna Tenho duas tabelas uma TEAM outra MATCH_DETAILS. A tabela TEAM tem a coluna id e é chave primaria. Fiz duas relaçoes da tabela TEAM para MATCH_DETAILS. Na MATCH_DETAILS assumiu como chave estrangeira team_id e team_id1.
Com a seguinte query:
SELECT
  team_name, team_id1, Umpire_name,
  playermatch_name, score_id
FROM
  Match_details m, Team t,
  Umpire u, player_match p, Score s
WHERE m.TEAM_TEAM_ID = t.TEAM_ID
  and m.TEAM_TEAM_ID1 =  m.TEAM_TEAM_ID1
  and m.UMPIRE_UMPIRE_ID = u.UMPIRE_ID
  and p.Match_details_MATCH_ID = m.match_id
  and s.Match_details_MATCH_ID = m.match_id;

Retorna o seguinte:

A euipa Chelsea tem como id numero 1  o id numero 2 na coluna team_id1 corresponde a euipa liverpool. aquilo que pretendo é aparecer Liverpool e não o id que corresponde.

A: Em primeiro lugar, eu sugeria utilizar junções explícitas ao invés de junções implícitas (ANSI-92). Apesar de não haver diferenças de performance, a "nova" sintaxe é bastante mais legível quando existem muitas tabelas envolvidas (como é o seu caso).
Dito isto, a sua query pode ser re-escrita da seguinte forma.
SELECT  T1.TEAM_NAME,
        T2.TEAM_NAME,
        U.Umpire_name,
        playermatch_name,
        score_id
  FROM Match_details m_d,
 INNER JOIN Team T1  -- Detalhes da primeira equipa
    ON T1.TEAM_ID = m_d.TEAM_ID
 INNER JOIN Team T2  -- Detalhes da segunda equipa
    ON T2.TEAM_ID = m_d.TEAM_ID1
 INNER JOIN Umpire U
    ON U.UMPIRE_ID = m_d.UMPIRE_UMPIRE_ID
 INNER JOIN player_match P
    ON P.Match_details_MATCH_ID = m_d.match_id
 INNER JOIN Score S
    ON S.Match_details_MATCH_ID = m_d.match_id

Note a dupla junção na tabela TEAM: Uma para a primeira equipa (no seu exemplo Chelsea) e outra para a segunda equipa (Liverpool). Para mostrar o nome da segunda equipa no resultado, basta selecionar o nome da tabela respective (T2) ao invés do ID.


text:
Q: How to manipulate string items in a 3d list in python? (without numpy) I have a 3d list 6 items long and 6 items wide, which is a list of lists of a list of strings.
lst = [   [['A'],['A'],['B'],['B'],['A'],['A']],
          [['B'],['B'],['A'],['A'],['B'],['B']],
          [['A'],['A'],['B'],['B'],['A'],['A']],
          [['B'],['B'],['A'],['A'],['B'],['B']],
          [['A'],['A'],['B'],['B'],['A'],['A']],
          [['B'],['B'],['A'],['A'],['B'],['B']],
  ]

I want to move the strings into other locations on the list, but I know I'm not using the right code:
lst.insert([1][0][0], 'A')

gives me a TypeError: 'int' object is not subscriptable
I know how to add items by doing this:
lst2 = lst[0][0]

lst2.append('A')

(adds another 'A' string to the first item)
I want to perform various actions on the lowest list like:

*

*add/remove strings to that list,

*check how many string items are in that list

*move 'A' or 'B' strings to different locations so that they have multiple strings.

*Check to see what the first string is in the list is

I am very new to programming and I am just starting to understand how to use 2d lists.
How do I accomplish this without any additional modules or libraries?

A: First of all, let me clarify this line:

lst.insert([1][0][0], 'A')

The insert method expects an int argument for the index. If you want to insert an element in a multidimensional list it should be done as:
lst[1][0].insert(0, 'A')

After all, it is a list of list (of lists). Only if you look at an inner index (defined by 2 coordinates), will you get a simple list (of strings in this case). You can then insert a string element to this simple list, by calling the insert() method.

check how many string items are in that list

count = 0
for d2 in lst: #d2 is a 2d list (an element of a 3d list)
    for d1 in d2: # d1 - 1 dimensional
        count += len(d1)

Here, I have gone through each of the lowermost-level (simple) lists using a nested loop, counted how many elements are there in each and added them up.

move 'A' or 'B' strings to different locations so that they have multiple strings.

Say I want to move the element from [3][2][0] to [1][2][1]. I would insert it in the new position and then delete from the old.
element = lst[3][2][0]         # the task can be accomplished without using another variable, but this is for better understanding
lst[1][2].insert(1, element)   # inserting
lst[3][2].pop(0)               # deleting

The element could even be moved to a position like [1][2]. So there would be one string along with the other 'sub-lists'

Check to see what the first string is in the list is

Do you mean lst[0][0][0].


text:
Q: Facebook POST callback I have a Facebook "Like" button, I placed it in my site, I can easily detect if someone click on the "Like":
// DETECT LIKE
FB.Event.subscribe('edge.create',
    function(response) {
        alert('You LIKED My Page');
    }
);

Right after he "Like" my page, a small flying window will be opened by the button so the user could also "Post" something about my page on his wall.
I looked all around, I can't see anyway to detect while a user "Post" a thing on his wall from my "Like" button, is there anyway for doing this?
Thanks in advance

A: AFAIK there is one way. If you saved the user's ID and object ID (this kind of "Like" is done by OG) you can grab all og.likes from this user FB.api('/USER_ID/og.likes', function(response) {
  <iterate through response to find specified object ID and user's post message will be under "message" field>
});
Try it here: Facebook OG explorer og.likes
GL!

A: Why not analyse the response from the post action?
FB.ui('/me/feed', {method: 'feed'}, function (response){
    if (response.post_id){
        // Something was posted by the user
    } else {
        // Nothing was posted
    }
});


text:
Q: Parallax in WordPress I have the following parallax code in my page-parralax.php file:
get_header(); ?>

<?php
    $args = array(
        'post_type' => 'parallax',
        'order' => 'ASC',
        'orderby' => 'menu_order'
        );
    $parallax = new WP_Query($args);
        while($parallax->have_posts()) : $parallax->the_post();

        $parallaxImage = wp_get_attachment_image_src( get_post_thumbnail_id($post->ID), 'large');
        $breakUrl = str_replace('http://localhost/themes', '', $parallaxImage[0]); ?>

            <section class="parallax" id="section_<?php echo the_ID(); ?>" style="background: url('../<?php echo $breakUrl; ?>') fixed;">

            <section id="section_<?php echo the_ID();?>" class="parallax" style="background: url('../<?php echo $breakUrl; ?>') fixed;">

<?php the_title(); ?>

                <?php the_content();?>

<?php
    endwhile;
    wp_reset_postdata();
    get_footer();
?>

But when I try to see it, it returns the following error:
GET http://localhost/themes/index.php/wp-content/uploads/2015/10/macbook_overview_og-700x700.jpg 404 (Not Found) for each image.
If i change it in the console afterwards to:
http://localhost/themes/wp-content/uploads/2015/10/macbook_overview_og-700x700.jpg it displays correctly.
Is it because I am using localhost it creates this error?

A: You got to go deeper upper:
background: url('../..<?= $breakUrl; ?>')

I've removed the trailing slash, as your URL starts with it. Also you might consider setting up <base> URL and working with relative URLs from the start.


text:
Q: Build Failed Flutter Note: Recompile with -Xlint:deprecation for details.
D8: Program type already present: android.support.v4.os.ResultReceiver$MyResultReceiver
FAILURE: Build failed with an exception.

*

*What went wrong:
Execution failed for task ':app:transformDexArchiveWithExternalLibsDexMergerForDebug'.

com.android.builder.dexing.DexArchiveMergerException: Error while merging dex archives:
  Learn how to resolve the issue at https://developer.android.com/studio/build/dependencies#duplicate_classes.
  Program type already present: android.support.v4.os.ResultReceiver$MyResultReceiver

*Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.

*Get more help at https://help.gradle.org

BUILD FAILED in 8s
  ******************************************************************************************* The Gradle failure may have been because of AndroidX incompatibilities
  in this Flutter app. See https:/goo.gl/CP92wY for more information on
  the problem and how to fix it.
  ******************************************************************************************* Finished with error: Gradle task assembleDebug failed with exit code 1

in my pubspec.yaml file

dependencies:   flutter:
      sdk: flutter   flutter_localizations:
      sdk: flutter
# The following adds the Cupertino Icons font to your application.
Use with the CupertinoIcons class for iOS style icons.   cupertino_icons: ^0.1.2   image_picker: ^0.4.12+1   image_cropper:
^1.0.1   http: ^0.12.0+1   sqflite: ^1.1.3   path_provider: ^0.5.0+1
  rxdart: ^0.21.0   share: ^0.6.0+1   shared_preferences: ^0.5.1+2
  flutter_svg: ^0.12.1   material_search: ^0.2.8   flushbar: ^1.3.0
  connectivity: ^0.4.3+1   flutter_bloc: ^0.9.1   bloc: ^0.11.2   dio:
  ^2.1.3

A: its right in the warning message
org.jetbrains.kotlin:kotlin-gradle-plugin:1.2.71
update your kotlin plugin in the gradle file to 1.3.0

A: I had to upgrade my kotlin version to something later - I chose 1.3.60 and my gradle version to 3.5.2 in my android-level build.gradle:
// android/build.gradle
buildscript {
    ext.kotlin_version = '1.3.60'
    repositories {
        google() // Google's Maven repository
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.5.2'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath 'com.google.gms:google-services:4.3.3' // Google Services plugin
    }
}

I then had also to upgrade my gradle distribution url:
// android/gradle/wrapper/gradle-wrapper.properties
distributionUrl=https\://services.gradle.org/distributions/gradle-5.4.1-all.zip

I was able to successfully flutter run after changing these.


text:
Q: Add subview to view at particular position I've used the this reference to display the line graph
By above code, graph gets displayed on separate view.
I want to display it in particular area of view and not as new view. So, I used this snippet
 layout.addView(graphView, 200, 250);

This works fine but the issue is how do I specify the starting co-ordinates for this view.
It's getting placed at left top. I want it at some particular position.
THANKS IN ADVANCE !!

A: After adding view in layout, try using LayoutParams to set attributes of it. I think that way you can set X and Y co-ordinate of view.


text:
Q: How to remove iPad device from App Store in developer account? How to remove an iPad device from App Store in developer account?
I am following this process from my understanding --

*

*Remove the live app completely

*Again upload a new build of the same package without Ipad device

Is it okay or I am following the incorrect procedure. Do let me know, please?

A: Yes, you can remove it or submit a new version. You can check which device screens your app consists of by clicking "View All Sizes in Media Manager in your developer account App page"

A: As far as I remember, once you've released a build with iPad support, AppStore Connect will reject any future builds that don't include iPad support.
So you can't remove iPad support.

A: Refer to this image to remove iPad from your next build:

A: No need to remove your app from AppStore to support just only iPhone devices. App store connect is responsible to manage the device family support
Archive your new build with deployment info iPhone and increase version number as shown in the image

*

*Push your new build at AppStore

*Open app store connect and select your App

*check device family support in the build metadata section


text:
Q: Shell: why [ x"$myvar" = x0 ] instead of [ "$myvar" = 0 ] / why add a letter character to tested variable? There may be a duplicate somewhere (I guess), but I didn't find it so:
Why do I see in some scripts those kind of tests:
if [ x"$quiet_boot" = x0 ]

with an x added before the actual variable that is tested? I checked this related question but it tries to avoid problems with unset variables when the shell is configured to stop a script immediately if that script uses an unset variable.
So, why this use here?
Why not just writing if [ "$quiet_boot" = 0 ]?

A: I actually found a duplicate (second) while writing this question...
Adding a letter prefix is actually a workaround for some (mostly legacy) implementations of the test (aka [) utility, within a shell context. Such as when myvar is equal to -o, -n or (, which in some cases could be confused with an operator (and that would be avoided by prefixing with say x). By design of how the shell is working, the test command has no way to be sure that, when it receives its arguments, a given particular arg is either an operator or an operand.
My test(1) manual warns:

NOTE:  Binary  -a  and -o are inherently ambiguous.  Use 'test EXPR1 && test EXPR2' or 'test EXPR1 || test EXPR2' instead.

So, today, my dash sh implementation is like this:
b="("
test "AAA" = "AAA" -a "$b" = "BBB"
# yields "test: closing paren expected"

could be avoided with x"$b" = x"BBB" or with two tests like test "AAA" = "AAA" && test "$b" = "BBB".
a='='
b=x
test -n "$a" -a -n "$b"
# yields test: -a: unexpected operator

this shows ambiguity which could be avoided by using "$empty" = "" (rather than -n) if -a or -o is in use, and thus using prefixing (x"$empty" = x) for parenthesis issues in this case.

Usually, nowadays:

*

*doing only one test is safe (max 3 arguments, not using -o nor -a) and doesn't require this workaround (except old/buggy implementation),

*Using -o/-a, especially when operands may look like operators or parenthesis (/) can be ambiguous and buggy, and this workaround can help.

Note that for safety you should always quote "$variables" passed to test, so that they are always interpreted as one argument, even if they contain spaces.
For more details, Stéphane Chazelas wrote a quite comprehensive answer to this question that I encourage you to read. I'm still posting this question & answer so that more cues point to the information that would be easier to find.
Today implementations corrected many legacy implementation problems leading to ambiguous behaviour, so that on those, prefixing with say x for tests not using -o or -a is often unnecessary.


text:
Q: What is the sum of a generalised gamma variable and a normal variable? If $G\sim \mathcal{GG}(\alpha,\beta,\gamma)$ and $N\sim\mathcal{N}(\mu,\sigma^2)$ then what is $G+N$? Can it even exist since the two distributions have different support?
I have tried to solve this two ways using a convolution, but get stuck on the integrals.
The first is to take a standard convolution
\begin{align*}
f_{G+N}(x)&=\int_{0}^{\infty} f_N(x-y)f_G(y)dy\\
&=C_1\int_0^{\infty}y^{\beta-1}e^{-C_2 (x-y-\mu)^2-C_3y^\gamma}dy
\end{align*}
but this integral is difficult to solve (Mathematica has no solutions).
The other is to see that you can write $G=|N^*|^p$ where $N^*$ is normal. Then
\begin{align*}
f_{|N^*|^p+N}(x)&=\int_0^{\infty} f_{N^*}(x-|y|^p)f_N(y)dy\\
&=C_1\int_0^{\infty} e^{-C_2(x-|y|^p-\mu_{N^*})^2-C_3(y-\mu)^2}dy
\end{align*}
but this integral is also very difficult to solve (Mathematica fails once again).
If there is a suggestion regarding the integrals, or a known result regarding the main question, I would appreciate it.

A: This is just an extended comment in that using Assumptions in Mathematica will find the pdf of the sum for $\gamma=1$ and $\gamma=2$.
Integrate[E^(-((x - y - μ)^2/(2 σ^2)))/(Sqrt[2 π] σ)*
  (E^-(y/β)^γ (y/β)^(-1 + α γ) γ)/(β Gamma[α]) /. {γ -> 1},
  {y, 0, ∞}, Assumptions -> {σ > 0, α > 0, β > 0}]

Integrate[E^(-((x - y - μ)^2/(2 σ^2)))/(Sqrt[2 π] σ)*
  (E^-(y/β)^γ (y/β)^(-1 + α γ) γ)/(β Gamma[α]) /. {γ -> 2},
  {y, 0, ∞}, Assumptions -> {σ > 0, α > 0, β > 0}]

There might be other special cases.


text:
Q: Regex direct capture group replace I am creating steps in Notepad++ to convert code from one form to another. For each line, I want to add "+@lin" at the beginning, then for each tab that follows add a "+@tab",then a single quote, then whatever remains, then another quote. Example:
Hi,
    adorable SO ppl!

should become
+@lin+'Hi'
+@lin+@tab+'adorable SO ppl!'

I have managed this in two steps:
First: replace ^(\t*)(.*)$ with \+@lin\1\+'\2'
Second: replace \t with \+@tab
I am wondering if this can be done better with a single replace. Can it be done?
One think I thought: Is it possible to use the asterisk of the \1 capture group to replace each \t instance with something else?

A: You might use a 2 capture groups with a conditional replacement.
Find what:
^\t(.*)|(.*)

*

*^ Start of string

*\t(.*) match a tab and capture the rest of the string in group 1

*| or

*(.*) Capture the whole line in group 2
Replace with:
(?{2}\+@lin\+'\2':\+@lin\+@tab\+'\1')

*

*(?{2} Check if capture group 2 exists

*

*\+@lin\+'\2' If it does, use the replacement with the capture group 2 value

*:\+@lin\+@tab\+'\1' else use the replacement with the capture group 1 value

*) Close


text:
Q: wxPython wx.FileDialog does not show wildcard filter on MacOS Using wxPython (3.0.2) on MacOS (10.13), I would like to open a file dialog with a wildcard filter. To do so, I tried the following snippet:
import wx

app = wx.App()

frame = wx.Frame(None, -1, 'win.py')

# Create open file dialog
openFileDialog = wx.FileDialog(frame, "Open", "", "",
                                      "Python files (*.py)|*.py",
                                       wx.FD_OPEN | wx.FD_FILE_MUST_EXIST)

openFileDialog.ShowModal()

that I borrowed from here
The dialog pops up but without the wildcard filter widgets. The same code works as expected on ubuntu-xenial. Would you have any idea of what is wrong with that snippet and how to fix this to make this code OS independant ?

A: The following system option has to be set:
wx.SystemOptions.SetOption(u"osx.openfiledialog.always-show-types","1")
In doing so, a combo box for selecting the files according to a set of file filters will be available when opening a file dialog.


text:
Q: How can I make this animation "Rail Text" seen on example I am very curious about how this rail text animation is made ("Creativity meets healthy food")
https://www.studiogusto.com/project/misura/
I've looked thousands of css generator webs and I can't find that animation! When going into developer tools, I don't understand why they copy and paste it so many times. Does anybody has a clue? I'd like to use it to put an "under construction" in my own web.
I tried to look for animation examples and I don't find it. When inspecting the code, I don't understand why they copy and paste it so many times.
Please note I am a beginner :)
Thanks,

A: ... it looks like a CSS TRANSFORMATION of the block of text. And there's always the option to use something like GreenSock js lib (that's a whole different bag of possibilities though)


text:
Q: Passing and using function as constructor argument in Kotlin How to create a class that takes function as a constructor argument. Then, use this function at some later point in the class.

A: You can have a property with a function type just like you would with any other type:
class A(val f: () -> Unit) {

    fun foo() {
        f()
    }

}

From here, you can pass that function to the constructor as a method reference:
fun bar() {
    println("this is bar")
}

val a = A(::bar)
a.foo()             // this is bar

Or as a lambda:
val a = A({ println("this is the lambda") })

And you can even do the usual syntactic sugar for lambdas that are the last parameter of a function (although this is getting a little wild):
val a = A { println("this is the lambda") }

A: If you have more than one constructor declarations you can use this
...

private var listener : (() -> Unit)? = null

constructor(context: Context, listener: (() -> Unit)?) : this(context){
        this.listener = listener
}

constructor(context: Context) : super(context, attrs = null)

...

A: A real world example can be observed in SynchronizedLazyImpl, the class backing lazy delegates.
public fun <T> lazy(lock: Any?, initializer: () -> T): Lazy<T> =
    SynchronizedLazyImpl(initializer, lock)

When we use val x by lazy {...}, the initializer, passed as a lambda, is actually stored as a property in an instance of SynchronizedLazyImpl and called later when the corresponding val x is being accessed for the first time.


text:
Q: Ruby on Rails Multiple HTTP request at the same time? I'm pulling multiple requests (its pulling one at a time), I was wondering if there's a way pull requests all at the same time if I have something like this:
client = Instagram.client(:access_token => session[:access_token])
@user = client.user
@recent_media_items = client.user_recent_media

@lv = client.tag_recent_media('lv', options = {:count => 60})
@lv1 = client.tag_recent_media('lv1', options = {:count => 60})
@lv2 = client.tag_recent_media('lv2', options = {:count => 60})
@lv3 = client.tag_recent_media('lv3', options = {:count => 60})

Each lv makes a request to client. I was wondering if there's a way to do such so it can do the request all at once (together), instead of one finishes the request, then goes on to the next request, and so on...
Thanks!

A: There are gems like spawn that do this in a forked process or as a new thread in your process.. Here is a link to another SO post that discusses it
What is the difference between forking and threading in a background process?
Here is the gem in question: https://github.com/tra/spawnling

A: Yes! For a proof-of-concept, try
require 'thread'

client = Instagram.client(:access_token => session[:access_token])
@user = client.user
@recent_media_items = client.user_recent_media

threads = []
threads << Thread.new { @lv = client.tag_recent_media('lv', options = {:count => 60}) }
threads << Thread.new { @lv1 = client.tag_recent_media('lv1', options = {:count => 60}) }
threads << Thread.new { @lv2 = client.tag_recent_media('lv2', options = {:count => 60}) }
threads << Thread.new { @lv3 = client.tag_recent_media('lv3', options = {:count => 60}) }
threads.each(&:join) # this waits for all the threads to finish before proceeding
puts [@lv, @lv1, @lv2, @lv3]

In practice, you will want to set up some error handling and retry settings within the threads. Also, you may run into issues with thread-safety in the Instagram gem. If you are doing this on a large scale with hundreds or thousands of requests, you may want to try a concurrent HTTP client like Typhoeus or an evented HTTP client like EM-HTTP-Request. For these, you would have to manually implement the tag_recent_media method that is in the Instagram gem.


text: Q: Does Format Function Work In SQL Server 2012? I want to use the format function to format a phone number in an SQl 2012 database but i keep on saying that format is not a recognized build in function? what do you think is wrong?


text:
Q: Intuition behind linear differential operators In an introductory course on linear differential equations I was introduced to an operator $D$ of order $n, \frac{d^n}{dx^n}$ and subsequently, all problems thereafter were solved by treating it as any other real number. For instance to solve a linear O.D.E,

$a_0(x)\frac{d^2y}{dx^2}+a_1(x)\frac{dy}{dx}+a_2(x)y=0$
$a_0(x)D^2y+a_1(x)Dy+a_2(x)y=0$
$(a_0(x)D^2+a_1(x)D+a_2(x))y=0$
$(D-m_1)(D-m_2)y=0$

The last step is not intuitive at all. How can we justify such a treatment of $D$? Can anyone explain/point me to a reference?


text:
Q: Definition of Quality Factor $Q$ The stored energy definition of the quality factor $Q$from wiki Q-factor from wiki
is given by
$$ Q = 2\pi \frac{\text{energy stored}}{\text{energy dissipated per cycle}}=
 2\pi f_0 \frac{\text{energy stored}}{\text{power loss}} $$
($f_0=$ resonance frequency) More generally and in the context of reactive component specification
(especially inductors or caps),
the frequency-dependent definition of $Q(f)$ is used:
$$Q(f)=  2\pi f \frac{\text{maximum energy stored}}{\text{power loss}}$$
Question: I not understand how to interpret what is meant here by
"power loss" in the denominator in pure mathematical terms?
Note that in both cases we deal with formulas of the form $Q= \frac{A}{\text{ power loss }}$ resp
the frequency dependent $Q(f)= \frac{A(f)}{\text{ power loss(f) }}$ where $Q, A $ and the "power loss" are regarded as "constants. (In frequency dependent case these are considered as constants too after having fixed an concrete $f$)
In LCR-oscillator case it's rather easy to write down the constant $A$ as $2 \pi f_0 \cdot E$ where $E:= \frac{1}{2}CV(t)^2+ \frac{1}{2}LI^2(t)$. Note, that although $\frac{1}{2}CV(t)^2$ and $\frac{1}{2}LI^2(t)$ aren't constant, their sum $E$ is; that's energy conservation.
In second case we have $A(f)= 2 \pi f \cdot \max\{E(t) \ \vert \ t \in [0, T]\}$.
Now the question is what is the explicit expression for "power loss"?
My conjecture is that the "power loss" here should be somehow related to the real power $P_R(t)$ discussed here, but how? Is it it's maximal value within $[0,T]$, or it's average value?
Note, here was asked another question about the definition of the Q-factor but it not treats the "power loss" interpretation; that's exactly the concern of this question.


text:
Q: Time Tracker in Android Independent of the System time I've tried to google around but I still can't find the best answer.
All I want is very simple, I am new to Android and I am developing a Game which will give some daily Bonuses to the user, if he plays Everyday.
My Code is:
date = new Date();
    dateFormate = new SimpleDateFormat("yyyy/MM/dd");
    dateString = dateFormate.format(date);
        if(!sharedPreferences.getString("date").equals(dateString))
    {
            sharedPreferences.putString("date", dateString).commit();
            ... Here I give Bonus to user
        }

BUT the Problem is, This code is dependent on the System Date. User can Easily change the date and can get its daily Reward.
I want to track 24 hours time once he starts playing The game.
Can Anyone Help me Please.
This would be much Appreciated.

A: If your app has internet access you could get time from your own server, rather than user time.
You could listen to Intent.ACTION_TIME_CHANGED and sync with server time only if you have recieved this intent.  You wont be syncing with server unless user changes time manually.

A: instead of comparing that date has changed you can check if

*

*date is bigger than previos one: asssign bonus and remeber date

*date is smaller than previos one: user is cheating-remove all bonuses and do not update old date

this solution is of course not bullet proof but more secure than you previos one


text:
Q: Fixing Broken Indexer Process: Table Truncation Safety Earlier today, I had a (third party) product price indexer that consistently failed with the following message:

"Product Prices Index process is working now. Please try run this process later."

First, I attempted to remove the lock files from /var/locks.  This did not resolve the issue.  Next, I manually truncated the following tables:
catalog_product_index_price
catalog_product_index_price_bundle_idx
catalog_product_index_price_bundle_opt_idx
catalog_product_index_price_bundle_opt_tmp
catalog_product_index_price_bundle_sel_idx
catalog_product_index_price_bundle_sel_tmp
catalog_product_index_price_bundle_tmp
catalog_product_index_price_cfg_opt_agr_idx
catalog_product_index_price_cfg_opt_agr_tmp
catalog_product_index_price_cfg_opt_idx
catalog_product_index_price_cfg_opt_tmp
catalog_product_index_price_downlod_idx
catalog_product_index_price_downlod_tmp
catalog_product_index_price_final_idx
catalog_product_index_price_final_tmp
catalog_product_index_price_idx
catalog_product_index_price_opt_agr_idx
catalog_product_index_price_opt_agr_tmp
catalog_product_index_price_opt_idx
catalog_product_index_price_opt_tmp
catalog_product_index_price_tmp
catalog_product_index_tier_price

This did seem to resolve the issue.
My question is this: Are there any hidden consequences of truncating these tables that might show up later?  Is this a safe operation to perform on a live database?  If so, I will be creating a tool for the project administration to use in the future.
Thanks for your time.

A: I would suggest getting the Magento database repair program. Then compare your database to a good backup.


text:
Q: Moving a file from a directory to home directory using shell script, it works as a standalone command(as in outside the .sh file) Below is my .sh file
sh summaryByClient.sh $1 - takes around 10 mins to fetch the required data
mv summary.html ~/public_html/chats/ - **this is not happening**
exit 0

I do not understand why mv summary.html ~/public_html/chats/ this is not working inside .sh file, However I am able to mv separately using the same above command.

A: Could you be running into the issue from this answer with expanding the user's home directory?  What happens if you write your script like this:
#!/bin/bash

# Other tasks to retrieve summary.html done here
mv ./summary.html $HOME/public_html/chats/
exit 0

Also, it's always a good idea to check whether the destination directory exists before a mv command.  Examples are shown in this answer


text:
Q: How to use the new iOS 6 registerClass UITableView method with multiple cell types I am running into an issue using the new registerClass method for UITableView. I register my cell fine, and then when I want to make a cell I do this:
static NSString *imageIdentifier = @"image";
CustomCell *cell = [self.tableView dequeueReusableCellWithIdentifier:imageIdentifier];

if (!cell) {
    cell = [[CustomCell alloc] initWithQuestion:self.question reuseIdentifier:imageIdentifier];
    [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
}

This may not be the modern way to do it, but it is how I've done it before. The issue is that because the new registerClass method makes a new cell for you if there isn't one in the queue, the if (!aCell) check fails, and the cell isn't built correctly.
Am I not using this new approach to dequeueing correctly?

A: 1) Set up the cell (in your case the selectionStyle) in the prepareForReuse method of your UITableViewCell subclass.
2) Set the content of the cell after the dequeueReusableCellWithIdentifier: call in tableView:cellForRowAtIndexPath: delegate method.
dequeueReusableCellWithIdentifier: will always return a cell if you have called registerClass: with the corresponding identifier.

A: You use the new method, dequeueReusableCellWithIdentifier:forIndexPath:, and leave out the if clause.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    CustomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"myCell" forIndexPath:indexPath];
    // configure cell here
    return cell;
}

You would use the same reuse identifier when you register your class or xib.


text:
Q: input text size attribute not working IE8 I have an html page dynamically generated by javascript with the onLoad event.
This is the javascript:
function populateTable(q,a1,a2,a3,a4) {
    var i;
    for (i=0;i<10;i++) {
        table = document.createElement("table");
        table.appendChild(createQuestion(q,i));
        for (var j=0;j<4;j++) {
            var answer= eval("a" + (j+1));
            table.appendChild(createAnswers(j,answer,i));
        }
        var tabform= document.getElementById("tablesform");
        tabform.appendChild(table);
    }
}

function createQuestion(quest,i) {
    var row = document.createElement("tr");
    var tabd = document.createElement("td");
    tabd.setAttribute("class","question");
    var qinput=document.createElement("input");
    qinput.setAttribute("type","text");
    qinput.setAttribute("name","q" + (i+1));
    qinput.setAttribute("value",quest[i]);
    qinput.setAttribute("readonly","readonly");
    qinput.setAttribute("size","50");
    row.appendChild(qinput);
    var tabd1 = document.createElement("td");
    var rdiv = document.createElement("div");
    rdiv.setAttribute("id","result" + (i+1));
    tabd1.appendChild(rdiv);
    row.appendChild(tabd1);

    return row;
}

in FF it works fine, it makes 10 neat tables, each with the question inside the text input on the first row, with all of the text input fields of the same size (50), etc etc..
on IE8 the text field remains empty, and moreover its size is not fixed! The strange thing is that if I go look at the html that was generated i see:
<FORM id=tablesform method=post action=processquiz.php>
    <INPUT value=" - Correct The Test - " type=submit>
    <INPUT onclick="window.location='logout.php'" value=" - Log Out -  " type=button>

            <INPUT value="What browser has the most DHTML extentions?" readOnly size=50 type=text name=q1>

which is perfectly fine! What could be the problem?
EDIT: document is html 4.01 strict


text:
Q: Spark - Is it possible to control placement of partitions to nodes? In Spark, custom Partitioners can be supplied for RDD's. Normally, the produced partitions are randomly distributed to set of workers. For example if we have 20 partitions and 4 workers, each worker will (approximately) get 5 partitions. However the placement of partitions to workers (nodes) seems random like in the table below.
          trial 1    trial 2
worker 1: [10-14]    [15-19]
worker 2: [5-9]      [5-9]
worker 3: [0-4]      [10-14]
worker 4: [15-19]    [0-4]

This is fine for operations on a single RDD, but when you are using join() or cogroup() operations that span multiple RDD's, the communication between those nodes becomes a bottleneck. I would use the same partitioner for multiple RDDs and want to be sure they will end up on the same node so the subsequent join() would not be costly. Is it possible to control the placement of partitions to workers (nodes)?
          desired
worker 1: [0-4]
worker 2: [5-9]
worker 3: [10-14]
worker 4: [15-19]

A:
I would use the same partitioner for multiple RDDs and want to be sure
  they will end up on the same node so the subsequent join() would not
  be costly.

This is the right way to handle joins between RDDs so that records to be joined are ensured to be in the same partition/executor.

Is it possible to control the placement of partitions to workers
  (nodes)

It is not possible to explicitly specify the worker node for each partition. This would break the abstractions of parallel computation defined for Spark or any other parallel computation frameworks like Map-Reduce/Tez etc.
Spark and other parallel computation frameworks are designed to fault tolerant. So this means if a small subset of worker nodes fail, then are replaced with other worker nodes and this process occurs transparently to the user application.
These abstractions would break if a user is allowed to explicitly refer a worker-node in the application. The only means of governing the placement of a partition of RDD is by specifying your own partitions for the RDD partitioner.


text:
Q: Microsoft.VisualStudio.TestTools.LoadTesting cannot be found after upgrading to Visual Studio 2017 Having recently updated from Visual Studio 2015 to 2017, I ran into a referencing issue where performance testing namespaces and dll references seem to have disappeared.
I finally figured out what had caused it, but figured a few people may run into this, so I will also be including the solution.

A: To solve this you have to first load up visual studio installer (It's installed alongside Visual Studio 2017) and click on modify.
Then click on Individual components and select the items shown in this image:
Microsoft test manager
testing tools core features
Web performance and load testing tools

Make sure you restart VS 2017 after installing these, I had to do a clean and rebuild as well.


text:
Q: Find duplicate data in last 1 hour I am looking for a SQL script to find the data which has more than 2 entries in last 1 hour.
I have a table having user_id & event_time. I want a way to find out if the user_id has more than 1 entries in last 1 hour.
I have tried below till now:

*

*Create temp table to put all duplicate entries :

SELECT a.*
INTO #temp
FROM Table a
JOIN (
    SELECT USERID, COUNT(*) AS Duplicates
    FROM Table
    GROUP BY userid
    HAVING count(*) > 1
) AS b ON a.userid = b.USERID

*Run self Joins to fetch records having time difference of 1 hour or less:

SELECT a.*
FROM #temp a
INNER JOIN #temp b ON a.userid = b.USERID
WHERE DATEDIFF(hour, a.EVENTTIME, b.EVENTTIME) = 1

Once first script is ran it gives around 800+ rows for duplicate data. But after running the second script the data I get is in thousands.
Can anyone help here?

A: cross apply can be used to get all related events for each event according to your criteria as follows:
With CTE As (
Select USERID, EVENTTIME, Row_Number() Over (Order by USERID, EVENTTIME) As ID
From Tbl
)
Select a.ID, a.USERID, a.EVENTTIME, T.ID, T.USERID, T.EVENTTIME
From CTE As a Cross Apply (Select ID, USERID, EVENTTIME
                           From CTE
                           Where Abs(datediff(minute, a.EVENTTIME, EVENTTIME))<=60
                                 And USERID=a.USERID And ID<>a.ID) As T
Order by a.ID, a.USERID, a.EVENTTIME, T.ID, T.USERID, T.EVENTTIME

or you can get a list of events without binding to a specific event:
With CTE As (
Select USERID, EVENTTIME, Row_Number() Over (Order by USERID, EVENTTIME) As ID
From Tbl
)
Select T.USERID, T.EVENTTIME
From CTE As a Cross Apply (Select USERID, EVENTTIME
                           From CTE
                           Where Abs(datediff(minute, a.EVENTTIME, EVENTTIME))<=60
                                 And USERID=a.USERID And ID<>a.ID) As T
Group by T.USERID, T.EVENTTIME

db<>fiddle
to get the events only for last hour, you can add the appropriate filter to Where clause in CTE.
With CTE As (
Select USERID, EVENTTIME, Row_Number() Over (Order by USERID, EVENTTIME) As ID
From Tbl
Where EVENTTIME Between dateadd(minute, -60, GetDate()) And GetDate()
)
Select T.USERID, T.EVENTTIME
From CTE As a Cross Apply (Select USERID, EVENTTIME
                           From CTE
                           Where Abs(datediff(minute, a.EVENTTIME, EVENTTIME))<=60
                                 And USERID=a.USERID
                                 And ID<>a.ID) As T
Group by T.USERID, T.EVENTTIME

A: Give a row number for each group of user_id in the order of date difference in hours. Remember to filter the rows which have the event_date in last 1 hour.
Query
;with cte as(
    select [rn] = row_number() over(
        partition by [user_id]
        order by [user_id], datediff(hour, [event_time], getdate())
    ), *
    from [your_table_name]
    where datediff(hour, [event_time], getdate()) < 2
)
select * from [your_table_name] as [t1]
where exists(
    select 1 from cte as [t2]
    where [t1].[user_id]= [t2].[user_id]
    and [t2].[rn] > 1
);


text:
Q: How should we structure App with Domain-Driven Design in mind? We are building an ERP with 7+ distinct bounded contexts. Our concern is how to structure the application. We have looked at a few architectures like the onion and the n-layer architecture.
A few questions have emerged

*

*Should every bounded context form a system of sorts? With this I mean, should we have the following layers in each of the contexts, Presentation (UI), Application Services, Domain and Infrastructure. If so, at what point do they integrate?

*How do we create a composite application using ASP.NET MVC like one offered by prism using WPF?

A:
Should every bounded context form a system of sorts?

Yes. Every bounded context has its ubiquitous language. Distinct bounded contexts have relationships with each other via translation maps.

With this I mean, should we have the following layers in each of the contexts, Presentation (UI), Application Services, Domain and Infrastructure. If so, at what point do they integrate?

A layered architecture is one approach. Another one that fits well with hosting a bounded context is the hexagonal architecture with the domain model (including business logic) in the very center and adapters for user interfaces (web, mobile, ...), databases, REST clients, and so on.


text:
Q: Make an Image that can be flipped over in Unity 4.6 I am trying to implement a card (think trump card) in Unity 4.6 2D. I am generally working on a prefab Image, let's call the prefab Card.
Card has the Image script (of course), with the Source Image set to the backside of a card. This would be the same for all cards. How do I implement the frontside, with a unique texture/image/sprite for each type of card (five of hearts, king of spades etc)?
I currently do the flipping using animations. The default state of the card is face down. The "flip up" animation does this:

*

*Halfways through the anim, set rotate Y axis to 90 degrees.

*Set a new Source Image - for now this is "hard coded" to a "hearts_5.png", i.e. five of hearts.

*Set scale X to -1. (the keyframe would need to be edited to turn off the tween that would occur over time from start of animation!)

*As a last keyframe in the anim, Rotate Y axis again, to 180 degrees.

Because I rotate the card to 180 degrees, the Source Image would be shown mirrored, that's why I need to set the scale X to -1 in order to mirror the texture back.
It works pretty well, I just now need to find out how to (from C# code) set another Sprite for the Card(GameObject)>component(Image)>sprite variable depending on the actual card (Spades ten etc). How do I do that?
If there's any better way to accomplish this, go ahead.

A: public List<Sprite> sprites;
    private int m_index;

    public SpriteRenderer m_renderer;

    void Start() {
        m_index = 0;
        m_renderer = GetComponent<SpriteRenderer>();
    }
    public void SwitchSprite(somecardtype) {
        m_renderer.sprite = sprites[(int)somecardtype];

    }

or you can use that private m_index variable to index the array of sprites that will hold all of your card sprites. Does this help or do I need to elaborate more?


text:
Q: OpenLDAP API Search I'm attempting to do an LDAP search using the OpenLDAP API. I've already successfully connected and bound to the server. I've done the search with ldap_search_ext_s() and parsed the result with ldap_parse_result(). However, I can't seem to figure out how to get the actual results of the search. Unfortunately, the OpenLDAP C API has changed recently and many of the existing examples on the Internet do not use the current API.
I've already attempted to use ldap_first_attribute(), ldap_next_attribute(), and ldap_get_values() as shown on http://www-archive.mozilla.org/directory/csdk-docs/search.htm (Example 6-13). However, it appears that ldap_get_values() is now deprecated and that ldap_get_values_len() is the closest replacement. Instead of returning a char**, the new function returns a berval**. I've attempted to tweak this example code by creating a berval* with the value of barval**[i]. This results in a successful compile, but a core dump at ber_scanf().
Does anyone know how to get the results of an LDAP search with the OpenLDAP C API?
UPDATE:
In particular, I'm asking how to get the attributes requested from the search message.

A: The result of a search request always contains a series of SearchResultEntry or SeachResultReference messages, this series terminated by a SearchResultDone message. Calling getNextAttribute (in any language and in any API) makes no sense whatever because the search results are a list of messages. An API should package the array of entries or references in such a way wherein the caller can simply retrieve the list of entries or references. Look for a method that does that.

A: After taking a look at the OpenLDAP API source code and seeing how the berval value was used, I eventually stumbled upon how to get it's value.
First, you have to get the first entry with ldap_first_entry(). Then, you need to get the first attribute in that entry with ldap_first_attribute(). Then, put the values in a berval** array with ldap_get_values_len(). The returned attribute values can then be access with berval[i]->bv_val.
You can get the next entries and attributes with ldap_next_entry() and ldap_next_attribute(), respectively.
I hope this helps anyone who has a similar issue.

A: hope the bellow function may help you,
int ldap_search_result(LDAP *ld, char *search_filter, char *search_base)
{
    LDAPMessage *result;
    BerElement *ber;
    char *attr;
    char **val;

    if(ldap_search_ext_s(ld, search_base, LDAP_SCOPE_CHILDREN,
            search_filter, NULL, 0, NULL, NULL, NULL, -1, &result) != LDAP_SUCCESS) {
        return -1;
    }

    if(ldap_count_entries(ld,result) != 1) {    // assuming search_filter is unique,
                                                // matches only one entry, and so
                                                // search routine returns only one entry
        return -1;
    }

    if((attr = ldap_first_attribute(ldp, result, &ber)) == NULL) {
        return -1;
    }

    do {
        if((val = ldap_get_values(ldp,result,attr)) == NULL) {
            return -1;
        }
        printf(" %s : %s \n", attr, val[0]); // assuming all attributes are single -
                                             //valued.
        ldap_memfree(attr);
        ldap_value_free(val);
    while((attr = ldap_next_attribute(ld,result,ber)) != NULL);
    return 0;
}


text:
Q: Is it really downcasting not possible? It is working fine for me I know there are already some questions posted related to this same topic, but I have seen different answers so I am quite confused on which answer is correct.
On the below link, people mentioned that downcasting is not possible
Convert/Cast base type to Derived type
While on this link below, people mentioned that downcasting is possible only if the derived class is an instance of the base class
downcast and upcast
I did a little experiment and implemented the downcasting on a mini project(C#) using direct casting, for example: DerivedClass dc = (DerivedClass) baseClass without checking whether or not DerivedClass is an instance of BaseClass, and to my surprise, it is working fine with no errors at all, so why people said downcasting is not possible?
So my question is, is downcasting really not possible?  Why people seem to have different answers on this topic? after-all which one is the REAL answer?  Could someone please explain this in more detail?
Sample code:
public class Order {  }

public class PurchaseOrder : Order { // some new properties here for PurchaseOrder}

public static PurchaseOrder GetOrder()
{
    Order order = new Order();
    return (PurchaseOrder)order;
}

A: Downcasting is possible if you are sure about your type, this works fine:
class Base {}
class Derived : Base {}

Base b = new Derived();
Derived d = (Derived) b;

This does not work:
class Other : Base {}

Base b = new Other();
Derived d = (Derived) b; // InvalidCastException

A: Downcasting isn't possible when the object isn't actually an instance of the type you're trying to convert to - if it's just an instance of the base class.
It is possible when it's an instance of the derived class already1.
For example, this is fine:
object x = "hello";
string y = (string) x;

Here the value of x is a reference to an instance of string, so downcasting to string is fine.
This is not fine:
object x = new object();
string y = (string) x; // Bang!

Here the value of x is a reference to an instance of object, so the cast fails.
EDIT: The code you've now included in the question is like my second example - you're creating an instance of just Order and trying to cast it to PurchaseOrder. That won't work - it isn't a PurchaseOrder. If you change it like this, however:
public static PurchaseOrder GetOrder()
{
    Order order = new PurchaseOrder();
    return (PurchaseOrder)order;
}

... it's fine. (It's odd code, but it works.)
See "Casting and type conversions" in MSDN for more information.

1 Or if you're trying to convert to some other interface or class in the object's actual type's hierarchy. For example, this is okay too:
object x = new MemoryStream();
Stream y = (Stream) x; // Stream is in the type hierarchy of MemoryStream


text:
Q: Error commonly occurs when code is incompatible I wrote a VBA module within an excel document I am working on. I got everything working on my laptop and finally published it to my team to begin a wave of testing.
Unfortunately, a lot of them are met with the following error:

Compile error in hidden module: pushEmail. This error commonly occurs when code is incompatible with the version, platform, or architecture of this application.

At first, I assumed that people were not using the same version of Excel as I was (Excel 2016), however, it turns out that they all were. Other solutions I've attempted are:

*

*Checking the references to ensure that all were included on other user's computers. They were.

*Check the add-ins I was using on excel. Besides the default ones, I had none.

*Ensure I was using 32/64bit compatible code (as per a recommended solution I found through google). Me and my team all have x64 computers.

I'm not sure what else to try and I have been through the first 30 pages of Google to try and find a solution, to no avail. Could someone suggest a solution that I could attempt?
Thank you in advance.
UPDATE
Here is the code in question:
 Sub AcceptPush()
    Dim track As Excel.Workbook
    Dim push As Excel.Workbook
    Dim trackFC As Excel.Workbook
    Dim trackWks As Excel.Worksheet
    Dim pushWks As Excel.Worksheet
    Dim FCWks As Excel.Worksheet
    Dim pName As String
    Dim TLPass As Variant
    Dim lastrow As Long
    Dim rngFoundCell As Range
    Set rng = Nothing
    Dim MyCell As Range

    Set push = Workbooks("Push Alert - Software.xlsm")
    Set pushWks = push.Worksheets("Push")
    Set rngFoundCell = pushWks.Range("R11:R53").Find(What:="y")

    pName = pushWks.Range("D2").Value

    TLPass = InputBox("Enter the TL Password")

    Select Case TLPass
        Case "password"
            MsgBox "Password correct"
            If rngFoundCell Is Nothing Then
                MsgBox "You did not select a push to accept."
            Else
                Set track = Workbooks.Open(ThisWorkbook.Path & "\Account Pushing Tracker - Software.xlsm")
                Set trackWks = track.Worksheets("Accounts")
                Set trackFC = Workbooks.Open(ThisWorkbook.Path & "\Account Pushing Tracker - Team Tax.xlsm")
                Set FCWks = trackFC.Worksheets("Accounts")
                pushWks.Range("PushData[#All]").AdvancedFilter _
                Action:=xlFilterInPlace, _
                CriteriaRange:=push.Worksheets("Filter Criteria").Range("B6:Q7")
                pushWks.Range("R:S").EntireColumn.Hidden = True
                pushWks.Range("PushData").Copy
                trackWks.Range("B" & Rows.Count).End(xlUp).Offset(1).PasteSpecial xlValues
                pushWks.Range("PushData").Copy
                FCWks.Range("B" & Rows.Count).End(xlUp).Offset(1).PasteSpecial xlValues
                pushWks.Range("R:S").EntireColumn.Hidden = False
                pushWks.Range("PushData").ClearContents
                pushWks.ShowAllData
                Range("A1").Select
                Application.CutCopyMode = True
                track.Close SaveChanges:=True
                trackFC.Close SaveChanges:=True
            End If
        Case Else
            MsgBox "INCORRECT! Your attempt has been recorded"
            ActiveWorkbook.Worksheets("Log").Unprotect "123"
            ActiveWorkbook.Worksheets("Log").Range("A" & Rows.Count).End(xlUp).Offset(1).Value = Application.UserName
            ActiveWorkbook.Worksheets("Log").Range("B" & Rows.Count).End(xlUp).Offset(1).Value = Format(Now(), "dd/mm/yyyy hh:mm:ss")
            ActiveWorkbook.Worksheets("Log").Protect "123"
    End Select
End Sub

A: When I try to compile your code, it shows you haven't declared the Rng variable:
Set Rng = Nothing

A: this can occure if 2 Installation of Word/Excel (64 /32 ) or rest of them are on computer.
The apdada....\Excel\STARTUP must be empty too
Maybe try to deinstall all Excel entirely and after new installation try again


text:
Q: Express form post request handling middleware returns RangeError I have a form from which i have to get my data. I'm using ejs templates.
My "/" route renders "main" view and I have a middleware to work with my data coming from the form, but it returns an error of "RangeError: Maximum call stack size exceeded"
My Express code:
const express = require('express');
const app = express();
const path = require('path');
const bodyParser = require('body-parser');
const validator = require('validator.js');

app.set('view engine','ejs');

const urlEncodedParser = app.use(bodyParser.urlencoded({extended:false}));
app.use(bodyParser.json());

app.use(express.static(path.join(__dirname + '/public')));

app.get('/',(req,res)=>{
    res.render('main');
});

app.post('/register', urlEncodedParser, (req,res)=>{
    console.log(req.body);
});

app.listen(3000);

My form:
<form action="/register" method="POST">
        <input type="text" name='name' class="form-control">
        <input type="text" name='surname' class="form-control">
        <input type="number" name='age' class="form-control">
        <input type="email" name='email' class="form-control">
        <input type="password" name='password' class="form-control">
        <input type="password" name='confirm' class="form-control">
        <input type="submit" name="submit" class="btn btn-block btn-success" value="OKAY">
</form>

The full error which I get:
RangeError: Maximum call stack size exceeded
    at next (C:\xampp\htdocs\express+mongo\node_modules\express\lib\router\index.js:202:7)
    at Layer.handle [as handle_request] (C:\xampp\htdocs\express+mongo\node_modules\express\lib\router\layer.js:97:5)
    at trim_prefix (C:\xampp\htdocs\express+mongo\node_modules\express\lib\router\index.js:317:13)
    at C:\xampp\htdocs\express+mongo\node_modules\express\lib\router\index.js:284:7
    at Function.process_params (C:\xampp\htdocs\express+mongo\node_modules\express\lib\router\index.js:335:12)
    at next (C:\xampp\htdocs\express+mongo\node_modules\express\lib\router\index.js:275:10)
    at jsonParser (C:\xampp\htdocs\express+mongo\node_modules\body-parser\lib\types\json.js:101:7)
    at Layer.handle [as handle_request] (C:\xampp\htdocs\express+mongo\node_modules\express\lib\router\layer.js:95:5)
    at trim_prefix (C:\xampp\htdocs\express+mongo\node_modules\express\lib\router\index.js:317:13)
    at C:\xampp\htdocs\express+mongo\node_modules\express\lib\router\index.js:284:7

A: The cause of your issue is that you are passing in an app as middleware to your request handler. Specifically here:
const urlEncodedParser = app.use(bodyParser.urlencoded({extended:false}));

app.post('/register', urlEncodedParser, (req,res)=>{
    console.log(req.body);
});

urlEncodedParser is just another reference to your app. Thus you are stuck in a infinite loop where the route calls urlEncodedParser that flows down to your route which in turn calls urlEncodedParser and so on until you pop the stack.

A: urlEncodedParser is making issue it should not be in middleware :
    const express = require('express');
    const app = express();
    const path = require('path');
    const bodyParser = require('body-parser');
    const validator = require('validator.js');

    app.set('view engine','ejs');

    app.use(bodyParser.urlencoded({extended:false}));
    app.use(bodyParser.json());

    app.use(express.static(path.join(__dirname + '/public')));

    app.get('/',(req,res)=>{
        res.render('main');
    });

    app.post('/register', (req,res)=>{
        console.log(req.body);
    });

    app.listen(3000);


text:
Q: Assign two tables join result to List in c# I'd like to return two tables result to list .
public List<dynamic> GetStatistics(DateTime startDate , DateTime endDate)
{
    try
    {
        List<dynamic> result = new List<dynamic>();

        using (XactETLEntities xactCtxt = new XactETLEntities())
        {
            var query = (from a in xactCtxt.XactETL_Activity_Log
                     join b in xactCtxt.XactETL_Shred_Mode on a.ShredModeID
                                                         equals b.ShredModeID
                    where a.CreatedDate >= startDate && a.CreatedDate <= endDate
                    select new { a, b });

            result = query.ToList();
        }
    }

I am not able to assign result to query.ToList()

A: The problem is query is not an IEnumerable so the ToList() function is not returning the correct list type. Also, anonymous types can not be cast to anything but object, and are internal. Your best bet is trying to make your select more explicit.
Instead of:
select new { a, b });

you could use:
select (dynamic)new Tuple<DateTime, DateTime>(a, b)

this will result in your query returning an IEnumerable of dynamic, where each item is actually a tuple underneath.
EDIT:
The solution was to have the query cast all the items as objects, before converting to a list.
query.Select(o => (object)o).ToList();


text:
Q: no idea why I am getting a nullpointerexception for my gui app When I call getText() on any of my textfields inside my actionListener it keeps throwing a nullpointer error. I have done this a dozen times and I must be having a brain fart.
  import java.awt.BorderLayout;
    import java.awt.GridLayout;
    import java.awt.event.ActionEvent;
    import java.awt.event.ActionListener;
    import java.util.concurrent.ExecutionException;

    import javax.swing.JButton;
    import javax.swing.JFrame;
    import javax.swing.JPanel;
    import javax.swing.JTabbedPane;
    import javax.swing.JTextField;
    import javax.swing.SwingUtilities;
    import javax.swing.SwingWorker;

public class Addressbook {
    private JTextField firstName;
    private JTextField lastName;
    private JTextField number;
    private JTextField address;
    private JTextField zipcode;
    private ConnectDB db;

    public void buildGui() {
        JFrame frame = new JFrame("hakob AddressBook");
        JTabbedPane tabs = new JTabbedPane();
        JPanel mainPanel = new JPanel();
        mainPanel.add(tabs);

        JPanel addContact = new JPanel(new GridLayout(3, 2));
        JTextField firstName = new JTextField("first name", 9);
        lastName = new JTextField("last name", 10);
        number = new JTextField("number", 9);
        address = new JTextField("address", 15);
        zipcode = new JTextField("zipcode", 5);
        JButton addButton = new JButton("add contact");
        addButton.addActionListener(new addListener());
        addContact.add(firstName);
        addContact.add(lastName);
        addContact.add(number);
        addContact.add(address);
        addContact.add(zipcode);
        addContact.add(addButton);

        JPanel editContact = new JPanel();
        // select contact
        // make changes
        // submit changes

        JPanel viewContacts = new JPanel();
        // table show contacts
        // sort contacts
        // edit?
        tabs.addTab("add new contact", addContact);
        tabs.addTab("edit contact", editContact);
        tabs.addTab("view contacts", viewContacts);
        frame.add(mainPanel, BorderLayout.CENTER);
        frame.setSize(450, 630);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // frame.pack();

    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            public void run() {
                new Addressbook().buildGui();
            }
        });
    }

    public class addListener implements ActionListener {
        public void actionPerformed(ActionEvent ev) {
            new SwingWorker<Person, Void>() {
                @Override
                protected Person doInBackground() throws Exception {
                    System.out.println("adding");
                    Person person = new Person(firstName.getText(),
                            lastName.getText(), (Integer.parseInt(number
                                    .getText())), address.getText(),
                            (Integer.parseInt(zipcode.getText())));
                    System.out.println(person);
                    clearText();
                    return person;
                }

                @Override
                protected void done() {
                    try {
                        db.add(get());
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                        System.out.println("interupt");
                    } catch (ExecutionException e) {
                        e.printStackTrace();
                        System.out.println("execution exc");
                    }
                    System.out.println("done");
                }
            }.execute();
        }
    }

    public void clearText() {
        firstName.setText("");
        lastName.setText("");
        number.setText("");
        address.setText("");
        zipcode.setText("");
    }
}

error:
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException
    at Addressbook.clearText(Addressbook.java:105)
    at Addressbook$addListener$1.done(Addressbook.java:98)
    at javax.swing.SwingWorker$5.run(Unknown Source)
    at javax.swing.SwingWorker$DoSubmitAccumulativeRunnable.run(Unknown Source)
    at sun.swing.AccumulativeRunnable.run(Unknown Source)
    at javax.swing.SwingWorker$DoSubmitAccumulativeRunnable.actionPerformed(Unknown Source)
    at javax.swing.Timer.fireActionPerformed(Unknown Source)
    at javax.swing.Timer$DoPostEvent.run(Unknown Source)
    at java.awt.event.InvocationEvent.dispatch(Unknown Source)
    at java.awt.EventQueue.dispatchEventImpl(Unknown Source)
    at java.awt.EventQueue.access$200(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.awt.EventQueue$3.run(Unknown Source)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.security.ProtectionDomain$1.doIntersectionPrivilege(Unknown Source)
    at java.awt.EventQueue.dispatchEvent(Unknown Source)
    at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
    at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
    at java.awt.EventDispatchThread.run(Unknown Source)

When I tried explicitly creating a person object it worked fine, but not if I grab text from the textfields

A: You are hiding your class attribute when you do this in the buildGui method:
JTextField firstName = new JTextField("first name", 9);

So your attribute firstName doesn't get initialized and stays null. Change it to:
firstName = new JTextField("first name", 9);


text:
Q: Returning a single column value from SQL database I need to get the latest entry from my database, but not the autoincrement.
This function is in my databasehandler:
public int getLatestRouteNumber()
{
    int number = 0;
    SQLiteDatabase db = this.getReadableDatabase();
    String query = "SELECT MAX("+ KEY_ROUTENUMBER + ") FROM " + TABLE_LOCATIONS;
    Cursor c = db.rawQuery(query, null);
    if (c.moveToFirst() && c != null) {
        number = c.getInt(3);
    }
    return number;
}

it craches at the line where "number = c.getInt(3).
The third column in my database exists and has data in it.
The error I'm gettin is "Couldn't read row 0, col 3 from CursorWindow.  Make sure the Cursor is initialized correctly before accessing data from it." I only need one value in the entire database, not even an entire row.

A: You have only one column in cursor but trying to get value of 3rd column... Tat is the error
Change it to getInt(0);

A: The returned result-set has nothing to do with table columns in your case. You should use
number = c.getInt(0);

A: Your resultset contains just one column and one row, basically a scalar value, it doesn't matter how many columns you have in your table, what you should consider here is the value you obtain from your query In your case just one value. Use
getInt(0)

A: have you tried something like this :
String query = "SELECT MAX("+ KEY_ROUTENUMBER + ") as my_max FROM " + TABLE_LOCATIONS;

And :
columnIndex = c.getColumnIndexOrThrow("my_max");
number = c.getInt(columnIndex );

That's better than using indexes, indexes may be wrong if the raw query changes.

A: getInt (3) returns the value of the 3rd column returned by the query. Your query only had 1 column.
Change getInt (3) to getInt (0)

A: "c.getInt(3);" does not get the value from the column in your table, it gets it from the column in your cursor.
And you only selected one column into your cursor.
So I believe it should be "c.getInt(1);"


text:
Q: Database use in xcode for multiple locations? I am trying to make annotations on a map in Xcode for every gas station and major grocery store. Does anybody have a clue about how to go about this except for entering them in all by hand? Maybe a database of some sort?
And if you do have an idea, please explain so that I can follow along. Sorry, I am very new to this. :) Any help is appreciated!

A: If you have access to this data and just want to store it in the app, you should use Core Data.
If you are looking for the data to begin with, see if Factual will work for you.


text:
Q: Difference between symbolic variables and normal variables in MATLAB? I have read about symbolic variables in different google searches but still not satisfied/understood
Can some one please let me know difference between symbolic variables and normal variables in MATLAB?especially difference in their application scenarios?


text:
Q: Drools: Execute a rule only after another was executed I have two Drools rules in the same drl file like:
rule "If critical"
when
incident:Incident(state=CRITICAL)
then
incident.getIncidentValve().activateAlarm();
end;

rule "If alarm"
when
valve:Valve(hasAlarm==true)
then
SMS.send(valve.getId());
end;

My idea is to process, with the first rule, all the incidents that are in critical state. And then with the second rule, if any valve has an alarm, that was set by the "If critical" rule,  send an SMS.
The problem is that the very first time I execute the rules the SMS are not sent. This seems to be so because the 'when' of both rules is verified at the same time.
My question is how can I tell Drools that I want to execute first the "If critical" and then, once the 'activateAlarm' methods have been called, execute the rule "If alarm" so the SMS are sent.
I have tried with salience, but that's not what I am looking for because that is only the execution order, after the validation of the 'when' is done, which as I said is done for both rules at the same time.
Also tried with agenda-group and setFocus, but it didn't take me anywhere.
Any idea? Is this possible with Drools?

A: The problem is that the facts after the 1st rule is executed are not updated. To use the values changed in the 1st rule you have to update the values using the update function.

A: You can use salience keyword of Drools. Give positive Salience value to the first rule. See documentation here. Try defining your rule like this
rule "If critical"
salience 100
when
incident:Incident(state=CRITICAL)
then
incident.getIncidentValve().activateAlarm();
end;

rule "If alarm"
when
valve:Valve(hasAlarm==true)
then
SMS.send(valve.getId());
end;.

A: Use extends attribute
ex- rule If alarm extends If critical
So If alarm rule will fire only after IF critical rule task completed
It means creating complete dependency on previous rule
And also you must have to update the fact in first rule by using modify or update if any updated value required in second rule. Hope my answer will help you.let me know if any quires on same.