text:
Q: Mount CD disk on mac as if it was mounted on windows Okay, the title is not really clear enough, but I can't think how to phrase it better.
So, the problem is, I have starcraft (1 and Brood Wars) CD that I'd like to play on mac 10.8 using Wine.
However, there's a difference when I insert the CD under mac os and under windows. On windows, there is setup.exe file, for example. On mac, I get different files (incompatible (classic) Starcraft Installer.app, some other folders) that don't exist when I insert the CD on windows
So, in short - CD has different files when mounted on windows, and when mounted on mac. I want to mount the 'windows' version of the starcraft cd on mac. How?
I tried making a cd image under windows (daemon tools lite), but when I mounted iso file, guess what, same thing happened.

A: This happens because you mount CD in mixed format that has separate files for Mac and for PC. You need to edit image with utility like Ultraiso/Toast to make it Win only.
For old Mac games I suggest you to using virtual machine with Mac version that can handle classic applications instead of running Wine port. (Actually this is not my idea, it is Apple's decision. After removing Rosetta this is all that we have)


text:
Q: finding the value of $f(2001) $ if..... if $f (\frac{x}{y}) =\frac{f(x)}{y} $ and $f(2000)=1$ ; then what's the value of $f(2001)$.
I tried hard but can't figured out anything. please help me, how can I proceed?

A: Put $x=y \neq 0$ and we get
$$f(1)={f(x)\over x} \Rightarrow f(x)=f(1)x.$$
Since $f(2000)=1$, $f(1)=1/2000$. Therefore
$$f(2001)={2001\over2000}.$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: Showing $\mathbb{R}^2 \cong \mathbb{R}\times (-\frac{\pi}{2}, \frac{\pi}{2})$ using $\tan^{-1}$ just a quick, if not obvious, question here -- since the $\arctan$ function from $\mathbb{R}$ to $(-\pi /2, \pi /2)$ is a homeomorphism, does it naturally follow that the function $f: \mathbb{R}^2 \to \mathbb{R}\times (-\frac{\pi}{2}, \frac{\pi}{2})$ defined by $$ (x,y)\mapsto (x, \tan^{-1}y)$$ is a homeomorphism, because the first component remains constant and the second gets mapped by a homeomorphism? Or does it need to be further justified? I am aware of this post here, but I think my case is simpler and no further justification is needed. Thanks.

A: Everything in maths has to be justified. Especially when in doubt. Even the greatest minds made the "this is obvious" mistake. The most recent example that comes to my mind is Michael Atiyah's proof attempt of the Riemann hypothesis (2018 I think).
Anyway there's a general construction: if $f:X\to Y$ and $g:X'\to Y'$ are two continuous functions (between any topological spaces) then
$$f\times g:X\times X'\to Y\times Y'$$
$$f\times g(x,x')=\big(f(x), g(x')\big)$$
is a continuous function as well. Note that this is unrelated to "component wise continuity" that you've mentioned. It follows directly from the construction of product topology, i.e. it is enough to consider preimages of open sets of the form $U\times V$.
Now if both $f,g$ are homeomorphisms, then $f\times g$ is a homeomorphism as well with the explicit inverse $f^{-1}\times g^{-1}$.
And so if you already know that $arctan:\mathbb{R}\to(-\frac{\pi}{2},\frac{\pi}{2})$ is a homeomorphism (note the different symbol, since technically $tan$ is not invertible) then the rest follows from the simple observation that the identity $\mathbb{R}\to\mathbb{R}$, $x\mapsto x$ is a homeomorphism as well.


text:
Q: Background color of nav menu items UPDATE: For clarity, I added the yellow background color to see what "shows through" or is "transparent"
I can't seem to figure out how to keep the same styling in this nav bar, but make the background color white, not transparent. I'd also like to get rid of the transparency between each of the drop down menu items.
http://jsfiddle.net/trevoray/VZ7qD/20/
Any help would be greatly appreciated!
Trevor
 .nav {
border-radius:4px;
box-shadow: 0 3px 4px #8b8b8b;
 }

A: You need to set background-color in following CSS class
.nav > li
{
   background-color:white;
}

JS  Fiddle Example


text:
Q: Inlining infinite recursion Is this code defined behavior?
inline int a() { return 0 + a(); }

int main() { a(); }

If optimizations are enabled then Clang optimizes it out but GCC doesn't. So the code is not portable in practice. Does the C++ spec say anything about this?

A: As I discuss in this answer, regardless of the presence of the inline keyword, the behaviour of your code is certainly undefined since you call this function:

[C++11: 1.10/24]: The implementation may assume that any thread will eventually do one of the following:

*

*terminate,

*make a call to a library I/O function,

*access or modify a volatile object, or

*perform a synchronization operation or an atomic operation.

Clang is permitted to elide the entire thing, just as GCC is permitted to run it without inlining and reach a stack overflow. A compiler would also be free to attempt actual inlining, and it is even permitted to crash during compilation in such a case.
Crucially, there is no rule in the standard that makes the semantics for an infinite recursion differ just because a function is marked inline or even actually inlined ([C++11: 7.1.2]).
Of course, I reckon that if you were to never invoke this function, by the as-if rule a compiler can elide it entirely and then you have no problem.


text:
Q: How to simple overwrite showContextMenu on all columns of a grid? If I overwrite showContextMenu on a grid it only add additional menu to the pop up menu when I click on a grid but do not click on any column. One way is to overwrite showContextMenu on all columns in grid but this solution does not looks right. Is there some better way how to insertItem to showContextMenu on all columns of a grid?
I am using AX 2012.
Standard code works only if grid is clicked but not a single column of a grid.
int ret,ii;
int                     myMenu = 2;
PopupMenu               popupMenu = PopupMenu::create(_menuHandle);
FormListItem item;
;
deleteAttachment = popupMenu.insertItem('My menu');

ret = super(_menuHandle);

if(ret == myMenu)
{
    //My code
}

return ret;

A: You need to use method registerOverrideMethod.
You can test how it works as follows. E.g. you have a form with a grid (property Name = 'Grid', AutoDeclaration = 'Yes'), and there are a few StringEdit controls in that grid.
1) Create following method in your form:
public void formControlContext(FormStringControl _formStringControl)
{
    _formStringControl.context();
    info(strFmt(@"Overridden context of control '%1'", _formStringControl.name()));
}

2) Override method init in your form:
public void init()
{
    FormStringControl fsc;
    int controlNum;

    super();

    for (controlNum = 1; controlNum <= Grid.controlCount(); controlNum++)
    {
        fsc = Grid.controlNum(controlNum);
        fsc.registerOverrideMethod(methodStr(FormStringControl, context), identifierStr(formControlContext));
    }
}

You only need to modify method 'formControlContext' according to your needs.
P.S. I just noticed you need to override method showContextMenu anot not context. The idea is the same - use registerOverrideMethod. You can override any method this way.

A: I've never played with overwriting the ShowContextMenu, but I did just make a blog post about how to recursively loop over every form control that sounds like it might help you.
http://alexondax.blogspot.com/2014/05/how-to-use-recursion-to-loop-over-form.html
I'd imagine you could create some sort of handler and key/value thing if you're creative.


text:
Q: building new column with values depending on values above and below a specific row in r Consider any data frame in long format (each row is one measurement point)
            col1   col2
row.name11    A     0
row.name12    A     1
row.name13    A     0
row.name14    A     0
row.name15    B     0
row.name16    B     0
row.name17    B     1

col1 indicates the participants (here just 2 individuals, A and B). col2 indicates with a 1 that at this measurement point an event has occurred (i.e., it indicates a status change for example from single to married).
Now, I would like to create a variable that is 0 for all measurement points prior to the event and 1 for the measurement point where the event occurs and is also 1 for all following measurement points.
             col1   col2  col3
row.name11    A     0     0
row.name12    A     0     0
row.name13    A     1     1
row.name14    A     0     1
row.name15    A     0     1
row.name16    B     0     0
row.name17    B     0     0
row.name18    B     1     1

Do you have an advice how to do this? Thanks a lot!

A: You're looking for cumsum per group; here is a base R solution using ave
transform(df, col3 = ave(col2, col1, FUN = cumsum))
#           col1 col2 col3
#row.name11    A    0    0
#row.name12    A    1    1
#row.name13    A    0    1
#row.name14    A    0    1
#row.name15    B    0    0
#row.name16    B    0    0
#row.name17    B    1    1

Or the dplyr way
library(dplyr)
df %>% group_by(col2) %>% mutate(col3 = cumsum(col2))

