Javascript: what's the point of RegExp.compile()?

Question: I've got a situation where I want to get a regexp from the user and run it against a few thousand input strings. In the manual I found that the RegExp object has a .compile() method which is used to speed things up ins such cases. But why do I have to pass the regexp string to it again if I already passed them in the constructor? Perhaps constructor does the compile() itself?
Answer: The RegExp().compile() method is deprecated.  It's basically the same as the constructor, which I assume is why it was deprecated.  You should only have to use the constructor nowadays.
In other words, you used to be able to do this:
var regexp = new RegExp("pattern");
regexp.compile("new pattern");

But nowadays it is not any different from simply calling:
var regexp = new RegExp("pattern");
regexp = new RegExp("new pattern");

Answer: And with Opera 11, running RegExp.compile() will actually cause errors.
Evidently, when Opera "compiles" a regex, it wraps the re.source string in forward slashes (e.g. re.source == "^(.)" becomes "/^(.)/"). If you manually compile the regex, Opera doesn't recognize this fact and goes ahead and compiles it again (re.source becomes "//^(.)//"). Each compile results in an extra set of forward slashes, which changes the meaning of the regular expression and results in errors.
Answer: You have to compile your regex first to use it if you are using /, try this out:

var regex=new RegExp('/[a-zA-Z]/')

console.log("not compiled with escape /", regex.test("ciao") )

regex.compile()

console.log("compiled", regex.test("ciao") )

var regex=new RegExp('[a-zA-Z]')

console.log("not compiled, but no escape /", regex.test("ciao") )
Comment: Wow, that's interesting. I just checked it, and you're right! It's not mentioned in MDN though.
Comment: To make the point - `new RegExp('/[a-zA-Z]/').test('/a/')` *is* `true`. The forward slashes are properly interpreted as part of the pattern.

`compile()` actually changes this (Chrome 85), which I don't think it should. However, `compile()` itself is now marked deprecated in MDN.
Comment: You shouldn't use forward slashes when using the `RegExp` constructor. Forward slashes are used to start and end `RegExp` *literal*, they are not part of the pattern (unless you actually mean to match literal forward slashes). IMO, this is actually buggy behaviour in `compile` and shouldn't be relied on.
Answer: As far as i can tell all RegExp.compile does is replace the underlying regular expression of a RegExp object.  I think compile may have had value in the past, but all modern JS engines "compile" the regex on first call and cache that "compiled" version.
Comment: Which engines exactly do cache regular expressions? And do they always do it? How long is an expression kept in cache? I'm particularly interested in V8.


Unexplained URL's on my site

