text:
Q: Big O or Big Omega? Here's my answers to Is A O or Ω of B ? Do you think I got it right?
A               B           O   Ω
(log n)^3       N           No  Yes
2n^2+4n         4n^2        Yes No
n!              2^n         No  Yes
n^5             n^4         No  Yes
100             10000       Yes No
n^2             (1.5)^n     No  Yes

A: Big O is asymptotically upper bound while Big Omega is asymptotically lower bound.

*

*A = O(B) if and only if limit A(n)/B(n) < C as n approach infinity and C is a positive constant.

*A = Ω(B) if and only if limit A(n)/B(n) > C > 0 as n approach infinity and C is a positive constant.

You can use Wolframe Alpha to find such limit.
A               B           O   Ω
(log n)^3       N           Yes  No
2n^2+4n         4n^2        Yes Yes
n!              2^n         No  Yes
n^5             n^4         No  Yes
100             10000       Yes Yes
n^2             (1.5)^n     Yes  No

For example:

*

*limit n2/1.5n as n goes to infinite is 0. Therefore, we know that 1.5n grow faster than n^2 as n is getting larger and larger. So, 1.5n is upper of n2 but not a lower bound of n2.

*limit (2n^2+4n)/(4n^2) as n goes to infinite is 0.5.

*

*We could say that limit A(n)/B(n) < 1. Therefore, A = O(B).

*We could say that limit A(n)/B(n) > 0.4 > 0. Therefore, A = Ω(B).


text:
Q: Facebook SDK IOS login issue I have followed the instruction to implement a login process to Facebook from my app:
https://developers.facebook.com/docs/mobile/ios/build/#implementsso
Here is my code:
- (IBAction)facebookButton:(id)sender {

    facebook = [[Facebook alloc] initWithAppId:@"383032031757454" andDelegate:self];

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if ([defaults objectForKey:@"FBAccessTokenKey"]
        && [defaults objectForKey:@"FBExpirationDateKey"]) {
        facebook.accessToken = [defaults objectForKey:@"FBAccessTokenKey"];
        facebook.expirationDate = [defaults objectForKey:@"FBExpirationDateKey"];
    }

    if (![facebook isSessionValid]) {
        NSArray *permissions = [[NSArray alloc] initWithObjects:
                                @"user_likes",
                                @"read_stream",
                                nil];
        [facebook authorize:permissions];
        permissions=nil;
    }
}

- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
    return [facebook handleOpenURL:url];
}

- (void)fbDidLogin {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:[facebook accessToken] forKey:@"FBAccessTokenKey"];
    [defaults setObject:[facebook expirationDate] forKey:@"FBExpirationDateKey"];
    [defaults synchronize];

}

After login and allow permissions to the app, Safari remains opened and I have to return back to my app manually, but the sample app "Hackbook" provided with SDK, after accepting permissions and login within Safari, it dismisses Safari and returns back to the app. I want to do the same but I wasn't successful.
This is the .plist file:

Thanks

A: Have you set your facebook app id in info.plist file of your iOS app?
Similar cases are in this link and this link.
Hope this helps you.

A: You can easily determine why it doesn't work by digging a little bit inside Facebook.m. Check for the method handleOpenURL: in Facebook.m.
    // Facebook.m
- (BOOL)handleOpenURL:(NSURL *)url {
    // If the URL's structure doesn't match the structure used for Facebook authorization, abort.
    if (![[url absoluteString] hasPrefix:[self getOwnBaseUrl]]) {
        return NO;
    }

    NSString *query = [url fragment];

    // Version 3.2.3 of the Facebook app encodes the parameters in the query but
    // version 3.3 and above encode the parameters in the fragment. To support
    // both versions of the Facebook app, we try to parse the query if
    // the fragment is missing.
    if (!query) {
        query = [url query];
    }

    NSDictionary *params = [self parseURLParams:query];

Set a breakpoint below NSDictionary *params = [self parseURLParams:query]; and read the content of it. You should see an error message why the login did not work.

A: On the app Facebook page, did you configure the app for iOS SSO?
What OS are you using? Your code will only work for 4.2+
You didn't follow the instructions completely, your plist file is slightly wrong (I don't think this is the problem).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Cordova - How to open to full screen an image (for loop + jQuery) I store the images in the localStorage, the value is the base64 encoded image.
That function looping through localStorage and get the keys and values, then the jQuery append that image in the html.
My question is, how can i make these generated list of images to be able to go to full screen on tap?
function show() {
  $( "#gallery" ).empty();
  for(var i=0, len=localStorage.length; i<len; i++) {
    var key = localStorage.key(i);
    var value = localStorage[key];
    $('#gallery').append('<img src=data:image/jpeg;base64,' + value + ' </img>');
  }
}

I hope my problem is clear, this is my first question here.
Thanks for the answers!

A: jquery:
$('#gallery').on('click', 'img', function(){
  $(this).toggleClass('fullscreen');
});

css:
.fullscreen {
 position: fixed;
 top: 0;
 left: 0;
 right: 0;
 bottom: 0;
}

This will allow the user to click an image, and if its not fullscreen then make it full screen and vice versa.
If you are specifically talking about a 'tap' (like on a phone) rather than a click you would need to get jQuery mobile and replace 'click' with 'tap' in the jquery code above.


text:
Q: Wayland session on Ubuntu 18.04: why is /usr/bin/Xwayland running? I'm looking at the Wayland session in Ubuntu 18.04.
I've thought that things like conky won't run or won't run properly. So I installed conky (and its dependencies). Then, I ran conky from a terminal. There was flickering and so I commented out no_buffers = true, in ~/.config/conky/conky.conf and added double_buffer = true,. That fixed the flickering but man conky has:
-b | --double-buffer
       Use double buffering (eliminates "flicker").
       Only available with build flag BUILD_X11
       enabled.

So that puzzled me and I ran ps -aux | grep wayland
dkb@dkb:~$ ps -aux | grep wayland
gdm        750  0.0  0.1 197792  5548 tty1     Ssl+ 21:56   0:00 /usr/lib/gdm3/gdm-wayland-session gnome-session --autostart /usr/share/gdm/greeter/autostart
gdm        850  0.0  0.8 202732 35992 tty1     S+   21:56   0:00 /usr/bin/Xwayland :1024 -rootless -terminate -accessx -core -listen 4 -listen 5 -displayfd 6
dkb       1925  0.0  0.1 197792  5376 tty2     Ssl+ 22:09   0:00 /usr/lib/gdm3/gdm-wayland-session env GNOME_SHELL_SESSION_MODE=ubuntu  gnome-session --session=ubuntu
dkb       1977  0.1  1.3 263692 56052 tty2     S+   22:09   0:00 /usr/bin/Xwayland :0 -rootless -terminate -accessx -core -listen 4 -listen 5 -displayfd 6
dkb       2469  0.0  0.0  21536  1076 pts/0    S+   22:17   0:00 grep --color=auto wayland
dkb@dkb:~$

That shows an Xwayland process running as well even though echo $XDG_SESSION_TYPE returns wayland.
So is it that a wayland session automatically includes Xwayland?

A: The best answer comes from Wayland authors:
X Clients under Wayland (XWayland)
Wayland is a complete window system in itself, but even so, if we're migrating away from X, it makes sense to have a good backwards compatibility story. With a few changes, the Xorg server can be modified to use wayland input devices for input and forward either the root window or individual top-level windows as wayland surfaces. The server still runs the same 2D driver with the same acceleration code as it does when it runs natively. The main difference is that wayland handles presentation of the windows instead of KMS.

When you boot with Wayland you still may need to access X-based applications: Why don't gksu/gksudo or launching a graphical application with sudo work with Wayland?
To summarize many Q&A's on running an X applicatin within Wayland you need to use:
xhost +si:localuser:root


text:
Q: Heroku / Kotlin: java.lang.NoClassDefFoundError: kotlin/jvm/internal/Intrinsics I try to run kotlin spring webapp via heroku run bash. I run then:
java -cp ./build/libs/pss_kotlin-1.0-SNAPSHOT.jar pl.makzyt.pss_kotlin.MainKt

Then I get this error:
Exception in thread "main" java.lang.NoClassDefFoundError: kotlin/jvm/internal/Intrinsics
        at pl.makzyt.pss_kotlin.MainKt.main(Main.kt)
Caused by: java.lang.ClassNotFoundException: kotlin.jvm.internal.Intrinsics
        at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
        at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:338)
        at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
        ... 1 more

I know I could run this if I get kotlin-runtime.jar. Is there possibility to obtain it with some command or should I download it manually?
EDIT
Here are my build.gradle dependencies:
dependencies {
    compile "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
    compile "org.jetbrains.kotlin:kotlin-reflect:$kotlin_version"

    compile group: 'org.springframework.boot',
            name: 'spring-boot-autoconfigure',
            version: '2.0.0.RELEASE'

    compile group: 'org.springframework.boot',
            name: 'spring-boot-starter-data-jpa',
            version: '2.0.0.RELEASE'

    compile group: 'org.springframework.boot',
            name: 'spring-boot-starter-web',
            version: '2.0.0.RELEASE'

    compile group: 'org.postgresql',
            name: 'postgresql',
            version: '42.2.2'

    compile group: 'org.hibernate',
            name: 'hibernate-core',
            version: '5.2.12.Final'

    compile group: 'org.hibernate',
            name: 'hibernate-entitymanager',
            version: '5.2.12.Final'

    compile group: 'javax.xml.bind',
            name: 'jaxb-api',
            version: '2.1'

    compile group: 'org.springframework.boot',
            name: 'spring-boot-starter-thymeleaf',
            version: '2.0.0.RELEASE'

    compile group: 'nz.net.ultraq.thymeleaf',
            name: 'thymeleaf-layout-dialect',
            version: '2.3.0'
}

A: If your spring boot app is configured correctly (spring boot plugin is applied in build.gradle) you just need to run the jar.
java -jar yourjar.jar

You don't need to use the -cp option because Spring Boot repackages all dependencies in the jar that's why you get a class not found error.

A: I'm not sure why you're getting this error. But you might want to try generating a new Spring + Kotlin app from https://start.spring.io and copying the Maven dependencies/plugins into your pom.xml.


text:
Q: Limit of a sequence of functions recursively defined by integrals $f_n:[0,\infty)\to\mathbb{R}$ is defined recursively by $f_1:=0$ and
$$f_{n+1}(x)=e^{-2x}+\int_0^xf_n(t)e^{-2t}dt,\qquad n\ge 1$$
I need to show that the limit $f(x):=\lim_{n\to\infty} f_n(x)$ exists and find it explicitly.
I've found that $f_n$ is of the following form $$f_n(x)=\sum_{i=0}^{n-1} a_{n,i}e^{-2i}$$
and $$a_{n,i}=(-2)^{-i}\frac{a_{n-i+1,1}}{i!},\qquad \forall n,i\ge 2$$
But I can't find a function that looks like the limit.

A: The limit, if it exists, must satisfy $$f(x)=e^{-2x}+\int_0^xf(t)e^{-2t}dt$$
which after differentiation becomes
$$f'(x) = -2e^{-2x} + f(x)e^{-2x}$$
This is a linear ODE you can solve. One approach is to write $g=f-2$, so that $g'(x)=g(x)e^{-2x}$; separate and integrate, eventually arriving at
$$
f(x) = 2 +C \exp\left(-\frac12 \exp(-2x)\right)
$$
The existence of limit follows from the proof of Picard uniqueness theorem for ODE, since the formula for $f_n$ is the Picard iteration.