Sample data
df <- read.table(text =
    "            col1   col2
row.name11    A     0
row.name12    A     1
row.name13    A     0
row.name14    A     0
row.name15    B     0
row.name16    B     0
row.name17    B     1  ", header = T)

A: data.table solution.
df[, cummax(col2), by = col1]

Where:
df <- data.frame(
  col1 = c("A", "A", "A", "A", "B", "B", "B"),
  col2 = c(0L, 1L, 0L, 0L, 0L, 0L, 1L)
)


text:
Q: SFMC Mobile Connect, Update Data Extension After sending a Response in SMS I need to update sales cloud and a data extension whenever a customer replied UNSUB to the sms that we send using Marketing Cloud.
This is how I get the response
IF Uppercase([MSG(0).NOUN(0)]) == "UNSUB" THEN
//Update DE
//Update Sales Cloud
ENDIF

BUt I can't seem to make it work.
I also tried this
Set @inbound = [MSG(0).NOUN(0)]

IF UpperCase(@inbound) == "UNSUB" THEN
//update sales cloud
//update de
ENDIF

But upon doing a subscriber preview I get a "An Unrecognized expression appears in a script block"
I already tested the script block in cloud pages for updating sales cloud and de and it's working so I guess it's not the issue orrrrrr you can't update both sales cloud and de in one transaction in regards to response sms.
Am I Missing something? any tip or suggestion will do. Thanks

A: Your outbound message from Content Builder can't contain this code - for your unsub process to work, you actually need to have 2 messages:

*

*A message from the Text Response template that's configured in Mobile Connect which needs to be set up on a new keyword (like UNSUB). Here you need to implement the code you had before or the code I posted below.

*Your initial text message from Content Builder will now have to use the Next Keyword option you need to set it to your new keyword (like UNUSB). This option will not appear in Content Builder, but will be displayed in Journey Builder in Advanced Options when you configure your SMS for sends.

This will work this way:
Your outbound message gets sent to the customer and the system will know thanks to the Next Keyword that it should treat all incoming text (probably for a limited time period like an hour) as if it was coming to your Text Response message configured on the Unsub keyword.
Any tests of the Text Response keyword can be done by just sending the keyword. You won't get any information about sender of the sms apart from the number, so you will need to do lookups based on this information to your data.

Old answer before the comments posted below
I think I had the same issue, as I never could get [MSG(0).NOUN(0)] to work while using a Text Response template, so I went with a workaround:
set @inbound = [MSG(0)]
set @verb = [MSG(0).VERB]
set @message = Trim(Replace(@inbound, @verb, ''))


text:
Q: Gradle - DexException: Multiple dex files define I know this question has been asked already but I cannot find a suitable answer for my problem among the available solutions. I hope you guys can help me out.
The exception tells that Multiple dex files defined and I tried several common ways to fix this problem. Unfortunately, this didn't help.
* What went wrong:
Execution failed for task ':app:transformClassesWithDexForDebug'.
> com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process 'command '/Library/Java/JavaVirtualMachines/jdk1.7.0_79.jdk/Contents/Home/bin/java'' finished with non-zero exit value 2

Cause: com.android.dex.DexException: Multiple dex files define Lnet/jcip/annotations/GuardedBy;
        UNEXPECTED TOP-LEVEL EXCEPTION:
        com.android.dex.DexException: Multiple dex files define Lnet/jcip/annotations/GuardedBy;
            at com.android.dx.merge.DexMerger.readSortableTypes(DexMerger.java:579)
            at com.android.dx.merge.DexMerger.getSortedTypes(DexMerger.java:535)
            at com.android.dx.merge.DexMerger.mergeClassDefs(DexMerger.java:517)
            at com.android.dx.merge.DexMerger.mergeDexes(DexMerger.java:164)
            at com.android.dx.merge.DexMerger.merge(DexMerger.java:188)
            at com.android.dx.command.dexer.Main.mergeLibraryDexBuffers(Main.java:504)
            at com.android.dx.command.dexer.Main.runMonoDex(Main.java:334)
            at com.android.dx.command.dexer.Main.run(Main.java:277)
            at com.android.dx.command.dexer.Main.main(Main.java:245)
            at com.android.dx.command.Main.main(Main.java:106)

*

*I tried to clean and rebuild the project.

*

*Build -> Clean Project

*Build -> Rebuild Project

*Then I tried to Invalidate Caches and Restart.

*

*File -> Invalidate Caches and Restart

*I also run this command to understand the duplications in dependencies:

./gradlew -q dependencies app:dependencies --configuration compile --stacktrace

and here is the output. As you can see there are no duplications.
+--- com.jakewharton.hugo:hugo-annotations:1.2.1
+--- com.google.code.findbugs:annotations:3.0.1
|    +--- net.jcip:jcip-annotations:1.0
|    \--- com.google.code.findbugs:jsr305:3.0.1
+--- com.michaelpardo:activeandroid:3.1.0-SNAPSHOT
+--- com.android.support:appcompat-v7:23.1.1
+--- com.crashlytics.sdk.android:crashlytics:2.3.0
|    +--- com.crashlytics.sdk.android:crashlytics-core:2.3.0
|    |    \--- io.fabric.sdk.android:fabric:1.3.1
|    +--- io.fabric.sdk.android:fabric:1.3.1
|    \--- com.crashlytics.sdk.android:beta:1.1.2
|         \--- io.fabric.sdk.android:fabric:1.2.0 -> 1.3.1
+--- com.greenhalolabs:emailautocompletetextview:1.3.0
+--- com.facebook.android:facebook-android-sdk:4.2.0
|    \--- com.parse.bolts:bolts-android:1.2.0
+--- com.android.support:cardview-v7:23.1.1
+--- com.jakewharton.hugo:hugo-runtime:1.2.0
|    +--- com.jakewharton.hugo:hugo-annotations:1.2.0 -> 1.2.1
|    \--- org.aspectj:aspectjrt:1.8.5
+--- joda-time:joda-time:2.0
+--- io.keen:keen-client-api-android:2.1.2
+--- com.googlecode.libphonenumber:libphonenumber:6.3.1
+--- net.simonvt.menudrawer:menudrawer:3.0.6
+--- com.squareup:otto:1.3.0
+--- com.google.android.gms:play-services-base:8.4.0
|    \--- com.google.android.gms:play-services-basement:8.4.0
+--- com.google.android.gms:play-services-analytics:8.4.0
+--- com.google.android.gms:play-services-gcm:8.4.0
|    \--- com.google.android.gms:play-services-measurement:8.4.0
+--- com.jeremyfeinstein.slidingmenu:library:1.3
+--- com.android.support:support-v4:23.1.1
|    \--- com.android.support:support-annotations:23.1.1
+--- com.jakewharton.timber:timber:3.1.0
+--- com.viewpagerindicator:library:2.4.1
+--- com.ouralabs:ouralabs:2.7.0
+--- com.android.support.test.espresso:espresso-idling-resource:2.2.1
+--- project :domain
|    \--- joda-time:joda-time:2.0
\--- project :remote
     +--- com.squareup.retrofit:retrofit:1.6.0
     |    \--- com.google.code.gson:gson:2.2.4
     +--- com.squareup.okhttp:okhttp:2.4.0
     |    \--- com.squareup.okio:okio:1.4.0
     \--- com.squareup.okhttp:okhttp-urlconnection:2.4.0

*I also read about the multiDexEnabled true but I'm sure that I didn't exceed the methods limit. This issue appeared instantly and without adding any libraries. I even can't assemble the older production versions of the code. They are in production and absolutely compilable.
Module's build.gradle:
dependencies {
    apply plugin: 'idea'

    compile "com.michaelpardo:activeandroid:${rootProject.ext.activeandroid}"
    compile(group: 'com.google.code.findbugs', name: 'annotations', version: "${rootProject.ext.findbugs}") {
        exclude(group: 'net.jcip', module: 'jcip-annotations')
    }
    compile(group: 'com.android.support', name: 'appcompat-v7', version: "${rootProject.ext.supportv4}") {
        exclude(group: 'com.android.support', module: 'support-v4')
    }
    compile(group: 'com.crashlytics.sdk.android', name: 'crashlytics', version: "${rootProject.ext.crashlytics}") {
        exclude(group: 'com.crashlytics.sdk.android', module: 'answers')
    }
    compile "com.greenhalolabs:emailautocompletetextview:${rootProject.ext.emailautocomplete}"
    compile(group: 'com.facebook.android', name: 'facebook-android-sdk', version: "${rootProject.ext.facebook}") {
        exclude(group: 'com.android.support', module: 'support-v4')
    }
    compile "com.android.support:cardview-v7:${rootProject.ext.supportv4}"
    compile "com.jakewharton.hugo:hugo-runtime:${rootProject.ext.hugo}"
    compile "joda-time:joda-time:${rootProject.ext.jodatime}"
    compile "io.keen:keen-client-api-android:${rootProject.ext.keen}"
    compile "com.googlecode.libphonenumber:libphonenumber:${rootProject.ext.libphonenumber}"
    compile "net.simonvt.menudrawer:menudrawer:${rootProject.ext.menudrawer}"
    compile "com.squareup:otto:${rootProject.ext.otto}"
    compile(group: 'com.google.android.gms', name: 'play-services-base', version: "${rootProject.ext.playservices}") {
        exclude(group: 'com.android.support', module: 'support-v4')
    }
    compile(group: 'com.google.android.gms', name: 'play-services-analytics', version: "${rootProject.ext.playservices}") {
        exclude(group: 'com.google.android.gms', module: 'play-services-basement')
    }
    compile(group: 'com.google.android.gms', name: 'play-services-gcm', version: "${rootProject.ext.playservices}") {
        exclude(group: 'com.google.android.gms', module: 'play-services-base')
        exclude(group: 'com.google.android.gms', module: 'play-services-basement')
    }
    compile "com.jeremyfeinstein.slidingmenu:library:${rootProject.ext.slidingmenu}"
    compile "com.android.support:support-v4:${rootProject.ext.supportv4}"
    compile "com.jakewharton.timber:timber:${rootProject.ext.timber}"
    compile "com.viewpagerindicator:library:${rootProject.ext.viewpagerindicator}"
    compile "com.ouralabs:ouralabs:${rootProject.ext.ouralabs}"
    compile "com.android.support.test.espresso:espresso-idling-resource:$rootProject.ext.espressoVersion"

    compile project(':domain')
    compile(project(':remote')) {
        exclude module: 'domain'
    }

    // Local Unit testing
    testCompile "junit:junit:$rootProject.ext.junit"
    testCompile "org.mockito:mockito-all:$rootProject.ext.mockitoVersion"
    testCompile "org.hamcrest:hamcrest-all:$rootProject.ext.hamcrestVersion"

    // Instrumentation Testing
    androidTestCompile "com.android.support.test.espresso:espresso-core:$rootProject.ext.espressoVersion"
    androidTestCompile "com.android.support.test.espresso:espresso-contrib:$rootProject.ext.espressoVersion"
    androidTestCompile "com.android.support.test.espresso:espresso-intents:$rootProject.ext.espressoVersion"
    androidTestCompile "com.android.support.test.uiautomator:uiautomator-v18:$rootProject.ext.uiautomator"
    androidTestCompile "com.android.support.test:runner:$rootProject.ext.runnerVersion"
    androidTestCompile "com.android.support.test:rules:$rootProject.ext.runnerVersion"
    androidTestCompile "org.mockito:mockito-core:$rootProject.ext.mockitoVersion"
    androidTestCompile "com.google.dexmaker:dexmaker:$rootProject.ext.dexmaker"
    androidTestCompile "com.google.dexmaker:dexmaker-mockito:$rootProject.ext.dexmaker"
}

UPDATE
I checked the project for GuardedBy. Is it looks like duplication?

A: Looks like hugo-annotations is included twice.  It's a dependency of hugo-runtime and added from somewhere else.  Try excluding it from the hugo-runtime
compile("com.jakewharton.hugo:hugo-runtime:${rootProject.ext.hugo}") {
    exclude(group: 'com.jakewharton.hugo' module: 'hugo-annotations')
}

Also since the error is due to the jsr library may need to exclude it from the findbugs dependency.
compile(group: 'com.google.code.findbugs', name: 'annotations', version: "${rootProject.ext.findbugs}") {
    exclude(group: 'net.jcip', module: 'jcip-annotations')
    exclude(group: 'com.google.code.findbugs', module: 'jsr305')
}

Edit:
There is a nuclear option if you really can't find it, but I'm not sure if it would break something else or is best practice.  This removes jsr305 from the classpath completely.
dependencies {
    ...
}
configurations.all*.exclude module: 'jsr305'

A: Check your jar files. You can expand the files in the project explorer.
If it has unnecessary path and BuildConfig, DexException should be occured.


text:
Q: Memory address of list elements in cpython I have heard that Python uses indirection to implement lists. That is, each element in a Python list is actually a pointer or reference to the place in memory where the actual element data (which could be an integer, string or any other data type) is stored. So when I created a list using
    a = ["xyz",2,"deer"]
    id(a[0])

I get 43449600. However when I do this:
        id(a[1])
        id(a[2])
yields 1403048416 and 43489824 respectively, instead of the expected 43449616 (or some multiple), and 43449632 (or some multiple) assuming memory pointers use the same chunk of memory !
Can someone explain what is wrong with my understanding of indirection (or with calling id()) ???
Thanks !

A: When you use id() you are pulling the object out of the array and getting the address of the object. You can see in the following example that the string "xyz" has the same address whether it is in an array or stored in a variable:
>>> a = ["xyz",2,"deer"]
>>> id(a[0])
43449600
>>> b = a[0]
>>> id(b)
43449600

It looks like you were expecting id() to give you the address of the pointers in the list, python does not provide any way to get this address but you can figure it out if you want.

*

*To start you would need to do id(a), which would give you the location of the list data structure, I'll use 4346000 as an example.

*The list data structure contains some standard python bookkeeping fields followed by the array of pointers that you are interested in. The size of the bookeeping fields depends on your system and python build but lets say it is 24 bytes.

*If you look past the bookkeeping at address 43460024 you would find your first pointer to 43449600

*Assuming 8 byte pointers the next element is at 43460032 and contains the pointer 1403048416

*The last at 43460040 you would find 43489824.

Of course there is no good reason you would need those addresses. You can find more details about the of a list by seeing the struct definitionin the cpython headers.


text:
Q: 2 Points, 3 points, 4 points Numerical Differentiation (forward) http://www.shodor.org/cserd/Resources/Algorithms/NumericalDifferentiation/
How did they get the three points
$$y'(x)=\frac{y(x+h)-y(x-h)}{2h}$$
to
$$y'(x)=\frac{-3y(x)+4y(x+h)-y(x+2h)}{2h}$$
Where does the $-3y + 4y$ come from? It does not make sense to me.

A: It arises as follows (based on the method discussed in the answer here:
$$ y(x+h) \approx y(x) + hy'(x) + \frac{h^2}{2}y''(x)$$
$$y(x+2h) \approx y(x) + 2hy'(x) + 2h^2y''(x)$$
To cancel the $y''$ terms, we take
$$4y(x+h) - y(x+2h) \approx 3y(x) + 2hy'(x)$$
The advantage of canceling these terms is that it gives us a better estimate -- the error here is now on the order of $h^3$, since we've canceled the $h^2$ terms.
Thus we get $$-3y(x) + 4y(x+h)-y(x+2h) \approx 2hy'(x)$$
So $$y'(x) \approx \frac{-3y(x) + 4y(x+h)-y(x+2h)}{2h}$$ with error on the order of $\frac{h^3}{h}=h^2$.


text:
Q: setContentView not working in my android code I have an error in my android code..my setContentView is not working.
my code is setContentView(R.layout.secondlayout);
Error is secondlayout cannot be resolved or it is not a feild.

A: Make sure that you placed the secondlayout.xml file inside res -> layout folder. Also make sure there is no error in this file. If the below line is there in your import statements, remove it.
import android.R;

A: Try this
import com.example.appname.R
Then, in eclipse go to project>clean , choose your project and press OK. Then wait until it is done. The clean operation regenrates R.


text:
Q: Forcing an Alignment to a Specific Part of the Page I know how to align these equations along the equal sign. What I want to do is put the equal sign anywhere on the page I want to, as though I was taking the aligned equations and shifting them left or right. Any ideas?
\documentclass{article}
\usepackage{mathtools}
\begin{document}
\begin{align*}
W&=\frac{4}{3}\cdot\rho_w\cdot L_s\int\displaylimits_1^3(3-x)xdx\\
W&=78480J\int\displaylimits_1^3(3x-x^2)dx\\
W&=261600J
\end{align*}
\end{document}

A: Adding an \hspace before or after the longest align field will shift the whole block 1/2 of the \hspace value.  So, in this MWE, after showing the generic align, I add a 2in shift first to the left and then to the right of the longest element.  These should result in a net 1" shift of the block.
\documentclass{article}
\usepackage{mathtools}
\begin{document}
\begin{align*}
W&=\frac{4}{3}\cdot\rho_w\cdot L_s\int\displaylimits_1^3(3-x)xdx\\
W&=78480J\int\displaylimits_1^3(3x-x^2)dx\\
W&=261600J
\end{align*}
\begin{align*}
\hspace{2in}W&=\frac{4}{3}\cdot\rho_w\cdot L_s\int\displaylimits_1^3(3-x)xdx\\
W&=78480J\int\displaylimits_1^3(3x-x^2)dx\\
W&=261600J
\end{align*}
\begin{align*}
W&=\frac{4}{3}\cdot\rho_w\cdot L_s\int\displaylimits_1^3(3-x)xdx\hspace{2in}\\
W&=78480J\int\displaylimits_1^3(3x-x^2)dx\\
W&=261600J
\end{align*}

\end{document}

As seen in the result, enhanced with the PDF measuring tool, the left/right shifts are as predicted.

A: Here is a solution useing parbox
\documentclass{article}
\usepackage{mathtools}
\begin{document}\begin{align*}
W&=\frac{4}{3}\cdot\rho_w\cdot L_s\int\displaylimits_1^3(3-x)xdx\\
W&=78480J\int\displaylimits_1^3(3x-x^2)dx\\
W&=261600J
\end{align*}

\hspace{5cm}\parbox{\textwidth}{%
\begin{align*}
W&=\frac{4}{3}\cdot\rho_w\cdot L_s\int\displaylimits_1^3(3-x)xdx\\
W&=78480J\int\displaylimits_1^3(3x-x^2)dx\\
W&=261600J
\end{align*}}

\hspace{-5cm}\parbox{\textwidth}{%
\begin{align*}
W&=\frac{4}{3}\cdot\rho_w\cdot L_s\int\displaylimits_1^3(3-x)xdx\\
W&=78480J\int\displaylimits_1^3(3x-x^2)dx\\
W&=261600J
\end{align*}}
\end{document}


text:
Q: How to template sql with python and deal with sql composition problem? I need to format an SQL query, and it looks like this:
s += " t{}.{} = '{}' and".format(t_c, filter_c, filter_value)
but when the filter_value is something like m's it will result in
psycopg2.errors.SyntaxError: syntax error
if I use the double quote, it will say there's no such column
Any way I can resolve this problem, please?

A: Caused by injection vulnerability. Use parameters for filter_value and let the database API handle it.
If the table/schema names are coming from user input, whitelist those too. Parameters aren't possible for table names).

A: try this:
def format_value( string ):
    if '\'' in string:
        k           = string.split('\'')
        string_list = list(map(lambda x: '\'' + x+ '\'', k ))
        return  ''.join(string_list )
    else:
        return string

then
filter_value = format_value(filter_value)

before you pass filter_value to your query


text:
Q: Flutter Firebase Integration Build failed with :app:processDebugManifest I just started flutter with firebase integration.
I am getting errors when I run the project after the basic steps, which is guided by firebase.
My app build.gradle
buildscript {
    ext.kotlin_version = '1.2.71'
    repositories {
        google()
        jcenter()
    }

    dependencies {
        classpath 'com.android.tools.build:gradle:3.2.1'
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath 'com.google.gms:google-services:4.0.1'
    }
}

allprojects {
    repositories {
        google()
        jcenter()
    }
}

rootProject.buildDir = '../build'
subprojects {
    project.buildDir = "${rootProject.buildDir}/${project.name}"
}
subprojects {
    project.evaluationDependsOn(':app')
}

task clean(type: Delete) {
    delete rootProject.buildDir
}

My android build.gradle
def localProperties = new Properties()
def localPropertiesFile = rootProject.file('local.properties')
if (localPropertiesFile.exists()) {
    localPropertiesFile.withReader('UTF-8') { reader ->
        localProperties.load(reader)
    }
}

def flutterRoot = localProperties.getProperty('flutter.sdk')
if (flutterRoot == null) {
    throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")
}

def flutterVersionCode = localProperties.getProperty('flutter.versionCode')
if (flutterVersionCode == null) {
    flutterVersionCode = '1'
}

def flutterVersionName = localProperties.getProperty('flutter.versionName')
if (flutterVersionName == null) {
    flutterVersionName = '1.0'
}

apply plugin: 'com.android.application'
apply plugin: 'kotlin-android'
apply from: "$flutterRoot/packages/flutter_tools/gradle/flutter.gradle"

android {
    compileSdkVersion 28

    sourceSets {
        main.java.srcDirs += 'src/main/kotlin'
    }

    lintOptions {
        disable 'InvalidPackage'
    }

    defaultConfig {
        // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html).
        applicationId "com.rental.asp.rental_actual"
        minSdkVersion 21
        targetSdkVersion 28
        versionCode flutterVersionCode.toInteger()
        versionName flutterVersionName
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }

    buildTypes {
        release {
            // TODO: Add your own signing config for the release build.
            // Signing with the debug keys for now, so `flutter run --release` works.
            signingConfig signingConfigs.debug
        }
    }
}

flutter {
    source '../..'
}

dependencies {
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'com.android.support.test:runner:1.0.2'
    androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
    implementation 'com.google.firebase:firebase-analytics:17.2.0'
}
apply plugin: 'com.google.gms.google-services'

When I build this is the output
21:30:55.498 1 info flutter.tools Launching lib\main.dart on SM N975U1 in debug mode...
21:30:55.505 2 info flutter.tools Initializing gradle...
21:30:56.251 3 info flutter.tools Resolving dependencies...
21:31:02.480 4 info flutter.tools Running Gradle task 'assembleDebug'...
21:31:05.312 5 info flutter.tools registerResGeneratingTask is deprecated, use registerGeneratedResFolders(FileCollection)
21:31:05.313 6 info flutter.tools registerResGeneratingTask is deprecated, use registerGeneratedResFolders(FileCollection)
21:31:05.313 7 info flutter.tools registerResGeneratingTask is deprecated, use registerGeneratedResFolders(FileCollection)
21:31:12.464 8 info flutter.tools H:\Rental\rental\rental_actual\android\app\src\debug\AndroidManifest.xml:22:18-91 Error:
21:31:12.464 9 info flutter.tools   Attribute application@appComponentFactory value=(android.support.v4.app.CoreComponentFactory) from [com.android.support:support-compat:28.0.0] AndroidManifest.xml:22:18-91
21:31:12.464 10 info flutter.tools  is also present at [androidx.core:core:1.0.0] AndroidManifest.xml:22:18-86 value=(androidx.core.app.CoreComponentFactory).
21:31:12.464 11 info flutter.tools
21:31:12.464 12 info flutter.tools  Suggestion: add 'tools:replace="android:appComponentFactory"' to <application> element at AndroidManifest.xml:9:5-32:19 to override.
21:31:12.464 13 info flutter.tools
21:31:12.464 14 info flutter.tools FAILURE: Build failed with an exception.
21:31:12.464 15 info flutter.tools
21:31:12.464 16 info flutter.tools * What went wrong:
21:31:12.465 17 info flutter.tools Execution failed for task ':app:processDebugManifest'.
21:31:12.465 18 info flutter.tools > Manifest merger failed : Attribute application@appComponentFactory value=(android.support.v4.app.CoreComponentFactory) from [com.android.support:support-compat:28.0.0] AndroidManifest.xml:22:18-91
21:31:12.465 19 info flutter.tools      is also present at [androidx.core:core:1.0.0] AndroidManifest.xml:22:18-86 value=(androidx.core.app.CoreComponentFactory).
21:31:12.465 20 info flutter.tools      Suggestion: add 'tools:replace="android:appComponentFactory"' to <application> element at AndroidManifest.xml:9:5-32:19 to override.
21:31:12.465 21 info flutter.tools
21:31:12.465 22 info flutter.tools * Try:
21:31:12.465 23 info flutter.tools Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output. Run with --scan to get full insights.
21:31:12.465 24 info flutter.tools
21:31:12.466 25 info flutter.tools * Get more help at https://help.gradle.org
21:31:12.466 26 info flutter.tools
21:31:12.466 27 info flutter.tools BUILD FAILED in 9s

Also in my android/build.gradle the first line
def localProperties = new Properties()

&
throw new GradleException("Flutter SDK not found. Define location with flutter.sdk in the local.properties file.")

Getting 'Cannot resolve symbol'

A: Just add AndroidX in your project by adding the following two lines in your android package's "gradle.properties" file.
android.useAndroidX=true
android.enableJetifier=true

Done.
Also, i will suggest you to use kotlin version above 1.3 like 1.3.31 etc. It's your choice.


text:
Q: Optimizing Xcode Build time when using Firebase library Since I'm building using FireStore and few other Firebase library, the build time has doubled down. I'm wondering if there is a way to avoid compiling it every time I clean & build my project.

A: Don't clean & build, just build. ;)
Disclaimer: Before doing releases, a clean build is preferred, of course.

UPDATE with better answer: Use cocoapods-binary plugin.
https://guides.cocoapods.org/plugins/pre-compiling-dependencies.html

One solution for this is to not give Xcode the chance to re-compile code. CocoaPods Binary will pre-compile your Pods during pod install, and then add the binary assets (e.g. .framework files) into the generated Xcode projects instead of the source code.

Like this.
plugin 'cocoapods-binary'
use_frameworks!

target "MyApp" do
  pod "NeededPod", :binary => true
end

A: For anyone stumbling on this post, we finally found a way to optimize Firestore build time while still using cocoapods.
We are using THIS REPO
It's a precompiled Firestore iOS SDK xcframework files extracted from the Firebase iOS SDK repository release downloads, tagged by Firebase iOS SDK version and presented as a consumable podspec.
Why
Currently the Firestore iOS SDK depends on some 500k lines of mostly C++, which when compiling as part of your Xcode build takes a long time - even more so in CI environments.


text:
Q: How to copy data from txt file and paste to XLSX as value with Python? How to copy data from txt file and paste to XLSX as value with Python?
(txt)File: simple.txt which contains date,name,qty,order id
I need the data from txt and copy paste to xlsx as VALUE.
How it's possible it? Which package could handle this process with Python?
openpyxl?Panda? Could you please give an example code?
My code which not suitable for the paste and save as values:
import csv
import openpyxl
input_file = 'C:\Users\mike\Documents\rep\LX02.txt'
output_file = 'C:\Users\mike\Documents\rep\LX02.xlsx'
wb = openpyxl.Workbook()
ws = wb.worksheets[0]
with open(input_file, 'r') as data:
reader = csv.reader(data, delimiter='\t')

for row in reader:

    ws.append(row)

wb.save(output_file)

A: In pandas, with pandas.read_csv and pandas.DataFrame.to_excel combined, you can store the content of a comma delimited .txt file in an .xlsx spreedsheet by running the code below :
#pip install pandas
import pandas as pd

input_file = r'C:\Users\mbalog\Documents\FGI\LX02.txt'
output_file = r'C:\Users\mbalog\Documents\FGI\LX02.xlsx'

pd.read_csv(input_file).to_excel(output_file, index=False)


text:
Q: Generate copies of a code with just one line different in all of them I need to make a copy of a large code and replace just a name in the code. I have to do this multiple times with a list of names.
eg:
I have the names:
Jay
Joy
Jane
Juda

and I have an example code/text:
print("Hi");
Print("Hello")
print("Jay"); # here

I want the output to be like:
print("Hi");
Print("Hello")
print("Jay"); # here

print("Hi");
Print("Hello")
print("Joy"); # here

print("Hi");
Print("Hello")
print("Jane"); # here

ie, just changing one part of the code but have to repeat all the other steps.

A: awk '{printf("print(\"Hi\");\nprint(\"Hello\");\nprint(\"%s\"); # here\n\n",$0)}' input_file.txt

UPDATE: as I understand your comment, you need a template
template-file:
bla
bla bla
bla %NAME% bla
bla

script:
IFS=$'\n'
for i in `cat names`; do
sed "s/%NAME%/$i/" template-file
done


text:
Q: Unable to locate PolarAxesOrigin at its correct place I found sometimes I cannot locate PolarAxesOrigin at its correct place which I defined.
For example,
PolarPlot[Sqrt[n], {n, 1, 100}, PolarAxes -> True, PolarTicks -> {"Degrees", {#, #} & /@ Range[0, 15]}, PolarAxesOrigin -> {Pi/6, 13}]

returns

.
Obviously, the shown origin is placed at $r=15$, not at $r=13$.
Why does it happen? Could I avoid getting the wrong origin?
Update
Sorry. I found there is a question which refers to this problem as a bug. However, Has Wolfram neglected the bug for eight years? If so, should I make axes by hand?
Remedy for the problem
Although you can see a great answer below, but I add my remedy including some corrections and some improvements.
ClearAll[fixPolarAxesCT]

fixPolarAxesCT[plot_,
  radius_] := (Module[{scale =
     radius/Max@Cases[plot, Circle[_, r_, _] :> r, All]},
   MapAt[
    (*remove unwanted PolarGridLines*)
    ReplaceAll[#, Circle[{0, 0}, r_ /; r > radius, {0, 2 Pi}] -> {}] &,
    MapAt[
     ReplaceAll[#, {Text[i_,
          Offset[a_, Scaled[b_, c_ /; Abs[c[[1]]] > radius]],
          k___] -> {} (*remove unwanted radial tick labels*),
        Style[Line[{Scaled[_, a_], _Scaled}] /; Norm[a] > radius,
          Except[{}]] -> {} (*remove unwanted radial ticks*),
        Line[{{0, 0}, a : {_, _}}] :>
         Line[{{0, 0}, scale a}] (*crop the radial axis*)}] &,
     (MapAt[
       ReplaceAll[#, {Circle[c_, r_, a_] :>
           Circle[c, radius, a] (*change angular axis radius*),
          Text[t_, Offset[a_, b : Except[_Scaled]], c___] :>
           Text[t, Offset[a, scale b],
            c] (*move angular labels towards new axis*),
          Style[Line[x_], dir_] :>
           Style[Line[
             x /. {{{a_, b_}, Scaled[c_, d_]} :> {scale {a, b},
                 Scaled[c, scale d]} (*relocate minor angular ticks*),

               Scaled[a_, b_] :>
                Scaled[a, scale b] (*relocate major angular ticks*)}],
             dir] }] &, plot
       , {1, 7, 1}])
     , {1, 7, 2}]
    , {1, 1, 2}]]
  )

You can use this function as
plot = PolarPlot[Sqrt[n], {n, 1, 100}, PolarAxes -> True, PolarTicks -> {"Degrees", {#, #} & /@ Range[0, 15]}, PolarAxesOrigin -> {Pi/6, 13}];

fixedplot = fixPolarAxesCT[plot, 13]

(an example).
Note that the fixedPolarAxesCT is compatible with both PolarPlot and ListPolarPlot (the original answer is also compathible with them.).
Furthermore, this can also be applied when you are using PolarGridLines, customized PolarTicks, and customized TicksStyle. Finally, thanks again to kglr!!

A: This seems to be a consequence of excessive smarts in polar axes code that  seems to be picking a "nice" number for radial axis range overriding user specifications.
A work-around is to post-process PolarPlot output to modify the positions of angular axis, angular ticks and tick labels and to remove the unwanted radial ticks/labels:
ClearAll[fixPolarAxes]

fixPolarAxes[radius_] :=
  Module[{maxradius = Max @ Cases[#, Circle[_, r_, _] :> r, All], scale},
   scale = radius / maxradius;
   ReplaceAll[
    {Circle[c_, maxradius, a_] :> Circle[c, radius, a] (* change angular axis radius *),
     Circle[_, r_/; r > radius,_] -> {} (* remove unwanted radial gridlines *),
     Text[_, Offset[_, Scaled[_, a_ /; Norm[a] > radius]], ___] ->
           {} (* remove unwanted radial tick labels *),
     Style[Line[{Scaled[_, a_], _Scaled}] /; Norm[a] > radius, Except[{}]] ->
           {} (* remove unwanted radial ticks *),
     Text[t_, Offset[a_, b : Except[_Scaled]], c___] :>
          Text[t, Offset[a, scale b], c] (* move angular labels towards new axis*),
     Line[{{0, 0}, a : {_, _}}] :>
       Line[{{0, 0}, scale a}] (* crop the radial axis and angular gridlines *),
     Style[Line[x_], {}] :>
      {Line[x /. { {{a_, b_}, Scaled[c_, d_]} :>
          {scale {a, b}, Scaled[c, scale d]} (* relocate minor angular ticks *),
      Scaled[a_, b_] :> Scaled[a, scale b] (* relocate major angular ticks *)}]}}] @ #]&

Examples:
pp = PolarPlot[Sqrt[n], {n, 1, 100},
    PolarAxes -> True,
    PolarTicks -> {"Degrees", {#, #} & /@ Range[0, 15]},
    PolarAxesOrigin -> {Pi/6, 13},
    PlotRangeClipping -> False,
    ImageSize -> Large]

fixPolarAxes[13] @ pp

fixPolarAxes[11] @ pp

An example with polar gridlines and custom polar ticks:
SeedRandom[7];

pp2 = PolarPlot[Sqrt[n], {n, 1, 100},
    PolarAxes -> True,
    PolarTicks -> {Sort[RandomSample[Subdivide[0, 360, 36], 20]] Degree,
      {#, #} & /@ Sort[ RandomSample[Range[0, 24], 10]]},
    PolarAxesOrigin -> {Pi/6, 13},
    PlotRangeClipping -> False,
    PolarGridLines -> Automatic,
    GridLinesStyle -> Directive[Thick, Red],
    ImageSize -> Large]

fixPolarAxes[13] @ pp2

fixPolarAxes[11] @ pp2


text:
Q: exception in file processing Suppose we need to process 100 files(one by one) and if we get an exception while reading one of the file, the process should leave that file(and put contents in log) and start processing the next file:
What I think:
for (File f: listOfFiles) {
    try {
        //implementation of processing each file
    } catch (Exception e) {
        //logging
    }
}

Am I correct?

A: Yes, should work. But, you may also want to be more specific in catching Exception.

A: Yes! You are correct and put some code in finally block. I mean closing any stream or closing file itself. Similar to below pseudo-code.
for(File f : listOfFiles){
   try{
      //implementation of processing each file
   }catch(Exception e){
      logException(e);
   }finally{
      //close stream or file.
   }
}


text:
Q: anomalous behaviours of jQuery ajax function's success I wrote following code :
$.ajax({ url: link + "?" + Math.random(), success: function (response) {
            alert(response);
}});

Although the alert gives me what responseText should give ideally when I use from glassfish. But when I loaded exactly same file in VS, to my horror, I got [Object] as the output of alert.
What's wrong?
By the way, what I return is XML not JSON.

A: jquery will by default perform an "intelligent guess" on your data type and pass the success function the formatted response. So if, for example, your url supplies json data the success function will be handed the parsed json object, not just a string. So alert({...}) will show [object Object]
If you want just the textual output, use:
$.ajax({
   url: link + "?" + Math.random(),
   success: function (response) { alert(response); },
   dataType: 'text'
});

A: I would suspect that in the second case JSON is being returned you will need to do:
$.ajax({ url: link + "?" + Math.random(), success: function (response) {
            $(response).each(function() {
/*do something with data, firefox with firebug allows you to do console.log($this) which will show you the data in a window below the browser, Chrome also has a similar feature, alerting in an iterator is never a good idea.*/
})
}});


text:
Q: How can I putting dynamically string into array using C J have below a code which display the name (this is char[]/string) of directories or files in given directory. I want to put this names dynamically to array. In print table1 displays correct the values(name of directories or files) which are iterate. But in other print table3 displays incorrect values. Could anybody help me with that? Is this problem with memory or something else?
char** do_ls( char dirname[] ){
DIR *dir_ptr;
struct dirent *direntp;
char **strArray;
int count=0;
strArray = (char**)malloc(1 * sizeof(char*));
strArray[0] = NULL;

if ( ( dir_ptr = opendir( dirname ) ) == NULL )
    fprintf(stderr,"ls1: cannot open %s\n", dirname);
else {
    while ( ( direntp = readdir( dir_ptr ) ) != NULL ) {
        if(strchr(direntp->d_name, '.') == NULL) {

            strArray[count] = (char*)direntp->d_name;
            printf("\nTable1: %s \n", strArray[count]);
            count++;
            strArray = (char **)realloc(strArray, sizeof(char *) * (count + 1));
            printf("\nCount: %d \n", count);

        }
    }
    strArray[count] = NULL;  /* Terminate the array */
printf("\nTable3: %s \n", strArray[0]);
printf("\nTable3: %s \n", strArray[1]);
printf("\nTable3: %s \n", strArray[2]);
printf("\nTable4: %s \n", strArray[strlen(strArray)-1]);
printf("\nIndex: %d \n", strlen(strArray)-1);

    closedir(dir_ptr);
}

return strArray;

}

A: Here is an alternate method to how to grow a dynamically allocated array:
char **do_ls(
      const char *dirname
      )
   {
   DIR *dir_ptr = NULL;      /* A handle to iterate the specified directory. */
   int tmp;                  /* Used to iterate the array when printing it out. */

   char **strArray = NULL;   /* Array of string pointers for directory names. */
   int count=0;              /* Number of elements in the array */

   /* Open the specified directory. */
   dir_ptr = opendir(dirname);
   if(NULL == dir_ptr)
      {
      fprintf(stderr,"ls1: cannot open %s\n", dirname);
      goto CLEANUP;
      }

   /* Scan directory entries. */
   while((direntp = readdir( dir_ptr )))
      {
      struct dirent *direntp;   /* Pointer to a directory entry. */
      char **tmp;               /* Used to safely grow the array. */

      /* Ignore current & parent directories, and all files with an extension. */
      if(strchr(direntp->d_name, '.'))
         continue;

      /* Increase the size of the array. */
     tmp=realloc(strArray, count+1 * sizeof(*strArray));
     if(NULL == tmp)
         {
         fprintf(stderr, "realloc() failed.\n");
         goto CLEANUP;
         }
      strArray = tmp;

      /* Store directory entry name into new array slot. */
      strArray[count] = strdup(direntp->d_name);
      count++;
      }

   /* Print array entries. */
   for(tmp=0; tmp < count; ++tmp)
      printf("Slot #%d: %s\n", tmp, strArray[tmp]);

   /* Add a last "termination" entry to the array. */
   tmp=realloc(strArray, count+1 * sizeof(*strArray));
   if(NULL == tmp)
      {
      fprintf(stderr, "realloc() failed.\n");
      goto CLEANUP;
      }
   strArray = tmp;
   strArray[count] = NULL;

CLEANUP:

   if(dir_ptr)
      closedir(dir_ptr);

   return(strArray);
   }

A: The pointer returned by readdir() points to a statically allocated structure, so you should not retain references to it after making subsequent calls, since every time you call readdir() again it'll just get overwritten.
You'll want to change:
strArray[count] = (char*)direntp->d_name;

to something like:
strArray[count] = strdup(direntp->d_name);

to make a copy of what it points to, rather than just trying to retain the pointer. Don't forget to call free() when you're done with it, since strdup() malloc()s the memory for you.
An alternative is to use readdir_r() which uses a caller-allocated structure, but for what you're doing this is likely not necessary, since you just want to store the name.
As always, don't cast the return from malloc() in C.
strlen(strArray) is wrong, since strArray is not a string, and strlen() only works for strings. You already maintain a count variable to keep track of the length of it, so just use that. This whole block:
printf("\nTable3: %s \n", strArray[0]);
printf("\nTable3: %s \n", strArray[1]);
printf("\nTable3: %s \n", strArray[2]);
printf("\nTable4: %s \n", strArray[strlen(strArray)-1]);

is an obvious candidate for a loop, and can be replaced by:
for ( int s = 0; s < count; ++s ) {
    printf("\nTable3: %s \n", strArray[s]);
}

or:
int s = 0;
while ( strArray[s] ) {
    printf("\nTable3: %s \n", strArray[s++]);
}

since you set the last element to NULL.
Here's a fixed version:
#define _POSIX_C_SOURCE 200809L

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <dirent.h>

char ** do_ls(const char * const dirname) {
    DIR * dir_ptr;
    struct dirent * direntp;
    char ** strArray;
    size_t count = 0;

    if ( (strArray = malloc(sizeof(*strArray))) == NULL ) {
        fprintf(stderr, "ls1: couldn't allocate memory");
        exit(EXIT_FAILURE);
    }
    strArray[0] = NULL;

    if ( (dir_ptr = opendir(dirname)) == NULL ) {
        fprintf(stderr, "ls1: cannot open %s\n", dirname);
        exit(EXIT_FAILURE);
    }
    else {
        while ( (direntp = readdir(dir_ptr)) != NULL ) {
            if ( strchr(direntp->d_name, '.' ) == NULL ) {
                strArray[count] = strdup(direntp->d_name);
                if ( strArray[count] == NULL ) {
                    fprintf(stderr, "ls1: couldn't allocate memory");
                    exit(EXIT_FAILURE);
                }

                printf("Table1: %s\n", strArray[count++]);
                printf("Count: %zu\n\n", count);

                strArray = realloc(strArray, sizeof(*strArray) * (count + 1));
                if ( strArray == NULL ) {
                    fprintf(stderr, "ls1: couldn't reallocate memory");
                    exit(EXIT_FAILURE);
                }

                strArray[count] = NULL;
            }
        }

        for ( size_t s = 0; s < count; ++s ) {
            printf("Table3: %s\n", strArray[s]);
        }
        printf("Number of elements: %zu\n\n", count);

        closedir(dir_ptr);
    }

    return strArray;
}

void free_ls_array(char ** strArray) {
    size_t s = 0;
    while ( strArray[s] ) {
        free(strArray[s++]);
    }
    free(strArray);
}

int main(void) {
    char ** strArray = do_ls("./");
    free_ls_array(strArray);
    return 0;
}

and outputs:
paul@MacBook:~/Documents/src/scratch/dir_test$ ls
README      ls1         ls1.c       nothing.txt
paul@MacBook:~/Documents/src/scratch/dir_test$ ./ls1
Table1: ls1
Count: 1

Table1: README
Count: 2

Table3: ls1
Table3: README
Number of elements: 2

paul@MacBook:~/Documents/src/scratch/dir_test$


text:
Q: The 'return' keyword is not working correctly in PHP I am using this piece of function to check if a file exists. If the file exists then I am changing its name:
function checkFileExist($fileName, $z, $ext, $folderWIthFileName){
    $tmpNam = "";
    if (file_exists($fileName . "_" . $z . "." . $ext)) {
        $z = $z + 1;
        checkFileExist($fileName, $z, $ext, $folderWIthFileName);
    }
    else {
        $tmpNam = $fileName . "_" . $z;
        echo "in else
 " . $fileName . "_" . $z . "
";
    }
    return $tmpNam;
}

And calling this function like
$definename = checkFileExist($folderWIthFileName . "/" . $InvId, $z, $ext, $folderWIthFileName);
echo "new name is " . $definename;

But this gives me output like this:
in else
444_2015-10-27/444_3
new name is

You can see return is not working correctly. What am I doing wrong here?

A: You should use return checkFileExist($fileName, $z, $ext, $folderWIthFileName); in the first block to return back a value from the recursively made calls. Use this clean version:
function checkFileExist($fileName, $z, $ext, $folderWIthFileName) {
    if (file_exists($fileName . "_" . $z . "." . $ext)) {
        return checkFileExist($fileName, $z+1, $ext, $folderWIthFileName);
    }
    return $fileName . "_" . $z;
}


text:
Q: Java datatype that is symmetric pair? I would like to pre-calculate a similarity score of a group of elements.
So if the group has three elements, A, B, C, then there are scores for similarity:
A,B: score1
A,C: score2
B,C: score3
C,B: score3
The relationship is symmetric, so f(B,A) is the same as f(A,B).  I would like to do something like: HashMap<Pair<>, Score>, but so far of the tuple classes I have looked at, f(B,A).equals(f(A,B)) does not hold.
Is there a Pair tuples implementation where Pair(A,B) == Pair(B,A)?

A: As suggested, if you really wanted to you could use a Set, but much nicer to write your own, especially if you need to preserve the order of your two elements.
public class Eg {

    public static void main(String[] args) {
        Set<String> ab = new LinkedHashSet<String>(List.of("A", "B"));
        Set<String> ba = new LinkedHashSet<String>(List.of("B", "A"));

        System.out.println(ab.equals(ba));
        System.out.println(ba.equals(ab));
        System.out.println(ab.stream().findFirst().get());
        System.out.println(ab.stream().skip(1).findFirst().get());
        System.out.println(ba.stream().findFirst().get());
        System.out.println(ba.stream().skip(1).findFirst().get());

        MyTuple<String> mab = new MyTuple<>("A", "B");
        MyTuple<String> mba = new MyTuple<>("B", "A");
        System.out.println(mab.equals(mba));
        System.out.println(mba.equals(mab));
    }

    public record MyTuple<T>(T first, T second) {
        @Override
        public boolean equals(Object o) {
            return o instanceof MyTuple<?> other &&
                    ((other.first.equals(first) && other.second.equals(second)) ||
                            (other.first.equals(second) && other.second.equals(first)));
        }

        @Override
        public int hashCode() {
            return Objects.hash(first, second);
        }
    }
}


text:
Q: Concatenating trigrams from a tuple in a dictionary Ok, so I am working on an assignment for a course in my linguistics BA where we are working with python to process texts. This is what I needed to do:

Create a script that counts trigrams frequencies

*

*Do not add dummy tokens

*Lowercase every token and concatenate trigram units with an
  underscore

*What are the missing values in the output box?

*Bonus: Try to solve the task by storing trigrams a tuples in the
  dictionary

This is how I solved most if it:
lyrics = "Do you remember 21st night of September ? Love was changing the mind of pretenders While chasing the clouds away Our hearts were ringing In the key that our souls were singing As we danced in the night Remember how the stars stole the night away yeah yeah yeah Hey hey hey Ba de ya say do you remember ? Ba de ya dancing in September Ba de ya never was a cloudy day Ba duda ba duda ba duda badu Ba duda badu ba duda badu Ba duda badu ba duda yeah My thoughts are with you Holding hands with your heart to see you Only blue talk and love Remember how we knew love was here to stay Now December Found the love we shared in September Only blue talk and love Remember the true love we share today Hey hey hey Ba de ya say do you remember ? Ba de ya dancing in September Ba de ya never was a cloudy day There was a Ba de ya say do you remember ? Ba de ya dancing in September Ba de ya golden dreams were shiny days Now our bell was ringing aha Our souls was singing Do you remember every cloudy day yau There was a Ba de ya say do you remember ? Ba de ya dancing in September Ba de ya never was a cloudy day There was a Ba de ya say do you remember ? Ba de ya dancing in September Ba de ya golden dreams were shiny days Ba de ya de ya de ya Ba de ya de ya de ya Ba de ya de ya de ya de ya Ba de ya de ya de ya Ba de ya de ya de ya Ba de ya de ya de ya de ya"

lyric = lyrics.lower()
listText = lyric.split(" ")
freq = {}

while len(listText) > 2:
    trigram = (listText[0], listText[1], listText[2])
    if trigram in freq.keys():
        freq[trigram] += 1
    else:
        freq[trigram] = 1
    listText.pop(0)

sorted_data = sorted(freq.items() , key=lambda x: x[1], reverse = True)

for entry in sorted_data:
    print(str(entry[0])+"\t"+str(entry[1]))

The only part I am missing is to concatenate the trigram units with an underscore. It's supposed to be so simple, but I can't for the life of me find out how to make it happen. The output is supposed to be the concatenated trigrams followed by the frequency of said trigram. The teacher said it can be solved so easily, but I can't figure it out. Which is funny, because everything else I did here was super quick and easy (relatively).
I have tried many things, but for some reason, I can't get it to work.

A: You can use string's join method. All you have to do is call a '_'.join on the tuple of trigrams when you print.
print(str('_'.join(entry[0]))+"\t"+str(entry[1]))

Other notes:
(1) You can be more pythonic and generate your listText using list comprehension like this: listText = [word.lower() for word in lyrics.split()]
(2)You can use setdefault of a dictionary instead of the if/else to increment/initialize the trigram like this: freq.setdefault(trigram, 0) and then increment freq[trigram] += 1 without using any if/else block. Right now you are iterating through freq.keys() searching for trigram in your if statement, which is constant in time in Python 3 (equivalent to saying trigram in freq) but linear in time in Python 2.

A: if its just a matter of contacting them you can use str.join
trigram = (listText[0], listText[1], listText[2])
c_trigram = '_'.join(*trigram)

you can see a shameless self plugging example here


text:
Q: Intersection of $36x^2 -9y^2+4z^2+36 = 0$ with plane $x=1$, derivative at a point The exercise asks me to find the inclination of the line tangent to the intersection of $36x^2 -9y^2+4z^2+36 = 0$ with the plane $x=1$ in the point $(1,\sqrt{12},3)$, and then say to me that I have to interpret this as a partial derivative.
So, that's what I did:
if we solve for $z$ in the equation, we have:
$$z = \pm \frac{\sqrt{9y^2-36x^2-36}}{2} \implies $$
if I take the partial with respect to $x$ for the $+$ function (because the point in $z$ is positive), all I'm doing is taking the partial derivative with respect to $x$, of the function defined by the intersection of that graph and the plaxe $x=1$, so I have:
$$\frac{\partial z}{\partial x} = \frac{-6x}{\sqrt{-4-4 x^2+y^2}}$$
that, in the point $(1,\sqrt(12),3)$ gives:
$$-3$$
Is everything ok?

UPDATE: I think now that this partial derivative should be with
  respect to $y$, rigth?

A: Notice
Vector normal to the surface $f(x, y, z)=36x^2-9y^2+4z^2+36$ is given as $$\overrightarrow n=\left(i\frac{\partial f}{\partial x }+j\frac{\partial f}{\partial y }+k\frac{\partial f}{\partial z }\right)$$
$$=i(72x)+j(-18y)+k(8z)$$ Hence, the normal vector at the point of intersection $(1, \sqrt{12}, 3)$ is given as follows $$\overrightarrow n=i(72\times 1)+j(-18\sqrt {12})+k(8\times3 )$$$$=72i-36j\sqrt 3+24k$$ Now, the normal vector to the given plane $x=1$ is $i$ Hence, the angle say $\theta$ between the normal vector  to the surface & the normal vector to the plane: $$\theta=\cos^{-1}\left(\frac{(72i-36j\sqrt 3+24k)\cdot (i)}{\sqrt{72^2+(-36\sqrt 3)^2+24^2}\times 1}\right)$$
$$=\cos^{-1}\left(\frac{72}{6\sqrt{187}}\right)=\cos^{-1}\left(\frac{12}{\sqrt{187}}\right)\approx 28.65^\circ$$
Since, the normal & tangent are perpendicular to each other hence, the angle between the tangent to the curve & the plane $x=1$ is $$=90^\circ-\theta$$
$$\bbox[5px, border:2px solid #C0A000]{\color{red}{90^\circ-\cos^{-1}\left(\frac{12}{\sqrt{187}}\right)\approx 61.34^\circ}}$$

A: For $x=1$, points on the curve satisfy $9y^2-4z^2=72$. Taking  this to define $z$ as a function of $y$ in a small neighborhood of $( \sqrt 12 ,3)$ ,we obtain $dz/dy = 3 \sqrt 3 /2$ when  $y=  \sqrt 12$,  which is therefore the partial  deriv of $z$ with respect to $y$ at the point $(1,\sqrt 12 ,3)$.The tangent line meets the plane $z=0$ at an angle $\arctan (3 \sqrt 3 /2)$.

A: For $x=1$, points on the curve satisfy $9y^2-4z^2=72$. Taking  this to define $z$ as a function of $y$ in a small neighborhood of $( \sqrt 12 ,3)$ ,we obtain $dz/dy = 3 \sqrt 3 /2$ when  $y=  \sqrt 12$,  which is the partial  deriv of $z$ with respect to $y$ at the point $(1,\sqrt 12 ,3)$.The tangent line meets the plane $z=0$ at an angle $\arctan (3 \sqrt 3 /2)$.


text:
Q: How to respond image data to only authenticated user in Blazor application? In my Blazor application, I have written an authentication logic using LocalStorage. However, I need to my the application responds image data to authorized users. I think that Blazor can not realize it.
So, I'd like to coexist an MVC controller in a Blazor application and use the same user authentication, but the Blazor's authentication logic does not work in MVC controller.
Do you have any good ideas? The authentication logic does not need to use LocalStorage, but BASIC authentication is unacceptable.

I tried:
public class MyController : Controller
{
    AuthenticationStateProvider Auth;
    public RawFileController(AuthenticationStateProvider auth)
    {
        Auth = auth;
    }
    [HttpGet("...")]
    public async Task<IActionResult> MyGet()
    {
        var authState = await Auth.GetAuthenticationStateAsync();
        Console.WriteLine(authState);
        Console.WriteLine(authState.User);
        Console.WriteLine(authState.User.Identity);
        Console.WriteLine(authState.User.Identity.Name); // output empty !!
        ...
    }
}

My AuthenticationStateProvider is here.
My Startup.cs is here.
Could you give me any suggestions?
My concrete code is here: https://github.com/kjmtks/LMS7.

A: At MVC side create a login (.cshtml) and have user available in HttpContext.
In Blazor side, you can use AuthenticationStateProvider.
var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();
var user = authState.User;

You can wrap your image for authenticated user with:
       <AuthorizeView> <Authorized> ... <Authorized> </AuthorizeView>


text:
Q: How to measure the length of a 2-dimensional path in separate steps I am a newbie in python. I am stuck by finding the length of a path in 2d. I have no idea what I'm doing wrong. Please help!
import math
vector1 = v1
vector2 = v2
def length (v):

    """ Length of a vector in 2-space.

    Params: v (2-tuple) vector in 2-space
    Returns: (float) length
    """
    v = sqrt(v1**2 + v2**2)
    return v

def dist (P,Q):

    """ Distance in 2-space.

    Params:
        P (2-tuple): a point in 2-space
        Q (2-tuple): another point in 2-space
    Returns: (float) dist (P,Q)
    """
    dist = [(Q - P) **2]
    dist = math.sqrt(sum(dist))
    return dist

P = [p0, p1]
Q = [q0, q1]
def pathLength2d (pt):

    """Length of a 2-dimensional path.

    Standard length as measured by a ruler.

    Params: pt (list of 2-tuples): path in 2-space

    Returns: (float) length of this path
    """
    pt = math.hypot(q0 - p0, q1 -p1)
    return pt

print (pathLength2d ([(0,0), (1,1)]))

A: Yes, please fix your formatting, shift everything by four spaces.
But I believe your first method is:
   def length(v):
       """ Length of a vector in 2-space.
       Params: v (2-tuple) vector in 2-space
       Returns: (float) length
       """
       v = sqrt(v1**2 + v2**2)
       return v

That method doesn't know what v1 and v2 are, you need to define them like this:
def length(v):
    """ Length of a vector in 2-space.
    Params: v (2-tuple) vector in 2-space
    Returns: (float) length
    """
    v1 = v(0)
    v2 = v(1)
    v = math.sqrt(v1**2 + v2**2)
    return v

you also need to use math.sqrt
For the distance function, you can't subtract two tuples like that.
you'll need something as follows:
def dist(P, Q):
    """ Distance in 2-space.
    Params:
        P (2-tuple): a point in 2-space
        Q (2-tuple): another point in 2-space
    Returns: (float) dist (P,Q)
    """
    dist = math.sqrt((P[0] - Q[0])**2 + (P[1]-Q[1])**2)
    return dist

A: def euc_distance (x_1,y_1,x_2,y_2):
    x = (x_1 - x_2)**2
    y = (y_1 - y_2)**2

    distance = ( x + y)**0.5

    return distance


text:
Q: Better Excel Formula for Complex Lookup I am trying to improve a complex lookup procedure that I have inherited. The lookup was being generated through several UDF combined with some standard worksheet functions. However, the issue was that when the user updated some data in the source sheet, the re-calc time was unacceptable.
So, I took a look and thought I may be able to write a better Excel formula only solution. Well, I did find a solution, but it is too much for Excel to handle on large data sets, and it crashes (understandably so!) when my VBA runs the formulas against the dataset.
Now, I could implement this in VBA fully, but then the user would have to press a button or something to update after every change. What I would like is a more simpler approach, if there is one, using some of the advanced Excel 2007 formulas. Since I am not as well-versed on those formulas, I am reaching out for some help!
Okay, here is what I have to work with.
SourceSheet
Tid's, Settlement Dates, and month-end prices (layer periods identified by 1,2,3, etc) in columns like below
Tid   SettleDate   1   2   3   4   5   6   7   8   9   10  ...   n

FormulaSheet
Amongst other columns, I have the following columns
InitLayer   LiqdLayer   InstrClass   Tid   SettleDate   InitPrice   LiqdPrice   Position

I also have the layer numbers in columns to the right of the entire data set, like this:
1   2   3   4   5   ...   n

What I need to do is fill in the proper price changes in these columns based on some logic in the dataset by looking up the prices on the source sheet.
In psuedo-formula, this is what I need to happen for each layer column in the FormulaSheet
If Layer < InitLayer OR Layer > LiqdLayer Then Return "-"

ElseIf Layer = InitLayer Then (Layered Price - InitPrice) * Position

     where Layered Price is obtained by finding the Intersect of the LayerNumber
     Column and Tid Row in the SourceSheet

ElseIf Layer = LiqdLayer Then Previous Layered Price * Position

     where Previous Layered Price is obtained by finding the Intersect of the Previous
     LayerNumber Column and Tid Row in the SourceSheet

Else (LayeredPrice - Previous Layered Price) * 6

     where Layered Price and Previous Layered Price are defined as above

End If

I did come up with this formula, which works well on small data sets, but its toooooooooo big and nasty for large data sets, or just too big and nasty period!
=IF(OR(CH$3<$AT6,CH$3>$AU6),"-",IF($AT6=CH$3,(HLOOKUP(CH$3,layered_prices,RIGHT(ADDRESS(MATCH(IF($AX6="CUR",$T6 & " " & $G6,$T6),IF($AX6="CUR",layered_curtid,layered_tid),1),1,4),LEN(ADDRESS(MATCH(IF($AX6="CUR",$T6 & " " & $G6,$T6),IF($AX6="CUR",layered_curtid,layered_tid),1),1,4))-1)-1,FALSE)-$AV6)*$C6,IF($AU6=CH$3,($AW6-HLOOKUP(CG$3,layered_prices,RIGHT(ADDRESS(MATCH(IF($AX6="CUR",$T6 & " " & $G6,$T6),IF($AX6="CUR",layered_curtid,layered_tid),1),1,4),LEN(ADDRESS(MATCH(IF($AX6="CUR",$T6 & " " & $G6,$T6),IF($AX6="CUR",layered_curtid,layered_tid),1),1,4))-1)-1,FALSE))*$C6,(HLOOKUP(CH$3,layered_prices,RIGHT(ADDRESS(MATCH(IF($AX6="CUR",$T6 & " " & $G6,$T6),IF($AX6="CUR",layered_curtid,layered_tid),1),1,4),LEN(ADDRESS(MATCH(IF($AX6="CUR",$T6 & " " & $G6,$T6),IF($AX6="CUR",layered_curtid,layered_tid),1),1,4))-1)-1,FALSE)-HLOOKUP(CG$3,layered_prices,RIGHT(ADDRESS(MATCH(IF($AX6="CUR",$T6 & " " & $G6,$T6),IF($AX6="CUR",layered_curtid,layered_tid),1),1,4),LEN(ADDRESS(MATCH(IF($AX6="CUR",$T6 & " " & $G6,$T6),IF($AX6="CUR",layered_curtid,layered_tid),1),1,4))-1)-1,FALSE))*$C6)))

Formula Key
CH = Layer Number
CG = Previous Layer Number
AT = InitLayer
AU = LiqdLayer
AX = InstrClass (used to find a separate lookup for Currencies)
T = Tid
G = SettleDate (used to find a separate lookup for Currencies)
AV = InitPrice
AW = LiqPrice
C = Position
layered_prices = named range for the range of prices under the layer columns in SourceSheet
layered_tid = named range for tid rows in SourceSheet
layered_curtid = named range for currency tid rows in Source Sheet (just a separte lookup if InstrType = Currency, formula the same

Are there any other formulas, or combination of formulas that will allow me to get what I am seeking in a more efficient manner than the monstrosity I have created?

A: I agree with Kharoof's comment. You should break this formula into several columns. From my count, you need 4 more columns. The benefits are two-fold: 1) Your formula gets much shorter because you're not repeating the same function over and over and 2) You save memory because Excel will calculate it once instead of several times.
For instance, you call the exact same ADDRESS function four times. Excel doesn't "remember" what it was when evaluating a formula and so it calculates it anew each time. If you put it in it's own cell, then Excel will evaluate the cell before any cells that depend on it and store it as a value instead of the formula. When other cells reference it, Excel will provide the pre-evaluated result.

First, here's what your final formula should be: (The names in [brackets] indicate that a helper column fits there. It'll be some cell reference like CI$3 but I wasn't sure where you'd want to put it. You'll have to update those references based on where you add these columns.)
=IF(OR(CH$3<$AT6,CH$3>$AU6),"-",IF($AT6=CH$3,([LayerNumber]-$AV6)*$C6,IF($AU6=CH$3,($AW6-[PreviousLayerNumber])*$C6,([LayerNumber]-[PreviousLayerNumber])*$C6)))

And here are the four helper columns:
[ADDRESS] = ADDRESS(MATCH(IF($AX6="CUR",$T6 & " " & $G6,$T6),IF($AX6="CUR",layered_curtid,layered_tid),1),1,4)
[RIGHT] = RIGHT([ADDRESS],LEN([ADDRESS])-1)
[LayerNumber] = HLOOKUP(CH$3,layered_prices,[RIGHT]-1,FALSE)
[PreviousLayerNumber] = HLOOKUP(CG$3,layered_prices,[RIGHT]-1,FALSE)

By splitting it up, each step of the formula is easier to follow / debug as well as faster to process for Excel. If you want some quantitative improvement, the five formulas combined will be around 70% shorter than the single formula you have right now.


text:
Q: IntelliJ IDEA does not display TypeScript errors when Vue framework being used In below experiment, I have assigned the numeric value to the constant annotated as string.
The ESLint complains that I have not used this variable, but TypeScirpt is silent.

This happen when Vue framework is being used in the project.
Let me show what IntelliJ IDEA will display in the project where there is no Vue framework:

I have been faced with this problem before and there was the solution.
Although the Webpack does not need the target files and directories been explicitly specified in tsconfig.json, IDE does. So include option has solved the problem for a while:
{
  "compilerOptions": {

    // ...
  },
  "include": [
    "Project.d.ts",
    "Source/**/*",
    "Tests/**/*"
  ]
}

But now, the problem has revived.
Herewith, the TypeScript error does not display in the plain TypeScript file below Source.
Something else IntelliJ IDEA needs, or it is just the bug?
Appendix
The bottom bar

Full TypeScript configuration
{
  "compilerOptions": {

    "target": "ES2020",
    "moduleResolution": "node",
    "allowSyntheticDefaultImports": true,
    "esModuleInterop": true,

    "strict": true,
    "noUnusedLocals": true,
    "noUnusedParameters": false, /* Actual for Vue3; see https://github.com/vuejs/vue-next/issues/4668 */
    "experimentalDecorators": true,
    "allowJs": true, /* Actual for Vue3; */
    "skipLibCheck": true,

    "baseUrl": "./",
    "paths": {
      "@Source/*": [ "./Source/*" ],
      "@Components/*": [ "./Source/Components/*"],
      "@SVG_Icons/*": [ "./Source/SVG_Icons/*"]
    },
    "declaration": true
  },
  "include": [
    "Project.d.ts",
    "Source/**/*",
    "Tests/**/*"
  ]
}

The TypeScript configuration in IDE


text:
Q: Python: Run bash command with redirection in background and get the process id I am using Python 2.6.6 from Centos 6 platform.
I need to run a bash command from Python in background which contains redirection operators and need to read the background process's pid from the sub-process object.
I have tried the following code snippets, but it is not working.
My Code:
import subprocess

# Below code throws child_exception
myProcess = subprocess.Popen('tail -f -n 0 /home/user123/mainFile.txt >> /home/user123/tailFile.txt &', subprocess.PIPE)

#If I use the below command, terminating the process kills
#only the shell process and leaves the tail process as orphan
myProcess = subprocess.Popen('tail -f -n 0 /home/user123/mainFile.txt >> /home/user123/tailFile.txt', shell=True, subprocess.PIPE)

cmd = ['tail', '-f', '-n', '0', '/home/user123/mainFile.txt', '>>', '/home/user123/tailFile.txt', '&']
#Below line throws bash error saying: "cannot open file '>>'"
myProcess = subprocess.Popen(cmd, stdout=subprocess.PIPE)

myProcessPid = myProcess.communicate()[0]

At the end I need to get the tail process's pid which is running in background.

A: It's not useful or wise to wrap pure shell in python.
The subprocess.Popen object has ways of doing redirection and things like that by itself rather than by relying on a shell. Here's one example.
 import subprocess
 with open("ls.output.txt", "w") as f:
     # This is the way you'd run "ls -al > ls.output.txt" in the background
     p = subprocess.Popen(["ls", "-al"], stdout=f) # This will run in the background

 p.wait() # Wait till process completes

 with open("ls.output.txt") as f:
        print (f.readline()) # Will print first line of ls -al output (total 2657828)

A: These redirections won't be performed unless shell=True is passed to your subprocess.Popen() call.  The better way to do it is to use the stdout=subprocess.PIPE option and capture the output yourself.
The shell normally does the redirection for you. and this deal where you break the command up into a vector (list) of command and arguments is for the command as the shell would have passed those to an execve() system call.  The shell redirection, piping, and other operators aren't part of that.
Also you don't need the & operator as your subprocess.Popen() process is automatically running in the background.  It may be blocked on I/O, and you can poll and read that from the suprocess.PIPE.
More to the point you don't have to use a subprocess running the tail command at all.  If you just want to follow the end of the file you can do that using the file.seek(), file.tell(), file.readline() and the os.fstat() methods.
Here's a simple class which implements tail -f semantics directly in Python:
#!/usr/bin/env python
from __future__ import print_function
import os, time

class Tail(object):
    def __init__(self, filename):
        self.fd = open(fn, 'r')  # file descriptor
        self.off = self.fd.seek(0, 2)  # end of file: skip the previous contents
        self.buff = list()
        self.last_line = 0
        self.sz = os.fstat(self.fd.fileno()).st_size

    def sleep(self):
        self.off = self.fd.tell()
        while self.sz - self.off == 0:
            self.sz = os.fstat(self.fd.fileno()).st_size
            time.sleep(0.1)

    def follow(self):
        while self.sz - self.off > 0:
            self.buff.append(self.fd.readline())
            self.off = self.fd.tell()
            self.sz = os.fstat(self.fd.fileno()).st_size

    def fetch(self):
        end = self.last_line
        self.last_line = len(self.buff)
        return '\n'.join(self.buff[end:])

... and here's some sample code using it:
if __name__ == '__main__':
    import sys

    if len(sys.argv[1:]) < 1:
        print('Must supply filename', file=sys.stderr)
        sys.exit(1)
    fn = sys.argv[1]

    tail = Tail(fn)
    while True:
        print('... sleeping ...')
        tail.sleep()
        tail.follow()
        print(tail.fetch())

... which shows one way of using it.
I wouldn't use this class.  I'd change Tail.sleep() to Tail.poll() which would just immediately return a value indicating whether there's data ready at the end of the file. I'd also use the Python Standard Library: select module for the polling and sleep. Then you could maintain a list of files that you're tailing all at once. Also the endlessly growing Tail.buff would be a problem; I'd either flush it automatically after each fetch or I'd add a method to flush it.


text:
Q: Problems rendering a Polar Zonohedron in Processing I've recently been looking into Zonohedrons and Rob Bell made beautiful ones. I had a play with the free Polar Zonohedron Sketchup Plugin and thought about playing with the geometry using Processing. So far I've open up the plugin/Ruby script and tried to port it directly, but I am not experienced with Ruby and have been using the Sketchup Ruby API  reference.
The geometry part of the code is mostly in the polar_zonohedron function:
def polar_zonohedron #frequency, pitch = atan(sqrt(2)/2), len = 1.0 # frequency,pitch,length

  mo = Sketchup.active_model
  mo.start_operation "polar_zonohedron"

  prompts = ["Frequency", "Pitch in radians", "Length"]
  values = [8, "atan( sqrt(2)/2 )", 12.inch]
  results = inputbox prompts, values, "Polar Zonohedron"

  return if not results # This means that the user canceld the operation

  ents = mo.active_entities
  grp = ents.add_group
  ents = grp.entities

  grp.frequency = results[0]
  grp.pitch = eval( results[1] )
  grp.length = results[2]

  pts=[]

  #we begin by setting pts[0] to the origin
  pts[0] = Geom::Point3d.new(0,0,0)

  vector = Geom::Vector3d.new(cos(grp.pitch),0,sin(grp.pitch) ) #tilt pitch vector up the xz plane
  vector.length = grp.length

  #Using the origin as the initial generator we iterate thru each zone of the zonohedron
  #our first task is to define the four points of the base rhomb for this zone
  #at the end the pts[3] becomes our new origin for the rhomb of the next zone
  1.upto(grp.frequency-1){ |i|
    p_rotate = Geom::Transformation.rotation( pts[0] , Geom::Vector3d.new(0,0,1), i*2*PI/grp.frequency )

    #obtain the other three points of the rhomb face
    pts[1] = pts[0].transform vector
    pts[3] = pts[1].transform( p_rotate )
    pts[2] = pts[3].transform( vector )

    #we now have the 4 points which make this zone's base rhomb
    #so we rotate around the origin frequency times making a star pattern of faces
    0.upto(grp.frequency-1){ |j|
      f_rotate = Geom::Transformation.rotation( Geom::Point3d.new(0,0,0) , Geom::Vector3d.new(0,0,1), j*2*PI/grp.frequency )
      ents.add_face( pts.collect{|p| p.transform(f_rotate)} )
    }

    #set the origin for the rhomb of the next zone
    pts[0] = pts[3]
  }

  mo.commit_operation
end

I've understood the loops but am slightly confused by transforms:
pts[1] = pts[0].transform vector
pts[3] = pts[1].transform( p_rotate )
pts[2] = pts[3].transform( vector )

As far as I can tell pts[1] is the vector addiction of pts[0] and vector,
and pts[3] is pts[1] multiplied by the p_rotate rotation matrix. Would pts[2] also be an addition (between pts[3] and vector )?
Here's what my attempt looks like so far:
//a port attempt of Rob Bell's polar_zonohedron.rb script - http://zomebuilder.com/

int frequency = 3;
float pitch   = atan(sqrt(2)/2);
float length  = 24;

ArrayList<Face> faces = new ArrayList<Face>();

void setup(){
  size(400,400,P3D);
  strokeWeight(3);
  setupZome();
}
void setupZome(){
  faces.clear();
  PVector[] pts = new PVector[4];
  pts[0] = new PVector();

  PVector vector = new PVector(cos(pitch),0,sin(pitch));
  vector.mult(length);

  for(int i = 1 ; i < frequency; i++){
    PMatrix3D p_rotate = new PMatrix3D();
    p_rotate.rotate(i * TWO_PI / frequency,  0,0,1);
    //PVector v = new PVector();
    //p_rotate.mult(pts[0],v);
    //pts[0] = v;

    pts[1] = PVector.add(pts[0],vector);
    pts[3] = new PVector();
    p_rotate.mult(pts[1],pts[3]);
    pts[2] = PVector.add(pts[3],vector);

    for(int j = 0; j < frequency; j++){
      PMatrix3D f_rotate = new PMatrix3D();
      f_rotate.rotate(j*2*PI/frequency , 0,0,1);

      Face f = new Face();
      for(PVector pt : pts){
        PVector p = new PVector();
        f_rotate.mult(pt,p);
        f.add(p.get());
      }
      faces.add(f);
    }

    pts[0] = pts[3];
  }
}
void draw(){
  background(255);
  lights();

  translate(width * .5, height * .5,0);
  rotateY(map(mouseX,0,width,-PI,PI));
  rotateX(map(mouseY,0,height,-PI,PI));
  drawAxes(100);
  pushMatrix();
  translate(0,0,-frequency * length * .25);
  for(Face f : faces){
    beginShape(mousePressed ? QUADS : POINTS);
      for(PVector p : f.pts) vertex(p.x,p.y,p.z);
    endShape();
  }
  popMatrix();
}
void keyPressed(){
  if(keyCode == UP  && frequency < 32) frequency++;
  if(keyCode == DOWN && frequency > 2) frequency--;
  setupZome();
}
void drawAxes(int size){
  stroke(192,0,0);
  line(0,0,0,size,0,0);
  stroke(0,192,0);
  line(0,0,0,0,size,0);
  stroke(0,0,192);
  line(0,0,0,0,0,size);
}
class Face{
  ArrayList<PVector> pts = new ArrayList<PVector>();
  Face(){}
  void add(PVector p){
    if(pts.size() <= 4) pts.add(p);
  }
}

I feel I'm close, but I'm getting the loop conditionals and vertex indices wrong.
Any tips on how to fix this?

A: I was very close, but not paying attention to all the details.
Turns out I get the correct mesh if I don't increment the rotation on p_rotate:
p_rotate.rotate(TWO_PI / frequency,  0,0,1);

instead of
p_rotate.rotate(i * TWO_PI / frequency,  0,0,1);

Here is the full code listing:
//a port attempt of Rob Bell's polar_zonohedron.rb script - http://zomebuilder.com/

int frequency = 3;
float pitch   = atan(sqrt(2)/2);
float length  = 24;

ArrayList<Face> faces = new ArrayList<Face>();

void setup(){
  size(400,400,P3D);
  strokeWeight(3);
  setupZome();
}
void setupZome(){
  faces.clear();
  PVector[] pts = new PVector[4];
  pts[0] = new PVector();

  PVector vector = new PVector(cos(pitch),0,sin(pitch));
  vector.mult(length);

  for(int i = 1 ; i < frequency-1; i++){
    PMatrix3D p_rotate = new PMatrix3D();
    p_rotate.rotate(TWO_PI / frequency,  0,0,1);

    pts[1] = PVector.add(pts[0],vector);
    pts[3] = new PVector();
    p_rotate.mult(pts[1],pts[3]);
    pts[2] = PVector.add(pts[3],vector);

    for(int j = 0; j < frequency; j++){
      PMatrix3D f_rotate = new PMatrix3D();
      f_rotate.rotate(j*2*PI/frequency , 0,0,1);

      Face f = new Face();
      for(PVector pt : pts){
        PVector p = new PVector();
        f_rotate.mult(pt,p);
        f.add(p.get());
      }
      faces.add(f);
    }

    pts[0] = pts[3];
  }
}
void draw(){
  background(255);
  lights();

  translate(width * .5, height * .5,0);
  rotateY(map(mouseX,0,width,-PI,PI));
  rotateX(map(mouseY,0,height,-PI,PI));
  drawAxes(100);
  pushMatrix();
  translate(0,0,-frequency * length * .25);
  for(Face f : faces){
    beginShape(mousePressed ? QUADS : POINTS);
      for(PVector p : f.pts) vertex(p.x,p.y,p.z);
    endShape();
  }
  popMatrix();
}
void keyPressed(){
  if(keyCode == UP  && frequency < 32) frequency++;
  if(keyCode == DOWN && frequency > 3) frequency--;
  setupZome();
}
void drawAxes(int size){
  stroke(192,0,0);
  line(0,0,0,size,0,0);
  stroke(0,192,0);
  line(0,0,0,0,size,0);
  stroke(0,0,192);
  line(0,0,0,0,0,size);
}
class Face{
  ArrayList<PVector> pts = new ArrayList<PVector>();
  Face(){}
  void add(PVector p){
    if(pts.size() <= 4) pts.add(p);
  }
}

And here a couple of screenshots:


text:
Q: Render after fetching async data I am fetching data in useEffect() and then modifying the object (modifying clients.unreadMessages based on what should render icon), which is later sent to the component to render. But this component does not render correctly always, the icon is sometimes missing. I think it's because data are modified after rendering.
ClientList
  import Colors from '@helper/Colors';
import { useSelector } from '@redux/index';
import { HealthierLifeOption } from '@redux/types';
import React, { useEffect, useState } from 'react';
import { View, Text, FlatList, ActivityIndicator } from 'react-native';
import ClientItem from './ClientItem';
import {usePubNub} from "pubnub-react";

export type Client = {
    id: number;
    username: string;
    individualPlanPaid: boolean;
    healthierLifeOption?: HealthierLifeOption;
    company?: {
      id: number;
      companyName: string;
    };
    mentor?: {
      id: number;
      username: string;
    };
}

type Props = {
    navigation: any;
    clients: Client[];
    isAdmin?: boolean;
    isLoading: boolean;
    onEndReached: Function;
    fromAdminTab?: boolean
}

const ClientList = ({ navigation, clients, onEndReached, isLoading, isAdmin = false, fromAdminTab= false }: Props) => {
    const resultCount = useSelector(state => state.user.menteesResultCount);
    const [hasMoreResults, setHasMoreResults] = useState(true);
    const userId = useSelector(state => state.user.id);
    const pubnub = usePubNub();

    useEffect(() => {
      setHasMoreResults(resultCount !== clients?.length);
    }, [resultCount, clients]);

    useEffect(() => {
        getUnreadMessagesProccess().then(r => console.log("aaaaaaaaa"));
    }, []);

    async function setGrant() {
        return new Promise( async resolve => {
            await pubnub.grant({
                channels: [userId.toString() + '.*'],
                ttl: 55,
                read: true,
                write: true,
                update: true,
                get: true,
            }, response => resolve(response));
        });
    }

    async function getMetadata() {
        const options = {include: {customFields: true}};
        return await pubnub.objects.getAllChannelMetadata(options);
    }

    function setChannelsAndTokens(channelMetadata, channels, tokens) {
        channelMetadata.data.forEach((value, index) => {
            tokens.push(value.custom.lastToken);
            channels.push(value.id)
        });
    }

    async function getUnreadedMessages(channels, tokens) {
        return await pubnub.messageCounts({
            channels: channels,
            channelTimetokens: tokens,
        });
    }

    async function getUnreadMessagesProccess() {
        const tokens = ['1000'];
        const channels = ['1234567'];

        const auth = await setGrant();
        const channelMetadata = await getMetadata();

        const l = await setChannelsAndTokens(channelMetadata, channels, tokens);
        const unread = await getUnreadedMessages(channels, tokens).then((res) => {
            clients.forEach((value, index) => {
                if (res.channels[value.id + '-' + userId + '-chat']) {
                    value.unreadMessages = res["channels"][value.id + '-' + userId + '-chat'];
                } else {
                    value.unreadMessages = 0;
                }
            })
            console.log(res);
        });

        return unread;
    }

    return (
        <View>
            <FlatList
                keyExtractor={item => item.id.toString()}
                data={clients}
                onEndReached={() => hasMoreResults ? onEndReached() : null}
                onEndReachedThreshold={0.4}
                renderItem={item => (
                    <ClientItem
                        client={item.item}
                        isAdmin={isAdmin}
                        navigation={navigation}
                        fromAdminTab={fromAdminTab}
                    />
                )}
                ListFooterComponent={isLoading
                  ? () => (
                      <View style={{ padding: 20 }}>
                        <ActivityIndicator animating size="large" color={Colors.border_gray} />
                      </View>
                    )
                  : null
                }
            />
        </View>
    );
}
export default ClientList;

ClientItem
import React, {useEffect, useState} from 'react';
import { Text, View, Image, TouchableOpacity } from 'react-native';
import Images from '@helper/Images';
import FontAwesome5 from 'react-native-vector-icons/FontAwesome5';
import Colors from '@helper/Colors';
import styles from '../styles';
import ClientModal from './ClientModal/ClientModal';
import { Client } from './ClientList';
import { HealthierLifeOption } from '@redux/types';

type Props = {
    client: Client;
    navigation: any;
    isAdmin?: boolean;
    fromAdminTab?: boolean
}

const ClientItem = ({ client, navigation, isAdmin = false, fromAdminTab= false }: Props) => {
    const [showModal, setShowModal] = useState(false);
    const [showIcon, setShowIcon] = useState(false)
    console.log(client.unreadMessages)

    useEffect(() =>{
        if(client.unreadMessages>0)
            setShowIcon(true);
    },[client.unreadMessages]);

    let clientIcon = Images.icon.logoIcon;

    const handleContinueButton = () => {
        if(!fromAdminTab) {
            navigation.navigate('ChatFromClientsList', { selectedId: client.id, showBackButton: true });
        }else {
            setShowModal(!showModal)
        }
    };

    return (
        <View style={styles.client_item_container}>
            <TouchableOpacity style={styles.client_content_container} onPress={handleContinueButton}
                >
                <View style={styles.image_container}>
                    <Image
                        style={styles.client_profile_img}
                        source={clientIcon}
                        resizeMode="contain"
                        resizeMethod="resize"
                    />
                </View>
                <View style={styles.title_container}>
                    <Text style={styles.title} >{ client.username } </Text>
                </View>
                <View style={styles.dot_container}>
                {showIcon  &&  <FontAwesome5
                    name="comment-dots"
                    size={20}
                    color={Colors.red}

                />  }
                </View>
                <View style={styles.hamburger_container} >
                    <FontAwesome5
                        name="bars"
                        size={30}
                        color={Colors.black}
                        onPress={() => setShowModal(!showModal)}
                    />
                </View>
                <View>
                    <ClientModal
                        isVisible={showModal}
                        onCollapse={(value: boolean) => setShowModal(value)}
                        closeModal={(value: boolean) => setShowModal(value)}
                        client={client}
                        navigation={navigation}
                        isAdmin={isAdmin}
                    />
                </View>
            </TouchableOpacity>
        </View>
    );
};
export default ClientItem;

This code does not render correctly always:
{showIcon  &&  <FontAwesome5
                    name="comment-dots"
                    size={20}
                    color={Colors.red}

                />  }

A: You should not calculate the value in renderItem.
Why you don't calc the value outside of renderItem in pass it in
useEffect(() =>{
        if(client.unreadMessages>0)
            setShowIcon(true);
    },[client.unreadMessages]);

Do something like:
renderItem={item => (
                    <ClientItem
                        client={item.item}
                        isAdmin={isAdmin}
                        navigation={navigation}
                        fromAdminTab={fromAdminTab}
                        showIcon={item.item.unreadMessages>0}
                    />
                )}

By the way renderItem should not be a anonymous function.


text:
Q: possibility of yield farming with flashloan is there possible to do a yield farming with flashloan? I can performed simple arbitrage with one single call back function.
but can I perform 2 call back function with Aave without executing 2 transactions instead of one, which I tried and it shows 2 tx in polyscan?
The simple function should be as such:
first callback to trigger deposit, and wait for 20 second the trigger second callback to withdraw and repayment?

A: Money loaned in flashloans must be returned in the same transaction, otherwise they will revert. This means that you can't perform any more than one transaction with the same loan.
Read more on flashloans here
Quote from that link:

If any of the following conditions occur, the transaction is reversed, and the funds are returned to the lender:

*

*The borrower does not repay the capital (within the same transaction)

*The trade does not lead to a profit


text:
Q: Horizontal scrollbar appearing on display: table element I have a simple page layout like this:
CSS:
html, body {
    height: 100%;
    margin: 0;
    padding: 0;
}

.table-wrapper {
    display: table;
    width: 1366px;
    height: 100%;
}

.cell-left {
    display: table-cell;
    width: 240px;
}

.cell-right {
    display: table-cell;
    width: 1126px;
}

HTML:

    /* Some really long content */

When a content in .cell-right becomes long enough for browser to display vertical scrollbar it also adds horizontal scrollbar which really ruins my layout. Problem goes away if I put 100% width on .table-wrapper but it also shrinks both cells which I do not want. I must have fixed widths on all 3 elements to do proper tweaks for responsive design which project requires. Also both cells need to span across document height.
Funny thing is that Internet explorer 11 does not have this problem but both Firefox and Chrome do. What can I do to prevent horizontal scrollbar appearing?
EDIT
I forgot to add that I'm testing this on screen resolution of 1366x768. If you wanna test this yourself on your own screen resolution just change the numbers.
Here's the fiddle:
http://fiddle.jshell.net/zddm6asz/1/show/
Here is another one for 1920x1200:
http://fiddle.jshell.net/zddm6asz/2/show/

A: Edit: See my first comment under this answer, before trying out this.
If you add
overflow-x: hidden;

for the .cell-left and .cell-right, then this should prevent the cells from getting a horizontal scrollbar.

A: I have had the same issue with a horizontal scroll bar appearing when I was using display:table-cell; for some elements. The scroll bar was applied to the entire page but applying overflow:hidden; to the containing element of these cells solved the problem. In your case that would be applying overflow:hidden; to .table-wrapper.
Also, you may not want to set a pixel width to your table-wrapper. Why not just set it up as a percentage with a max-width if possible? This is especially true is you are attempting a responsive design.


text:
Q: CGRectMake doens't work in UITabBarController I have this code in my TabBarItem:
MeuPrimeiroViewController *primeiro = [[MeuPrimeiroViewController alloc] init];
    MeuSegundoViewController *segundo = [[MeuSegundoViewController alloc]init];

    UITabBarController *tabbar = [[UITabBarController alloc] init];

    tabbar.viewControllers = [NSArray arrayWithObjects:primeiro,segundo, nil];

    primeiro.tabBarItem.title = @"Primeiro";

    UIImage *images = [UIImage imageNamed:@"1.jpg"];
    [images drawInRect:CGRectMake(0, 0, 30, 30)];

    primeiro.tabBarItem.image = images;
    segundo.tabBarItem.title = @"Segundo";
    segundo.tabBarItem.image = [UIImage imageNamed:@"2.jpg"];

And the CGRectMake doens't work, and the console give me a messange:

Mar  3 20:17:04 MacBook-Pro-de-William.local UITabBarController[1174]
  : CGContextSaveGState: invalid context 0x0. This is a serious
  error. This application, or a library it uses, is using an invalid
  context  and is thereby contributing to an overall degradation of
  system stability and reliability. This notice is a courtesy: please
  fix this problem. It will become a fatal error in an upcoming update.
  Mar  3 20:17:04 MacBook-Pro-de-William.local UITabBarController[1174]
  : CGContextSetBlendMode: invalid context 0x0. This is a serious
  error. This application, or a library it uses, is using an invalid
  context  and is thereby contributing to an overall degradation of
  system stability and reliability. This notice is a courtesy: please
  fix this problem. It will become a fatal error in an upcoming update.
  Mar  3 20:17:04 MacBook-Pro-de-William.local UITabBarController[1174]
  : CGContextSetAlpha: invalid context 0x0. This is a serious
  error. This application, or a library it uses, is using an invalid
  context  and is thereby contributing to an overall degradation of
  system stability and reliability. This notice is a courtesy: please
  fix this problem. It will become a fatal error in an upcoming update.
  Mar  3 20:17:04 MacBook-Pro-de-William.local UITabBarController[1174]
  : CGContextTranslateCTM: invalid context 0x0. This is a serious
  error. This application, or a library it uses, is using an invalid
  context  and is thereby contributing to an overall degradation of
  system stability and reliability. This notice is a courtesy: please
  fix this problem. It will become a fatal error in an upcoming update.
  Mar  3 20:17:04 MacBook-Pro-de-William.local UITabBarController[1174]
  : CGContextScaleCTM: invalid context 0x0. This is a serious
  error. This application, or a library it uses, is using an invalid
  context  and is thereby contributing to an overall degradation of
  system stability and reliability. This notice is a courtesy: please
  fix this problem. It will become a fatal error in an upcoming update.
  Mar  3 20:17:04 MacBook-Pro-de-William.local UITabBarController[1174]
  : CGContextDrawImage: invalid context 0x0. This is a serious
  error. This application, or a library it uses, is using an invalid
  context  and is thereby contributing to an overall degradation of
  system stability and reliability. This notice is a courtesy: please
  fix this problem. It will become a fatal error in an upcoming update.
  Mar  3 20:17:04 MacBook-Pro-de-William.local UITabBarController[1174]
  : CGContextRestoreGState: invalid context 0x0. This is a
  serious error. This application, or a library it uses, is using an
  invalid context  and is thereby contributing to an overall degradation
  of system stability and reliability. This notice is a courtesy: please
  fix this problem. It will become a fatal error in an upcoming update.

How can I solve it?

A: The CGRectMake works fine. Your problem is that you're trying to draw an image into a context that doesn't exist. Calling drawInRect: draws the image into the current context, and you don't have one (because you didn't create on / your code isn't running in drawRect:).
Your line calling drawInRect: doesn't look to be required so delete it. And consider what you were trying to achieve with that line.