Question: About 6 weeks ago my traffic stats jumped tremendously. I started noticing "top searches" for variations of porn words. In looking at my top landing pages in Google Analytics, it is showing landing page URLs ending in snippets such as "-cup-girl-porn-gif-xxx_e3ba94.html".  There are over 1000 of them!  Now Google webmaster is trying to crawl them and, of course are getting 404 errors.  I have asked my hosting to check for malware on my server and they can't determine the cause.  The increase in traffic is close to maxing out my server capacity (requiring me to upgrade). I was normally seeing daily traffic of around 150-200, but since this issue began, it is nearing 2000 daily.  How do I get rid of these fake (and pornographic) URLs?
Comment: @elbrant to stop it once it happened - delete everything in public web, install everything twice. Or: delete everything,  upload a backup. To prevent it: learn about web security in general, server security, cms security, if in use.
Comment: they aren't fake - they are real. Your site is hacked.
Comment: I lean towards them being real. 2,000 page requests should be a piece of cake for any properly configured server even if they are coming in all within the same hour of the day, unless you have a very heavy site. It's more likely that you have some unwanted content sucking up all your bandwidth.
Comment: @Evgeniy Is there somewhere to learn how to prevent this from happening, or how to stop it once it does?
Comment: Google maintains a large resource for this:  [Help, I think I've been hacked!  |  Web Fundamentals  |  Google Developers](https://developers.google.com/web/fundamentals/security/hacked/)
Answer: Based on what you have put in your question it would appear most likely that your site has been infected with malware. There is a broad range of malware out there which will only show content to a restricted range of requests but not to others or to search engines. This most often happens from insecure file uploading to your site but this is by no means the only way that this happens. Best thing to do at this point is to shutdown the site, erase everything, and reinstall from backups. This will give you a hopefully clean implementation (if you have a backup of the site before infection), and beyond that it would be strongly recommended to do a security health check of your site and secure any infection vectors including file upload. You should also implement antivirus and malware scanning on your webserver with regular scans and a realtime scan of all uploaded files prior to saving them on your server to aid in protecting your site from future attacks.

Unexplained URL's on my site


As a reviewer, is it appropriate to look up other work by an author and factor that into your decision?

Question: Assuming the process isn't double-blind, do you often look at other work by an author out of curiosity, and do you think this should influence your decision on a paper?
Comment: This seems like an "it depends" question. Can you clarify? What are you hoping to find? How might that be relevant?
Comment: If you are referring to 'reputation', then famous authors indirectly convey that information ; in my area, the title 'Fellow' conveys that a paper is of high quality (in theory).  Having said that, personally I do not really care about the standing of authors.  I judge a work purely based on what's presented to me.  I've rejected papers from many famous authors.  It is especially disappointing if these papers are sub-par, meaning  these famous authors have essentially sold their reputation/name -- they get a down vote from me.
Comment: As a referee, you don't make a decision on the paper.
Comment: I wonder what legit reasons you would have to factor in the previous works of the author(s). It is not like a paper suddenly becomes a bunch of lies if the previous paper or the author was a low impact one. Can you give examples where you think it may count?
Answer:
As a reviewer, is it appropriate to look up other work by an author and factor that into your decision?

No, this is not appropriate.
I would argue that this is one of the exact things double-blind review is supposed to prevent. In the context of double-blind reviewing I have heard the following scenarios / arguments, all of which I feel are invalid:

"If the authors have a history of writing bad papers, I should be more critical." No, you shouldn't. You should judge the paper in front of you, not previous papers the authors have written.
"If the authors are more famous than me, I am nervous that my criticism may be wrong." Uh oh. If you are unsure, don't criticize. If you are sure, criticize even if the authors are the most famous in your field. And don't worry, even the best researchers (and their students) get things wrong.
"If the authors have a history of academic misconduct, I should be more critical (e.g., not give them the benefit of doubt if data is not entirely provided)." I understand the sentiment here, but I would argue that you are overstepping your role as reviewer once you start judging the trustworthiness of researchers as people, and then apply different standards to the manuscript based on your assessment. Given that much reviewing in the sciences in practice operates on a certain basis of trust, and given that we also know that a minority is abusing this trust, there is likely a level where we need to take prior behavior into account, but individual paper reviewers are almost certainly not the people who should be making these decisions.
"If the authors are presenting many similar papers (or many papers building on top of each other), we should rather reject to prevent salami slicing": Ultimately, if a paper would have sufficient contribution if written by somebody else, it should also have sufficient contribution if written by the same authors. Conversely, if the contribution is very minor in comparison to existing work it should be rejected independently of who exactly wrote said earlier work.
Comment: @Buffy yes, and the same principles apply regardless, it's just that double blinding makes them more likely to be followed. I guess this could be pointed out in the answer.
Comment: The OP specifies _not_ double blind.
Answer: One of your jobs as reviewer is to determine the novelty of the work. For that you should acquaint yourself with what was known prior to it (if you are not already very familiar with the field), both due to the work of the same author and of others. To that end it can be useful to browse the author's earlier work.
It would not be ethical to let your judgement of the author's earlier work influence your opinion on the quality of the work under review just following the "logic" that the previous work was "meh", so this can't be any good either, or that this is such a famous author that the work under review must surely be great.
Comment: Checking originality is indeed a good reason to check literature, though strictly speaking it is not much to do if the previous (possibly overlapping) results were made by the authors or by others.
Answer: Indirectly yes as I like to read or browse through some papers in the bibliography, which often contains papers by the submitting authors.  This is pure intellectual curiosity, is independent of the review style (single or double blind): I often discover (or rediscover) unknown, unfamiliar or forgotten interesting papers.
I will also sometimes quickly read recent papers of the author (or group) to understand how the current submission is different from previous work.  I did this more regularly in the past because, when I was associate editor, I was regularly floored by the amount of self-plagiarism and duplication in some of the submissions I had to handle (the journal had access to a specialized plagiarism detection software).  Now I am more selective with my reviews and the journals I tend to review for usually check ahead of me for plagiarism, but I still do this on occasions.
Of course if I suspect (or detect) plagiarism it will influence my report.


Micro entity status for provisional patent application

Question: I am part of a small startup and we are in the process of filing our IPs. We fit the micro category as none of the inventors have any patents filed but have submitted 5 provisional applications. Is there a limit on the number of provisional patent applications that one can file as a micro entity?
Answer: The complete definition for micro entity eligibility is available here:
https://www.uspto.gov/web/offices/pac/mpep/s509.html#ch500_d1ff69_210b3_1ca
By my reading, you are allowed any number of provisionals that have not yet matured into non-provisional applications without giving up micro entity status thereby. Naturally, you must still meet all other criteria to be considered micro entity.
Also, since you seem to have a company ("startup"), you should investigate whether you need to have representation to file.


Will a Windows server 2003 operate on a domain functional level 2012 domain?

Question: I have found plenty of articles that address Server 2012 R2 on a functional level 2003 domain. What I haven't been able to find is anyone addressing weather or not a 2003 server would be fully operational in a 2012 functional level domain. Can anyone confirm that it would work?
Answer: A simple 2003 member server will have no problems working in a 2012 (or 2012 R2 for that matter) functional level domain.  But you won't be able to have a 2003 server running as a DC.
Comment: Yep, it'll run just fine as a server, but it cannot be a domain controller(or probably much else).


Declaring variables inside or outside of a loop

Question: Why does the following work fine?
String str;
while (condition) {
    str = calculateStr();
    .....
}

But this one is said to be dangerous/incorrect:
while (condition) {
    String str = calculateStr();
    .....
}

Is it necessary to declare variables outside the loop?
Comment: Does this answer your question? [Difference between declaring variables before or in loop?](https://stackoverflow.com/questions/407255/difference-between-declaring-variables-before-or-in-loop)
Answer: The scope of local variables should always be the smallest possible.
In your example I presume str is not used outside of the while loop, otherwise you would not be asking the question, because declaring it inside the while loop would not be an option, since it would not compile.
So, since str is not used outside the loop, the smallest possible scope for str is within the while loop.
So, the answer is emphatically that str absolutely ought to be declared within the while loop. No ifs, no ands, no buts.
The only case where this rule might be violated is if for some reason it is of vital importance that every clock cycle must be squeezed out of the code, in which case you might want to consider instantiating something in an outer scope and reusing it instead of re-instantiating it on every iteration of an inner scope. However, this does not apply to your example, due to the immutability of strings in java: a new instance of str will always be created in the beginning of your loop and it will have to be thrown away at the end of it, so there is no possibility to optimize there.
EDIT: (injecting my comment below in the answer)
In any case, the right way to do things is to write all your code properly, establish a performance requirement for your product, measure your final product against this requirement, and if it does not satisfy it, then go optimize things. And what usually ends up happening is that you find ways to provide some nice and formal algorithmic optimizations in just a couple of places which make our program meet its performance requirements instead of having to go all over your entire code base and tweak and hack things in order to squeeze clock cycles here and there.
Comment: @HarryJoy The right way to do things is to write all your code _properly_, establish a performance requirement for your product, measure your final product against this requirement, and if it does not satisfy it, then go optimize things. And you know what? You will usually be able to provide some nice and formal algorithmic optimizations in just a couple of places which will do the trick instead of having to go all over your entire code base and tweak and hack things in order to squeeze clock cycles here and there.
Comment: You see, modern multi-gigahertz, multi-core, pipelined, multi-level-memory-cache CPUs allow us to focus on following best practices without having to worry about clock cycles. Furthermore, optimization is only advisable _if and only if_ it has been determined that it is necessary, and when it is necessary, a couple of highly localized tweaks will usually achieve the desired performance, so there is no need to be littering all of our code with little hacks in the name of performance.
Comment: Query on last paragraph: If it was another then String which is not immutable then does it affect?
Comment: @HarryJoy Yes, of course, take for example StringBuilder, which is mutable. If you use a StringBuilder to build a new string in each iteration of the loop, then you could optimize things by allocating the StringBuilder outside the loop. But still, this is not an advisable practice. If you do it without a very good reason, it is a premature optimization.
Comment: @MikeNakis i thing you are thinking in very narrow scope.
Comment: I want to ask about cost of declaration (initialization cost will be same in both case), leave about string, think about object, when we are declaring object inside large loop so does it effect on performance at least little?
Comment: @Nirmal-thInkbeYond I just answered this using StringBuilder as an example. Read 3 comments above.
Comment: @MikeNakis What will be behaviour of method stack in both the cases? How many times the variable type is put into stack frame?
Comment: @Siten Variable types are not put into stack frames. Please carefully read the article at "livingtao.blogspot.com" that you linked to; it explains it quite well.
Comment: @MikeNakis my dear friend i read it very very carefully it said there is no way to declare it. so the main thing about the performance of executing loop.
Comment: @MikeNakis would you agree with the answer I provided or did I miss something?
Comment: @PrimosK No, you did not miss anything, you are right on the money. That's what the "livingtao" blog post linked by Siten's answer also found. What I am saying is that _even if_ declaring the string inside the while loop was incurring some performance penalty, (which, as you have proved, it doesn't,) the best coding practice would _still_ be to declare the string inside the loop, because that's the smallest possible scope for it.
Comment: If you are writing functions so large that scoping a few loop variables is a major concern to you, then you have far greater problems than variable scoping.
Comment: 1: In a language like Java, which is fast and has good garbage collection, maybe. In a language like Perl, which is slow and has terrible garbage collection, maybe not. 2: See Onur Gunduru's speed test below, which is a different case, but shows a big runtime win for declaring it inside the loop.
Comment: @PhilGoetz 1. This question is tagged with [java].  2. A programmer's choice to use a scripting language instead of a real language automatically disqualifies them from participating in performance-related discussions.
Comment: @MikeNakis The second one is the recommendation in this case but in every loop a new `str` variable will be created and it will consume the memory. How do you thing about that?
Answer: I compared the byte code of those two (similar) examples:
Let's look at 1. example:
package inside;

public class Test {
    public static void main(String[] args) {
        while(true){
            String str = String.valueOf(System.currentTimeMillis());
            System.out.println(str);
        }
    }
}

after javac Test.java, javap -c Test you'll get:
public class inside.Test extends java.lang.Object{
public inside.Test();
  Code:
   0:   aload_0
   1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
   4:   return

public static void main(java.lang.String[]);
  Code:
   0:   invokestatic    #2; //Method java/lang/System.currentTimeMillis:()J
   3:   invokestatic    #3; //Method java/lang/String.valueOf:(J)Ljava/lang/String;
   6:   astore_1
   7:   getstatic       #4; //Field java/lang/System.out:Ljava/io/PrintStream;
   10:  aload_1
   11:  invokevirtual   #5; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
   14:  goto    0

}

Let's look at 2. example:
package outside;

public class Test {
    public static void main(String[] args) {
        String str;
        while(true){
            str =  String.valueOf(System.currentTimeMillis());
            System.out.println(str);
        }
    }
}

after javac Test.java, javap -c Test you'll get:
public class outside.Test extends java.lang.Object{
public outside.Test();
  Code:
   0:   aload_0
   1:   invokespecial   #1; //Method java/lang/Object."<init>":()V
   4:   return

public static void main(java.lang.String[]);
  Code:
   0:   invokestatic    #2; //Method java/lang/System.currentTimeMillis:()J
   3:   invokestatic    #3; //Method java/lang/String.valueOf:(J)Ljava/lang/String;
   6:   astore_1
   7:   getstatic       #4; //Field java/lang/System.out:Ljava/io/PrintStream;
   10:  aload_1
   11:  invokevirtual   #5; //Method java/io/PrintStream.println:(Ljava/lang/String;)V
   14:  goto    0

}

The observations shows that there is no difference among those two examples. It's the result of JVM specifications...
But in the name of best coding practice it is recommended to declare the variable in the smallest possible scope (in this example it is inside the loop, as this is the only place where the variable is used).
Comment: For any of you `final` lovers: declaring `str` as `final` in the `inside` package case **also** makes no difference =)
Comment: It is the result of the JVM Soecification, not 'compiler optimization'. The stack slots required by a method are all allocated on entry to the method. That's how the bytecode is specified.
Comment: @Arhimed there is one more reason to put it inside the loop (or just '{}' block): the compiler will reuse the memory allocated in the stack frame for the variable in another scope if you declare in that other scope some over variable.
Comment: If its looping thru a list of data objects, then will it make any difference for bulk of data? Probably 40 thousands.
Answer: Declaring objects in the smallest scope improve readability.
Performance doesn't matter for today's compilers.(in this scenario)
From a maintenance perspective, 2nd option is better.
Declare and initialize variables in the same place, in the narrowest scope possible.
As Donald Ervin Knuth told:

"We should forget about small efficiencies, say about 97% of the time:
  premature optimization is the root of all evil"

i.e) situation where a programmer lets performance considerations affect the design of a piece of code. This can result in a design that is not as clean as it could have been or code that is incorrect, because the code is complicated by the optimization and the programmer is distracted by optimizing.
Comment: *"2nd option has slightly faster performance"* => have you measured it? According to one of the answers, the bytecode is the same so I don't see how performance could be different.
Comment: I'm sorry but that's really not the right way to test the performance of a java program (and how can you test the performance of an infinite loop anyway?)
Comment: I agree with your other points - it's just that I believe that there is no performance difference.
Answer: if you want to use str outside looop also; declare it outside. otherwise, 2nd version is fine.
Answer: Please skip to the updated answer...
For those who care about performance take out the System.out and limit the loop to 1 byte. Using double (test 1/2) and using String (3/4) the elapsed times in milliseconds is given below with Windows 7 Professional 64 bit and JDK-1.7.0_21. Bytecodes (also given below for test1 and test2) are not the same. I was too lazy to test with mutable & relatively complex objects.
double
Test1 took: 2710 msecs
Test2 took: 2790 msecs
String (just replace double with string in the tests)
Test3 took: 1200 msecs
Test4 took: 3000 msecs
Compiling and getting bytecode
javac.exe LocalTest1.java

javap.exe -c LocalTest1 > LocalTest1.bc

public class LocalTest1 {

    public static void main(String[] args) throws Exception {
        long start = System.currentTimeMillis();
        double test;
        for (double i = 0; i < 1000000000; i++) {
            test = i;
        }
        long finish = System.currentTimeMillis();
        System.out.println("Test1 Took: " + (finish - start) + " msecs");
    }

}

public class LocalTest2 {

    public static void main(String[] args) throws Exception {
        long start = System.currentTimeMillis();
        for (double i = 0; i < 1000000000; i++) {
            double test = i;
        }
        long finish = System.currentTimeMillis();
        System.out.println("Test1 Took: " + (finish - start) + " msecs");
    }
}

Compiled from "LocalTest1.java"
public class LocalTest1 {
  public LocalTest1();
    Code:
       0: aload_0
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V
       4: return

  public static void main(java.lang.String[]) throws java.lang.Exception;
    Code:
       0: invokestatic  #2                  // Method java/lang/System.currentTimeMillis:()J
       3: lstore_1
       4: dconst_0
       5: dstore        5
       7: dload         5
       9: ldc2_w        #3                  // double 1.0E9d
      12: dcmpg
      13: ifge          28
      16: dload         5
      18: dstore_3
      19: dload         5
      21: dconst_1
      22: dadd
      23: dstore        5
      25: goto          7
      28: invokestatic  #2                  // Method java/lang/System.currentTimeMillis:()J
      31: lstore        5
      33: getstatic     #5                  // Field java/lang/System.out:Ljava/io/PrintStream;
      36: new           #6                  // class java/lang/StringBuilder
      39: dup
      40: invokespecial #7                  // Method java/lang/StringBuilder."<init>":()V
      43: ldc           #8                  // String Test1 Took:
      45: invokevirtual #9                  // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
      48: lload         5
      50: lload_1
      51: lsub
      52: invokevirtual #10                 // Method java/lang/StringBuilder.append:(J)Ljava/lang/StringBuilder;
      55: ldc           #11                 // String  msecs
      57: invokevirtual #9                  // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
      60: invokevirtual #12                 // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
      63: invokevirtual #13                 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
      66: return
}

Compiled from "LocalTest2.java"
public class LocalTest2 {
  public LocalTest2();
    Code:
       0: aload_0
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V
       4: return

  public static void main(java.lang.String[]) throws java.lang.Exception;
    Code:
       0: invokestatic  #2                  // Method java/lang/System.currentTimeMillis:()J
       3: lstore_1
       4: dconst_0
       5: dstore_3
       6: dload_3
       7: ldc2_w        #3                  // double 1.0E9d
      10: dcmpg
      11: ifge          24
      14: dload_3
      15: dstore        5
      17: dload_3
      18: dconst_1
      19: dadd
      20: dstore_3
      21: goto          6
      24: invokestatic  #2                  // Method java/lang/System.currentTimeMillis:()J
      27: lstore_3
      28: getstatic     #5                  // Field java/lang/System.out:Ljava/io/PrintStream;
      31: new           #6                  // class java/lang/StringBuilder
      34: dup
      35: invokespecial #7                  // Method java/lang/StringBuilder."<init>":()V
      38: ldc           #8                  // String Test1 Took:
      40: invokevirtual #9                  // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
      43: lload_3
      44: lload_1
      45: lsub
      46: invokevirtual #10                 // Method java/lang/StringBuilder.append:(J)Ljava/lang/StringBuilder;
      49: ldc           #11                 // String  msecs
      51: invokevirtual #9                  // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
      54: invokevirtual #12                 // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
      57: invokevirtual #13                 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
      60: return
}

UPDATED ANSWER
It's really not easy to compare performance with all the JVM optimizations. However, it is somewhat possible. Better test and detailed results in Google Caliper

Some details on blog:Should you declare a variable inside a loop or before the loop?
GitHub repository: https://github.com/gunduru/jvdt
Test Results for double case and 100M loop (and yes all JVM details): https://microbenchmarks.appspot.com/runs/b1cef8d1-0e2c-4120-be61-a99faff625b4

DeclaredBefore 1,759.209 ns
DeclaredInside 2,242.308 ns

Partial Test Code for double Declaration
This is not identical to the code above. If you just code a dummy loop JVM skips it, so at least you need to assign and return something. This is also recommended in Caliper documentation.
@Param int size; // Set automatically by framework, provided in the Main
/**
* Variable is declared inside the loop.
*
* @param reps
* @return
*/
public double timeDeclaredInside(int reps) {
    /* Dummy variable needed to workaround smart JVM */
    double dummy = 0;

    /* Test loop */
    for (double i = 0; i <= size; i++) {

        /* Declaration and assignment */
        double test = i;

        /* Dummy assignment to fake JVM */
        if(i == size) {
            dummy = test;
        }
    }
    return dummy;
}

/**
* Variable is declared before the loop.
*
* @param reps
* @return
*/
public double timeDeclaredBefore(int reps) {

    /* Dummy variable needed to workaround smart JVM */
    double dummy = 0;

    /* Actual test variable */
    double test = 0;

    /* Test loop */
    for (double i = 0; i <= size; i++) {

        /* Assignment */
        test = i;

        /* Not actually needed here, but we need consistent performance results */
        if(i == size) {
            dummy = test;
        }
    }
    return dummy;
}

Summary: declaredBefore indicates better performance -really tiny- and it's against the smallest scope principle. JVM should actually do this for you
Comment: 1) Java Bytecode gets optimized (reordered, collapsed, etc) on runtime, so don't care about what is written at the .class files too much.