text:
Q: Looking for a pre-1975 short story about a space ship carrying male and female clones A short story of a science fiction collection set on a ship or freighter in space from the captain's point of view. He once refers to his second in command or pilot as "Little One".
The male and female clones (possibly 10 or more) of a single person come aboard. Even though genetically brothers and sisters (or twins), they have sex together and the captain wonders if he can approach one of the women.

A: Reminiscent of the LeGuin story Nine Lives. You can read it at baen.com.
It definitely concerns a multiple clone that has sexual relations among themselves. But, it mostly takes place on a planet, not in a ship.
The publication date (1969) also matches.
It's also the accepted answer to this old question: Two normal humans interact with a team of clones


text:
Q: How to get an arrow line from the center of the point (tikz) I draw a Bezier curve and get points at 0.2,0.4 etc position. I want to draw a vector from one of the points.
But the vector doesn't originated from the point. There is some gap between the point and the vector. How can I fix it?
\documentclass{report}

\usepackage{tikz}
\usetikzlibrary{arrows,shapes.geometric}

\begin{document}

\begin{tikzpicture}
\draw[very thin,black!50, step=0.5] (-1,-1) grid (6,6);
\draw[->,>=stealth',very thick] (-1,0)--(6,0);
\draw[->,>=stealth',very thick] (0,-1)--(0,6);
\draw (0,0) .. controls (1,1) and (-5,1) .. (6,6)
\foreach \p/\l in {0.2/A,0.4/B,0.6/C,0.8/D} {node[pos=\p,label=$\l$,anchor=base](\l) {}};
\foreach \l in {A,B,C,D} {\draw[fill] (\l) circle (2pt);}
\draw[red, thick, ->, >=stealth'] (C) -- +(2,1) node[right] {$\vec F_C$};
\end{tikzpicture}

\end{document}

A: You can define the anchor of the first arrow point to C.center. Is that what you mean? See pgfmanual section 17.5 Positioning Nodes
\documentclass{report}

\usepackage{tikz}
\usetikzlibrary{arrows,shapes.geometric}

\begin{document}

\begin{tikzpicture}
\draw[very thin,black!50, step=0.5] (-1,-1) grid (6,6);
\draw[->,>=stealth',very thick] (-1,0)--(6,0);
\draw[->,>=stealth',very thick] (0,-1)--(0,6);
\draw (0,0) .. controls (1,1) and (-5,1) .. (6,6)
\foreach \p/\l in {0.2/A,0.4/B,0.6/C,0.8/D}     {node[pos=\p,label=$\l$,anchor=base](\l) {}};
\foreach \l in {A,B,C,D} {\draw[fill] (\l) circle (2pt);}
\draw[red, thick, ->, >=stealth'] (C.center) -- +(2,1) node[right] {$\vec F_C$};
\end{tikzpicture}

\end{document}


text:
Q: How do I return a value from a new object, whilst keeping its methods So I have code like so:
function set(a) {
  this.foo = function(){
    alert('bar');
  }

  return a;
}

var b = new set([2,3,4]);

b; //returns [2,3,4]
b.foo(); //undefined function

I would like to return the array input as the return value of the new set, rather than having to attach it to a property e.g. this.arr = a;
How can I achieve this without wiping the foo method from the object?

A: You can do it like this, I think!
function set(a) {
  a.foo = function(){
    alert('bar');
  }

  return a;
}

var b = new set([2,3,4]);

b; //returns [2,3,4]
b.foo(); //this shows alert

A: If I understand properly what you're after, you need:
function set(a) {
  a.foo = function(){
    alert('bar');
  }
  return a;
}

var b = new set([2,3,4]);
b.foo(); //alerts

...i.e. attach the method to the input, not, as you were, to the global namespace.

A: function set(a) {
  var o = {};

  o.foo = function(){
    alert('bar');
  };
  return o;
}

Should be what you want - you do not need the parameter.

A: To keep the constructor clean and if you want  to keep this.foo inside set()  you probably should  add new set().foo method to Array.prototype
function set(a) {

   this.foo = function(){
    alert('bar');
  };

   return a;

}
Array.prototype.foo=new set().foo;
var b = new set([2,3,4]);

console.log(b); //returns [2,3,4]
b.foo();// alerts 'bar'


text:
Q: splice(index,1) not removing element I am writing a small program in Vue.js, but I am getting stuck with an error.
I want the X button to remove each item in a list. I used splice(index,1), but the item isn't being removed. What am I missing?
My HTML:

Add Student

          Name
          <input type="text" id="name" v-model="newStudent.name" class = "form-control" placeholder="Student Name">

          Address
          <input type="text" id="address" v-model="newStudent.address" class = "form-control" placeholder="Address">

        <button class="btn btn-success" v-on:click = "addStudent">Add</button>

All Students

              Name
              Address
              Action

              {{student.name}}
              {{student.address}}
              <button type="button" class="btn btn-danger" v-on:click="deleteStudent($index)">X</button>

{{ $data |  json }}

My JS:

A: The $index variable was removed in Vue 2. So, you're not passing the index in correctly.
Specify the index variable in the v-for and pass that to the deleteStudent method instead:

  {{student.name}}
  {{student.address}}

    <button
      type="button"
      class="btn btn-danger"
      v-on:click="deleteStudent(index)"
    >X</button>

This is covered in the documentation on list rendering in Vue.


text:
Q: How can I use Excel to parse Google Analytics UTM URLs How could I take a URL such as...
website url/directory/another-directory?utm_id=inc0000000&utm_source=facebook&utm_medium=affiliate&utm_campaign=2021+q3+campaign&utm_content=post&utm_adsize=1200x628&utm_audience=general&utm_product=loan+product&promocode=250offer
and parse it down across multiple cells in a row?

A: The basic approach is to find ways to strip out pieces of the string by finding starting points and ending points.
IF your string had a regular separator dividing the information of interest, you could use a neat trick using FILTERXML() and use it to easily pick each piece out for your output cells. However, this is not the case for your data.
So, somewhat harder. Not to understand, just a bunch to do since you want 11 pieces of data from the string.
I have altered your given string to replace your "website url" with the "ht tps://www.mysite.com" you show in your desired output giving this string that I used in the following material:
ht tps://www.mysite.com/directory/another-directory?utm_id=inc0000000&utm_source=facebook&utm_medium=affiliate&utm_campaign=2021+q3+campaign&utm_content=post&utm_adsize=1200x628&utm_audience=general&utm_product=loan+product&promocode=250offer
(Pretend both uses of "ht tps" are really "https"... this editor shows errors if I use them correctly.)
First bit is pretty easy. You know the starting point. It is character 1. So you can use the easier to understand LEFT() function. Easier to understand because it isn't too complicated writing the part that finds the stopping point.
(Strictly speaking, it finds the length of string to take out, but that's a stopping point too, so it fits the language I'm describing your approach in. But it's important to know that it's actually a length you will calculate.)
So, how to tell Excel "Stop HERE"? You need to locate something unique enough in the string but still CLOSE (it gets a lot harder to figure the further away it is) to the stopping point you want. Fortunately, there is a "/" after ".com" that you can use. There's a function called FIND() that will locate its position. But there's a problem:  there are two of them BEFORE the end of the string. Don't want Excel to pick one of them! But FIND() also lets you tell Excel where to start looking so you can tell it "Look in A1 for a "/" but start looking at character 10" so it will never notice those first two.
So then, your formula for the first bit would be:
=LEFT(A1,  FIND("/",A1,  FIND("//",A1)+2) - 1)

Excel finds the "/" (position 23). You want the character before that to be the end, so you subtract 1 from that. So Excel ends up starting with character 1 and using all characters up to 22. Notice that if the website name had been longer or shorter, Excel wouldn't be slowed down as you are not using its name directly, just things around it.
The next nine bits follow the same idea:  find a starting point and an ending point by using bits of the string before and after the desired data. You will use the MID() function for these. It needs to know where to look, where to start, and how far to go after it starts. These formulas assume the datum is in cell A1, so that's done. Finding something that you can use before and after then depends completely on the exact stuff in the string. Notice that the formulas work for the string you give in the question, but if every string has different dividers, they will not work for the different ones.
So, for the rest of the directory structure datum, use:
=MID(A1,  FIND("/", A1, FIND("//", A1)+2),  FIND("?",A1) - FIND("/", A1,
FIND("//", A1)+2) - 1)

The part right after A1 is the starting position. It finds that FIRST single "/" found for the website URL in exactly the same way it found it there. It finds how many characters to read before stopping by looking for the "?" that comes after the directory material. But you don't want that actual number. You need to subtract 1 from it since it is one character past the correct end AND you need to subtract off all the characters that come before the starting point. That's what the second FIND() in that last part gives you (just like it helped in the second part to find the starting point) and you can see 1 is subtracted after that.
The last eight of those nine bits use the same kind of idea, but the have the handy pieces of string like "utm_source=" to use since they are not duplicated and occur exactly before and after each piece. You COULD use shorter pieces of them, but I prefer to use the whole things as they are easy to choose that way, have the "odd" "utm_" and "=" in them so they are unlikely to occur in the material you desire to extract (which would ruin their use), and it just seems clearer why to choose them if one chooses the whole thing. So they look like this:
=MID(A1,  FIND("utm_id=",A1) + LEN("utm_id="),  FIND("utm_source=",A1) - (FIND("utm_id=",A1) + LEN("utm_id=")) - 1)

The first one finds "utm_id" and uses it four times. The first two find its starting point, then add its length to that to find the desired string's starting point. Then one finds the start of the following "utm_" string (and subtracts 1) to find the end position, then uses the "utm_id" the last two times to subtract off the beginning length. So you've isolated the "inc0000000" bit.
You can open the formula editor line (above the cells) and highlight, then copy the formula, and go on to the next seven cells, open the formula editor ("F2") and paste them. Then they just need edited for exact strings to search for. (If you use $A$1 instead of A1 in the formulas — as you really should (I was just answering the question, not building a spreadsheet) — you can just copy the whole cell, like you may have done before, and paste that in the seven cells. That's a bit easier...
Anyway, you have the same formula now in all eight cells. Go through the seven you pasted in and replace the "utm_something" strings in the formulas until you have edited all seven and they have their own unique pairs. Definitely copy the exact string right from the big string so you have no typos.
When done, you'll have:
=MID(A1,FIND("utm_source=",A1)+LEN("utm_source="),FIND("utm_medium=",A1)-(FIND("utm_source=",A1)+LEN("utm_source="))-1)

=MID(A1,FIND("utm_medium=",A1)+LEN("utm_medium="),FIND("utm_campaign=",A1)-(FIND("utm_medium=",A1)+LEN("utm_medium="))-1)

=MID(A1,FIND("utm_campaign=",A1)+LEN("utm_campaign="),FIND("utm_content=",A1)-(FIND("utm_campaign=",A1)+LEN("utm_campaign="))-1)

=MID(A1,FIND("utm_content=",A1)+LEN("utm_content="),FIND("utm_adsize=",A1)-(FIND("utm_content=",A1)+LEN("utm_content="))-1)

=MID(A1,FIND("utm_adsize=",A1)+LEN("utm_adsize="),FIND("utm_audience=",A1)-(FIND("utm_adsize=",A1)+LEN("utm_adsize="))-1)

=MID(A1,FIND("utm_audience=",A1)+LEN("utm_audience="),FIND("utm_product=",A1)-(FIND("utm_audience=",A1)+LEN("utm_audience="))-1)

=MID(A1,FIND("utm_product=",A1)+LEN("utm_product="),FIND("promocode=",A1)-(FIND("utm_product=",A1)+LEN("utm_product="))-1)

The final one is something like the first one except you are looking for the RIGHT end of the string this time. The last piece you want is the actual end of the string, so you only need to figure the starting point and length:
=RIGHT(A1,  LEN(A1) - (FIND("promocode=",A1) + LEN("promocode=") - 1))

Well, you know how to find "promocode=" since you found it for the 10th cell. If you find that here, you can subtract it (minus 1 from it since its calculation will give you the position right before your actual starting position) from the the whole string's length to get the length of character's you want Excel to read from the END of the string.
This is how you approach ALL such things. If your strings are well-behaved (say you have 10,000 of these and ALL of them have those same "utm_something" strings inside them), it's "as easy as this." This is a bunch of work, but think of it honestly:  once you saw how to do it, it was just a bunch of typing and mousing, not a bunch of thinking and doing a million different things. Just gruntwork, monkey work.
Remember there is the FILTERXML() trick I mentioned at the start if the string is even more predictable. Well, completely predictable in using the same divider ("delimiter") in all positions. Then it's super easy.
One can actually take some other approaches, but they are much harder to work with. And... finicky.
When you learn how to use the LET() function, you can make those formulas above look much easier to read. AND easier to edit for the different pieces of information.
Good luck with Excel! It's a great tool. Hope you have good experiences with it!


text:
Q: Nodemcu bootloader incompatible with ESP32-C3? I thought that the WeMos LOLIN Mini ESP32-C3 looked like a great board - same footprint as a D1 Mini; fast; sensible price; good availability.  I purchased a few.
However flashing with Nodemcu failed, and I discovered that the ESP32-C3 starts its bootloader at 0x0000, not the 0x1000 address used by (all?) other ESP32 devices.
"make menuconfig" does have a bootloader submenu, but that doesn't have a "start address" option.
I think the Bootloader start offset is defined by BOOTLOADER_OFFSET in 'Makefile.projbuild' in '~/sdk/esp32-esp-idf/components/bootloader/' but have no idea if there are any absolute jumps in or out of the bootloader, or anything else that will be messed up by just changing this.
So - has anybody been down this rabbithole before?  Am I on the right track or is unrealistic to expect to run Nodemcu on an ESP32-C3?
Thanks

A: Original NodeMCU were designed to run on Xtensa cores (ESP8266/ESP12), and ESP32-C3 runs a RISC-V core, it's like apples and pears, from the same farm. No, they are not inherently interchangeable. It's not impossible to create a compatible eco-system around these two species, but a lot of extra efforts are expected.


text:
Q: Type variance error in Scala when doing a foldLeft over Traversable views I am trying concatenate a series of Traversable views in Scala using a foldLeft operator and am hitting type variance errors that I don't understand.
I can use reduce to concatenate a list of Traversable views like so.
val xs = List(1,2,3,4).map(Traversable(_).view).reduce((a: TraversableView[Int, Traversable[_]], b: TraversableView[Int, Traversable[_]]) => a ++ b) // TraversableView[Int,Traversable[_]]
// xs.force returns Traversable[Int] = List(1, 2, 3, 4)

(Note that I have to write the type annotation on the reduce arguments: reduce(_ ++ _) does not compile. I don't understand why and would be grateful for an explanation of this too.)
I can also break the list up into a head and a tail and concatenate them.
import collection.TraversableView
val ns = List(1,2,3,4)
val h = Traversable(ns.head).view
val t = ns.tail.map(Traversable(_).view).reduce((a: TraversableView[Int, Traversable[_]], b: TraversableView[Int, Traversable[_]]) => a ++ b)
val xs = h ++ t // TraversableView[Int,Traversable[_]]
// xs.force returns Traversable[Int] = List(1, 2, 3, 4)

But if I try to do the same thing with a foldLeft I get type variance errors.
import collection.TraversableView
val ns = List(1,2,3,4)
val h = Traversable(ns.head).view
val t = ns.tail.map(Traversable(_).view)
val xs = (h /: t)((a: TraversableView[Int, Traversable[_]], b: TraversableView[Int, Traversable[_]]) => a ++ b)
<console>:14: error: type mismatch;
 found   : scala.collection.TraversableView[Int,Traversable[_]]
 required: java.lang.Object with scala.collection.TraversableView[Int,Traversable[Int]]
              (h /: t)((a: TraversableView[Int, Traversable[_]], b: TraversableView[Int, Traversable[_]]) => a ++ b)

I suspect the issue has to do with the existential type in Traversable[_], but I can't figure out what exactly I'm doing wrong. I've tried various type signatures in the above expression to no avail. Judging from other questions on Stackoverflow, there is something tricky about the typing of foldLeft, but I couldn't find one that addresses this issue.
For comparison, the same algorithm with Stream works without a hitch.
val xs = (1 #:: Stream.empty /: List(2,3,4).map(_ #:: Stream.empty))(_ ++ _)
// xs.force returns Stream[Int] = Stream(1, 2, 3, 4)

The above is what I want to do, except I want to use a view instead of Stream because I don't need to memoize all my results.
This might seem like an odd request. The reason I want to do things this way is because performing foldLeft over Traversable views provides an efficient way to implement a lazy depth first search.

A: Here's a workaround (tested on 2.9.2 and 2.10.0-RC2):
import scala.collection.TraversableView

implicit def `I'm a lie!`[A]: collection.generic.CanBuildFrom[
  TraversableView[A, Traversable[A]], A, TraversableView[A, Traversable[A]]
] = null

val xs = List(1, 2, 3, 4).map(Traversable(_).view).reduce(_ ++ _)

Which both compiles and does what we want:
scala> xs.toList
res0: List[Int] = List(1, 2, 3, 4)

The left fold version will also work, even with the (_ ++ _) syntax.
The issue is that the ++ method expects an implicit CanBuildFrom instance, but it doesn't actually use it. The TraversableView object provides a dummy instance, but it's bizarrely typed (or at least the type seems odd to me—maybe there's a reasonable explanation for it).
In any case putting your own appropriately typed dummy instance into scope works, for now at least.

A: Views don't maintain the identity of the contained element across ++ operations.  I'm pretty sure that this is a bug.  You can fix it by casting:
val xs = List(1,2,3,4).map(Traversable(_).view).
  reduce((a,b) => (a ++ b).asInstanceOf[TraversableView[Int,Traversable[Int]]])

In the fold case also:
val xs = (Traversable(1).view /: List(2,3,4).map(x => Traversable(x).view)){ (l,r) =>
  (l ++ r).asInstanceOf[TraversableView[Int,Traversable[Int]]]
}

Be careful, though!  Once you start explicitly casting, your type safety goes way down (i.e. it is up to you to not make a mistake).
I'd guess this is a symptom of views not being very heavily used.  I generally try to use Iterator if at all possible rather than various different views.


text:
Q: Vertical and horizontal centering
Possible Duplicate:
Best way to center a <div> on a page vertically and horizontally?

I have a canvas element, and I'd like it to be right in the very center of a page, both vertical and horizontal.
I'm a programmer, and I don't much about CSS. Can anybody help me with centering my canvas both vertically and horizontally?
Here's my current CSS code:
/* Set up canvas style */
#canvas {
  font-family: 'pixel';
  margin-left: auto;
  margin-right: auto;
  display: block;
  border: 1px solid black;
  cursor: none;
  outline: none;
}

It's already being centered horizontally, but not vertically, thank you in advance!

A: this should do the trick:
#canvas {
    position: absolute;
    top: 50%; left: 50%;
    width: 200px;
    height: 200px;
    margin: -100px 0 0 -100px;
}

The margin top and left has to be negative half the height and width of the element.
The same principal applies if you don't know the width and height and need to calculate it with javascript. Just get the width/height, divide those by half and set the values as a margin in the same way as the example above.
Hope that helps :)

A: I don't know if this would help, but I wrote this jQuery plugin that might help. I also know this script needs adjustments. It'd adjust the page when needed.
(function($){
    $.fn.verticalCenter = function(){
        var element = this;

        $(element).ready(function(){
            changeCss();

            $(window).bind("resize", function(){
                changeCss();
            });

            function changeCss(){
                var elementHeight = element.height();
                var windowHeight = $(window).height();

                if(windowHeight > elementHeight)
                {
                    $(element).css({
                        "position" : 'absolute',
                        "top" : (windowHeight/2 - elementHeight/2) + "px",
                        "left" : 0 + "px",
                        'width' : '100%'
                    });
                }
            };
        });

    };
})(jQuery);

$("#canvas").verticalCenter();

Refined Code + Demo
Please, view this demo in "Full page" mode.

(function($) {
  $.fn.verticalCenter = function(watcher) {
    var $el = this;
    var $watcher = $(watcher);
    $el.ready(function() {
      _changeCss($el, $watcher);
      $watcher.bind("resize", function() {
        _changeCss($el, $watcher);
      });
    });
  };
  function _changeCss($self, $container) {
    var w = $self.width();
    var h = $self.height();
    var dw = $container.width();
    var dh = $container.height();
    if (dh > h) {
      $self.css({
        position: 'absolute',
        top: (dh / 2 - h / 2) + 'px',
        left: (dw / 2 - w / 2) + 'px',
        width: w
      });
    }
  }
})(jQuery);

$("#canvas").verticalCenter(window);

$(function() {
  var canvas = document.getElementById('canvas');
  var ctx = canvas.getContext('2d');
  drawSmile(ctx, 0.9, 'yellow', 'black', 0.75);
});

function drawSmile(ctx, scale, color1, color2, smilePercent) {
  var x = 0, y = 0;
  var radius = canvas.width / 2 * scale;
  var eyeRadius = radius * 0.12;
  var eyeXOffset = radius * 0.4;
  var eyeYOffset = radius * 0.33;
  ctx.save();
  ctx.translate(canvas.width / 2, canvas.height / 2);
  ctx.beginPath(); // Draw the face
  ctx.arc(x, y, radius, 0, 2 * Math.PI, false);
  ctx.fillStyle = color1;
  ctx.fill();
  ctx.lineWidth = radius * 0.05;
  ctx.strokeStyle = color2;
  ctx.stroke();
  ctx.beginPath(); // Draw the eyes
  ctx.arc(x - eyeXOffset, y - eyeYOffset, eyeRadius, 0, 2 * Math.PI, false);
  ctx.arc(x + eyeXOffset, y - eyeYOffset, eyeRadius, 0, 2 * Math.PI, false);
  ctx.fillStyle = color2;
  ctx.fill();
  ctx.beginPath(); // Draw the mouth
  ctx.arc(0, 0, radius * 0.67, Math.PI * (1 - smilePercent), Math.PI * smilePercent, false);
  ctx.stroke();
  ctx.restore();
}
#canvas {
  border: 3px dashed #AAA;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<canvas id="canvas" width="256" height="256"></canvas>


text:
Q: Create Angular 1 Browserify module for use in multiple applications Im trying to create a reusable package of both angular and nodejs code into a single repo, and then use that via bower or npm internally. Taking this simple example below, I cannot get it to work in an existing angular app.
getting the typical angular error below because the module cannot be found.
Error: [$injector:modulerr] Failed to instantiate module toolkit due to:
Error: [$injector:nomod] Module 'toolkit' is not available!

Here is my test.module.js file.
var testService = require('./test.service.js');

angular.module('noble.test', [
]).service('TestService', testService);

here is test.service.js
module.exports = function($http){
   this.exposedFn = exposedFn;

        ////////////////

        function exposedFn() {
            alert('Hello!');
        }
}

Here is my index.js
require('./test/test.module.js')
angular.module('noble.toolkit', [
    'noble.test'
]);

directory structure:
index.js
   test
       test.service.js
       test.module.js

browserify command
browserify --entry index.js -o dist.js


text:
Q: Compare a string by giving two possibilities for each character in Swift I need to compare a string by giving two possibilities for each character in the string in an (if) statement eg:
let str = "2 3 1 2"
if str == "(1||2) (2||3) (1||2) (1||2)" {
//Do Something
}

I know the code is not written correctly, but just to understand what I mean.
I used to use (Like Operator) in VB eg:
Dim s As String = "2 3 1 2"
If s Like "[1-2] [3-4] [2-3] [1-2]" Or s Like "[1-2] [1-2] [2-3] 2"  Then
//Do something
End If

I couldn't find anything similar in swift.
Please help, Thank you.

A: Looks like what you are asking for is support for regular expressions. They don't exist directly in Swift (yet?). But you might want to have a look at RegEx in Swift? and http://nomothetis.svbtle.com/clean-regular-expressions-using-conversions .

A: The problem you describe is crying out to solved using regular expressions.
Last time I looked, Swift did not support regular expressions, but it does allow use of NSRegularExpression. See Regex in Swift for an example of a Regex class.
So you'd end up writing something like
if Regex("[12] [23] [12] [12]").test("2 3 1 2") {
  println("matches pattern")
}

Another blog post on this topic is Clean Regular Expressions In Swift.


text:
Q: How to put watermark on image? How to put water mark on image without affecting the source image.
$SourceFile = '/uploadedimage/gallery/thumble/';
$DestinationFile = '/uploadedimage/gallery/thumble/image-watermark.jpg';
$WaterMarkText = 'Copyright appsbee.com';
watermarkImage ($SourceFile, $WaterMarkText, $DestinationFile);

function watermarkImage ($SourceFile, $WaterMarkText, $DestinationFile) {
   list($width, $height) = getimagesize($SourceFile);
   $image_p = imagecreatetruecolor($width, $height);
   $image = imagecreatefromjpeg($SourceFile);
   imagecopyresampled($image_p, $image, 0, 0, 0, 0, $width, $height, $width, $height);
   $black = imagecolorallocate($image_p, 0, 0, 0);
   $font = 'arial.ttf';
   $font_size = 10;
   imagettftext($image_p, $font_size, 0, 10, 20, $black, $font, $WaterMarkText);
   if ($DestinationFile<>'') {
      imagejpeg ($image_p, $DestinationFile, 100);
   } else {
      header('Content-Type: image/jpeg');
      imagejpeg($image_p, null, 100);
   };
   imagedestroy($image);
   imagedestroy($image_p);
};

If I do this the image which are present on thumble folder are effected.

A: Use this class, before putting water mark just make the copy of original image.
<?php
class Watermark{
    # given two images, return a blended watermarked image
    # given two images, return a blended watermarked image
    function create_watermark( $main_img_obj, $watermark_img_obj, $alpha_level = 100 ) {
        $alpha_level /= 100; # convert 0-100 (%) alpha to decimal
        # calculate our images dimensions
        $main_img_obj_w = imagesx( $main_img_obj );
        $main_img_obj_h = imagesy( $main_img_obj );
        $watermark_img_obj_w = imagesx( $watermark_img_obj );
        $watermark_img_obj_h = imagesy( $watermark_img_obj );
        # determine center position coordinates
        $main_img_obj_min_x = floor( ( $main_img_obj_w / 2 ) - ( $watermark_img_obj_w / 2 ) );
        $main_img_obj_max_x = ceil( ( $main_img_obj_w / 2 ) + ( $watermark_img_obj_w / 2 ) );
        $main_img_obj_min_y = floor( ( $main_img_obj_h / 2 ) - ( $watermark_img_obj_h / 2 ) );
        $main_img_obj_max_y = ceil( ( $main_img_obj_h / 2 ) + ( $watermark_img_obj_h / 2 ) );
        # create new image to hold merged changes
        $return_img = imagecreatetruecolor( $main_img_obj_w, $main_img_obj_h );
        # walk through main image
        for( $y = 0; $y < $main_img_obj_h; $y++ ) {
            for( $x = 0; $x < $main_img_obj_w; $x++ ) {
                $return_color     = NULL;

                # determine the correct pixel location within our watermark
                $watermark_x      = $x - $main_img_obj_min_x;
                $watermark_y      = $y - $main_img_obj_min_y;

                # fetch color information for both of our images
                $main_rgb = imagecolorsforindex( $main_img_obj, imagecolorat( $main_img_obj, $x, $y ) );

                # if our watermark has a non-transparent value at this pixel intersection
                # and we're still within the bounds of the watermark image
                if (  $watermark_x >= 0 && $watermark_x < $watermark_img_obj_w &&
                $watermark_y >= 0 && $watermark_y < $watermark_img_obj_h ) {
                    $watermark_rbg = imagecolorsforindex( $watermark_img_obj, imagecolorat( $watermark_img_obj, $watermark_x, $watermark_y ) );

                    # using image alpha, and user specified alpha, calculate average
                    $watermark_alpha  = round( ( ( 127 - $watermark_rbg['alpha'] ) / 127 ), 2 );
                    $watermark_alpha  = $watermark_alpha * $alpha_level;

                    # calculate the color 'average' between the two - taking into account the specified alpha level
                    $avg_red          = $this->_get_ave_color( $main_rgb['red'],            $watermark_rbg['red'],        $watermark_alpha );
                    $avg_green  = $this->_get_ave_color( $main_rgb['green'],      $watermark_rbg['green'],      $watermark_alpha );
                    $avg_blue         = $this->_get_ave_color( $main_rgb['blue'],      $watermark_rbg['blue'],       $watermark_alpha );

                    # calculate a color index value using the average RGB values we've determined
                    $return_color     = $this->_get_image_color( $return_img, $avg_red, $avg_green, $avg_blue );

                    # if we're not dealing with an average color here, then let's just copy over the main color
                } else {
                    $return_color     = imagecolorat( $main_img_obj, $x, $y );

                } # END if watermark

                # draw the appropriate color onto the return image
                imagesetpixel( $return_img, $x, $y, $return_color );

            } # END for each X pixel
        } # END for each Y pixel
        # return the resulting, watermarked image for display
        return $return_img;
    } # END create_watermark()

    # average two colors given an alpha
    function _get_ave_color( $color_a, $color_b, $alpha_level ) {
        return round( ( ( $color_a * ( 1 - $alpha_level ) ) + ( $color_b  * $alpha_level ) ) );
    } # END _get_ave_color()

    # return closest pallette-color match for RGB values
    function _get_image_color($im, $r, $g, $b) {
        $c=imagecolorexact($im, $r, $g, $b);
        if ($c!=-1) return $c;
        $c=imagecolorallocate($im, $r, $g, $b);
        if ($c!=-1) return $c;
        return imagecolorclosest($im, $r, $g, $b);
    } # EBD _get_image_color()
} # END watermark API
?>

and this is how to use it
$watermark = new Watermark();
        $actual_image = imagecreatefromjpeg("images/$image_file");
        $watermark_image = imagecreatefrompng("images/water_mark.png");
        //create water marked image with 66% transparency
        $return_img_obj = $watermark->create_watermark( $actual_image, $watermark_image, 66 );

        //now save the updated image
        imagejpeg($return_img_obj,"images/$image_file1");

        //clear the memory
        imagedestroy($actual_image);
        imagedestroy($watermark_image);
        imagedestroy($return_img_obj);

A:
without affecting the source image.

Doing this without affecting the actual image is possible only by adding a HTML layer containing a transparent image. That is pretty useless as a means of protection though, because everyone with a tiny bit of technical knowledge can fetch the original image in seconds.

A: Using the GD image library: http://php.net/manual/en/book.image.php
This way I would create a web watermark version of the image and also store the source image.
Unless you mean to add a watermark on the fly in which case I'm not sure you can that easily.

A: If you don't want to affect the source image, then I'd recommend putting a transparent image in an absolutely positioned div over the image in your HTML. This means you don't have to process an image on each page load (because you want to keep the original intact), and you don't have to mess about with storing an extra image.

A: From the first sight, I think this code will not affect the source file if u didn't provide a destination file name to the function.


text:
Q: Double integral $x^2(x^2+y^2+1)^{3/2}$ How to evaluate $\int_{-1}^1 \int_{-1}^1 x^2(x^2+y^2+1)^{3/2} \ dx \ dy$ ? I tried substituting $x^2+y^2=tan^2(u)$ but it becomes more complicated. Using Wolfram Alpha Widget the answer is $3.64092$. Any idea? Thanks.

A: The symmetry of the integrand implies $$I = \int_{y=-1}^1 \int_{x=-1}^1 x^2 (x^2 + y^2 + 1)^{3/2} \, dx \, dy = \int_{x=-1}^1 \int_{y=-1}^1 y^2 (x^2 + y^2 + 1)^{3/2} \, dy \, dx.$$  Thus $$2I = \int_{y=-1}^1 \int_{x=-1}^1 (x^2 + y^2)(x^2 + y^2 + 1)^{3/2} \, dx \, dy.$$  Now perform the coordinate transformation $$(x,y) = (r \cos \theta, r \sin \theta)$$ to obtain $$2I = 8 \int_{\theta = 0}^{\pi/4} \int_{r = 0}^{\sec \theta} r^2 (r^2 + 1)^{3/2} r \, dr \, d\theta.$$  Since
$$\begin{align*} \int r^3 (r^2 + 1)^{3/2} \, dr
&= \frac{1}{2} \int r^2 (r^2 + 1)^{3/2} 2r \, dr \\
&= \frac{1}{2} \int (u-1)u^{3/2} \, du \\
&= \frac{1}{2} \left( \frac{2}{7} u^{7/2} - \frac{2}{5} u^{5/2} \right) + C \\
&= \frac{(r^2+1)^{7/2}}{7} - \frac{(r^2+1)^{5/2}}{5} + C,
\end{align*}$$
we obtain
$$
I = 4 \int_{\theta=0}^{\pi/4}  \frac{(\sec^2 \theta + 1)^{7/2} - 1}{7} - \frac{(\sec^2 \theta + 1)^{5/2} - 1}{5} \, d\theta.$$
At this point, I don't have a simple way to evaluate this integral; however, the value provided is $$I = \frac{2}{105}\left(96 \sqrt{3} + \pi + 33 \coth^{-1} \sqrt{3} \right) \approx 3.640919532942123602084014417112851989279\ldots.$$


text:
Q: What will be expected number of iterations in the following Algorithm? Algorithm RSearch(A,n,k)
//A is list of n distinct unsorted elements
//assuming index starts from 1 and ends at n
// k is element we want to search, assuming there is k at exactly one index
{
    repeat
    {
      i= random(1,n);    // pick random index from 1 to n with equal probability
      if(A[i]==k)
        return true;
    }
    until true;
}

A: The answer highly depends on random(1,n) function. If random function obeys a uniform distribution (means probability of each number in the range:[1,n]  is the same as others) then you can consider 2 situations:

*

*The first random index is the index of k : It is the best case, So the complexity of best case is O(1)

*You choose n-1 random numbers and try n-1 times and fail! so in your nth try You have the desired index. Notice that if the random function has uniform distribution, probability of getting each element in the set(range) is p=1/n. So for having a special element you have to try at least 1/p=n times! This the worst case! So the complexity of worst case is Omega(n)


text:
Q: ¿Alguien me propria explicar como cargar componentes asíncronos de vue js? Ya estuve buscando por varios lados y no encuentro un ejemplo practico de como cargar componentes dinámicos mediante larvel mix.
En la documentacion de vue js dice que solo debes de modificar require locual quedaria de la siguiente manera.
Vue.component('async-example' , function ( resolve, reject )
{
  setTimeout ( function ()
      {
         // Pasar la definición del componente a la resolución resuelta de
                devolución de llamada
      ({
          template: '<div> ¡Soy asincrónico! </ Div>'
       })
      }, 1000 )
})

Pero el copilador que viene por defecto en laravel (webpack) no compila. Tengo entendido que esto se debe a que necesita una configuración especial para procesar estos archivos que cargaran de forma asíncrona y dinámica.
Si alguien me puede pasar un ejemplo practico donde pueda manosear el código se lo agradecería. No importa que este en ingles.


text:
Q: how do tell if its better to standardize your data matrix first when you do principal component analysis in R? I'm trying to do principal component analysis in R . There are 2 ways of doing it, I believe.
One is doing principal component analysis right away the other way is standardizing the matrix first using s = scale(m) and then applying principal component analysis.
How do I tell what result is better? What values, in particular, should I look at? I already managed to find the eigenvalues and eigenvectors, the proportion of variance for each eigenvector using both methods.
I noticed that the proportion of the variance for the first pca without standardizing had a larger value. Is there a meaning to it? Isn't this always the case?
At last, if I am supposed to predict a variable ie weight should I drop the variable ie weight from my data matrix when I do a principal component analysis?

A: Are your variables measured on a common scale?  If yes, then don't scale.  If no, then it's probably a good idea to scale.
If you are trying to predict the value of another variable, PCA is probably not the correct tool.  Maybe you should look at a regression model instead.


text:
Q: Core Data, "sorting by transient property" workaround Let's say I have a Core Data entity called Event, which represents recurrent (yearly) events. Each Event has a "date" property.
I need to present this events to the user sorted by "next occurrence of date". This property, of course, depends on the current date and as such should be marked as transient: there's no point in storing it in the database.
But, as you know, you can't query sorting by a transient property in Core Data.
Is there a smart way to keep this property transient and still have Core Data sort for me? I don't want to fetch and then sort myself, but I would also like to avoid storing this transient info in the database.

A: If you store the date in a separate entity, then you can fetch just the dates and sort them yourself however you like. You'd have a relationship from Event to EventDate, and a corresponding inverse relationship that lets you find the Event from a given EventDate.
Suggestion: Specify a sort descriptor in your fetch request so that you get the dates sorted from the beginning of the year. Then all you have to do is locate the current date in the returned array, and move everything before that point to the end of the array.
Make the EventDate->Event relationship to-many, since it might happen that more than one Event falls on the same date. Setting your model up like this gives you the nice property that you can easily answer the question "What events happen on date X?"


text:
Q: Query to extract only records which have failed I need a help in writing a SQL for the below table. I have a table with two columns (Name and Status).
Name    Status
Kevin   success
Mark    fail
Mark    success
Mike    success
Yann    fail
Yann    success
George  fail
Boi     Fail

From the above table, I would like to extract only records which have failed and also which are failed then succeeded. Basically I would like to exclude the records which are just succeeded.

A:
Basically I would like to exclude the records which are just succeeded.

If you want all records whose name has at least one non-'success' status, you can use exists:
select t.*
from mytable t
where exists(
    select 1 from mytable t1 where t1.name = t.name and t1.status <> 'success'
)

Alternatively, if you want a list of names that have at least one non-'success' status, then you can use aggregation and filter with a having clause:
select name
from mytable
group by name
having max(case when status <> 'success' then 1 else 0 end) = 1

A: Just another option is using WITH TIES
Not clear if you want ALL records or just distinct Names
Example
Declare @YourTable Table ([Name] varchar(50),[Status] varchar(50))
Insert Into @YourTable Values
 ('Kevin','success')
,('Mark','fail')
,('Mark','success')
,('Mike','success')
,('Yann','fail')
,('Yann','success')
,('George','fail')
,('Boi','Fail')

Select top 1 with ties *
 From @YourTable
 Order By min(case when status='Fail' then 0 else 1 end) over (partition by [Name] )

Returns
Name    Status
Boi     Fail
George  fail
Mark    fail
Mark    success
Yann    fail
Yann    success

Kevin and Mike are excluded


text:
Q: tf.Keras custom layer output shape is None I was building a custom layer and encounter output shape problem when adding a dense layer afterward. The output shape of that layer seems doesn't seem to be defined, even if I explicitly do so. Here is a minimal code that is reproducing the issue:
import tensorflow as tf
from tensorflow import keras

class fakeLayer(keras.layers.Layer):

    def __init__(self, **kwargs):
        super().__init__(**kwargs)

    def compute_output_shape(self, input_shape):
        return ((input_shape[0], input_shape[1]* input_shape[2], input_shape[3]))

    def build( self, input_shape):
        super().build(input_shape)

    def call(self, inputs):
        return(tf.reshape(inputs , self.compute_output_shape(tf.shape(inputs))))

inp = keras.layers.Input((32,32,3))
x = keras.layers.Conv2D(16, (3,3))(inp)
x = fakeLayer()(x)
# x = keras.layers.Flatten()(x)
# x = keras.layers.Dense(1)(x)
model = keras.models.Model(inputs= inp, outputs = x)

print(model.summary())

ouputs this :
WARNING:tensorflow:Entity <bound method fakeLayer.call of <__main__.fakeLayer object at 0x0000021A7370E470>> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause:
WARNING: Entity <bound method fakeLayer.call of <__main__.fakeLayer object at 0x0000021A7370E470>> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause:
Model: "model_9"
_________________________________________________________________
Layer (type)                 Output Shape              Param #
=================================================================
input_37 (InputLayer)        [(None, 32, 32, 3)]       0
_________________________________________________________________
conv2d_10 (Conv2D)           (None, 30, 30, 16)        448
_________________________________________________________________
fake_layer_28 (fakeLayer)    (None, None, None)        0
=================================================================
Total params: 448
Trainable params: 448
Non-trainable params: 0
_________________________________________________________________
None

We can see here that model.summary() can't get the output shape of the layer.
We thus obtain this error while uncommenting the flatten and dense layer:
WARNING:tensorflow:Entity <bound method fakeLayer.call of <__main__.fakeLayer object at 0x0000021A737535C0>> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause:
WARNING: Entity <bound method fakeLayer.call of <__main__.fakeLayer object at 0x0000021A737535C0>> could not be transformed and will be executed as-is. Please report this to the AutoGraph team. When filing the bug, set the verbosity to 10 (on Linux, `export AUTOGRAPH_VERBOSITY=10`) and attach the full output. Cause:
Traceback (most recent call last):

  File "C:\Users\integration\Documents\Scripts\minimalBug.py", line 31, in <module>
    x = keras.layers.Dense(1)(x)

  File "C:\Users\integration\.conda\envs\py36\lib\site-packages\tensorflow_core\python\keras\engine\base_layer.py", line 817, in __call__
    self._maybe_build(inputs)

  File "C:\Users\integration\.conda\envs\py36\lib\site-packages\tensorflow_core\python\keras\engine\base_layer.py", line 2141, in _maybe_build
    self.build(input_shapes)

  File "C:\Users\integration\.conda\envs\py36\lib\site-packages\tensorflow_core\python\keras\layers\core.py", line 1015, in build
    raise ValueError('The last dimension of the inputs to `Dense` '

ValueError: The last dimension of the inputs to `Dense` should be defined. Found `None`.

A: I don't know if it makes a difference, but you have double parentheses here, don't know why:
def compute_output_shape(self, input_shape):
    #wrong: return ((input_shape[0], input_shape[1]* input_shape[2], input_shape[3]))
    return (input_shape[0], input_shape[1]* input_shape[2], input_shape[3])

Now, the real problem is in call, where you're mixing a lot of different things.

*

*tf.shape returns a tensor, not a tuple

*compute_output_shape returns a tuple

*if you give a tensor to compute_output_shape it will return a tuple of tensors (never do this!)

*tf.reshape accepts either "a tuple" or "a tensor", it does not accept a tuple of tensors

*Keras shapes are tuples that contain None values, reshape accepts tuples with -1 values, not None.

Solution:
def call(self, inputs):
    keras_shape = keras.backend.int_shape(inputs) #tuple containing None and numbers
    tf_shape_tuple = tuple(-1 if s is None else s for s in keras_shape) #None -> -1

    return tf.reshape(inputs , tf_shape_tuple)

A: I would use tf.shape(x) which deals Ok with the problem of the None shape (source):
def call(self, inputs):
    in_shape = tf.shape(inputs)
    return tf.reshape(inputs , (in_shape[0], in_shape[1]*in_shape[2], in_shape[3]))

For the compute output shape I would first redefine the input shape as:
from tensorflow.python.framework import tensor_shape

def compute_output_shape(self, input_shape):
    input_shape = tensor_shape.TensorShape(input_shape).as_list()
    return (input_shape[0], input_shape[1]* input_shape[2], input_shape[3])


text:
Q: How to dynamically increase the length of the url? How to dynamically increase the length of the url ?
Let me be more descriptive. I want to use it in asp.net version 2.0 and 3.5. The maximum length of the url in (IE 7 +) is 2048.
Various size support in different browsers:
IE 7 + - 2048
Firefox - 65000
Safari - 80000
Opera - 190000

A: Put a query string on the url, and increase the size of it's value:
Response.Redirect("ThisPage.aspx?param=" + Request.QueryString("param") + "x");

A: You add more characters to it.

A: Use http://www.hugeurl.com/ ?
Seriously though, nothing stopping you from adding random junk to the query string.  If you want the URL to be immutable, include a checksum or something and require it to match the added text for the URL to resolve.  Or just use a reversible transformation to generate your URL, which is probably what hugeurl does.


text:
Q: Find match in csv file I have two CSV files.
1.csv
contains:
46700468915;2000

2.csv
contains:
4670046;Tele2

I am trying to searching from 2.csv if 4670046 exists in 1.csv which is does and then take from 2.csv Tele2 and add in 1.csv if no match do not add
awk 'NR==FNR {a[$1]=$2; next} $2 in a {print $0, a[$2]}' OFS='\t' 2.csv 1.csv

A: You have a few issues here:

*

*you need to set awk's field separator appropriately: by default it is whitespace, whereas your files appear to be delimited by semicolons

*you are trying to match on a partial field: 4670046 is in a but 46700468915 isn't

*you seem to be confused about which field you are matching, $1 or $2
If you know that you want to match the first 7 characters, you can try
awk -F ';' '
  NR==FNR {a[$1]=$2; next} {k = substr($1,1,7)} k in a {print $0, a[k]}
' OFS='\t' 2.csv 1.csv

or equivalently
awk '
  BEGIN{FS=";"; OFS="\t"}
  NR==FNR {a[$1]=$2; next} {k = substr($1,1,7)} k in a {print $0, a[k]}
' 2.csv 1.csv

Ex. given
$ head ?.csv
==> 1.csv <==
46700468915;2000

==> 2.csv <==
4670046;Tele2

then
$ awk 'BEGIN{FS=";"; OFS="\t"} NR==FNR {a[$1]=$2; next} {k = substr($1,1,7)} k in a {print $0, a[k]}' 2.csv 1.csv
46700468915;2000    Tele2

A: The awk solution should be much faster but here is an example, how to achieve this via bash script, which read each line of 2.csv as -array and then uses sed to do the changes (the if statement is not essential part of the script).
$ cat ./script.sh

#!/bin/bash

TARGET_FILE="./1.csv"
ORIGIN_FILE="./2.csv"

# In order to append new column to a line, comment-out -i.bak
while IFS=';' read -r -a line
do
        if grep -q "${line[0]}" "$TARGET_FILE"
        then
                sed "/^${line[0]}/ s/$/;${line[1]}/" "$TARGET_FILE" #-i.bak
        fi
done < "$ORIGIN_FILE"

echo '-----'

# In order to replace the second column of a line, comment-out -i.bak
while IFS=';' read -r -a line
do
        if grep -q "${line[0]}" "$TARGET_FILE"
        then
                sed -r "s/(^${line[0]}.*\;).*$/\1${line[1]}/" "$TARGET_FILE" #-i.bak
        fi
done < "$ORIGIN_FILE"

Example of usage:
$ cat 1.csv
46700468915;2000
46700568916;3000
46700668917;4000

$ cat 2.csv
4670046;Tele2
4670047;Tele3
4670048;Tele4

$ ./script.sh
46700468915;2000;Tele2
46700568916;3000
46700668917;4000
-----
46700468915;Tele2
46700568916;3000
46700668917;4000


text:
Q: Getting rid of Plesk on a VPS I've been using a relatively expensive VPS for hosting about 30 domains and I want to migrate to a cheaper one, without Plesk. Both use CentOS.
My users will not care, they don't use Plesk anyway.
But I will not be able to use it for creating new virtual hosts, FTP accounts etc. I'm not a commandline guru, esp. not in a server environment.
Is there a free Plesk alternative for these purposes? I need to:

*

*Create a new virtual host with it's own FTP account

*Setup some basic FTP quota

I don't need:

*

*DNS management (the new VPS service has an external DNS management GUI)

*Mail server management (I use Google Apps)

Any suggestions welcome, from Plesk alternatives to "RTFM" or links to tutorials.

A: Cost is a bad reason to move off of Plesk.  They are clearly providing value to you, the freedom from having to understand what's actually going on under the hood.
The right reason to move off Plesk is because you don't like what it does under the hood, and want to take back control.  You can save a few bucks a month that way, which you almost immediately eat up by spending time doing things by hand that Plesk used to do for you automatically.
I say this as someone who moved his site off a VPS running Plesk to a bare-bones VPS service.  But then, I am a command line guru. :)

A: My two cents is keep plesk. It makes managment a dead simple task and makes it very easy to see what is going on with your server. I am a command line semiguru however I like plesk because it is web based access from anywhere no ssh client needed, and gives a quick visualization of what is going on with the server usage.


text:
Q: Programmatically detect whether command can be run as module I have a function which takes a command:
import subprocess

def run_command(command: str):
    subprocess.run(['python', '-m', command])

I would like to tell whether command is something which can be run as python -m <command>.
For example:

*

*doctest would count, as I can run python -m doctest

*foo would not, as it would return No module named foo
Is there a way to tell, inside my function, whether command is a Python module which can be run?
The simplest way would just be try-except, but I would like to avoid that as it might mask other errors.

A: You can capture the output of the command and check stderr to see what it returned. This code checks if the binary string "No module named" is in the stderr, which means the command wasn't found
import subprocess

def run_command(command: str):
    output = subprocess.run(['python', '-m', command], capture_output=True)
    if b"No module named" in output.stderr:
      print("Command not found")
    else:
      #command was found


text:
Q: Let user edit data table variable names in R Shiny I am building an R Shiny app where the user selects columns in a data table, and the app then returns a list of the selected variables. I want the user to be able to change the names of the variables/columns in the app.
I used DT to make this interactive table. I got the code for changing the column headers from an answer by Stéphane Laurent on this post.
While both the column selection and editable column names work fine in the DT table, the problem is that changing the variable names only edits the displayed table, and the original data frame still retains its original column names. I am hoping that when users edit the variable names in the app, it changes the variable names in the actual data frame. How do I achieve this?
I was thinking about using observeEvent() to change the column names every time the user changes the column names, but since the method given by Stéphane Laurent uses JS, I'm not really sure how to do that.
(screenshot of the app here;  I have changed the column names of 2 selected columns, but the original dataframe has not been updated.)
library(shiny)
library(DT)

getlist <- function(df, colnums){
  data <- df
  if(length(colnums)==1){
    column_names <- colnames(data)[colnums]
  } else{
    selected_data <- data[,colnums]
    column_names <- colnames(selected_data)
  }
  return(column_names)
}

callback <- c(
  "table.on('dblclick.dt', 'thead th', function(e) {",
  "  var $th = $(this);",
  "  var index = $th.index();",
  "  var colname = $th.text(), newcolname = colname;",
  "  var $input = $('<input type=\"text\">')",
  "  $input.val(colname);",
  "  $th.empty().append($input);",
  "  $input.on('change', function(){",
  "    newcolname = $input.val();",
  "    if(newcolname != colname){",
  "      $(table.column(index).header()).text(newcolname);",
  "    }",
  "    $input.remove();",
  "  }).on('blur', function(){",
  "    $(table.column(index).header()).text(newcolname);",
  "    $input.remove();",
  "  });",
  "});"
)

ui <- fluidPage(

  DTOutput("table"),
  textOutput('preview'),
  tableOutput('table2')

)

server <- function(input, output){

  data <- reactiveVal(iris)

  output[["table"]] <- renderDT({
    datatable(data(), selection = list(target = 'column'), options= list(ordering = FALSE, pageLength = 25), callback = JS(callback))
  })

  #selected columns of the tables
  vlist <- reactive(c(getlist(data(),input$table_columns_selected)))

  #display list of selected variables
  output$preview <- renderText(paste(c('Selected variables :', vlist()), collapse=' '))

  output$table2 <- renderTable({data()})

}

shinyApp(ui, server)

A: You can use Shiny.setInputValue() to send messages from JS to shiny and generate an input value. I use this to send the old and new column name from the JS function to the input$change_colname. Then you can use observeEvent to update your data. In your case, I would use different objects that are used to render table and table2, because right now table gets rerendered after a column name change as the underlying data() is updated:
library(shiny)
library(DT)

getlist <- function(df, colnums){
  data <- df
  if(length(colnums)==1){
    column_names <- colnames(data)[colnums]
  } else{
    selected_data <- data[,colnums]
    column_names <- colnames(selected_data)
  }
  return(column_names)
}

callback <- c(
  "table.on('dblclick.dt', 'thead th', function(e) {",
  "  var $th = $(this);",
  "  var index = $th.index();",
  "  var colname = $th.text(), newcolname = colname;",
  "  var $input = $('<input type=\"text\">')",
  "  $input.val(colname);",
  "  $th.empty().append($input);",
  "  $input.on('change', function(){",
  "    newcolname = $input.val();",
  "    if(newcolname != colname){",
  "      $(table.column(index).header()).text(newcolname);",
  "      Shiny.setInputValue('change_colname', [colname, newcolname]);",
  "    }",
  "    $input.remove();",
  "  }).on('blur', function(){",
  "    $(table.column(index).header()).text(newcolname);",
  "    $input.remove();",
  "  });",
  "});"
)

ui <- fluidPage(

  DTOutput("table"),
  textOutput('preview'),
  tableOutput('table2')

)

server <- function(input, output){

  data <- reactiveVal(iris)
  vlist <- reactiveVal()

  output[["table"]] <- renderDT({
    datatable(data(), selection = list(target = 'column'), options= list(ordering = FALSE, pageLength = 25), callback = JS(callback))
  })

  #selected columns of the tables
  observeEvent(input$table_columns_selected, {
    vlist(getlist(data(),input$table_columns_selected))
  })

  # update column names
  observeEvent(input$change_colname, {
    old_colnames <- vlist()
    old_colnames[old_colnames == input$change_colname[1]] <- input$change_colname[2]
    vlist(old_colnames)

    # update the data
    old_data <- data()
    colnames(old_data)[colnames(old_data) == input$change_colname[1]] <-
      input$change_colname[2]
    data(old_data)
  })

  #display list of selected variables
  output$preview <- renderText(paste(c('Selected variables :', vlist()), collapse=' '))

  output$table2 <- renderTable({data()})

  output$changed_var <- renderPrint({input$change_colname})

}

shinyApp(ui, server)


text:
Q: How do I search a file and return an array of the results and line number in PHP? How do I search a file and return an array of the results so that I can use it in a collection in PHP?
So, for example, say I have a .txt file with something like:
hellohello
hihi
heywhats up
hello hey whats up
hello

And I want to search for all occurrences with hello and its line number, then return it as an array so I can use it in a data collector.
So, it would  return the line number and line, like:
$results = array
(
array('1', 'hellohello'),
array('4', 'hello hey whats up'),
array('5', 'hello'),
);

My idea is to us file_get_contents.
So, for example..
$file = 'example.txt';

function get_file($file) {
  $file = file_get_contents($file);
  return $file;
}

function searchFile($search_str) {
  $matches = preg_match('/$search_str/i', get_file($file);
  return $matches;
}

A: As an alternative, you could also use file() function so it reads the entire file into an array. Then you could just loop, then search. Rough example:
$file = 'example.txt';
$search = 'hello';
$results = array();
$contents = file($file);
foreach($contents as $line => $text) {
    if(stripos($text, $search) !== false) {
        $results[] = array($line+1, $text);
    }
}
print_r($results);

Sidenote: stripos() is just an example, you could still use your other way/preference to search the needle for that particular line.


text:
Q: How does the force of tension really work? Here's a diagram of the issue I'm having problem. It's based on an experiment we did in class:

Note that the surface is assumed to be frictionless. Also note that I have assigned a positive and negative direction using that arrow and the plus sign. There are two masses, A and B (A on the track, B hanging) which is tied together by a rope  that passes over a pulley.
I have added in the free-body force diagrams for each mass that I was told were correct.
When we did the experiment in class, the blocks were only motionless when someone was holding block A back. But when it was let go (and that is the situation represented by the diagram I displayed) the whole system accelerated in the positive direction (I have assigned that positive and negative direction to make discussing the problem easier).
The question is, "What is the net force in the entire system (both blocks)?" In other words, what is causing the movement?
(I have also been told that the blocks will have the same magnitude of acceleration. Why is this?)
Anyway, I've been told that the net force is the force of gravity on mass B (the hanging one). But I don't really understand why, even after extensive discussion with various people.
Looking back at those force diagrams: I understand that the force of normal and weight of mass A cancel out, so the only remaining force is tension. And I understand that mass B has tension and weight acting on it.
But here's where it gets tricky:
The tension on A is apparently pulling it in the positive direction, while the tension on B is pulling it in the negative direction. Do those opposite tensions cancel one another, causing force of gravity to become the net force?
There must be some sort of cancellation in play, I figure, because I've been told that when all the forces are summed, you just end up with force of gravity propelling the system.
Some questions I've been asking myself about this have been:

*

*How does the relationship between the force of gravity on mass B and the tension in the rope play into this? Isn't the tension caused by that force of gravity? Doesn't that mean that if tensions cancel, the force of gravity's effect is canceled as well?

*Does the pulley affect tensions? For example, we know that there's a positive tension affecting mass A. Is there still a positive tension in existence on the other side of the pulley, or just the negative tension that's acting on B? Might there be some sort of effect whereby two sets of opposite tensions, one set on each side of the pulley, cancel each other out?

*If you pick any and all points on the rope, would there be two opposing tensions at every one of those points?

*Is tension uniform throughout the rope?

*How might differences in mass between object A and object B (which, sorry if the diagram was misleading in the sizes, can have any mass) play into the tension?
Etc.

A: The forces will cancel the way you imagine when the system is not moving. That is, in a static situation in which the friction on block A is enough to prevent movement. And with no acceleration the forces must add up to zero.
However, if it starts moving, it must be accelerating (or it could not change from zero) and there must be a net force.
Your blocks are physically connected. Usually we assume a mass-less unstretchable rope, but you can more realistically think of it as a spring that is stiff enough that you can ignore it. The masses are connected and must move together, so naturally the blocks accelerate at the same rate though in different directions. The condition for movement is mg for block B is greater than N*coefficient of dynamic friction for block A - after it starts moving.
The pulley is considered frictionless. It acts like a lever that pivots around the center of the wheel and redirects motion between horizontal and vertical. The tensions are just bookkeeping, like the signs in arithmetic. The tensions can still be equal. The main thing is that the force on A from the rope is greater than the frictional force.
You can use this experiment to find the coefficient of dynamic friction for block A. If you slowly add weight to Block B, you can find both the dynamic friction, and the static friction, or stiction. Was that the purpose?
For understanding tension better, try to imagine yourself on the block and holding the rope. You can feel the tension pulling. Imagine two of you, one on each end. Can one be pulling harder than the other?

A: It's alright, tension is pretty subtle! Let me answer your questions a bit out of order.

*

*If you pick any and all points on the rope, would there be two opposing tensions at every one of those points?

*Is tension uniform throughout the rope?

You can think about the rope as a lot of tiny masses connected together by springs; this is a cheap approximation for how tension works on the atomic level, where the springs are stretching chemical bonds and the masses are atoms.
In our simple model of tension, every atom is pulled by a spring on the left and a spring on the right, with forces $T_1$ and $T_2$. Then by Newton's second law,
$$T_1 - T_2 = ma$$
where $m$ is the mass of the atom. Since $m$ is very very tiny compared to the other masses in the problem, we must have
$$T_1 \approx T_2.$$
Applying this to every mass, we conclude that each little spring / chemical bond has approximately the same tension, so we can simply talk about "the tension in the rope". This is a good approximation as long as the total mass of the rope is much smaller than the masses of the blocks.

How might differences in mass between object A and object B (which, sorry if the diagram was misleading in the sizes, can have any mass) play into the tension?

Well, now that we've established that there's a uniform tension $T$, we need to figure out what that tension is. The constraint here is that the rope is taut, which means that it can't be scrunching up or stretching out; that translates to the constraint that the accelerations of the two blocks are equal in magnitude. This equation determines the tension.

How does the relationship between the force of gravity on mass B and the tension in the rope play into this? Isn't the tension caused by that force of gravity? Doesn't that mean that if tensions cancel, the force of gravity's effect is canceled as well?
  (I have also been told that the blocks will have the same magnitude of acceleration. Why is this?)

No, the tension isn't equal to the weight of block B, it's whatever is necessary to satisfy the above constraint. For example, suppose that block B was very very heavy, so the acceleration of the whole system will be close to $g$. In this case, the tension is actually quite small compared to the weight of block B, because you only need a little tension to make block A have the same acceleration.
(In fact, as block B gets infinitely heavy, you can show that the tension doesn't go to infinity -- instead, it becomes the weight of block A! It's neat to try to prove this, and see how it works.)

Does the pulley affect tensions? For example, we know that there's a positive tension affecting mass A. Is there still a positive tension in existence on the other side of the pulley, or just the negative tension that's acting on B? Might there be some sort of effect whereby two sets of opposite tensions, one set on each side of the pulley, cancel each other out?

This is a little tricky to word. The tensions of the two tiny springs attached to each atom approximately cancel out, as shown above. But that doesn't mean that the tension is zero -- all of those springs are still stretched.
Since the pulley is frictionless, it doesn't have any effect except that it 'turns around' the tension. You can show this by considering the three forces on each atom (two springs, one normal force) which gives $T_1 \approx T_2$ as before.

Anyway, I've been told that the net force is the force of gravity on mass B (the hanging one). But I don't really understand why, even after extensive discussion with various people.

That's not your fault, the question is just worded badly. There are lots of forces involved in this problem acting on different things: gravity on both blocks, normal on one block, and normal from the pulley on the rope. It's not very clear what "the" net force even means.

A: Actually, your understanding seems quite good, and much of what you wrote goes at least in the right direction. In particular you have done well on the crucial part of getting your free-body diagrams right. Let's take this one step at a time, starting with your first question (which happens to be a good question to answer first:
"I have also been told that the blocks will have the same magnitude of acceleration. Why is this?"
This is fundamentally important for this system: The two blocks are connected by a rope that is assumed to be massless and inextensible. The second part (rope being of fixed length) means that both blocks will move at the same speeds and hence identical accelerations: If that was not the case, their relative distance would have to change, by either the rope becoming slack, or the rope stretching. The latter is prevented by our assumption of the rigid rope, the former cannot happen since Block A must be pulled by a force from the rope.
So, at this point we know that both blocks move in unison, in the sense that their linear velocities and accelerations are the same. There is thus a single acceleration which we'll call $a$. Newton's Second Law then tells us that there must be accelerating forces acting on each of the masses.
For Block A, this means we have
$$m_A\,a=F_{net, A}=F_T$$
since this block has $F_T$ as the only force acting on it in the direction of the motion. For Block B, we get
$$m_B\,a =F_{net, B}=F_g-F_T$$
since the forces acting on Block B are the weight of the block and the tension force.
We can now add the above two equations to obtain
$$(m_A+m_B)a=F_g$$
(notice that the tension force cancels out; this is exactly the cancellation that people told you about), which allows us to find the acceleration of the blocks,
$$a=\frac{F_g}{m_A+m_B}=\frac{m_B}{m_A+m_B}g.$$
In addition, this equation also shows that it is the force of gravitation that is the relevant "net force" accelerating the entire system (Block A and Block B).
Finally, with the acceleration $a$ known, we can find the tension in the rope from our first equation above,
$$F_T=m_A\,a=\frac{m_A}{m_A+m_B}F_g=\frac{m_A\,m_B}{m_A+m_B}g.$$
We can look at the limiting cases of very small or large rations of the two masses. If we let $m_A\rightarrow\infty$, then $\frac{m_A\,m_B}{m_A+m_B}\rightarrow m_B$, so the tension in the rope is simply the weight of Block B and the acceleration goes to zero, $a\rightarrow0$. If we let $m_B\rightarrow\infty$, then $\frac{m_A\,m_B}{m_A+m_B}\rightarrow m_A$, so the tension in the rope is simply the weight of Block A and the acceleration becomes $a\rightarrow g$.
On your other questions:

*

*The pulley could affect the tension in two cases: (1) If the pulley has mass (or rather an inertial moment, don't worry, you'll learn about this later), then a force would be needed to accelerate the pulley as well. As a result, you would see different tension forces in the rope before and after the pulley. (2) If the pulley is subject to friction, a force would likewise be required to overcome it, and again the tension in the rope would differ before and after the pulley.

*Yes, we can imagine looking at any cross section of the rope and determining the force of tension there. If the rope has no mass, we will find the exact same force at any point of the rope. So, yes, the tension will be uniform in a massless rope. You may be able to see that this will not be true anymore if the rope has mass: In that case forces are required to accelerate the mass beyond the point we are considering. These forces will therefore be different and vary linearly along the rope.

*You can see the effect of different masses on tension in our last equation above.


text:
Q: font-awesome not working with Apache 2.4.x When I try to statically use font-awesome (fa) in my project with Apache 2.4.x the icons will not show up. Fa works with apache 2.2.x, and Python's SimpleHHTPServer.
This is not the IE/Firefox issue where a box is displayed instead of the icon.
I am using this in Dreamfactory (OSX), but I have also tried vanilla Apache from MacPorts with the same results.
Chrome's console reports the following when the page loads:
Resource interpreted as Stylesheet but transferred with MIME type text/troff: "http://localhost:8080/files/applications/CADRe/bower_components/font-awesome/css/font-awesome.min.css".
Fa was installed with bower and I am including it like this:
<link href="bower_components/font-awesome/css/font-awesome.min.css" rel="stylesheet">

My project also includes angularjs and bootstrap.

A: When you run the DreamFactory admin console, do you see icons?  Those use the Bootstrap CDN to serve up font awesome.
This could be an apache config issue , in which case you'd need to edit your apache config to support the mime type:
AddType application/vnd.ms-fontobject eot
AddType font/truetype ttf
AddType application/x-font-woff woff

I would put this as a comment, but this is a new account, and I'm disallowed.

A: Add css with full path and above provided add font mytype in either .htaccess or apachec config file
<link href="http://localhost:8080/files/applications/CADRe/bower_components/font-awesome/css/font-awesome.min.css" rel="stylesheet">

In .htaccess
AddType application/vnd.ms-fontobject eot
AddType font/truetype ttf
AddType application/x-font-woff woff


text:
Q: How to open a directory saved on SD Card Android I am programming a notepad android app but I am having difficulties with my Open button. How do i implement it so that when I click on it, a dialog box comes up with the .txt files saved in the folder I created on the SD card? Also, how do i load the chosen file to my current activity?
Thank You

A: Try the Following,
File f = new File(Environment.getExternalStorageDirectory() +"/"+ dirname);
if(f.isDirectory())
{
    ArrayList<String> files= new ArrayList<String>();
    File file = new File(Environment.getExternalStorageDirectory() +"/"+ dirname+"/");
    File fileList[] = file.listFiles();
    for(int i=0;i<fileList.length;i++)
    {
        files.add(filelist[i].getAbsolutePath());
        //here you can get all files.
    }
}


text:
Q: Unable to download the bitmap to a target using Picasso? I am trying to load the bitmaps to an arraylist as follows:
 Picasso.with(context).load(url).into(new Target(){

        @Override
        public void onBitmapLoaded(Bitmap bitmap, Picasso.LoadedFrom from) {
            //mainLayout.setBackground(new BitmapDrawable(context.getResources(), bitmap));
            photos.add(bitmap);
        }

        @Override
        public void onBitmapFailed(final Drawable errorDrawable) {
            Log.d("TAG", "FAILED");
        }

        @Override
        public void onPrepareLoad(final Drawable placeHolderDrawable) {
            Log.d("TAG", "Prepare Load");
        }
    });

But why is the onBitmapLoaded method never called?

A: Picasso, doesn't hold strong references to new Target() it will be garbage collected
look over this


text:
Q: with clause in oracle I am trying to get below expected result with WITH clause in Oracle.
Sample Data
Id          C_Symbol    C_Id
1001        DD          201
1001        VR          202
1002        VR          203
1002        AS          205
1002        QA          206
1003        DD          207
1003        QA          208
1004        AS          209
1004        QA          210

Expected
Id          IS_DD   C_Id(min c_id for each id)
1001        Y       201
1002        N       203
1003        Y       207
1004        N       209

Meaning: If any id contains DD in c_symbol it should return flag Y with min c_id.
I tried to achieve this with WITH clause but it doesn't help.
WITH A_Info As
    (Select id, c_symbol, c_id from XYZ),
    DD_Info As
    (select id, (case when c_symbol = 'DD' then 'Y' else 'N' END As MD),
    row_number() over(partition by a_id order by c_id) as RN)
select * from DD_info where RN = 1;

This executes row wise, so looking for some alternate solution.
Thank you,

A: I would just use aggregation:
select id,
       max(case when c_symbol = 'DD' then 'Y' else 'N' end) as is_dd,
       min(c_id) as c_id
from sample
group by id;

Here is an example.


text:
Q: Hashing With Chaining Collision We have $1000$ elements with key=1 to 1000, and a hashing function
$$
h(i)=i^3 \mbox{ mod } 10
$$
for an array with length $10$ (array index from $0$ to $9$) with chaining method.
What is the probability of two arbitrary keys mapping two different elements to one array index ( i means probability of collision two elements in one array slot)?
i try to solve it, but my last answer is : 0.02. i dont know it's correct or not. but need anyone help me in solving such  a question. thanks.

A: Since $gcd(3,10)=1$, than each key from 1 to 10 maps in different bin, and keys $n, m$ (1 to 1000) maps to same bin iff $n=m$ (mod 10). That means there are exactly 100 keys mapping to each bin.
Probability to have two different elements mapped to one given bin (e.g. bin 4) is
$$p = \frac {100 \choose 2} {1000 \choose 2} = \frac{11}{1110}.$$
Probability to have two different elements mapped to same bin is $10*p = \frac{11}{111}$.


text:
Q: WCF and protobuf with message signification I have an abstract base class can be serialized using protobuf:
[ProtoContract]
class DataPacket
{
  [ProtoMember(1)]
  public byte[] Data {set;get;}
  [ProtoMember(2)]
  public byte[] Sign {set;get;}
  [ProtoMember(3)]
  public long UserId {set;get;}
  [ProtoMember(4)]
  public DateTime Stamp {set;get;}
}

The challenge is to make WCF to signify every sended and check signature of every received message. There two static methods in one static class:
bool Verify(DataPacket pack)

and
void Sign(DataPacket pack)

So if verification method returns false we need to throw an Exception else - default WCF behavior.
Is it possible to solve?

A: You can wrap your data packet in a message contract and enforce signing:
[MessageContract]
public class {
    [MessageBodyMember(ProtectionLevel = ProtectionLevel.Sign)]
    public byte[] Packet { get; set; }
}

WCF will take care of it automatically (calculating the signature and embedding it into SOAP envelop). Of course, Protobuf (de)serialization is up to you.


text:
Q: SP2010: How to open iframe links in the main window I'm displaying a list on a page using page viewer webpart. When I click on the Title column (linked to Item), it opens as a popup on the iframe. Is there any way to open it in the main window?

A: First set open in dialogs to 'Yes' as belows

*

*Go to the List Settings.

*Now go to the advanced settings.

*Scroll down and go to the 'Dialogs' Section.

*Select "Yes"

Then  add below script on page where you added page viewer.

*

*Edit page and Add script editor webpart on it.

*Add below script in script editor and save the page

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
$(window).load(function(){
$("#MSOPageViewerWebPart_WebPartWPQ2").contents().find("a.ms-listlink").attr("target","_blank");
});
</script>

Note: Change 'MSOPageViewerWebPart_WebPartWPQ2' to your page viewer id.


text:
Q: PowerPoint ActiveX text boxes and labels split in to 2 parts during presentation When I add a text box or label from Powerpoint's developer tab, they look fine until I run the presentation and then they split into 2 boxes, one where it should be but is unfunctioning and another one above and left of the first that allows actions.
I haven't tried anything as I have no idea why it is acting this way
I simply want a control that I can activate to pop up an input box and to store the result. It happens with labels and text boxes as soon as I assign some vba code to it. The input box / vba works fine but having the ghost box ruins the page layout.enter image description here
presentation mode:
enter image description here

A: On the monitor that I was presenting on, I changed the display property scale settings from 100% to 125% and the issue resolved.


text:
Q: How do I tell if a TextView created in my SQLite database was clicked? I have a database with team names and team numbers(both stored as strings - the numbers sometimes have letters in them)
I want it so when you click the "Open" button, it'll bring up a popup that will have all of the teams' names and numbers, and if you click one, it will close the popup and set both editText's to the name & number.
                Dialog d = new Dialog(this);
            ScoutingFormData info = new ScoutingFormData(this);
            info.open();
            ScrollView scr = info.getData();
            info.close();
            d.addContentView(scr, null);
            d.show();

That's from the main program, when you click "Open", this happens. ScoutingFormData is my SQLite database, and here's getData:
    public ScrollView getData() {
    String[] columns=new String[]{KEY_ROWID,KEY_NAME,KEY_NUM};
    Cursor c = ourDatabase.query(DATABASE_TABLE, columns, null, null, null, null, null);
    ScrollView result=new ScrollView(null);
    int iID = c.getColumnIndex(KEY_ROWID);
    int iName = c.getColumnIndex(KEY_NAME);
    int iNum = c.getColumnIndex(KEY_NUM);
    LinearLayout vertlay = new LinearLayout(null);
    vertlay.setOrientation(LinearLayout.VERTICAL);
    for (c.moveToFirst(); !c.isAfterLast();c.moveToNext()){
        TextView tv=new TextView(null);
        tv.setText(c.getString(iNum)+"  "+c.getString(iName));
        vertlay.addView(tv);
    }
    result.addView(vertlay);
    return result;
}

So this builds the dialog, but how do I make it so the main program(the top code) will know when one of these TextViews have been clicked?
Side question: when making a View(like LinearLayout vertlay = new LinearLayout(null);), what context am I supposed to be using? I don't fully understand what a 'context' is, so I'm really at a loss of what to replace "null" with.

A:
How do I make it so the main program(the top code) will know when one of these TextViews have been clicked?

Simply make tv clickable and add an OnClickListener.

Side question: what context am I supposed to be using?

You hinted that getData() is in your database adapter class ScoutingFormData, save a reference to the Context passed to the Constructor and reuse it later:
private Context mContext;
public ScoutingFormData(Context context) {
    mContext = context;
}

All together:
TextView tv=new TextView(mContext);
tv.setClickable(true);
tv.setOnClickListener(new OnClickListener() {
    public void onClick(View view) {
        // Do something
    }
});


text:
Q: Consume all files in aws S3 where deleteAfterRead = false Is there a way to consume all the files in a S3 bucket without removing the files from S3 (in the S3, there are about 15,000 files)?
With the lag of noop parameter in aws-s3, the following configuration has a problem. And that problem is: it constantly retrieve the same 5 files over and over again.
    <endpoint id="fbPage" uri="aws-s3://bucket?amazonS3Client=#aws-credential&deleteAfterRead=false&maxMessagesPerPoll=5&prefix=dev/facebook/page"/>

    <route id="consumeS3FbPage">
        <from uri="ref:fbPage"/>
        <choice>
            <when>
                <simple>${header.CamelAwsS3ContentLength}  > 0</simple>
                <log message="Page File detected: ${header.CamelAwsS3Key}"/>
                <bean ref="dfaReportingRePull" method="s3toElasticFormat"/>

                <setHeader headerName="CamelHttpMethod">
                    <constant>POST</constant>
                </setHeader>
                <to uri="http://localhost:9200/fb_camel/page/_bulk"/>
                <log message="Success"/>
            </when>
            <when>
                <simple>${header.CamelAwsS3ContentLength} == 0</simple>
                <log message="Empty content, Probably the s3 key Folder itself: ${header.CamelAwsS3Key}"/>
            </when>
        </choice>
    </route>

The following log shows that the same file retrieved over and over again:
[Camel (camel-1) thread #0 - aws-s3://bucket] 21:26:46,904 INFO  consumeS3FbPage - Page File detected: dev/facebook/page/166866083481130/2014/05/31/9c9537e6-12a3-415e-aa3d-a450011008be.json
[Camel (camel-1) thread #0 - aws-s3://bucket] 21:26:46,993 INFO  consumeS3FbPage - Success
[Camel (camel-1) thread #0 - aws-s3://bucket] 21:26:46,994 INFO  consumeS3FbPage - Page File detected: dev/facebook/page/166866083481130/2014/06/01/97d85443-74af-4d64-9808-a4500110117a.json
[Camel (camel-1) thread #0 - aws-s3://bucket] 21:26:47,002 INFO  consumeS3FbPage - Success
[Camel (camel-1) thread #0 - aws-s3://bucket] 21:26:47,002 INFO  consumeS3FbPage - Page File detected: dev/facebook/page/166866083481130/2014/06/02/223410b2-b4ce-4b7f-8e47-a45001101254.json
[Camel (camel-1) thread #0 - aws-s3://bucket] 21:26:47,010 INFO  consumeS3FbPage - Success
[Camel (camel-1) thread #0 - aws-s3://bucket] 21:26:47,011 INFO  consumeS3FbPage - Page File detected: dev/facebook/page/166866083481130/2014/06/03/e5c21710-d764-453d-9736-a4500110132e.json
[Camel (camel-1) thread #0 - aws-s3://bucket] 21:26:47,019 INFO  consumeS3FbPage - Success
[Camel (camel-1) thread #0 - aws-s3://bucket] 21:26:47,019 INFO  consumeS3FbPage - Page File detected: dev/facebook/page/166866083481130/2014/06/04/851d3759-0c35-4679-838c-a4500110140b.json
[Camel (camel-1) thread #0 - aws-s3://bucket] 21:26:47,027 INFO  consumeS3FbPage - Success

[Camel (camel-1) thread #0 - aws-s3://bucket] 21:26:51,375 INFO  consumeS3FbPage - Page File detected: dev/facebook/page/166866083481130/2014/05/31/9c9537e6-12a3-415e-aa3d-a450011008be.json
[Camel (camel-1) thread #0 - aws-s3://bucket] 21:26:51,396 INFO  consumeS3FbPage - Success
[Camel (camel-1) thread #0 - aws-s3://bucket] 21:26:51,397 INFO  consumeS3FbPage - Page File detected: dev/facebook/page/166866083481130/2014/06/01/97d85443-74af-4d64-9808-a4500110117a.json
[Camel (camel-1) thread #0 - aws-s3://bucket] 21:26:51,409 INFO  consumeS3FbPage - Success
[Camel (camel-1) thread #0 - aws-s3://bucket] 21:26:51,410 INFO  consumeS3FbPage - Page File detected: dev/facebook/page/166866083481130/2014/06/02/223410b2-b4ce-4b7f-8e47-a45001101254.json
[Camel (camel-1) thread #0 - aws-s3://bucket] 21:26:51,419 INFO  consumeS3FbPage - Success
[Camel (camel-1) thread #0 - aws-s3://bucket] 21:26:51,420 INFO  consumeS3FbPage - Page File detected: dev/facebook/page/166866083481130/2014/06/03/e5c21710-d764-453d-9736-a4500110132e.json
[Camel (camel-1) thread #0 - aws-s3://bucket] 21:26:51,429 INFO  consumeS3FbPage - Success
[Camel (camel-1) thread #0 - aws-s3://bucket] 21:26:51,430 INFO  consumeS3FbPage - Page File detected: dev/facebook/page/166866083481130/2014/06/04/851d3759-0c35-4679-838c-a4500110140b.json
[Camel (camel-1) thread #0 - aws-s3://bucket] 21:26:51,439 INFO  consumeS3FbPage - Success

Even if i use Idempotent, it simply detect that all the 5 files are duplicate, and hence ignored.
I wonder if i do deleteAfterRead, and put it back will work?  No, when i look at the code in http://camel.465427.n5.nabble.com/camel-aws-s3-get-only-files-I-need-td5714095.html , it seems the code only will loop through the list on the current return list from aws s3.
When i look at the code ListObjectsRequest.java, i see there is a way to define a marker, which indicate on which was the last processed s# key. Is there a way to get this market set via Camel Spring DSL? [Updated]No.
After drilling down the code, i found the root cause on why this is the case. And Is trackable via this JiRA ticket: https://issues.apache.org/jira/browse/CAMEL-8431
note: the Camel version is 2.14.0

A: According to the Apache Committer  Willem Jiang, the fix will be part of release 2.14.3. Camel-8431


text:
Q: How do I hide an element defined as d-inline-block without making it it a block element? How do I hide an element defined as d-inline-block without making it it a block element? For example the bootstrap instruction for hiding an element on small devices is:
d-sm-none d-md-block

The problem is my element is already defined as d-inline-block on a medium device and the above instruction forces it into a block element on a medium device. I can't seem to hide an element on a small device without forcing it to be a block element on a medium device.