2) there are 1.000.000.000 runs to gain a performance win of 2.8s, so thats about 2.8ns per run vs. safe and proper programming style. A clear winner for me.

3) Since you provide no information about warmup, your timings are quite useless.
Comment: @EJP This should be pretty clear for those who have an interest in the subject. Methodology is taken from PrimosK's answer to provide more useful information. To be honest I have no idea how to improve this answer, maybe you can click edit and show us how to do it properly?
Comment: Invalid testing methodology, and you don't provide any explanation of your results.
Comment: @Hardcoded better tests/micro benchmarking with caliper only for double and 100M loops. Results online, if you want other cases feel free to edit.
Comment: Thanks, this elimiates point 1) and 3). But even if the time went up to ~ 5ns per cycle, this is still a time to be ignored. There's a small optimization potential in theory, in reality the stuff you are doing per cycle is usually a lot more expensive. So the potential would be a few seconds at maximum in a run of some minutes or even hours. There are other options with higher potential available (e.g. Fork/Join, parallel Streams) that I would check before spending time on this kind of low-level-optimizations.
Comment: @hardcoded yeah, don't get me wrong I'm not a fan of useless optimizations but if you need it, this is what you get. Actually such an optimization could even be possible in the JVM, however, that's another story...
Comment: @OnurGunduru That is a thoroughly futile comment. If I really had no 'interest in the subject' I would certainly not be commenting here. The fact that someone else used the same methodology doesn't make either of them valid. Circular argument. Your test code is liable to be optimized away entirely in either or both cases. It proves nothing. And you can't 'improve' an invalid result.
Comment: @EJP maybe you should take some time to understand how Calipher works or write another test case to prove yourself?
Comment: Not only you need to warm up, but also, you need to do multiple runs, record the standard deviation between all the runs, and see how the difference compares to the standard deviation.  If the difference is close to the standard deviation, then you can be pretty sure that you are just looking at noise.
Comment: @MikeNakis Calipher takes care of these, code is in the github please feel free to play with it. One thing to remark is that you have to return something from the method, otherwise JVM will skip the assignment code... so you need to have a dummy return variable. BTW I don't say Calipher is perfect, it's aimed at microbenchmarking if you have better alternatives please share to find a reasonable baseline to this argument. Long story short, declaredBefore indicates better performance -really tiny- and it's against the smallest scope principle. JVM should actually do this for you
Comment: @OnurGunduru okay, I am sorry, I should have looked it up before commenting.  Cool stuff.  I still find it hard to understand why there is a difference, and even to believe that there is in fact a difference.
Comment: @MikeNakis thanks, I've also came across with http://java-performance.info/jmh/ might be worth to check out
Comment: @MikeNakis Looks like JMH will be the 'official' tool in Java9 for microbechmarking https://javax0.wordpress.com/2016/09/11/microbenchmarking-comes-to-java-9/
Answer: Inside, the less scope the variable is visible into the better.
Answer: One solution to this problem could be to provide a variable scope encapsulating the while loop:
{
  // all tmp loop variables here ....
  // ....
  String str;
  while(condition){
      str = calculateStr();
      .....
  }
}

They would be automatically de-reference when the outer scope ends.
Answer: If you don't need to use the str after the while loop (scope related) then the second condition i.e.
  while(condition){
        String str = calculateStr();
        .....
    }

is better since if you define an object on the stack only if the condition is true. I.e. use it if you need it
Comment: Note that even in the first variant, no object is constructed if the condition is false.
Comment: Well "defining an object on the stack" is a somewhat weird term in the Java world. Also, allocating a variable on the stack is usually a noop at runtime, so why bother? Scoping to help the programmer is the real issue.
Comment: @ Phillip: Yes you are right. My bad. I was thinking as it is now.What do you think?
Answer: I think the best resource to answer your question would be the following post:
Difference between declaring variables before or in loop?
According to my understanding this thing would be language dependent. IIRC Java optimises this, so there isn't any difference, but JavaScript (for example) will do the whole memory allocation each time in the loop.In Java particularly I think the second would run faster when done profiling.
Answer: Declaring String str outside of the while loop allows it to be referenced inside & outside the while loop. Declaring String str inside of the while loop allows it to only be referenced inside that while loop.
Answer: Variables should be declared as close to where they are used as possible.
It makes RAII (Resource Acquisition Is Initialization) easier.
It keeps the scope of the variable tight. This lets the optimizer work better.
Answer: According to Google Android Development guide, the variable scope should be limited. Please check this link:
Limit Variable Scope
Answer: As many people have pointed out,
String str;
while(condition){
    str = calculateStr();
    .....
}

is NOT better than this:
while(condition){
    String str = calculateStr();
    .....
}

So don't declare variables outside their scopes if you are not reusing it...
Comment: except probably in this way:
[link](http://stackoverflow.com/questions/6133586/should-i-declare-variables-as-close-as-possible-to-the-scope-where-they-will-be/22245471#22245471)
Answer: Declaring inside the loop limits the scope of the respective variable. It all depends on the requirement of the project on the scope of the variable.
Answer: Truly, the question stated above is an programming issue. How would you like to program your code? Where do you need the 'STR' to be accessed? There is no use of declaring a variable which is used locally as a global variable. Basics of programming I believe.
Answer: These two examples result in the same thing. However, the first provides you with using the str variable outside of the while loop; the second is not.
Answer: The str variable will be available and reserved some space in memory even after while executed below code.
 String str;
    while(condition){
        str = calculateStr();
        .....
    }

The str variable will not be available and also the memory will be released which was allocated for str variable in below code.
while(condition){
    String str = calculateStr();
    .....
}

If we followed the second one surely this will reduce our system memory and increase performance.
Answer: I think the size of the object matters as well.
In one of my projects, we had declared and initialized a large two dimensional array that was making the application throw an out-of-memory exception.
We moved the declaration out of the loop instead and cleared the array at the start of every iteration.
Answer: Warning for almost everybody in this question: Here is sample code where inside the loop it can easily be 200 times slower on my computer with Java 7 (and the memory consumption is also slightly different). But it is about allocation and not only scope.
public class Test
{
    private final static int STUFF_SIZE = 512;
    private final static long LOOP = 10000000l;

    private static class Foo
    {
        private long[] bigStuff = new long[STUFF_SIZE];

        public Foo(long value)
        {
            setValue(value);
        }

        public void setValue(long value)
        {
            // Putting value in a random place.
            bigStuff[(int) (value % STUFF_SIZE)] = value;
        }

        public long getValue()
        {
            // Retrieving whatever value.
            return bigStuff[STUFF_SIZE / 2];
        }
    }

    public static long test1()
    {
        long total = 0;

        for (long i = 0; i < LOOP; i++)
        {
            Foo foo = new Foo(i);
            total += foo.getValue();
        }

        return total;
    }

    public static long test2()
    {
        long total = 0;

        Foo foo = new Foo(0);
        for (long i = 0; i < LOOP; i++)
        {
            foo.setValue(i);
            total += foo.getValue();
        }

        return total;
    }

    public static void main(String[] args)
    {
        long start;

        start = System.currentTimeMillis();
        test1();
        System.out.println(System.currentTimeMillis() - start);

        start = System.currentTimeMillis();
        test2();
        System.out.println(System.currentTimeMillis() - start);
    }
}

Conclusion: Depending of the size of the local variable, the difference can be huge, even with not so big variables.
Just to say that sometimes, outside or inside the loop DOES matter.
Comment: Sure, the second is faster, but you are doing different stuff: test1 is creating a lot of Foo-Objects with big arrays, test2 isn't. test2 is reusing the same Foo object over and over again, which might be dangerous in multithreaded environments.
Comment: Dangerous in multithreaded environment??? Please explain why. We are talking about a local variable. It is created at each call of the method.
Comment: If you pass down the Foo-Object to a operation that is processing the data asynchronously, the operation might still be working on the Foo-instance while you are changing the data in it. It doesn't even have to be multithreaded to have side-effects. So instance-reusing is quite dangerous, when you don't know who is still using the instance
Comment: Ps: Your setValue Method should be `bigStuff[(int) (value % STUFF_SIZE)] = value;` (Try a value of 2147483649L)
Comment: Speaking about sideeffects: Have you compared the results of your methods?
Comment: Yes there are side effects. My point is that sometimes, if you instantiate a big object (Even not so big: 512 longs...) in a loop, it is sometimes greatly faster to code differently and to reuse the same instance. Obviously, to be able to do that, the instance has to be reusable.
Answer: You have a risk of NullPointerException if your calculateStr() method returns null and then you try to call a method on str.
More generally, avoid having variables with a null value. It stronger for class attributes, by the way.
Comment: This is no way related to the question. The probability of NullPointerException(on future function calls) would not depend on how a variable is declared.
Comment: I don't think so, because the question is "What is the best way to do it ?". IMHO I would prefer a safer code.
Comment: There is zero risk of a `NullPointerException.` If this code attempted to `return str;` it would encounter a compilation error.


DTC checking while engine running

Question: Why it is said that DTC (Diagnostic Trouble Code) should not be checked when the engine is running?
Comment: Where has this been said for what make and model of car?
Comment: Who said? where?
Comment: http://www.aa1car.com/library/cm40122.htm
Comment: http://www.popularmechanics.com/cars/how-to/a3293/4267896/
Comment: Your first link says to read codes : turn ignition on but do not start the engine - not that you "must not start the engine" as some scanners can read data in real time the engine has to be running. Mind you given the spelling and other errors in that link I would go for the proper manual first...
Answer: In the two links you provided in comments, it states to plug in your code reader, turn the ignition on, but don't start the engine, then read the codes. It's not telling you "cannot run the engine" while reading the codes, it's just saying not to do it to read the codes at first.
There should be no issue using your code reader and checking DTCs with the engine started. I've done this many times with multiple different readers without ever having an issue with the vehicle I'm reading of the reader itself. One of the things most code readers do today is check live data. You cannot check live data without the engine running (well, you can, but it won't be "live data").
There are a lot of reasons why you might want to keep checking the vehicle, leaving the scanner plugged into the OBDII port and scanning for DTCs. One of them is vehicle readiness ... to see if the vehicle will pass emissions muster. Another reason is to see if a code comes back after clearing it. This is a typical diagnostic approach when trying to figure out an issue with a vehicle.
Answer: I have read my code reader instructions yesterday and it mentions that the DTC's can be read with the ignition on with the engine running or not - handy as I had the engine running at the time...
What it did say was that you should not connect the reader with the engine already running - which I found out after I had done exactly that... Seems fine so i must have been lucky.
However, this could be specific to your reader...

DTC checking while engine running


Outline text duplicate characters

Question: I have a large document in which I am converting texts to outlines using Adobe Acrobat Pro. But when I do so, the file size increases significantly. It is because it turns every character into a unique object. But if it converted every same character e.g., all e's of the same font to a symbol, then the file size would have been much smaller. Is there any program that is capable of doing so?
Comment: **Why** do you need fonts unrecognizable?? I can't think of any reason for that. - And once you outline type each and every path becomes solitary artwork, it's no longer a a collection of references to a built in library (font). So, naturally 1000 type characters that contain a common 26 characters, will be smaller in terms of KB than 1000 separate vector objects.
Comment: Yes -- any remotely capable PDF creator does this. The collection of outlines is called a "font".
Comment: Why do you want to turn your text to outlines?? I can't see any good reason for that; even the dumbest print shops are beginning to handle PDF properly…
Comment: But the fonts can be copied, while the outlines cannot. Can the fonts be rendered unrecognisable?
Comment: I want to render the fonts unrecognisable by any software that reads pdf
Answer: This is probably also available via Acrobat Pro: in InDesign's export to PDF panel you have options to password-protect files against printing, editing and/or copying of text. Not sure if this works for you, but it is something to consider instead of having huge files with outlined text.

Outline text duplicate characters


Why haven't I recieved my reputation for upvote?

Question:
Two upvotes and an accepted answer is not giving me rep. Why?
Comment: I think it has to do with the bounty that costs rep. Netto rep gain is still negative, so it doesn't show up here, I think.
Answer: You made your post community wiki. Reputation gained by accepted answers and votes (downvotes & upvotes) are not awarded for Community Wiki (CW) posts. Only a moderator will be able to revert the CW.

How do Community Wiki posts work?
Community wiki posts work by partly transferring ownership of the post from the original author to the community.  They make the post easier to edit and maintain by a wider group of users, but they do not contribute to any user's reputation.
Some of the key features are:

A much lower reputation (100 instead of 2000) is needed to freely edit a community wiki post. 1
Voting on a community wiki post (up or down) does not affect any user's reputation.
Accepting an answer marked as community wiki does not affect its original author's reputation, and does not give +2 to the question author.
Bounties awarded to answer marked as community wiki give reputation as usual.
The original author still gets badges based on community posts.
The original author keeps the reputation gained (or lost) before their post entered community mode.
The original author still receives notifications for edits or comments on the post.
The user listed in the author box need not be the original author. Rather, it is the user with the highest percentage of authorship in the final revision, determined by the number of lines inserted or deleted, with a bonus (factor of 2) for the original author.

See here for more information.


Frequency Modulation

Question: If FM radios work by modulating the frequency, how is it that we can tune into a specific channel, and hear a song or station? Wouldn't the channel need to be modulated along with the varying frequency?
Comment: The details of how FM works are a deeper question than just how signals can be selectively filtered, so I don't see this as a duplicate of 13599.
Comment: That is the work of Band-Pass Filter . https://en.wikipedia.org/wiki/Band-pass_filter
Answer: The frequency of the signal is modulated in a relatively narrow band, and drives the audio circuit in proportion to the resonant power between the signal and a resonating circuit tuned to almost the range where the signal resides.
The result is that the power in the audio circuit varies with the frequency of the driving signal
Other signals are far from the resonant frequency of the tuner and do not drive it to an appreciable degree. Further regulatory steps are taken in most place to reduce insure a minimum difference between nearby stations.
Comment: This is why FM radio stations in the US use the odd points only.  98.1, 98.3, 95.5, 98.7, 98.9, etc. (all in MHz).  There are no .{0,2,4,6,8} FM stations.  They are spaced out by 200 KHz even though each station is only about 25 - 50 KHz wide which gives about 75 KHz of padding on each side.
Comment: When you say other signals are far from the resonant frequency, do you mean that FM stations are fairly spaced out?
Comment: When you drive a resonator (within some limits in the power of the driver and the $Q$ of the resonator) the response is strongly dependent on the difference between the driving frequency and the natural frequency of the resonator divided by a width figure that is proportional to $1/Q$. The next station over differs in frequency by many times that width so there is negligible response from the resonator.
Answer: Modulation, whether AM, PM, FM or whatever (even CW), necessarily widens the spectrum from that of the pure tone of the carrier.
Thus, in the design of any radio demodulator circuit, the bandwidth of the modulated carrier must be taken into account.
Generally, the RF signal is down-converted, via a mixer and local oscillator, to an Intermediate Frequency (or more modernly, the RF is directly converted to baseband) where a sequence of filters and amplifiers, with the appropriate bandwidth, attenuate frequencies outside of the desired bandwidth and amplify the frequencies within.  This "groomed" IF signal is then passed to the demodulator.
For the commercial FM band, the channel spacing is 200kHz.  But, the actual bandwidth is (from Wiki):

Bandwidth of 200 kHz is not needed to accommodate an audio signal — 20
  kHz to 30 kHz is all that is necessary for a narrowband FM signal. The
  200 kHz bandwidth allowed room for ±75 kHz signal deviation from the
  assigned frequency, plus guard bands to reduce or eliminate adjacent
  channel interference. The larger bandwidth allows for broadcasting a
  15 kHz bandwidth audio signal plus a 38 kHz stereo "subcarrier"—a
  piggyback signal that rides on the main signal. Additional unused
  capacity is used by some broadcasters to transmit utility functions
  such as background music for public areas, GPS auxiliary signals, or
  financial market data.

Frequency Modulation


Powerline Ethernet Adapter and two electrical boxes

Question: I own a home and carriage house in the back.  They are on separate electrical boxes and pay separate in terms of utility bills.  My questions is, are these connected in any type of way where if I setup a Powerline Ethernet Adapter at my home, is there a way for the carriage house to pick this up.  Are the electrical boxes tied together in anyway at all?  Is there a way to find out?
Comment: It isn't ideal.  Performance can be hit or miss even on different breakers on the same feed.  This would be seriously pushing it.  However, the only way to know is to try it.
Comment: I would try it. The best more Ideal way would to be to setup a AP. or Repeater. If you knew how far away your current router is we could help you figure out the best setup.
Answer: They are tied together - they both share power from the grid.
Whether this will work depends on rather a large number of things, but particularly the sensitivity of the gear you choose and if they are on the same phase.
If it works, its unlikely to work well, but the only way to see if it works at all is to try it.
(Powerline networking is very similar to WIFI, only it uses the power cable rather then air as a wave guide.   Things like meter boxes and RCD's typically interfere somewhat with the signal)


Definition of a Graded Algebra and $R_0$

Question: Below we have a definition of a graded $k$-algebra where $k$ is a field. I have a few questions. First, looking it up, there seems to be some ambiguity as to what $R$ is a direct sum of the $R_n$ as. Groups? $k$-modules? Is there anything from context that could tell me? Secondly, why is $R_0$ a subalgebra. If the $R_n$ are submodules, then for $r\in R_n$, $kr\in R_n$, and therefore its not hard to see that if $R$ is an integral domain, $k\in R_0$, but I can't see why this should work if $R$ is not an integral domain. Thanks in advance.
Comment: Direct sum of $k$-vector subspaces. Since $R_0R_0\subseteq R_0$ we have that $R_0$ is a subring of $R$. And by assumption, $R_0$ is a $k$-vector subspace so $R_0$ is a $k$-subalgebra of $R$. For the general case when $R$ is not necessarily a $k$-algebra, see the beginning of https://math.unl.edu/~tmarley1/905notes.pdf
Comment: I assume your rings contain a $1$. Is this the case?
Comment: Yes, but why is it in $R_0$?
Comment: Remark 1.1 of the link I gave provides a nice proof that $1\in R_0$.
Comment: @MichaelMorrow please consider writing an answer so that this question can be marked as dealt with.
Answer: The phrase "where the subspaces..." indicates that we want to think of this as a direct sum of $k$-vector subspaces. The general definition of graded ring uses a direct sum of abelian groups, see https://math.unl.edu/~tmarley1/905notes.pdf for more details.
One can show without difficulty (see Remark 1.1 of the aforementioned link) that $1\in R_0$. Furthermore, since $R_0R_0\subseteq R_{0+0}=R_0$ we have that $R_0$ is a subring of $R$. Finally, combining this with the fact that $R_0$ is a $k$-subspace of $R$ we obtain that $R_0$ is indeed a $k$-subalgebra of $R$.


Copper (II) Acetate from 5% vinegar + salt, electrochemically

Question: I'm trying to create Copper (II) Acetate crystals, but in these times of Coronavirus it's difficult to come by hydrogen peroxide. I could be patient, but I'm not, so I'm trying to make it electrochemically. I have 5% vinegar and lots of copper scrap, and an adjustable power supply. Unfortunately I can't barely get any current going, so I've thought of adding salt, regular NaCl. I'm curious what effect this will have on the final outcome though. Balancing equations is something I struggle with, but I'd really like to learn the chemistry here. Will the salt interfere with or alter the growth of the copper acetate crystals? Ultimately I'm trying to make calcium copper acetate crystals, I've already made the calcium acetate.
Comment: With NaCl, there is danger copper would end bound in $\ce{CuCl4^2-}$
Comment: Another ways is to let time and aerial oxygen to oxidate cupper, leading to copper acetate.  $$\ce{4 HAc + O2 + 2 Cu -> 2 H2O + 2 Cu(Ac)2}$$
I once performed vinegar decalcification of aged boiling kettle. Its heating spiral had exposed cupper, with the stainless coating already mostly stripped away. I have shortly boiled vinegar and forgot it to let stay overnight. The solution got pretty blue.
Comment: Interesting. I thought about using a small air pump to bubble air through. As it is it's stood on a "hot plate" (coffee maker base wired to 20V DC, gets to about 200°F), with my small copper scrap in the bottom (lots of small pieces of 12 gauge solid wire). It's been about 12 hours and it's very slightly more blue than it was. I am impatient.
Comment: Welllll, all I had was a cheap 12v tire pump and some silicone tubing. I closed one end of the tubing and poked a bunch of needle holes in that end, then stuffed the other end into the tire chuck and applied 5v, to make it run a little more slowly. It's chugging along pumping a bunch of small bubbles through the copper. Not quiet, I probably won't leave it running, but it works!
Comment: I suppose forcing air must be much more efficient than heating, as heating expels oxygen from solution.
Answer: To prepare copper acetate absence H2O2, employ a known method from hydrometallurgy to process copper ore employing aqueous ammonia, air (a source of oxygen) and a small amount of salt (acting as an electrolyte for this, in part, spontaneous electrochemical reaction detailed below). This results in tetra-ammine copper hydroxide. The latter exists only in solution and upon evaporation yields CuO (and possibly some Cu2O also, see this old patent). Add an acid of choice (like vinegar, a source of acetate) to convert CuO into copper acetate.
Related copper chemistry with ammonia and oxygen:
Cited half-reactions:
$\ce{1/2 O2 + H2O + 2 e- -> 2 OH-}$ (cathodic reduction of O2 at surface of the Copper)
And, at the Copper anode, the formation of the complex:
$\ce{Cu + 4 NH3 + 2 H2O -> [Cu(NH3)4(H2O)2](2+) + 2 e-}$ (anodic dissolution of Cu by a complexing agent)
With an overall reaction:
$\ce{Cu + 4 NH3 + 1/2 O2 + 3 H2O -> [Cu(NH3)4(H2O)2](2+) + 2 OH-}$
Also, some interesting cited standard chemical reactions, where copper oscillates between cuprous and cupric states as noted by the source below:
$\ce{2 Cu + 4 NH3 + 1/2 O2 + H2O -> 2 [Cu(NH3)2]OH}$
$\ce{2[Cu(NH3)2]OH + 4 NH3 (aq) + 1/2 O2 + H2O -> 2 [Cu(NH3)4](OH)2}$
$\ce{Cu + [Cu(NH3)4](OH)2 <--> 2 [Cu(NH3)2]OH}$
Reference: "Kinetics and Mechanism of Copper Dissolution In Aqueous Ammonia" and a related work detailing reactions: 'Copper Dissolution in Ammonia Solutions: Identification of the Mechanism at Low Overpotentials', which is also a fully available PDF.
Some alternate preparations would be to follow paths to copper patina (see this site, which discusses three paths for the home chemists which includes an embodiment of the ammonia prep, and, with the addition of vinegar, would convert the basic copper carbonate to copper acetate.
Comment: Thank you, that's an awesome answer. I'll read more closely when I get home and I'm not on my phone, I think I have some 10% ammonia left from making ammonium sulfate. Thank you for the detailed information!


Cannot run stored procedure from Entity Framework Core

Question: I have the following code in EF Core to run a stored procedure:
TenandId = user.TenantId;
userName = user.UserName;
updateDate = DateTime.Now;
TimeStart = 139601;
TimeEnd = 139612;
RequestId = id;

_context.TempRequest.FromSql("EXEC dbo.AddRequest_To_TempRequest @TimeStart, @TimeEnd, @TenantId, @UpdateDate, @UserName, @RequestId",
                new SqlParameter("@TimeStart", TimeStart),
                new SqlParameter("@TimeEnd", TimeEnd),
                new SqlParameter("@TenantId", TenandId),
                new SqlParameter("@UpdateDate", updateDate),
                new SqlParameter("@UserName", userName),
                new SqlParameter("@RequestId", RequestId));

but when I run it, it is not working, but it is also not throwing any errors.
Am I making any mistake?
Thank you
Answer: FromSql is used when the raw SQL represents a query. And the method creates LINQ / EF Core query, but as usual with IQueryable<> / IEnumerable<> does not execute it until it is iterated (with foreach, ToList() etc.) - the so called deferred execution. This should explain why "it is not working, but it is also not throwing any errors".
For non query raw SQL statements EF Core provides another method  ExecuteSqlCommand (or ExecuteSqlRaw / ExecuteSqlInterpolated in EF Core 3.0+) which executes immediately.
Both methods can be used to call stored procedure when executed. Looks like the later is more appropriate for your scenario, so replacing the
_context.TempRequest.FromSql

with
_context.Database.ExecuteSqlCommand

should do the job.


Thunderbolt 1 to USB Type C adapter?

Question: I have a 2012 MacBook Pro.  It has a Thunderbolt (Mini DisplayPort) port.  I'd like to plug a USB Type-C device into it, since Thunderbolt is faster than my USB 3.0 port.  I'm having a hard time finding an adapter with male Mini DisplayPort on one end and female USB-C on the other.  Does such an adapter exist?
Comment: Potential dupe: https://apple.stackexchange.com/a/267009/119271.   Short answer is you're not going to find one.
Comment: Before (or while writing the comment *after*) starting a reverse downvote battle, please add the type of USB-C device you want to attach...
Comment: I don't have a particular type of device in mind.  Are there adapters that would only handle certain types of devices?
Answer: Use this adapter if it's a Thunderbolt device -> https://www.apple.com/shop/product/MMEL2AM/A/thunderbolt-3-usb-c-to-thunderbolt-2-adapter
You will need a Thunderbolt cable as well.  That should work for you, it's worked for me.
If this is not a Thunderbolt device with a USB-C port, but is instead a USB 3.x device with a USB-C port then you need a different cable.  Like this one -> https://www.amazon.com/AmazonBasics-Type-C-Adapter-Charger-Cable/dp/B01GGKYR2O
If you want to get gigabit speeds then make sure it's a USB 3.x cable and not a USB 2.0 cable.
If the device has a captive USB-C cable then there is no cheap solution.  You will need a Thunderbolt 2 dock with a USB-C port, and these are hard to find.  It would likely be cheaper to just replace this USB-C device with a USB-A or Thunderbolt 2 version than get an adapter.
Here's an upcoming option that may work, a Thunderbolt hub.  An example, not an endorsement: https://eshop.macsales.com/shop/owc-thunderbolt-hub
A Thunderbolt hub like this likely, but not absolutely, has a USB 3.x controller in it allowing USB 3.x devices to be used with Thunderbolt 1 and 2 hosts as well as any Thunderbolt devices.  I'm considering one for my own use and if I get one and I remember to come back to this post then I'll report on how it works.  But to get it to work means having a Thunderbolt/mini-DP to Thunderbolt/USB-C adapter and/or cable.
So, a quick summary.  A single Thunderbolt/USB-C device can be connected with a mini-DP to USB-C adapter.  A single USB 3.x/USB-C device can be connected by a USB-A to USB-C cable.  This will not always get the most bandwidth a USB-C device can offer but it is cheap and easy.  A Thunderbolt dock is an option, an expensive one that may be overkill.  A Thunderbolt/USB-C hub should allow use of multiple Thunderbolt and USB 3.x devices with a Thunderbolt 1 or 2 host.  I have not tested this myself but, like with the dock, I recall reading that people had success with this in the past.  The hub saves some money over the dock but the dock may have the ports you needed USB-C dongles for and so saves on clutter.
Edit to add:  I have tested a Thunderbolt hub with USB-C on a Thunderbolt 1 computer since I first posted this answer and it does provide useful USB-C ports.  Even though the hub is Thunderbolt 4 it worked on a Thunderbolt 1 Mac Mini by using an Apple Thunderbolt USB-C to mini-DP adapter and Thunderbolt/mini-DP cable.  The hub has a USB 3.x controller in it so USB devices that were plugged in still worked.  The way I read the Thunderbolt spec all Thunderbolt hubs with USB-C ports must have a USB 3.x controller for backward compatibility, so this should not be unique to the hub I bought.  The nice little bonus of this is I get a 10 Gbps USB controller in the hub on top of the 5 Gbps controller in the Mac Mini.  Since the Thunderbolt controller in the Mac Mini is 10 Gbps the bandwidth is limited, I can't get the same USB performance as if using the same hub on a computer with Thunderbolt 2, 3, or 4.  The Apple Thunderbolt adapter does not support DisplayPort so any video ports on a Thunderbolt dock or hub plugged in using the Apple adapter are not likely to work.  This should not impact the function of an eGPU as they use PCI or USB to produce video.
Comment: Oh, cool.  The first adapter you listed would work if I got a Thunderbolt 1 cable also.  I guess I'd also need a USB-C female to female adapter to plug in a flash drive or something with a USB-C male connector.
Comment: Please don't use a female to female adapter, this violates the USB specification and this restriction is in the specification for a reason.  You will run the risk of damaging the device and/or computer with these adapters.  I missed the point about a male USB-C connector the first time so I answered the question more generally, the last paragraph in my post above likely applies here.  If the cable is not hardwired then unplug it and use the right kind of cable.  If it is hardwired then this is probably something that requires a $300+ dock of some kind.

Thunderbolt 1 to USB Type C adapter?


Is it haram to be asexual?

Question: Is it haram to be asexual, having no sexual interest in anybody? If so, why is it? I am confused because normally asexuals are looked down upon when they simply just don't have any sexual desires. Is it the same for Islam?
Answer: It can never be haram to be. We are how God has made us.
Only what we do can be haram. In some cases but not in this case, it may also be haram not to do something.
God will not request sexual activity from somebody He has made without this desire.
So, the answer is: no, it can't be haram.

Is it haram to be asexual?


Intel-microcode Package on Ubuntu

Question: I saw the intel-microcode in the ubuntu repositories and was wondering if it was worth installing on my Yorkfield-6M based system. If so, what are the benefits from this package?
Answer: Microcode is update of processor of runtime. If any problems are found in hardware they may be fixed by such software update.

Intel-microcode Package on Ubuntu


Uncontrollable Offset with Follow Path

Question: When I set the target of the Follow-Path Constraint my object moves to some other position which I cant control and dont want. How can I fix this?
I think it has something to do with the blue dashed line (Relationship Line?) It seems to be relative to World origin.
Comment: https://blender.stackexchange.com/questions/260983/problems-with-follow-path?rq=1
Comment: to add to Hadriscus answer, the object also needs to be at the center of the scene if you want it to stick to the beginning of your curve, so once its origin is at it center, put the object at the center of the scene with an Alt G
Answer: Constraints operate on object transforms, regardless of the geometry they contain. It appears the cube mesh has moved from its origin, you probably moved it away while in edit mode. To recenter it, you can select the object (in object mode), shift+S -> cursor to selected, then enter edit mode, select all, and shift+S -> selection to cursor (offset).

Uncontrollable Offset with Follow Path


Why is Darth Maul red when other Zabraks (Nightbrothers on Dathomir) are mostly yellow/tan?

Question: We see no other Red Zabraks, specifically the Nightbrothers on Dathomir, throughout the Clone Wars and Star Wars. Why is Darth Maul red when other Zabraks are mostly yellow/tan?
Comment: I've always assumed that the red parts of his face are some sort of face paint, same as the yellow parts of Savage Oppress' face
Comment: You can't just ask people why they're red.
Answer: It's just his skin tone, and it kinda seems that in the period of the Clone Wars he is part of a minority group within his species (due to him being one of the few that looks like this). The black skin on the other hand are tattoos. The decision for this is probably to make him stand out more making him more memorable compared to others of his kin.
It is kinda like asking why Mace Windu is black. Seeing most human characters in Star Wars seem to be Caucasian.
Comment: FWIW this was also done well with the MCU's Kree population. They tend to be blue, but some Kree are white and this is taken as a normal thing.


Meaning of strong and weak drive in VHDL?

Question: What is the meaning and effect of "strong" and "weak" drive shown by (0,1) and (L,H) in VHDL's package  ieee.std_logic_1164?
Answer: The ieee.std_logic_1164 package allows two drive strengths.
(0,1) are normal drive strength and used for all normal purposes.
(L,H) are weak drivers, they are normally used to model pull-up and pull-down resistors.
Formally, ieee.std_logic_1164 distinguishes between the std_ulogic and std_logic types, even though they share the same set of values  (U,L,H,0,1,X,Z etc).
The difference between them is this : std_ulogic is an unresolved type. It is an error for a std_ulogic signal to be driven by two signal sources (like short circuiting 2 wires together - it's usually a mistake) - such errors will be caught (by the compiler) and fixed (by you!) even before you get to simulation.
On the other hand, std_logic is a resolved type. It is legal to have two or more drivers on a signal. The result is determined by a "resolution function" which looks at all the driving values and combines them into the value you will see on the signal. For example, 0 and '1' combine to produce X (the Unknown state) , and X and anything else produces X so that once Unknowns happen, they propagate through the design to show there's a problem.
But '0' and 'H' combine to produce '0' (because H is weak) and similarly, '1' and 'L' combine to produce '1'. So a strong driver can legally overpower a weak one : no harm done.
Let's look at the 'Z' state : it signifies Undriven, or High Impedance (High-Z). Now Z and H combine to produce H because H, though weak, is still stronger than no driver at all.
This is just a brief summary : for all details see a good VHDL book or even the ieee.std_logic_1164 package source code.
So one use of a weak H is in the so-called "wired-or" configuration, as used in I2C buses.
SDA <= `H`;   -- permanent pullup resistor
SDA <= `0` when I2C_Master_SDA = '0' else `Z`;
SDA <= `0` when I2C_Slave1_SDA = '0' else `Z`;
SDA <= `0` when I2C_Slave2_SDA = '0' else `Z`;

We are safely combining 4 drivers on the same signal : one I2C master, two slaves, and a permanent weak pullup.
Answer: This is one of those cases where IEEE Std 1076-2008 gives a concise answer.
188.8.131.52 The STD_LOGIC_1164 values

The logical values '1', 'H', '0', and 'L' of type STD_ULOGIC are interpreted as representing one of two logic levels, where each logic level represents one of two distinct voltage ranges in the circuit to be synthesized.
The resolution function RESOLVED treats the values '0' and '1' as forcing values that override the weak values 'L' and 'H' when multiple sources drive the same signal.
The values 'U', 'X', 'W', and '–' are metalogical values; they define the behavior of the model itself rather than the behavior of the hardware being synthesized. The value 'U' represents the value of an object before it is explicitly assigned a value during simulation; the values 'X' and 'W' represent forcing and weak values, respectively, for which the model is not able to distinguish between logic levels.
The value '–' is also called the don't care value. This standard treats it in the same way as the other metalogical values except when it is furnished as an actual parameter to the STD_MATCH functions in the IEEE.NUMERIC_STD package or as an operand to a predefined matching relational operator (see 9.2.3). The STD_MATCH functions and the predefined matching relational operators use '–' to implement a "match all" or "wild card" matching.
The value 'Z' is called the high-impedance value, and represents the condition of a signal source when that source makes no effective contribution to the resolved value of the signal.

From 4.6 Resolution functions:

A resolution function is a function that defines how the values of multiple sources of a given signal are to be resolved into a single value for that signal. ...

You can read how synthesis treats std_ulogic values in 188.8.131.52 Interpretation of logic values.
188.8.131.52.2 Interpretation of the forcing and weak values ('0', '1', 'L', 'H', FALSE, TRUE)

A synthesis tool shall interpret the following values as representing a logic value 0:

The BIT value '0'
The BOOLEAN value FALSE
The STD_ULOGIC values '0' and 'L'

It shall interpret the following values as representing a logic value 1:

The BIT value '1'
The BOOLEAN value TRUE
The STD_ULOGIC value '1' and 'H'

And this should tell us you don't short outputs together. There's also provision for 'Z' inferring tristate buffers.
Answer: I don't know what that standard is, to which you refer , but 'strong' and 'weak' refer to how much current a logic gate output can provide to maintain the appropriate voltage level corresponding to what the logic level should be.
E.g. if a logic 1 (H) output is supposed to be 5V, that voltage will drop if you connect a heavy load to it, perhaps to the point where it will no longer be considered a valid logic level.
Comment: Could a 'weak' drive be a pull-up / down resistor and a 'strong' be a transistor drive up / down?
Comment: @transistor yes, that is the usual case, but it could go the other way. One common use of a weak pullup  would be to give a defined default logic level (high) when there is no input connected, such as when the real logic source is not present (such as a plug-in card)


Lie or Hide the sins?

Question: I know this is a different question but I hope someone has an answer for it. In Islam, it's a sin to lie. At the same time, it's a sin to expose your sins. If a person asks another person to tell them if they have done a certain sin or not, and in reality they have done it, then what should they do? They can either say the truth which would mean exposing their sins. Or they can say that they haven't done the sin which would mean that they are lying.
Comment: In what context, in other words how important is it to tell the truth?
Comment: @Medi1Saif I am asking in the context of a random discussion.
Answer: Asalaam Alaikum
assuming that we have understood the gravity of exposing sins and lying (except in 3 cases), the best way to reconcile with the situation you have mentioned would be to avoid the person who is asking.
no good muslim would ask another muslim about their sins let alone try to expose them. when someone asks you such question, remind them that it is not permissible in islam and we should not entertain such people.
when faced with such situation, follow the example of Abu Bakr (R.A), the most trustful of this ummah. i will quote the incident below.

Abu Bakr al-Siddeeq the most truthful man of the 'Ummah who accompanied the prophet ( may  Allah exalt his mention ) on his flight to Madeenah, was accosted by an acquaintance of his who did not know the Prophet ( may  Allah exalt his mention ) by face but had probably heard of the Makkan search for him. He asked Abu Bakr (may  Allah  be  pleased  with) him about his companion, to which Abu Bakr  (may  Allah  be  pleased  with) him said: "He is my guide. He shows me the way." Abu Bakr did not lie even in such dire circumstances, but simply equivocated.
[refference : al-sira al nabawiyya by ibn kathir]

we must refrain from telling a lie as much as we can and avoid such scenarios that could lead us to it. next time when you are faced with a situtation like that, remind them of the hadith.

It was narrated from Abu Hurairah that the Messenger of Allah (ﷺ) said:
"Whoever covers (the sin of) a Muslim, Allah will cover him (his sin) in this world and in the Hereafter." [Sunan Ibn Majah 2544]

may Allah the mighty and sublime grant you mercy and guide you to the straight path.
Allah knows best.
Answer: In the name of Allah
Best way is to refuse to answer. At the same time try to learn that person that asking people about their sins is a bad thing.(indirectly)

Lie or Hide the sins?


Yamaha Crux-S Shock Absorbers-Rear

Question: I have Yamaha 'CRUX-S' model and back shock absorbers are hard. I was asked to get them changed with better by a mechanic as they are hard. What type will make me a better ride. Can I use 'CRUX' Shock absorbers or any other better suggestion is appreciable? Thank You
Comment: Welcome to the site. If you leave the part about better ride in the question, it will get closed as opinion based. Also, this question is precariously close to being a shopping question. If you limit it to what will physically fit (what will work in place of your current), I think we can salvage the question and make it viable.
Answer: The rear shocks being two hard can be solved in a number of ways, depending on what is available:
1) Adjust the preload.
A number of modern motorcycle shocks and forks have adjustment for preload. In fact if your motorcycle shocks or forks have any sort of adjustment available, it's probably for preload. Preload is the amount of squeezing force applied to the spring beyond the normal weight of the motorcycle and rider. It's usually achieved with a set of locknuts on threads that will tighten down onto the spring, or a stepped collar that spins into a few different positions. Squeezing the spring will have the affect of making the spring more firm, as it will take more energy to continue to squeeze it compared to when it was fully extended.
2) Swap out the spring. Springs in forks and shocks are designed for a specific weight range, usually measured in kg/mm. Preload adjustments will help fine tune them, but the adjustment will only go so far before all the preload has been removed and no more can be taken out, or the spring is compressed to the point that it no longer offers sufficient travel. If you want a softer or stiffer shock beyond what the adjustment will give, you need a spring that was manufactured with a higher or lower rating.
I would start by checking if you have a preload adjustment on the shocks, and if so, taking some out. This will have the affect of making the shocks feel softer, and also raising the ride height in the rear a little bit. Make sure both are adjusted to the same setting evenly, or you will negatively affect handling and stability.
If that isn't an option, or does not go as far as you need it to, you need to look at new springs. At this point I'd recommend talking to a suspension specialist, as changing springs isn't the kind of thing that people do themselves. You need special tools to compress the shock. An expert will also be able to help you determine the rating of the springs you already have, and a rating that would suit your weight.

Yamaha Crux-S Shock Absorbers-Rear


Should a chord be repeated in inversions?

Question: Just wondering, if the same chord is played for few bars. Is it common to invert this chord on every bar just to make it sound like the harmony is doing something?
Comment: If you want to make it sound like the harmony is doing something, maybe yes. Otherwise, maybe no. Eventually, you will learn that "there are no rules" except for "*use your ears.*" - but not if you keep looking for rules that don't exist!
Answer: When the same chord is repeated long enough, it tends to shift the focus to the rhythm. This is good if you want the rhythm to be the focus.
There are a few common things that are often done when the accompaniment keeps the same chord/harmony for a longer than usual time:

The chord is played with an interesting rhythm
The chord is arpeggiated and/or different notes of the chord are played in a certain sequence
The chord is replaced with a riff that implies the same tonality
A nearby or similar chord is played briefly between repeats of the actual harmony chord

The second bullet above is essentially playjng the chord in a repeating pattern of inversions, so the basic answer to your question is "yes". The inversion pattern is often repeated at least once a measure and if it's not repeated (i.e. If you just go through a long cycle of different inversions) then the effect will be to draw the focus back towards the harmony part, which you might not want.
Some examples to study and consider:

Any 12 bar blues song since the I is often repeated for four measures, especially delta blues
Bo Diddley, for example George Thorogood's cover of "Who Do You Love" is a whole song on basically one chord
Eric Clapton's cover of "Willie and the Hand Jive" shows a way to keep the same chord interesting for a whole verse
"Whole Lotta Love" by Led Zeppelin is basically an E minor chord all through the versus but instead of the chord there's an E minor riff that is repeated once a measure

Also note that a walking bassline under the same repeated chord is a tour of inversions.
Comment: That's Bo Diddley with an 'e'. Perhaps it's worth noting that a series of inversions rising in pitch will tend to build drama. It can be effective to use this trick in the bar approaching a chord change.
Answer: From a classical perspective - and referring to Walter Piston's textbook Harmony - changing the inversion of a chord gives you new voice leading possibilities. Although it's probably better to not think of only inversions - in the sense of the bass changing - but rather re-distributing the voices of the chord. In other words, you can also change the notes of the other voices above the bass.
Personally, I wouldn't call this 'making the harmony sound like it's doing something' as if it isn't important or meaningful. Sure, the chord root isn't changing, but the chords are changing. The effect can be more or less static depending on how it's handled. Arpeggiating the bass through root, third, fifth, octave could feel fairly static, whereas I to I6 has a more dynamic feel and can strongly imply moving to IV. Either way something is happening and should have some musical meaning.


2-way DC motor control for greenhouse IoT application

Question: Edit: After doing more research, it seems simply reversing the DC polarity would do the trick as explained here: https://www.precisionmicrodrives.com/content/are-dc-motors-reversible
This can be accomplished with a SPDT relay apparently, or with 2 regular relays. Thus, I see the following options:

Tasmota flashed Sonoff R3 Pro relay (https://www.itead.cc/smart-home/sonoff-4ch-r3-pro-r3.html)
Any regular 2 channel relay (http://yourduino.com/sunshop//index.php?l=product_detail&p=218)
Use an off the shelf SPDT relay (https://www.seeedstudio.com/Grove-2-Channel-SPDT-Relay.html)

I'd say option 1 is the best way to go, since I won't have to bother with supplying power to the microcontroller and I can just mount everything on a DIN rail in my central control box. Drawback is obviously an older platform with inherent security risks. Believe I can mitigate those with restricting role of Sonoff device on AWS IoT core though.
Am I on the right track here?
=================
I'm trying to build a low-cost PE-film greenhouse with as much automation as possible to reduce labor cost. Ventilation control by manually rolling up the film on the side of the greenhouse with a hand crank is one of the largest drivers of cost. Automating this seems like a low-hanging fruit, since there are tons of relatively cheap purpose-made greenhouse control motors out there on Alibaba.
Before buying though, I'd like to know what my options are when it comes to remote control. The ones I've seen are either 2 wire or 3 wire on DC24v and all of them come with 2 knobs to control maximum rollup/rolldown (under cover marked in red on schematic). There seems to be a way to control them, as some of the them come with manual control systems as in the pictures below.
Greenhouse overall will be controlled through AWS IoT cloud with ESP32-S2 units connected to sensors and control systems across the greenhouse, so an approach using an ESP32 driving the motor control is my preference, but open to any other ways too.
Any help or pointers would be greatly appreciated. Thank you!
Answer: You could use a 2 CH RF Operated Relay board with remote control.
You may get models prewired for DC Motor Reversing Control.
If you don't, the relays may be wired as shown.

The motor would be controlled by operating 2 buttons on the remote.


construction of cotangent bundle

Question: Cotangent Bundle $T^{*}(M)=\bigcup_{m\in M} M_m^{*}$ (disjoint union of contangent space) Could any one explain me how there is a natural projection from $T^{*}(M)\rightarrow M$ given by $\pi(f)=m$ if $f\in M^{*}_m$?
I am not able to understand and feel the map naturally Please explain.
Answer: For each point in $M$ you have a cotangent space $M_m^*$. So we now look at the disjoint union of all of them as a collection of fibers -- "above" each point in $M$ lies a cotangent space.
The canonical map just "projects" each fiber (end every point within it) onto the point above which it lies, just the same as with the tangent bundle.

construction of cotangent bundle


load_tool does not recognize python_repl in langchain

Question: I am using Langchain to connect to OpenAi and some basic python calculation. below is the code i am using:
from langchain.llms.fake import FakeListLLM
from langchain.agents import load_tools
from langchain.agents import initialize_agent
from langchain.agents import AgentType
tools = load_tools(["python_repl"])
responses=["Action: Python REPL\nAction Input: print(2 + 2)",
"Final Answer: 4"
]
llm = FakeListLLM(responses=responses)
agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
verbose=True)
agent.run("whats 2 + 2").

I am referred to the langchain document and the code seems to be fine, there is no sysntexical error. in another code i called another library and created a new object here as:
from langchain_experimental.utilities import PythonREPL
python_repl = PythonREPL()

This code when ran on a simple instance runs:
example:
python_repl.run("print(10+34)")

But when i try to call python_repl from load_tool it throws error as ValueError: Got unknown tool python_repl. what is missed in the above code block.
Answer: I believe this code as printed in the book "Generative AI with LangChain" relies on and older version of langchain. langchain[docarray]==0.0.284 to be exact.
I suggest setting up a conda environment for the book as there seemed to be breaking changes.
If on the other hand you would want to use the newest LangChain version, this would work:
from langchain.agents import load_tools
from langchain.agents import initialize_agent
from langchain.agents import AgentType, Tool
from langchain.utilities import PythonREPL
from langchain_experimental.tools import PythonREPLTool

agent = initialize_agent(
    tools=[PythonREPLTool()],
    llm=llm,
)

agent.invoke("what is 2 + 2?")ython_repl",
    description="A Python shell. Use this to execute python commands. Input should be a valid python command. If you want to see the output of a value, you should print it out with `print(...)`.",
    func=python_repl.run,
)

agent = initialize_agent(
    tools=[python_repl],
    llm=llm,
)

agent.invoke("what is 2 + 2?")


What is the easiest way to run a magento instance locally to test my requests with the rest API?

Question: I need to write working requests but I cant test them on our live systems. My idea was to run a local instance of Magento and test my requests there. Is that a good idea? What is the easiest way to do that? Any help is appreciated.
Answer: I can recommend AMPPS for a fast webserver setup, but of course you can also use MAMP, XAMPP etc.
Afterwards, you can either copy your live system to your local host or install the required Magento version from source. n98-magerun2 is a handy tool to install a specific Magento version using the command line.
Answer: I'd say that the easiest way is to create a copy of the live website files on the webserver along with a duplicate database and connect the two.
If the duplicate Magento instance is within a subdirectory of the live site (e.g. www.example.com/duplicate), you will just need to update the base urls accordingly.
I don't think that this is the best solution, but if all you need is a non-production website to test against remotely, I think that this would fit the bill.
You'd want to be sure that there is enough space on the server, and it would be a good idea to lock down access so that you don't attract confused public users and search engine indexers.
Running a local instance or a dev instance on a separate server are better solutions, and it is common to do both. But they require the ability to create and configure a webserver, database, install the nec. PHP version and extensions, etc.  Depending on the nature of your testing, this might be overkill.
Whatever the solution, I would recommend removing customer & order data from your test database.


What size breaker panels do I need for two small buildings?

Question: I have 2 buildings I'm wanting to supply power to strictly as a service and not adding the service from another source. The first building is more like a tiny home wanting to install 14 outlets, 4 lights with switches, be able to run refrigerator, microwave, air fryer, toaster oven, and electric heater and window air conditioner when needed. The other building I'd like to have 8 outlets (which will power things like a heat press, sewing machine, or other such equipment), 2 lights with switches, and be able to power window air conditioner or electric heater. What size breaker boxes do I need on my service pole and in each building if both buildings need one?
Comment: Consider deleting "window air conditioner and heater" and replacing both with "mini-split heat pump" of a suitable operating temperature range for your climate. You'll spend far less on heating and the A/C will be quieter and more efficient as well.
Comment: Step 1: Talk to your local utility. Find out what standard service is. Most likely this is residential service ("home", tiny or not, plus a workshop). If they give you options of 200A and something above 200A, 200A will be fine. If they give options that start *below* 200A then we need to first discuss some more details. Report back what the utility says - or if you already have service on the pole, report what that service is and what equipment is already there). One other key question: how far from from pole to each building?
Comment: Install larger boxes than you currently need. Someone always wants to add outlets or lights you didn't anticipate.
Comment: Yeah, or at the very least a window or through the wall mounted heat pump (such things exist!).  Also, is there electric service to the property already, and how many square feet of finished space will each building be?
Answer: The answer to your question is not that hard. It can be found in the NEC Article 230.79.
Part (C) States that if it is a one family dwelling it needs a service rating of not less than 100A.
Part (D) says for any other installations you will need a service rating of not less than 60A.
You need to check with your local AHJ and find out if they are going to require one of you buildings to be a one family dwelling.
The other option you have is to feed the less used building from the the first building. At that point you will have to do a load study to see if everything will fit under the code minimums.
Good luck.


python uwsgi not loading changes

Question: i am using uwsgi to serve python application. app was using a particular vrsion of falcon python now i upgraded the package by removing it and reinstalling it. but the change is not reflected by the uwsgi server it is still using the older code even when i restart uwsgi. why is this problem coming? i can see older version of code which was generating error in the uwsgi logs
Answer: You must restart uWSGI after code changes.
If you are using a virtual-environment:

Ensure that you haven't installed falcon globally (deactivate first)
Make sure that you've activated the right one, you can use echo $PATH and echo $VIRTUAL_ENV to check sanity.

If it still reads the older version, use pip freeze or pip list to debug your environment. Make sure you have totally uninstalled the older version.
As last resort, delete your virtual-environment and re-create it. If you're not using virtual-environments with Python, start using them.

python uwsgi not loading changes


What harmonic idea is being used in Measures 9-12 and 17-19 in "Recuerdos De La Alhambra? "

Question: I have done some harmonic analysis on Francisco Tárrega's "Recuerdos De La Alhambra", as you can see below. Most of it makes sense to me, but there are sections in measures 9-12 and 17-19 that the chords don't move in a way that makes sense to me. Can someone please explain to me the harmonic theory there?
Comment: A harmonic analysis should tell a "big picture," as well as perhaps small pictures, and isn't just about finding a chord name for every moment, but about finding the role of a group of notes. Measures 9 and 10 both start with an F chord. We haven't really "gone anywhere" in the last beat of m 9; you could think of it as "still an F," but with the two passing tones of B and G. The last beat of m. 10 is another matter though, and I'm still thinking about it...
Comment: Noted, though I assume the point of your analysis is to better understand that harmonic "big picture." Actual implementation often leaves out (or adds) a note, but the benefit of analysis to performance is knowing where we're going and why.
Comment: I should point out that I am a plectrum player, so in a few spots I have written an incorrect inversion, but it is because I am using a chord shape that would allow me to strum the guitar and sound only the needed notes. In those cases the bass note serves to deaden a string, but I do not sound it for this song. So, for example, I play the first E7 in the song with my ring finger on G# on string 6, to practice getting into that position.
Answer: Measures 9 – 12
Measure 9 and the first two beats of Measure 10 are just one long F major chord. The apparent CM7 is just a passing chord, meaning that it serves the purposes of connecting the harmonies on either side but isn't itself considered as affecting the harmony.
The G7/D chord in measure 10 is better analyzed as a Bdim/D chord. It's use here is as a common-tone chord. It shares the note B with the E chord that's coming up. For more information see A chord progression from Leavitt: how to analyze the diminished chord
Measure 11 is analyzed as an E chord (in root position, not /G#). The A at the beginning of the measure is an accented passing tone, delaying the arrival of the G#. It also could be viewed as a sort of suspension of the A from measure 10. If you really want to name it as a chord, it would be Esus4.
Measure 12 is an E7 leading back to A in Measure 13. The initial chord in Measure 13 is just A. The b9 is an accented upper neighbor, just there for color and not considered part of the overall harmonic analysis.
Measures 17 – 19
Measure 17 is still a Dm chord, continued from Measure 16. The E is another accented passing tone, as in Measure 11. The B is also serving a primarily melodic function rather than a harmonic one, but you could call the chord Dm6 if you want.
Measure 18 contains an Faug6 chord. The purpose of the chord is that the F resolves down to E, and the D# resolves up to E. (The expected resolution of an F7 chord would be to a Bb chord, with the Eb resolving down to D). "Augmented sixth chords" are explained in various posts on this site: for example, How does this chord work in the progression?.
Measure 19 is all one E chord, with an accented passing tone C on the first beat.


Do I need to buy a return ticket for my son coming here to Malaysia?

Question: Do I need to buy a return ticket for my son from Phillipines when visiting Malaysia? By "return ticket" I mean Malaysia to Philippines route. I have a spouse visa and I plan for my son to stay for a few months in Malaysia. Can I just extend his visa every month at the immigration office here in Malaysia or is there any other procedure?
Comment: The airline that flies him from the Philippines is required to make sure his travel is within the legal rules of Malaysia.  If he has no departure ticket and no long stay visa then he will not be able to prove that he is leaving Malaysia before his initial entry permit expires, they will likely not let him board.
Answer: Yes, you should have a return ticket for your son.  Timatic:

The following are exempt from holding a visa:
Nationals of Philippines for a maximum stay of 30 days.
Additional information:
Visitors are required to hold proof of sufficient funds (at least USD
  500.-.) to cover their stay.
Important: Nationals of Philippines not holding a return/onward ticket could be requested to purchase one or refused entry.

Note the 30-day limit: you will need to get an advance tourist visa if you want your son to stay longer, or plead for a visa extension on hardship grounds.
Answer: Current Malaysian Minimum  Entry Requirements as at  08/12/2019  for Tourists /Business Visitors /visit relatives /attending seminars.

CASH of RM 1,000
Tours Itinerary
Provide Hotel Bookings
Provide Invitation letters for Business Visits
Provide sponsors details for longer period of visit (max 30 days)
Provide a valid Return Ticket (Booking slips are rejected)
Provide a valid Outbound /onward Ticket for other destination country.
There must be a validity period of minimum 6 months in your passport.

Upon entry, you will be given a  Visit Pass stamp in your passport. This visit pass does not allow any extension.
Those who are working in other countries (not in PH) are required to pre-apply a Visa to enter to visit Malaysia. Direct Flight Entry from PH need not apply as Filipinos are given Free Visa to enter and 30 days Visit Pass to live inside Malaysia.
Even if you have a "spouse visa" you do not have right to sponsor your son to be here in Malaysia. Your current husband is the sponsor for you only.
What you can do is that 1 week before the expiry of the 30 days visit pass, go to the Immigration and apply for an extension of 1 more month with the submission of valid documents.
Critical docs that may be able to help :-

Proof of relationship with you.
Proof of funds to sustain the duration of the extension.
A letter of approval from your husband can be handy.
Providence of a Air Ticket direct back to source country if requested. Do not buy first. If Immigration approves the application, you will have to buy a return ticket in order to collect a "extension special pass".

For this type of case, it is at the discretion of IMMigration to allow or reject the application. Last minute application will sure to be rejected.


Exposed wiring outside

Question: I tore down an old shed that have electricity going to it. Now the shed is gone but I have an exposed wire outside. I want to install a small street light there next spring but what should I do with the electricle wiring till then? The wires still have power going to them because the shed didn't have its own breaker.
Comment: Is it a direct burial cable, or conduit?
Answer:
Pound a 2' - 3' pressure treated 2x4 into the ground, so that about 12" to 18" is above ground (cutting an angle in the end going into the ground, will help it go in better).
Mount a weatherproof 1-gang electrical box on the 2x4.
Pull the wiring into the box, using the appropriate clamp/bushing.
Secure the wiring to the 2x4 below the box, using an appropriate means.
Cap the wires off using weatherproof twist-on wire connectors.
Cover the box with a weatherproof blank cover.
Answer: Your best option would be to find out where the wire exits the house.  Then with the power off, cut the wire, install a steel box, and cap the wires off with wire nuts inside the steel box.  When you re-install, you can splice inside the box, as long as it is accessible.

Exposed wiring outside