text:
Q: Gradle failed to build when proguard is activated I am trying to release my Android application with Gradle.
Everything works, including the ./gradlew clean build assembleRelease command.
However, as soon as I try to use proguard, Gradle fail to build the release version.
Here is the error I get (stack trace activated):
...
:OSkin:validateDebugSigning
:OSkin:packageDebug
:OSkin:assembleDebug
:OSkin:prepareReleaseDependencies
:OSkin:compileReleaseAidl
:OSkin:generateReleaseBuildConfig
:OSkin:mergeReleaseAssets
:OSkin:compileReleaseRenderscript
:OSkin:mergeReleaseResources
:OSkin:processReleaseManifest
:OSkin:processReleaseResources
:OSkin:compileRelease UP-TO-DATE
:OSkin:proguardRelease
ProGuard, version 4.9
Reading input...
Reading program directory [/home/geantvert/workspace/OSkinProject/OSkin/build/classes/release]
:OSkin:proguardRelease FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':OSkin:proguardRelease'.
> Can't read [/home/geantvert/workspace/OSkinProject/OSkin/build/classes/release] (No such file or directory)

* Try:
Run with --info or --debug option to get more log output.

* Exception is:
org.gradle.api.tasks.TaskExecutionException: Execution failed for task ':OSkin:proguardRelease'.
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:69)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.execute(ExecuteActionsTaskExecuter.java:46)
    at org.gradle.api.internal.tasks.execution.PostExecutionAnalysisTaskExecuter.execute(PostExecutionAnalysisTaskExecuter.java:35)
    at org.gradle.api.internal.tasks.execution.SkipUpToDateTaskExecuter.execute(SkipUpToDateTaskExecuter.java:62)
    at org.gradle.api.internal.tasks.execution.ValidatingTaskExecuter.execute(ValidatingTaskExecuter.java:58)
    at org.gradle.api.internal.tasks.execution.SkipEmptySourceFilesTaskExecuter.execute(SkipEmptySourceFilesTaskExecuter.java:42)
    at org.gradle.api.internal.tasks.execution.SkipTaskWithNoActionsExecuter.execute(SkipTaskWithNoActionsExecuter.java:52)
    at org.gradle.api.internal.tasks.execution.SkipOnlyIfTaskExecuter.execute(SkipOnlyIfTaskExecuter.java:53)
    at org.gradle.api.internal.tasks.execution.ExecuteAtMostOnceTaskExecuter.execute(ExecuteAtMostOnceTaskExecuter.java:43)
    at org.gradle.api.internal.AbstractTask.executeWithoutThrowingTaskFailure(AbstractTask.java:286)
    at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.executeTask(AbstractTaskPlanExecutor.java:80)
    at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.processTask(AbstractTaskPlanExecutor.java:66)
    at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.executeTaskWithCacheLock(AbstractTaskPlanExecutor.java:58)
    at org.gradle.execution.taskgraph.AbstractTaskPlanExecutor$TaskExecutorWorker.run(AbstractTaskPlanExecutor.java:47)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor$1.run(DefaultTaskPlanExecutor.java:33)
    at org.gradle.internal.Factories$1.create(Factories.java:22)
    at org.gradle.cache.internal.DefaultCacheAccess.longRunningOperation(DefaultCacheAccess.java:214)
    at org.gradle.cache.internal.DefaultCacheAccess.longRunningOperation(DefaultCacheAccess.java:276)
    at org.gradle.cache.internal.DefaultPersistentDirectoryStore.longRunningOperation(DefaultPersistentDirectoryStore.java:142)
    at org.gradle.api.internal.changedetection.state.DefaultTaskArtifactStateCacheAccess.longRunningOperation(DefaultTaskArtifactStateCacheAccess.java:78)
    at org.gradle.execution.taskgraph.DefaultTaskPlanExecutor.process(DefaultTaskPlanExecutor.java:31)
    at org.gradle.execution.taskgraph.DefaultTaskGraphExecuter.execute(DefaultTaskGraphExecuter.java:89)
    at org.gradle.execution.SelectedTaskExecutionAction.execute(SelectedTaskExecutionAction.java:29)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:61)
    at org.gradle.execution.DefaultBuildExecuter.access$200(DefaultBuildExecuter.java:23)
    at org.gradle.execution.DefaultBuildExecuter$2.proceed(DefaultBuildExecuter.java:67)
    at org.gradle.execution.DryRunBuildExecutionAction.execute(DryRunBuildExecutionAction.java:32)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:61)
    at org.gradle.execution.DefaultBuildExecuter.execute(DefaultBuildExecuter.java:54)
    at org.gradle.initialization.DefaultGradleLauncher.doBuildStages(DefaultGradleLauncher.java:166)
    at org.gradle.initialization.DefaultGradleLauncher.doBuild(DefaultGradleLauncher.java:113)
    at org.gradle.initialization.DefaultGradleLauncher.run(DefaultGradleLauncher.java:81)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter$DefaultBuildController.run(InProcessBuildActionExecuter.java:64)
    at org.gradle.launcher.cli.ExecuteBuildAction.run(ExecuteBuildAction.java:33)
    at org.gradle.launcher.cli.ExecuteBuildAction.run(ExecuteBuildAction.java:24)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:35)
    at org.gradle.launcher.exec.InProcessBuildActionExecuter.execute(InProcessBuildActionExecuter.java:26)
    at org.gradle.launcher.cli.RunBuildAction.run(RunBuildAction.java:50)
    at org.gradle.api.internal.Actions$RunnableActionAdapter.execute(Actions.java:171)
    at org.gradle.launcher.cli.CommandLineActionFactory$ParseAndBuildAction.execute(CommandLineActionFactory.java:201)
    at org.gradle.launcher.cli.CommandLineActionFactory$ParseAndBuildAction.execute(CommandLineActionFactory.java:174)
    at org.gradle.launcher.cli.CommandLineActionFactory$WithLogging.execute(CommandLineActionFactory.java:170)
    at org.gradle.launcher.cli.CommandLineActionFactory$WithLogging.execute(CommandLineActionFactory.java:139)
    at org.gradle.launcher.cli.ExceptionReportingAction.execute(ExceptionReportingAction.java:33)
    at org.gradle.launcher.cli.ExceptionReportingAction.execute(ExceptionReportingAction.java:22)
    at org.gradle.launcher.Main.doAction(Main.java:48)
    at org.gradle.launcher.bootstrap.EntryPoint.run(EntryPoint.java:45)
    at org.gradle.launcher.Main.main(Main.java:39)
    at org.gradle.launcher.bootstrap.ProcessBootstrap.runNoExit(ProcessBootstrap.java:50)
    at org.gradle.launcher.bootstrap.ProcessBootstrap.run(ProcessBootstrap.java:32)
    at org.gradle.launcher.GradleMain.main(GradleMain.java:26)
    at org.gradle.wrapper.BootstrapMainStarter.start(BootstrapMainStarter.java:33)
    at org.gradle.wrapper.WrapperExecutor.execute(WrapperExecutor.java:130)
    at org.gradle.wrapper.GradleWrapperMain.main(GradleWrapperMain.java:48)
Caused by: java.io.IOException: Can't read [/home/geantvert/workspace/OSkinProject/OSkin/build/classes/release] (No such file or directory)
    at proguard.InputReader.readInput(InputReader.java:230)
    at proguard.InputReader.readInput(InputReader.java:200)
    at proguard.InputReader.readInput(InputReader.java:178)
    at proguard.InputReader.execute(InputReader.java:78)
    at proguard.ProGuard.readInput(ProGuard.java:197)
    at proguard.ProGuard.execute(ProGuard.java:79)
    at proguard.gradle.ProGuardTask.proguard(ProGuardTask.java:958)
    at org.gradle.api.internal.BeanDynamicObject$MetaClassAdapter.invokeMethod(BeanDynamicObject.java:248)
    at org.gradle.api.internal.BeanDynamicObject.invokeMethod(BeanDynamicObject.java:136)
    at org.gradle.api.internal.CompositeDynamicObject.invokeMethod(CompositeDynamicObject.java:147)
    at proguard.gradle.ProGuardTask_Decorated.invokeMethod(Unknown Source)
    at org.gradle.api.internal.BeanDynamicObject$MetaClassAdapter.invokeMethod(BeanDynamicObject.java:248)
    at org.gradle.api.internal.BeanDynamicObject.invokeMethod(BeanDynamicObject.java:136)
    at org.gradle.api.internal.CompositeDynamicObject.invokeMethod(CompositeDynamicObject.java:147)
    at proguard.gradle.ProGuardTask_Decorated.invokeMethod(Unknown Source)
    at org.gradle.util.ReflectionUtil.invoke(ReflectionUtil.groovy:23)
    at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.doExecute(AnnotationProcessingTaskFactory.java:220)
    at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.java:213)
    at org.gradle.api.internal.project.taskfactory.AnnotationProcessingTaskFactory$StandardTaskAction.execute(AnnotationProcessingTaskFactory.java:202)
    at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:530)
    at org.gradle.api.internal.AbstractTask$TaskActionWrapper.execute(AbstractTask.java:513)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeAction(ExecuteActionsTaskExecuter.java:80)
    at org.gradle.api.internal.tasks.execution.ExecuteActionsTaskExecuter.executeActions(ExecuteActionsTaskExecuter.java:61)
    ... 53 more
Caused by: java.io.IOException: No such file or directory
    at proguard.io.DirectoryPump.pumpDataEntries(DirectoryPump.java:50)
    at proguard.InputReader.readInput(InputReader.java:226)
    ... 75 more

BUILD FAILED

Total time: 42.363 secs

Here is my gradle file:
buildscript {
    repositories {
        mavenCentral()

    }
    dependencies {
        classpath 'com.android.tools.build:gradle:0.5.+'
    }
}
apply plugin: 'android'

repositories {
    mavenCentral()
    maven {
        url 'http://www.bugsense.com/gradle/'
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: '*.jar')

    compile 'com.google.guava:guava:14.+'
    compile 'com.google.code.gson:gson:2.+'
    compile 'org.zeroturnaround:zt-zip:1.+'
    compile 'com.github.japgolly.android:svg-android:2.+'
    compile('de.keyboardsurfer.android.widget:crouton:1.8.1') {
        exclude module: 'support-v4'
        compile 'com.android.support:support-v4:18.+'
    }
    compile 'com.squareup:otto:1.3.4'
    compile 'com.squareup.okhttp:okhttp:1.2.+'
    compile 'com.squareup.picasso:picasso:1+'
    compile 'com.bugsense.trace:bugsense:3.5'

    //Google Drive SDK
    compile 'com.google.android.gms:play-services:3.+'
    compile 'com.google.apis:google-api-services-drive:v2+'

    compile('com.google.api-client:google-api-client:1.+') {
        exclude(group: 'xpp3', module: 'xpp3')
        exclude(group: 'org.apache.httpcomponents', module: 'httpclient')
        exclude(group: 'junit', module: 'junit')
        exclude(group: 'com.google.android', module: 'android')
    }
    compile('com.google.api-client:google-api-client-android:1.+') {
        exclude group: 'xpp3'
        exclude group: 'com.google.android.google-play-services'
    }
    compile('com.google.http-client:google-http-client-jackson:1.+') {
        exclude group: 'xpp3'
    }
    compile('com.google.http-client:google-http-client-gson:1.+') {
        exclude group: 'xpp3'
    }

    compile 'com.google.apis:google-api-services-plus:v1+'

    compile 'com.netflix.rxjava:rxjava-android:+'

    compile('com.github.frankiesardo:icepick:2+') {
        exclude module: 'support-v4'
        compile 'com.android.support:support-v4:18.+'
    }

//    compile (group: 'com.google.apis', name: 'google-api-services-youtube', version: 'v3-rev56-1.15.0-rc')
}

android {
    compileSdkVersion 18
    buildToolsVersion "18.0.1"

    defaultConfig {
        minSdkVersion 14
        targetSdkVersion 18
    }
    signingConfigs {
        release {
                    storeFile file('path_to_file')
                    storePassword '***'
                    keyAlias '***'
                    keyPassword '***'
                }
    }

    buildTypes
            {
                release {
                    runProguard true
                    proguardFile getDefaultProguardFile('proguard-android.txt')
                    proguardFile 'proguard-project.txt'
                    signingConfig signingConfigs.release
               }
            }
}

Does anyone has an idea of what is the issue?
Regards
Edit: ./gradlew clean assembleDebug works perfectly! and ./gradlew clean build assembleRelease works if runProguard is set to off. So it's a 100% proGuard issue.

A: I've been battling this issue for the past few hours. Basically the proguard task will halt execution if there are any warnings. You can see the Proguard warnings, and the stacktrace, by adding -d to the build (as in: gradle clean assembleRelease -d). Note that the stacktrace mentions to "Please correct the above warnings first."
In order to just get to a point where the build would get through proguard, I had to add -dontwarn entries for packages it was complaining about to my proguard-project.txt file. Something along the lines of:
-dontwarn org.apache.lang.**

...etc
So put simply... do as the stacktrace instructs you to do. Fix the warnings! :)
BTW, I apologize, as I now recognize that the stacktrace in the original post is not quite the same as the one I encountered. However, I do feel my answer is helpful, as obviously I ended up here trying to search for answers to my issue.

A: Hmmm, I don't understand why but it seems if I start two times the same task with the same parameters (proguard...) the second one is the good one.
But if the second one the parameters change, the task fail.
Hope it will help someone.
Regards

A: You can use -ignorewarnings at proguard-project.txt so you don't need to specify each package.

A: Check that your minifyEnabled in build gradle is set to "false". Because when it will be "true" debugger while generating signed apk will give an error.


text:
Q: WireGuard error I'm trying to use WireGuard to configure a VPN tunnel via my server, and up to now it worked perfectly. However, I changed server, pasted my old config files (just changing the private and public keys newly generated) all according to this tutorial, and now when I activate wg0-client on my machine, I get:
[#] ip link add wg0-client type wireguard
[#] wg setconf wg0-client /dev/fd/63
[#] ip address add 10.200.200.2/32 dev wg0-client
[#] ip link set mtu 1420 up dev wg0-client
[#] resolvconf -a tun.wg0-client -m 0 -x
Too few arguments.
Too few arguments.
[#] wg set wg0-client fwmark 51820
[#] ip -4 route add 0.0.0.0/0 dev wg0-client table 51820
[#] ip -4 rule add not fwmark 51820 table 51820
[#] ip -4 rule add table main suppress_prefixlength 0

... and I can't connect to the Internet!
What am I doing wrong?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Better way of aligning Views when a View is set to GONE I have a bit of a debacle here. I have a simple vertical linear layout where there are 2 textviews. The bottom textview will only be displayed if there is data for it from a web service call.
Currently what happens is, by default its set to android:visibility="gone" and when there is data for it, I set it to android:visibility="visible". The issue I have is I need to top TextView to align centre in the view when the Bottom TextView is no longer visible. I know I could always set the layout params etc programmatically but I was thinking is there a better way to do this? For example somehow in the XML
View when both views are visible:
|--------LinearLayout--------|
|        TextView            |
|        TextView            |
|                            |
|----------------------------|

What the view looks like when the bottom View is set to GONE
|--------LinearLayout--------|
|         TextView           |
|                            |
|                            |
|----------------------------|

What I would like the View to end up looking like when the bottom TextView doesn't have data and is set to GONE:
|--------LinearLayout--------|
|                            |
|        TextView            |
|                            |
|----------------------------|

Thank you

A: You can do it programmatically.
Lets suppose When you have no data from webservices then.
Textview tvTop;
Textview tvBottom;

after initializing the view you check
if(there is no data from webservices){
tvBottom.setVisibility(View.GONE);
tvTop.setLayoutParams(new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1f));
}

Hope it will help.


text:
Q: In AppCenter Android phone is not cleared between tests I have written some UITests for my Xamarin application using Xamarin.UITest. One of the tests clicks on an element and then a pdf viewer is opened. When running this test in AppCenter this test succeed but a system popup is opened with 'no available app can execute this action'. All the tests after this test fails with this error:

System.Net.WebException : POST Failed  at Xamarin.UITest.Shared.Http.HttpClient.HandleHttpError (System.String method, System.Exception exception, Xamarin.UITest.Shared.Http.ExceptionPolicy exceptionPolicy) [0x0003c] in :0   at Xamarin.UITest.Shared.Http.HttpClient.SendData (System.String endpoint, System.String method, System.Net.Http.HttpContent content, Xamarin.UITest.Shared.Http.ExceptionPolicy exceptionPolicy, System.Nullable1[T] timeOut) [0x0013d] in <a0c3f09cbf9049cbb8d3a680a53dcf46>:0   at Xamarin.UITest.Shared.Http.HttpClient.Post (System.String endpoint, System.String arguments, Xamarin.UITest.Shared.Http.ExceptionPolicy exceptionPolicy, System.Nullable1[T] timeOut) [0x00014] in :0   at Xamarin.UITest.Shared.Android.HttpApplicationStarter.Execute (System.String intentJson) [0x00035] in :0   at Xamarin.UITest.Shared.Android.AndroidAppLifeCycle.LaunchApp (System.String appPackageName, Xamarin.UITest.Shared.Android.ApkFile testServerApkFile, System.Int32 testServerPort) [0x000a1] in :0   at Xamarin.UITest.Shared.Android.AndroidAppLifeCycle.LaunchApp (Xamarin.UITest.Shared.Android.ApkFile appApkFile, Xamarin.UITest.Shared.Android.ApkFile testServerApkFile, System.Int32 testServerPort) [0x00007] in :0   at Xamarin.UITest.Android.AndroidApp..ctor (Xamarin.UITest.Configuration.IAndroidAppConfiguration appConfiguration, Xamarin.UITest.Shared.Execution.IExecutor executor) [0x00193] in :0   at Xamarin.UITest.Android.AndroidApp..ctor (Xamarin.UITest.Configuration.IAndroidAppConfiguration appConfiguration) [0x00000] in :0   at Xamarin.UITest.Configuration.AndroidAppConfigurator.StartApp (Xamarin.UITest.Configuration.AppDataMode appDataMode) [0x00017] in :0   at iProvaSearch.UITests.AppInitializer.StartApp (Xamarin.UITest.Platform platform) [0x00019] in <80fc342154644106b99f6255aba5ae55>:0   at iProvaSearch.UITests.Tests.DocumentListTests.BeforeEachTest () [0x00001] in <80fc342154644106b99f6255aba5ae55>:0   at (wrapper managed-to-native) System.Reflection.MonoMethod:InternalInvoke (System.Reflection.MonoMethod,object,object[],System.Exception&)  at System.Reflection.MonoMethod.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00032] in <48b95f3df5804531818f80e28ec60191>:0

In the screenshot we can see the system popup is still shown. So it seems the app data is cleared correct between tests but the phone isn't. This only occurs on Android, iOS is ok. Is there a solution or workaround for this?

A: You need to understand why it works on iOS but not Android first:

*

*Opening a PDF in iOS is very simple, as iOS has a PDF viewer inbuilt that doesn't require any installations.

*However for Android, you need to install a 3rd party app (like Adobe PDF reader) to view a file of PDF format.

So in order to make the UITest pass, you can

*

*Either change the app to convert the PDF into a picture and then open it, requiring some work to be done.

*Or you can use a conditional compilation to only run certain code at the time of a UITest for Android, that will essentially override the test to perform the test function differently.


text:
Q: Output based on two inputs I'm trying to make this "Should I take this test or that test" Calculator. Nothing is output when I put in both values, so I'm looking for the error in my code. Thanks!

document.getElementById("test2score").onkeyup = function() {
  WhichTestFunction()
};

function WhichTestFunction() {
  var t1 = document.getElementById('test1score').value;
  var t2 = document.getElementById('test2score').value;

  if (t1 == 9) && (t2 < 120) {
    score = "Take Test 1";
  }

  else if (t1 == 9) && (t2 > 140) {
    score = "Take Test 2";
  }

  else if (act == 9) && (sat >= 120) && (sat <= 140) {
    score = "Toss up. Take the test you like better based on format and content.";
  }

  document.getElementById("testscore").innerHTML = score;
}

Which Test To Take?

Input Test 1 Score

        <input type="number" id="test1score">

Input Test 2 Score

        <input type="number" id="test2score">

A: First off, you need to wrap your if statements with outer parenthesis
if ((act == 9) && (sat >= 120) && (sat <= 140)) {...}

Then you have a couple of undeclared variables causing an exception
var score, sat, act;

Note 1a: Whether these 3 variables should be declared/available globally I don't know.
Note 1b: As not knowing what they actually should be, I commented out that last if statement so the code will run in this demo sample.
Stack snippet

Which Test To Take?

Input Test 1 Score

                <input type="number" id="test1score">

Input Test 2 Score

                <input type="number" id="test2score">


text:
Q: Why are two files different sizes when saved and loaded back again? I'm using Pygame in combination with StringIO to create two files from the same source. They seem to be different sizes; why?
import pygame
import StringIO

putimage = pygame.image.load("88keykbd.png")
buff = StringIO.StringIO()
buff.name = '88keykbd.png'

pygame.image.save(putimage, buff)

putimage = buff.getvalue()
print "buff:", type(buff), "myimage:", type(putimage), "getimage:", type(putimage)

print len(putimage) # 110564
with open('myscrambledimage.dat', 'w') as newfile:
    newfile.write(putimage)

with open('myscrambledimage.dat', 'r') as newfile:
    getimage= newfile.read()
print len(getimage) # 7502

A: You should be using binary access for your files:
with open('myscrambledimage.dat', 'wb') as newfile:
    newfile.write(putimage)

with open('myscrambledimage.dat', 'rb') as newfile:
    getimage= newfile.read()

When you do, the sizes are consistent.  Aside from line-endings, Windows (for example) sees a CTRL+Z character as EOF.


text:
Q: deparse() with 'else' statement I am trying to write a shiny app which prints my function code and saves it as a .R file which the I can run to get an desired output.
To get the function code I was using deparse. It was getting the job until recently, when one of my function had if else statement. deparse tends to separate else and } and hence if I run the code in the .R file I generate gives an error:
Error: unexpected 'else' in "else"
Is there a way to work around this issue?
My sample code is as follows:
 MyFunction <- function(dat){
    if(any(dat == 1)){
      print("1 is observed")
    }else{
      print("1 is not present")
    }

  }

  func.string <- deparse(MyFunction)
  codeOfInterest <-func.string[3:8]
  write(codeOfInterest, "Code.R")

A: You could use
func.string <- capture.output(print(MyFunction))

This is the approach I take in the docstring package to gather the source code to be able to detect and extract any documentation comments.


text:
Q: Combining two lists with different lengths to a single list I was tasked with combining two lists with different lengths to a single list and I'm confused? would it be this simple, or am I missing something. I used these two list as examples. I need to do it with a function.
def appArray(x,y):
   List1=[1,2]
   List2=[4,5,6]
   C= List1 + List2
    return C
print (C)


text:
Q: Finding class files that Eclipse builds When Eclipse builds my workspace, I assume that it creates Java .class files. What else should otherwise deploy to my running JBoss AS?
Do you know where I can find these class files that Eclipse temporarily creates?

A: Right click on your project, and then click on properties.  Now click on the Java Build Path section, and you will be able to see and set the Default output folder on the "Source" tab.  I believe Eclipse defaults to "bin"
More than likely though, it won't be enough to just copy these over to JBoss.  You'll need to deploy your application as a .war file, which is basically a .zip with a different extension.  Do some googling on "ant war task" for some examples and articles.

A: As gregcase has said, you want to deploy a .war file, and if you want Eclipse to do this for you, just right-click on the project, select "export" and under "web" choose "WAR file."
Copy this file to $JBOSS_HOME/server/default/deploy/ and you should be set.


text:
Q: Why not use parenthesis on return functions inside functions in Python? I'm reading this tutorial and under the Returning Functions part, there's an example something like below:
def parent(n):

    def child1():
        return "Printing from the child1() function."

    def child2():
        return "Printing from the child2() function."

    if n == 10: return child1
    else: return child2

The author mentions that the return functions should not have parenthesis in them but without giving any detailed explanation. I believe that it is because if parenthesis are added, then the function will get called and in some way the flow will be lost. But I need some better explanation to get a good understanding.

A: If you add parenthesis i.e. () to the return function then you will be returning the return-value of that function (i.e. the function gets executed and its result is returned). Otherwise, you are returning a reference to that function that can be re-used. That is,
f = parent(1)
f()  # executes child2()

A: return func()  # returns the result of calling func
return func    # returns func itself, which can be called later

A: We are defining the functions child1() & child2() and returning the references to these functions outside the nested scope (here, parent). So, every time you call the parent function, new instances of child1 & child2.
And we want these references only.That's why there's no parenthesis. If you add parenthesis, then the function will get called.


text:
Q: Как можно отправлять координаты каждые 5 секунд? Вопрос такой, как можно сделать что-бы на сервер отправлялись мои координаты раз в 5 секунд
public class MainActivity extends AppCompatActivity {

int PERMISSION_ID = 44;
FusedLocationProviderClient mFusedLocationClient;
TextView latTextView, lonTextView;
private Socket socket;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    ConnectionAsyncTask con = new ConnectionAsyncTask();
    con.execute("192.168.0.40", "7788");

    latTextView = findViewById(R.id.latTextView);
    lonTextView = findViewById(R.id.lonTextView);
    mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

    getLastLocation();
}

@SuppressLint("MissingPermission")
private void getLastLocation() {
    if (checkPermissions()) {
        if (isLocationEnabled()) {
            mFusedLocationClient.getLastLocation().addOnCompleteListener(
                    new OnCompleteListener<Location>() {
                        @Override
                        public void onComplete(@NonNull Task<Location> task) {
                            Location location = task.getResult();
                            if (location == null) {
                                requestNewLocationData();
                            } else {
                                Gson gson = new Gson();
                                String jsonCoords;

                                //Этот фрагмент кода

                                        double lat = location.getLatitude();
                                        double lon = location.getLongitude();

                                        Log.d("TAG", String.valueOf(lat));
                                        Log.d("TAG", String.valueOf(lon));

                                        Model model = new Model(lat, lon);
                                        jsonCoords = gson.toJson(model);

                                        Log.d("TAG", String.valueOf(model));

                                        SendAsyncTask sendAsyncTask = new SendAsyncTask();// {"lat": 37.4334, "lon": -122.32}
                                        sendAsyncTask.execute(jsonCoords);

                                             //

                            }
                        }
                    }
            );
        } else {
            Toast.makeText(this, "Turn on location", Toast.LENGTH_LONG).show();
            Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            startActivity(intent);
        }
    } else {
        requestPermissions();
    }
}

@SuppressLint("MissingPermission")
private void requestNewLocationData() {

    LocationRequest mLocationRequest = new LocationRequest();
    mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);
    mLocationRequest.setInterval(0);
    mLocationRequest.setFastestInterval(0);
    mLocationRequest.setNumUpdates(1);

    mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);
    mFusedLocationClient.requestLocationUpdates(
            mLocationRequest, mLocationCallback,
            Looper.myLooper()
    );

}

private LocationCallback mLocationCallback = new LocationCallback() {
    @Override
    public void onLocationResult(LocationResult locationResult) {
        Location mLastLocation = locationResult.getLastLocation();
        latTextView.setText(mLastLocation.getLatitude() + "");
        lonTextView.setText(mLastLocation.getLongitude() + "");
    }
};

private boolean checkPermissions() {
    if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED &&
            ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
        return true;
    }
    return false;
}

private void requestPermissions() {
    ActivityCompat.requestPermissions(
            this,
            new String[]{Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION},
            PERMISSION_ID
    );
}

private boolean isLocationEnabled() {
    LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled(
            LocationManager.NETWORK_PROVIDER
    );
}

@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
    super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    if (requestCode == PERMISSION_ID) {
        if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
            getLastLocation();
        }
    }
}

@Override
public void onResume() {
    super.onResume();
    if (checkPermissions()) {
        getLastLocation();
    }

}

class ConnectionAsyncTask extends AsyncTask<String, Void, Socket> {
    Socket s = null;

    @Override
    protected Socket doInBackground(String... params) {
        try {
            s = new Socket(params[0], Integer.parseInt(params[1]));
            socket = s;
            Log.d("Tag", s.toString());
        } catch (IOException e) {
            e.printStackTrace();
        }
        return s;
    }

}

class SendAsyncTask extends AsyncTask<String, String, Void> {

    @Override
    protected Void doInBackground(String... params) {
        try (PrintWriter printWriter = new PrintWriter(new BufferedOutputStream(socket.getOutputStream()))) {
            printWriter.write(params[0] + "\n");
            printWriter.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

}

}

A: Создайте таймер, а ещё лучше сервис с таймером и периодически отправляйте. В любом случае координаты у Вас обновятся не раньше, чем "железный" датчик устройства обнаружит изменение его местоположения и уведомит об этом систему.
Немножко уточню ответ, потому что из-за этого могут возникнуть дальнейшие сложности. Если нужно отсылать данные только тогда, когда приложение открыто создавать отдельный компонент Service для этого не стоит. Достаточно создать отдельный объект, который будет отвечать за отправку данных, внутри которого будет лежать таймер, и который будет крутиться на отдельном потоке. Так приложение будет потреблять меньше ресурсов. Если же данные должны отправляться в фоновом режиме, то обычный Service не поможет, необходимо использовать ForegroundService.


text:
Q: How do I add animation to this jquery? I would like to add some animation to this jquery, at the moment the div 'pops up' on hover.
$(document).ready(function() {

$('.recruiterLink').hover(function() {

    $(this).css({
        'bottom' : 0
    });

}, function() {

    $(this).css({
        'bottom' : -20
    });

});

});

How do I go about doing that? Thanks

A: Are you looking for something like this (should work out of the box)?
$('.recruiterLink').hover(function () {
    $(this).stop().animate({
        'bottom': '0px'
    }, 500);
}, function () {
    $(this).stop().animate({
        'bottom': '-20px'
    }, 500);
});

This will animate the bottom CSS property for 500 ms. It also aborts all running animations to prevent awkward behaviour (caused by queueing).

A: just change the .css to .animate
Something like the following would work:
$('.recruiterLink').hover(function() {
    $(this).animate({bottom : 0},1000);
}, function() {
    $(this).stop(false,false).animate({bottom: -20},1000);
});

I've added the stop function in the hover off so that if the previous animation hasn't finished it finishes straight away.

A: replace .css() function
with, for example
.stop().animate({ bottom:'-=20px' },"slow")

for JQuery animate() API reference:
http://api.jquery.com/animate/

A: just change .css() with .animate()


text:
Q: Playing .m3u8 file in Windows Store App I am able to play the HLS smooth streaming file (having extension .ism/maniest) using MediaElement and Microsoft Smooth Streaming client SDK in Windows Store App
However when set the source of MediaElement to .m3u8 file, the video is not played.
Is it possible to play .m3u8 file in Windows Store App?
Regards,
SRS

A: .m3u8 file does not seem to be supported in Windows Store App.
Supported audio and video formats (Windows Store apps)

A: HLS (m3u8) isn't supported by the platform. But you have these options:

*

*create your own media source provider

*3ivx, a library
that supports both Windows store apps, and windows phone 8, but they
are really expensive (for me the offer was 7500 Australian dollars
per app)

*Apptelic HLS, a commerical library for Windows 8
and windows Phone

A: I have been working on this for months and the only solution that works is this one
http://phonesm.codeplex.com/releases/view/119845
I know it says phone but it does support windows 8.1 store apps also
HLS is a nightmare to solve in Windows 8 apps, This option is open-source and is easy enough to implement Hope it helps you


text:
Q: ExecJS::RuntimeError when converting .js to .js.coffee I've been charged with changing a PHP application to a RoR application. Everything's going well, but turbolinks is causing me some trouble. In order to fix this, I've decided to convert the existing .js libraries to .js.coffee
I have two .js libraries:
lightbox-2.6.js
modernizr.custom.js

These work perfectly.
After converting these .js files to .js.coffee I incur the following error:
ExecJS::RuntimeError in Application#gallery

Installing node.js does not fix the problem.
Removing
//= require_tree .

from app/javascripts/application.js does solve the problem. However, according to this, removing this require method means that there is

an actual problem with ExecJS working properly with the JavaScript
  runtime on your system

Okay, I'll admit I don't really understand what to do with this. The .js works perfectly. When converted to .js.coffee this problem arises. I don't actually know what ExecJS is, either. Could someone clarify what's going on here? Why it doesn't work at all when converted to js.coffee and how I can fix this?

A: add this line to your Gemfile

gem 'therubyracer'

and then bundle install


text:
Q: unit test with CDI Unit and EasyMock I have a project with CDI and I would like to create unit test with mocks.
To manage mocks, I would like to use EasyMock and to run with CDI, I find the cdi-unit project which seem easy to use.
I have a problem to get a mock with EasyMock in CDI context. Here is my unit test:
@RunWith(CdiRunner.class)
@AdditionalClasses(MockFactory.class)
public class ResultYearMServiceImplTest {

    @Inject
    private IStockDao stockDao;

    @Inject
    private ResultYearMServiceImpl resultYearMService;

    @Test
    public void getResultList() {
        EasyMock.reset(stockDao);
        EasyMock.expect(stockDao.getListStocks()).andReturn(null).once()
                .andReturn(new ArrayList<DtoStock>()).once();
        EasyMock.replay(stockDao);
    }
}

IStockDao needs to be mock in the test, so to get it I would like to use a @Produces method like this (in MockFactory class given to cdi unit by @AdditionalClasses):
@Produces
@ApplicationScoped
public IStockDao getStockDao() {
    return EasyMock.createMock(IStockDao.class);
}

When I run my unit test, the mock is good in unit test but I get this error:

java.lang.IllegalArgumentException: Not a mock:
  org.jboss.weld.proxies.IStockDao$-1971870620$Proxy$_$$_WeldClientProxy

This one comes because CDI doesn't give an instance of EasyMock IStockDao but a proxified instance and EasyMock doesn't accept this in these methods (like reset method).
So I replace @ApplicationScoped in MockFactory by @Dependent which doesn't proxified the instance but I have a new problem:
This annotation give a new instance of mock at each injection point so I can use it because I have a mock in the unit test to mock method called in the tested class. And this instance of mock must be the same in the tested class (it's not the case with @Dependent).
How can I get the same instance in the unit test and the tested class ?
Thanks.

A: Needle is your friend for testing CDI.
http://needle.spree.de
public class ResultYearMServiceImplTest {
   @Rule
   public final NeedleRule needle = new NeedleRule();

   @Inject
   private IStockDao stockDao;

   @ObjectUnderTest
   private ResultYearMServiceImpl resultYearMService;
@Test
public void getResultList() {
    EasyMock.reset(stockDao);
    EasyMock.expect(stockDao.getListStocks()).andReturn(null).once()
            .andReturn(new ArrayList<DtoStock>()).once();
    EasyMock.replay(stockDao);
}
}

A: I was unit testing a CDI interceptor with easymock and had the same problem as you.
I would like to share the workaround I used.
It consists in producing the mocks in @Dependent scope. This way we can get over the CDI proxy problem with easymock.
import static org.easymock.EasyMock.createStrictControl;

import javax.enterprise.context.ApplicationScoped;
import javax.enterprise.context.Dependent;
import javax.enterprise.inject.Produces;

/**
 * Mock producer. Beans are produced in Dependent scope to not be proxied.
 */
@ApplicationScoped
public class CdiMockProducerUnitTests {

    /**
     * Mock
     */
    private final MyMockClass myMock;

    /**
     * Constructor creating mocks.
     */
    public CdiMockProducerTestesUnitarios() {
        myMock =  createStrictControl().createMock(MyMockClass.class);
    }

    /**
     * Produces mock in dependent scope.
     *
     * @return mock
     */
    @Produces
    @Dependent
    public MyMockClass produceMock() {
        return myMock;
    }

}

A: The next version of CDI-Unit (2.1.1) adds support for EasyMock in the same way that Mockito is currently supported.


text:
Q: How to change tags h2 to other tags header in jquery what is the function change tag h2 to other tag header(tag HTML) in jquery ? if not exist this function then i can use the syntax. how? thanks everyone !
ex:

DEMO
 --->
DEMO

A: You can use .replaceWith() selector:
$('h2').replaceWith(function () {
  return $('
', {html: this.innerHTML});
});

Working Demo

A: use replaceWith() in jquery
$("h2").replaceWith(function(i,cont){
return "
"+cont+"
";      // cont will return the inner html
});

DEMO


text:
Q: How to uncomment css imports with a button in React JS? Im implementing a RTL version of my project. For that I already have dedicated css files that when imported to the main css file is doing the right job. The question is how to control from a button or toggle for the user to change the disposition ? Right now its only working when Im manually uncomment those specifics files, which is of course not an option for deployment. Thanks in advance for your help.
 // RTL Mode
/* @import "./rtl/bootstrap-rtl";
 @import "./rtl/components-rtl";
 @import "./rtl/float-rtl";
 @import "./rtl/general-rtl";
 @import "./rtl/pages-rtl";
 @import "./rtl/plugins-rtl";
 @import "./rtl/spacing-rtl";
 @import "./rtl/structure-rtl";
 @import "./rtl/text-rtl";*/

body {
  * {
    outline: none;
  }
}


text:
Q: Should I use "did" or "does" when asking a question about the meaning of what someone said? Here are two example questions:

*

*What did he mean by that?

*What does he mean by that?

Question 1 seems correct to me because it uses the past tense word 'did,' but the word could also signify that his meaning has changed; which it hasn't. This is why I also think that question 2 could be correct. Would I use Question 2 if the statement the person is referring to was just asked, and use question 1 when the statement was said a while ago?
Can someone please clear my confusion? Thanks!

A: Using the present tense implies that whatever was said or written has present relevance; for example because a decision has to be made or action taken based on an interpretation of the message.
It is certainly more likely that a recent message will have present relevance, but it is also true that something written some time ago may require a present interpretation and consequent action. In such a case What does he mean by that? is perfectly acceptable.
If the past tense is used for the question, no implication is made as to the present relevance of what was said. The message may or may not have present relevance.
As an aside, it cannot be that the past tense may 'signify that his (the speaker's) meaning has changed'. Whatever the speaker meant at the time of saying it remains unchanged. What may have changed in the meantime is the speaker's position or opinion on the topic in question.

A: Here's a scenario:

Three guys are talking to each other.  Person A uses a word, or phrase, or sentence, or a complete, multi-sentence thought that either person B or person C does not understand.  When person A leaves the room, leaving persons B and C behind, person B might say to person C:
"What did he mean by that?"

That question refers to what person A just said.  However,

"What does he mean by that?"

is virtually the same, but person B, having heard person A use the same word or phrase, etc., for the second or third time, could be asking person C:

"What does he mean by that?"

meaning that what person A said before (at least two or more times) in person B's hearing includes both the past and the present.  Person B assumes the word or phrase, etc., meant the same thing the first time, the second time, the third time, etc., as well as the most recent time.
That's how I explain at least one possible difference between the two sentences.  There may be more.

A: Did is the past tense ,so it refers to what the person said in past.
Does is the present form so it implies what he says in the present
as simple as that.

A: According to my level of knowledge, I would agree that did connotes a past event while does indicates a present situation.
So if something immediate is being referenced, option two is correct. If, on the other hand, the reference concerns something that's already taken place, then option one applies. So in this case, given that you're referring to a past time frame, the accurate choice is option one, did.


text:
Q: Ratio and Proportion- Calculation Process How we arrived for for following:
$$\frac{441.66}{958.33}=\frac{441\cdot 3 +2}{958\cdot 3 +1}$$
I understand that $0.66$ is $\frac{2}{3}$ but want to know how we arrived at above relation.

A: The $2$ parts in the original "equation" are not actually equal to each other. Instead, assuming the "=" was meant to be "$\approx$", you get
$$\frac{441.66}{958.33} \approx \frac{441 + \frac{2}{3}}{958 + \frac{1}{3}} = \frac{441 \times 3 + 2}{958 \times 3 + 1} \tag{1}\label{eq1}$$
The approximation's numerator and denominator was multiplied by $3$, with $\frac{3}{3} = 1$, so the overall value doesn't change.


text:
Q: Periodically log gradients without requiring two functions (or slowdown) in Theano For diagnostic purposes, I am grabbing the gradients of the network periodically. One way to do this is to return the gradients as output of the theano function. However, copying the gradients from the GPU to CPU memory every time may be costly so I would prefer to do it only periodically. At the moment, I am achieving this by creating two function objects, one which returns the gradient and one which doesn't.
However, I do not know whether this is optimal and am looking for a more elegant way to achieve the same thing.

A: Your first function obviously executes a training step and updates all your parameters.
The second function must return the gradients of your parameters.
The fastest way to do what you are asking is to add the updates for the training step to the second function and when logging the gradients, don't call the first function, but only the second.
gradients = [ ... ]
train_f = theano.function([x, y], [], updates=updates)
train_grad_f = theano.function([x, y], gradients, updates=updates)
num_iters = 1000
grad_array = []
for i in range(num_iters):
   # every 10 training steps keep log of gradients
   if i % 10 == 0:
       grad_array.append(train_grad_f(...))
   else:
       train_f(...)

Update
if you wish to have a single function to do this, you can do the following
from theano.ifelse import ifelse

no_grad = T.iscalar('no_grad')
example_gradient = T.grad(example_cost, example_variable)

# if no_grad is > 0 then return the gradient, otherwise return zeros array
out_grad = ifelse(T.gt(no_grad,0), example_gradient, T.zeros_like(example_variable))

train_f = theano.function([x, y, no_grad], [out_grad], updates=updates)

So when you want to retrieve the gradients you call
train_f(x_data, y_data, 1)

otherwise
train_f(x_data, y_data, 0)


text:
Q: Simplify a sum with a product and multinomial coefficient This is a follow-up question to my previous post, where I've got a great help! (I created a new one to avoid editing the original one).
Can the following sum be simplified?
$$
 \sum_{\substack{k_1 + k_2 + \ldots + k_m &=& B \\ g_1 + g_2 + \ldots + g_m &=& W}} \left(\prod_{i=1}^{m}k_i\right) \cdot {B \choose k_1, k_2, \ldots k_m} \cdot {W \choose g_1, g_2, \ldots, g_m}
$$
where $B + W = n$, and $\forall_i: g_i = x - k_i$, where $x = \frac{n}{m}$, and $m\mid n$ and $k_i \geq 1$
I tried to follow the steps suggested in my previous post, but I got stuck. For $m=2$ I've got the following
$$
\sum_{\substack{k_1 + k_2 &=& B \\ k_1, k_2 &\geq& 0}} k_1 \cdot k_2 \cdot {B \choose k_1, k_2} \cdot {2N - B \choose N-k_1, N-k_2} \\ = \sum_{\substack{k_1 + k_2 &=& B \\ k_1, k_2 &\geq& 0}} k_2 \cdot {B \choose k_1-1} \cdot {2N - B \choose N-k_1, N-k_2} \\
= \sum_{k_1 = 0}^B \left(B-k_1 \right) \cdot {B \choose k_1-1} \cdot {2N - B \choose N-k_1} \\
$$
From the previous post I know how to handle the binomial coefficients, but I'm not sure what can I do now with the $B-k_1$ factor inside the sum?

A: We assume positive integers $m,n\geq 2$. Since $m\mid n$ we know that $n=Nm$ is a multiple of $m$ with $N\geq 1$. This way we can write $W=Nm-B$ and $x=N$. We show by induction of $m$ that for all $N\geq 1, m\leq B\leq Nm$ the following is valid:
\begin{align*}
\color{blue}{\sum_{\substack{k_1+\cdots+k_m=B\\k_1,\ldots,k_m\geq 0}}
\binom{B}{k_1,\ldots,k_m}\binom{mN-B}{N-k_1,\ldots,N-k_m}=B^{\underline{m}}\prod_{q=2}^m\binom{q(N-1)}{N-1}}\tag{1}
\end{align*}
with $B^{\underline{m}}=B(B-1)\cdots(B-m+1)$ the falling factorial.

Base step: $m=2$
We obtain for natural numbers $B,N$ with $2\leq B\leq  2N$:
\begin{align*}
\color{blue}{\sum_{\substack{k_1+k_2=B\\k_1,k_2\geq 0}}}&\color{blue}{k_1k_2\binom{B}{k_1,k_2}\binom{2N-B}{N-k_1,N-k_2}}\\
&=\sum_{k_1=0}^{B}k_1\left(B-k_1\right)\binom{B}{k_1}\binom{2N-B}{N-k_1}\tag{1}\\
&=B\sum_{k_1=1}^{B-1}\left(B-k_1\right)\binom{B-1}{B-k_1}\binom{2N-B}{N-k_1}\tag{2}\\
&=B(B-1)\sum_{k_1=1}^{B-1}\binom{B-2}{k_1-1}\binom{2N-B}{N-k_1}\tag{3}\\
&=B^{\underline{2}}\sum_{k_1=0}^{B-2}\binom{B-2}{k_1}[z^{N-k_1-1}](1+z)^{2N-B}\tag{4}\\
&=B^{\underline{2}}[z^{N-1}](1+z)^{2N-B}(1+z)^{B-2}\tag{5}\\
&\,\,\color{blue}{=B^{\underline{2}}\binom{2(N-1)}{N-1}}\tag{6}
\end{align*}

Comment:

*

*In (1) we write the multinomial as binomial coefficients, substituting $k_2=B-k_1$.

*In (2) we use the binomial identity $\binom{p}{q}=\frac{p}{q}\binom{p-1}{p-q}$ and we skip the indices $k_1=0$ and $k_1=B$ which do not contribute to the sum.

*In (3) we use again $\binom{p}{q}=\frac{p}{q}\binom{p-1}{q-1}=\frac{p}{q}\binom{p-1}{p-q}$ as in (2) and (3).

*In (4) we shift the index $k_1$ by one to start with $k_1=0$. We use the coefficient of operator $[z^N]$ to denote the coefficient of $z^N$ of a series.

*In (5) we apply the rule $[z^{p-q}]A(z)=[z^p]z^qA(z)$ and we apply the binomial theorem.

*In (6) we select the coefficient of $z^{N-1}$.
Induction hypothesis: $m=M$
We assume the validity of
\begin{align*}
\color{blue}{\sum_{\substack{k_1+\cdots+k_M=B\\k_1,\ldots,k_M\geq 0}}
\binom{B}{k_1,\ldots,k_M}\binom{MN-B}{N-k_1,\ldots,N-k_M}=B^{\underline{M}}\prod_{q=2}^M\binom{q(N-1)}{N-1}}\tag{7}
\end{align*}
Induction step: $m=M+1$
We have to show
\begin{align*}
&\color{blue}{\sum_{\substack{k_1+\cdots+k_{M+1}=B\\k_1,\ldots,k_{M+1}\geq 0}}
\binom{B}{k_1,\ldots,k_{M+1}}\binom{(M+1)N-B}{N-k_1,\ldots,N-k_{M+1}}}\\
&\qquad\qquad\color{blue}{=B^{\underline{{M+1}}}\prod_{q=2}^{M+1}\binom{q(N-1)}{N-1}}\tag{8}
\end{align*}
We obtain for $M\geq 2$:
\begin{align*}
&\color{blue}{\sum_{\substack{k_1+\cdots+k_{M+1}=B\\k_1,\ldots,k_{M+1}\geq 0}}
\binom{B}{k_1,\ldots,k_{M+1}}\binom{(M+1)N-B}{N-k_1,\ldots,N-k_{M+1}}}\\
&\qquad=\sum_{k_{M+1}=1}^{B-1}k_{M+1}\frac{B!}{k_{M+1}!(B-k_{M+1})!}\,\frac{((M+1)N-B)!}{(N-k_{M+1})!(MN-(B-k_{M+1}))!}\\
&\qquad\qquad\cdot\sum_{\substack{k_1+\cdots+k_{M}=B-k_{M+1}\\k_1,\ldots,k_{M}\geq 0}}
\binom{B-k_{M+1}}{k_1,\ldots,k_{M}}\binom{MN-(B-k_{M+1})}{N-k_1,\ldots,N-k_{M}}\tag{9}\\
&=B\sum_{k_{M+1}=1}^{B-1}\binom{B-1}{B-k_{M+1}}\binom{(M+1)N-B}{N-k_{M+1}}\\
&\qquad\qquad\cdot\left(B-k_{M+1}\right)^{\underline{M}}\prod_{q=2}^M\binom{q(N-1)}{q}\tag{10}\\
&=B\sum_{k_{M+1}=1}^{B-M+1}\frac{(B-1)^{\underline{M}}}{(B-k_{M+1})^{\underline{M}}}\binom{B-M-1}{B-k_{M+1}-M+1}\binom{(M+1)N-B}{N-k_{M+1}}\\
&\qquad\qquad\cdot\left(B-k_{M+1}\right)^{\underline{M}}\prod_{q=2}^M\binom{q(N-1)}{q}\\
&=B^{\underline{M+1}}\prod_{q=2}^M\binom{q(N-1)}{N-1}
\sum_{k_{M+1}=0}^{B-M}\binom{B-M-1}{k_{M+1}}\binom{(M+1)N-B}{N-k_{M+1}-1}\\
&=B^{\underline{M+1}}\prod_{q=2}^M\binom{q(N-1)}{N-1}
\sum_{k_{M+1}=0}^{B-M}\binom{B-M-1}{k_{M+1}}[z^{N-k_{M+1}-1}](1+z)^{(M+1)N-B}\\
&=B^{\underline{M+1}}\prod_{q=2}^M\binom{q(N-1)}{N-1}
[z^{N-1}](1+z)^{(M+1)N-B}(1+z)^{B-M-1}\\
&=B^{\underline{M+1}}\prod_{q=2}^M\binom{q(N-1)}{N-1}\binom{(M+1)N-M-1}{N-1}\\
&\,\,\color{blue}{=B^{\underline{M+1}}\prod_{q=2}^{M+1}\binom{q(N-1)}{N-1}}\\
\end{align*}
in accordance with (8) and the claim follows.
Comment:

*

*In (9) we separate $k_{M+1}$ and expand to get binomial coefficients in the next step.

*In (10) we apply the induction hypothesis.

Note: We obtain from (1):
\begin{align*}
\color{blue}{B^{\underline{m}}\prod_{q=2}^m\binom{q(N-1)}{N-1}}
&=B^{\underline{m}}\cdot\frac{\prod_{q=2}^m\left(q(N-1)\right)!}{\prod_{q=2}^m(N-1)!\prod_{q=2}^m\left((q-1)(N-1)\right)!}\\
&=B^{\underline{m}}\cdot\frac{\prod_{q=2}^m\left(q(N-1)\right)!}{\left((N-1)!\right)^{m-1}\prod_{q=1}^{m-1}\left(q(N-1)\right)!}\\
&=B^{\underline{m}}\cdot\frac{\left(m(N-1)\right)!}{\left((N-1)!\right)^{m}}\\
&\,\,\color{blue}{=\binom{B}{m}\frac{m!\left(m(N-1)\right)!}{\left((N-1)!\right)^{m}}}
\end{align*}
in accordance with the answer from @GCab.

A: We have
$$
S = \sum\limits_{\left\{ {\matrix{
   {k_{\,1}  + k_{\,2}  + \, \ldots  + \,k_{\,m}  = B}  \cr
   {g_{\,1}  + g_{\,2}  + \, \ldots  + \,g_{\,m}  = W}  \cr
 } } \right.} {\left( {\prod\limits_{i = 1}^m {k_{\,i} } } \right)
\left( \matrix{ B \cr  k_{\,1} ,\,k_{\,2} ,\, \ldots ,\,k_{\,m}  \cr}  \right)
\left( \matrix{W \cr g_{\,1} ,\,g_{\,2} ,\, \ldots ,\,g_{\,m}  \cr}  \right)}
$$
plus the added conditions
$$
\left\{ \matrix{
  B + W = n \hfill \cr
  g_{\,i}  = x - k_{\,i}  \hfill \cr
  1 \le k_{\,i}  \hfill \cr}  \right.
$$
Leave apart for the moment the fact that $x=n/m, \; m | n$.
Because of the product, we can consider $0 \le ki$, and for the multinomial not to be null it shall be
$0 \le g_i$.
Thus  the set of conditions becomes (if I understood them properly)
$$
\eqalign{
  & \left\{ {\matrix{
   {0\, \le \,k_{\,i} ,\;g_{\,i} \, \le \,x}  \cr
   {g_{\,i}  = x - k_{\,i} }  \cr
   {k_{\,1}  + k_{\,2}  + \, \ldots  + \,k_{\,m}  = B}  \cr
   {g_{\,1}  + g_{\,2}  + \, \ldots  + \,g_{\,m}  = W}  \cr
 } } \right.\quad  \Rightarrow   \cr
  &  \Rightarrow \quad \left\{ {\matrix{
   {0\, \le \,k_{\,i} ,\;g_{\,i} \, \le \,x}  \cr
   {g_{\,i}  = x - k_{\,i} }  \cr
   {k_{\,1}  + k_{\,2}  + \, \ldots  + \,k_{\,m}  = B}  \cr
   {\left( {x - k_{\,1} } \right) + \left( {x - k_{\,2} } \right)
 + \, \ldots  + \,\left( {x - k_{\,m} } \right) = W}  \cr
 } } \right.\quad  \Rightarrow   \cr
  &  \Rightarrow \quad \left\{ {\matrix{
   {0\, \le \,k_{\,i} ,\;g_{\,i} \, \le \,x}  \cr
   {g_{\,i}  = x - k_{\,i} }  \cr
   {k_{\,1}  + k_{\,2}  + \, \ldots  + \,k_{\,m}  = B}  \cr
   {W + B = mx = n}  \cr
 } } \right. \cr}
$$
Under these conditions the summand can be rewritten as
$$
\eqalign{
  & \left( {\prod\limits_{i = 1}^m {k_{\,i} } } \right)
\left( \matrix{ B \cr  k_{\,1} ,\,k_{\,2} ,\, \ldots ,\,k_{\,m}  \cr}  \right)
\left( \matrix{ W \cr  g_{\,1} ,\,g_{\,2} ,\, \ldots ,\,g_{\,m}  \cr}  \right) =   \cr
  &  = \left( {\prod\limits_{i = 1}^m {k_{\,i} } } \right){{B!} \over {k_{\,1} !\,k_{\,2} !\, \cdots \,k_{\,m} !}}
{{\left( {mx - B} \right)!} \over {\left( {x - k_{\,1} } \right)!\,\left( {x - k_{\,2} } \right)!\, \cdots \,\left( {x - k_{\,m} } \right)!}} =   \cr
  &  = {{B!\left( {mx - B} \right)!} \over {\left( {x!} \right)^{\,m} }}
\left( {\prod\limits_{i = 1}^m {k_{\,i} } } \right){{x!} \over {k_{\,1} !\,\left( {x - k_{\,1} } \right)!}}
{{x!} \over {k_{\,2} !\,\left( {x - k_{\,2} } \right)!}} \cdots {{x!} \over {k_{\,m} !\,\left( {x - k_{\,m} } \right)!}} =   \cr
  &  = {{B!\left( {mx - B} \right)!} \over {\left( {x!} \right)^{\,m} }}
\prod\limits_{i = 1}^m {{{x\left( {x - 1} \right)^{\,\underline {\,k_{\,i}  - 1\,} } } \over {\left( {k_{\,i}  - 1} \right)!\,}}}  =   \cr
  &  = {{B!\left( {mx - B} \right)!} \over {\left( {\left( {x - 1} \right)!} \right)^{\,m} }}
\prod\limits_{i = 1}^m {{{\left( {x - 1} \right)^{\,\underline {\,k_{\,i}  - 1\,} } } \over {\left( {k_{\,i}  - 1} \right)!\,}}}  =
 {{B!\left( {mx - B} \right)!} \over {\left( {\left( {x - 1} \right)!} \right)^{\,m} }}
\prod\limits_{i = 1}^m {\left( \matrix{ x - 1 \cr  k_{\,i}  - 1 \cr}  \right)}  \cr}
$$
so that the sum becomes
$$
\eqalign{
  & S(B,m,x)\quad \left| {\;1\, \le mx \le B} \right.\quad  =   \cr
 &  = \sum\limits_{\left\{ {\matrix{
   {0\, \le \,k_{\,i} ,\;g_{\,i} \, \le \,x}  \cr
   {g_{\,i}  = x - k_{\,i} }  \cr
   {k_{\,1}  + k_{\,2}  + \, \ldots  + \,k_{\,m}  = B}  \cr
   {g_{\,1}  + g_{\,2}  + \, \ldots  + \,g_{\,m}  = W}  \cr
 } } \right.}
 {\left( {\prod\limits_{i = 1}^m {k_{\,i} } } \right)
\left( \matrix{B \cr k_{\,1} ,\,k_{\,2} ,\, \ldots ,\,k_{\,m}  \cr}  \right)
\left( \matrix{ W \cr g_{\,1} ,\,g_{\,2} ,\, \ldots ,\,g_{\,m}  \cr}  \right)}  =   \cr
  &  = {{B!\left( {mx - B} \right)!} \over {\left( {\left( {x - 1} \right)!} \right)^{\,m} }}
\sum\limits_{\left\{ {\matrix{
   {\left( {1\, \le } \right)\,k_{\,i} \,\left( { \le \,x} \right)}  \cr
   {k_{\,1}  + k_{\,2}  + \, \ldots  + \,k_{\,m}  = B}  \cr
 } } \right.}
 {\prod\limits_{i = 1}^m {\left( \matrix{ x - 1 \cr  k_{\,i}  - 1 \cr}  \right)} }  =   \cr
  &  = {{B!\left( {mx - B} \right)!} \over {\left( {\left( {x - 1} \right)!} \right)^{\,m} }}
\sum\limits_{\left\{ {\matrix{ {\left( {0\, \le } \right)\,j_{\,i} \,\left( { \le \,x - 1} \right)}  \cr
   {j_{\,1}  + j_{\,2}  + \, \ldots  + \,j_{\,m}  = B - m}  \cr
 } } \right.}
 {\prod\limits_{i = 1}^m {\left( \matrix{ x - 1 \cr  j_{\,i}  \cr}  \right)} }  \cr}
$$
Now, since
$$
\eqalign{
  & \left( {\left( {1 + z} \right)^{x - 1} } \right)^{\,m}
  = \prod\limits_{i = 1}^m {\left( {\sum\limits_{\left( {0\, \le } \right)\,j_{\,i} \,\left( { \le \,x - 1} \right)}
 {\left( \matrix{ x - 1 \cr  j_{\,i}  \cr}  \right)z^{\,j_{\,i} } } } \right)}  =   \cr
  &  = \sum\limits_{0\, \le \,s\, \le \,m\,\left( {x - 1} \right)}
 {\sum\limits_{\left\{ {\matrix{ {\left( {0\, \le } \right)\,j_{\,i} \,\left( { \le \,x - 1} \right)}  \cr
   {j_{\,1}  + j_{\,2}  + \, \ldots  + \,j_{\,m}  = \,s}  \cr
 } } \right.}
 {\left( {\prod\limits_{i = 1}^m {\left( \matrix{ x - 1 \cr j_{\,i}  \cr}  \right)} } \right)z^{\,s} } }  \cr}
$$
we conclude that
$$ \bbox[lightyellow] {
\eqalign{
  & S(B,m,x)\quad \left| {\;1\, \le mx \le B} \right.\quad  =   \cr
 & = {{B!\left( {mx - B} \right)!} \over {\left( {\left( {x - 1} \right)!} \right)^{\,m} }}
\;\;\left[ {z^{\,B - m} } \right]\left( {1 + z} \right)^{m\left( {x - 1} \right)}  =   \cr
  &  = {{B!\left( {mx - B} \right)!} \over {\left( {\left( {x - 1} \right)!} \right)^{\,m} }}
\;\;\left( \matrix{ m\left( {x - 1} \right) \cr  B - m \cr}  \right) =   \cr
  &  = {{B!\left( {mx - B} \right)!} \over {\left( {\left( {x - 1} \right)!} \right)^{\,m} }}
\;{{\left( {m\left( {x - 1} \right)} \right)!} \over {\left( {B - m} \right)!\left( {mx - B} \right)!}}\; =   \cr
  &  = {{B!} \over {\left( {B - m} \right)!}}\;
{{\left( {m\left( {x - 1} \right)} \right)!} \over {\left( {\left( {x - 1} \right)!} \right)^{\,m} }}\;
 = \left( \matrix{ B \cr  m \cr}  \right)\;
{{m!\left( {m\left( {x - 1} \right)} \right)!} \over {\left( {\left( {x - 1} \right)!} \right)^{\,m} }} \cr}
}$$
--- in reply to your comment  ---
Consider the following simple case
$$
\eqalign{
  & \left( {1 + z} \right)^a \left( {1 + z} \right)^a
  = \left( {\sum\limits_{k_1 } {\left( \matrix{ a \cr  k_1  \cr}  \right)z^{k_1 } } } \right)
\left( {\sum\limits_{k_2 } {\left( \matrix{ a \cr   k_2  \cr}  \right)z^{k_2 } } } \right) =   \cr
  &  = \prod\limits_{i = 1}^2 {\left( {\sum\limits_{k_i }
 {\left( \matrix{a \cr k_i  \cr}  \right)z^{k_i } } } \right)}  =   \cr
  &  = \sum\limits_{k_1 } {\sum\limits_{k_2 }
 {\left( \matrix{ a \cr  k_1  \cr}  \right)\left( \matrix{ a \cr k_2  \cr}  \right)z^{k_1  + k_2 } } }
  = \sum\limits_s {\sum\limits_{k_1  + k_2  = s}
 {\left( \matrix{a \cr k_1  \cr}  \right)\left( \matrix{a \cr   k_2  \cr}  \right)z^s } }  =   \cr
  &  = \sum\limits_s {\left( {\sum\limits_{k_1  + k_2  = s} {\left( {\prod\limits_{i = 1}^2
 {\left( \matrix{ a \cr  k_i  \cr}  \right)} } \right)} } \right)z^s }
  = \sum\limits_s {\left( \matrix{ 2a \cr   s \cr}  \right)z^s }  \cr}
$$
which implies
$$
\sum\limits_{k_1  + k_2  = s} {\left( {\prod\limits_{i = 1}^2
 {\left( \matrix{a \cr  k_i  \cr}  \right)} } \right)}
  = \left( \matrix{ 2a \cr   s \cr}  \right)
$$
and which is just the Vandermonde convolution.


text:
Q: Syntax error at or near "$1" with postgres insert in Node Trouble with insert in Postgres from my nodeapi. I am getting syntax  error while performing insert operation. I am trying to insert data from POSTMAN.

function insertUser(req, res, next){
  req.body.users = parseInt(req.body.users);

  db.none('INSERT INTO office.users (role_id, office_id, user_name, full_name,password) ' +
        'VALUES (${role_id}, ${office_id}, ${user_name}, ${full_name}, ${password})', req.body.users)

   .then(function(){
        res.status(200)
        .json({
          status: 'success',
          message: 'Inserted one user'
   });
   })
 .catch(error => {
        console.log(error);
        next();
})
}

the error

POST /api/users 401 78.263 ms - 43
{ [error: syntax error at or near "$"]
  name: 'error',
  length: 102,
  severity: 'ERROR',
  code: '42601',
  detail: undefined,
  hint: undefined,
  position: '86',
  internalPosition: undefined,
  internalQuery: undefined,
  where: undefined,
  schema: undefined,
  table: undefined,
  column: undefined,
  dataType: undefined,
  constraint: undefined,
  file: 'src\\backend\\parser\\scan.l',
  line: '1053',
  routine: 'scanner_yyerror' }

Can anybody help me to understand what is wrong?

A: Silly Mistake with the variable
This is working now

 db.none('INSERT INTO office.users(role_id, office_id, user_name, full_name, password)' +
         'values(${role_id},${office_id},${user_name},${full_name},${password})', req.body)


text:
Q: How to create invoice in a different currency In Dolibarr, I have set the default currency to US Dollars. When I create a new invoice, the currency of the invoice will be in the default currency. Is there a way to change the currency for a single invoice? I want to create one invoice where the amounts are in Euros instead of US Dollars.
Dolibarr version: 15.0.3


text:
Q: How do I change this Greasemonkey script to work on a different page? I tried the script from How can I detect visited and unvisited links on a page?, and it works on the test page, but not on mine.
The answer, there, said that I need to change SelectorStr, but to what?
How do I check which are my options. I tried to search for ui.topicList and a.topicTItle but couldn't find anything on these values.
Edit (from a comment below):
I found this HTML in the page source:

    <a target="_top" href="/smartphones/clik-where-suppose.html" target="_self" ...

But, if set SelectorStr to td.plist a._top, It's still not working.

A: I haven't tried the code but i guess you have to put a Selector String there. In the example two things are used. The first is an unordered list with the class name topicList and the second are links with the class topicTitle.
So if you want to apply that code with that SelectorStr your html should look something like this:

listitem 1

listitem 2

listitem 3


text:
Q: how to pass position of listview items to another listview adapter and set text of textview according to position i have Two list-view activity.
In first list-view activity i have link to open second list-view activity. In Second list-view i have 5 rows. i want to pass the position of second list-view item to first first activity and according to position set text for only second row.
i can pass static data form second list-view activity to first list-view activity with finish(), but i don't know how to set it to selected row and i don't know how to pass position of second list-view with finish().
Anyone can help then please write code. for this
i want to set text for second row of first list-view.also write for this.
Thanks.

A: You could utilize startActivityForResult() to launch the second activity. By calling that instead of startActivity() your first activity will be noticed when the second one completes.
In your FirstActivity, launch the second activity using this:
Intent launch2ndActivity = new Intent(this, SecondActivity.class);
startActivityForResult(launch2ndActivity, 610);

Then on your SecondActivity:
// Do what do you need to do here.
//I assume you would need to get the position of your ListView upon item click.
..
yourListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Intent resultIntent = this.getIntent();
        resultIntent.putExtra("clicked_row", position);
        SecondActivity.this.setResult(RESULT_OK, resultIntent);
        finish();
    }
});

The last thing you'd need to do is specify how your FirstActivity should react upon recieving the result from SecondActivity:
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    switch(requestCode) {
    case 610:
        if (resultCode == RESULT_OK) {
            Bundle res = data.getExtras();
            int clickedRow = res.getInt("clicked_row");
            // Do what you want with that value..
        }
        break;
    }
}


text:
Q: Angular 7 Change Detection: Problem with NgZone.onMicrotaskEmpty I'm using chart.js in angular app and drawing the chart with the data coming from an API endpoint.
ngOnInit(): void {
this._route.params.subscribe(p => {
  let id: number = +this._route.snapshot.params["id"];
  this.busy = this._awpsService
  .getOutcomeItem("years", id).subscribe(data => {
      this.years = data;
      this.selYear = this.years[0];

      this.ngZone.onMicrotaskEmpty.first.subscribe(() => {
        $("#year").selectpicker();
        $(window).resize();
      });

      this.getProjectItems(id);

    });
});
}

The above code was working perfectly fine with angular 4 but after upgrading to angular 7, I had to change my code to
this.ngZone.onMicrotaskEmpty.subscribe(() => {
            $("#year").selectpicker();
            $(window).resize();
});

because .first is gone in angular 7. This has increased the CPU utilization and crashed the app.
The ngZone.onMicrotaskEmpty.first has been widely used in my app and I don't know how to hundle the change detection properly.I've also tried this way
this.ngZone.onMicrotaskEmpty.subscribe({
        next: () => {
          this.ngZone.run(() => {
            $('#year').selectpicker();
            $(window).resize();
          });
        }
});

but no luck. anyone can help me with this?
Thanks


text:
Q: string index out of range error - TBRPG - python ok, so i'm creating a rpg and i keep on getting this string error out of range thing
while playerturn1[0] != playerturn and playerturn1[1] != playerturn and playerturn[2]
!= playerturn:
IndexError: string index out of range

here is all the code so far

A: I suppose you meant to write
playerturn1[2]

instead of
playerturn[2]

Be sure to use clearly distinguishable variable names in order to avoid such mistakes.


text:
Q: In android voice call app, how do I hide the dialer and show the call activity in app? I hae the following code to dial a number
package com.example.callapp;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

makecall(); }

public void makecall()
    {
    Intent call = new Intent(Intent.ACTION_CALL);
    call.setData(Uri.parse("tel:90324567"));
    startActivity(call);
    }

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}

}
Now when i run this app it brings up a dialer and dials the number. I would like to hide the dialer and show the call activity in app - say Dialing this number - XXXX
And how do I end the call after specific time? and show the message on app screen with the time?


text:
Q: Fetching active record associations in batches with include Assuming standard simple models as following:
class User < ActiveRecord::Base
  has_many :posts
end

class Post < ActiveRecord::Base
  has_many :comments
end

class Comment < ActiveRecord::Base
end

And my queries:
includes = {:posts => [:comments]}
person = Person.where(:id => 5).includes(includes)

Is there some way I can fetch comments from posts in batches? Because in some cases, a one user has thousands of posts, so the query it constructs to fetch the comments becomes very big and slow.

A: You can solve this if you fetch the comments in a second query.
# in your controller
@person = Person.where(id: 5).includes(:posts)

# in your view (haml)
- @person.posts.each do |post|
  = post.title
  - post.comments.find_each do |comment| # find_each is batched
    = comment.message

Perhaps not the most clean solution (each post requires an extra query, querying in the view...), but I am not aware of a way to fetch included items in batches.


text:
Q: Export source code from Power Automate Desktop I have created some flow using "Power Automate Desktop".
Is there anyway I can see the action from this application or download the code. So that I can create an application then share it with other people.

A: You're unable to share within your organisation without a licence (trial or paid) in PowerAutomate.  You at least need to trigger a trial licence to have that feature.
See the text in orange ...

If you want to download the source, you can literally select all actions within your flow, hit Ctrl + C and then paste the result to a text editor (i.e. like Notepad), save the file and pass it on to another user.
The receiving user can then copy the steps from the text editor and paste them directly into their flow.  The steps will translate.
The annoying part comes if you have a lot of sub flows they'll have to be extracted and saved in a text file one by one and then recreated one by one.

A: stone age code i use to extract Power Automate Desktop query code to a text file
Public Sub glhPAD()

    xx = InputBox("Enter number of times to run")

    For x = 1 To xx
           Open "c:\temp\glhClipboard.txt" For Append As #1
                     Print #1, "==============================================================         "
                     Print #1, Now()
           Close #1

           AppActivate "Power Automate": Application.Wait Now + TimeValue("00:00:02")
           SendKeys "{F2}": Application.Wait Now + TimeValue("00:00:01")
           SendKeys "^c": Application.Wait Now + TimeValue("00:00:01")
           SendKeys "{esc}": Application.Wait Now + TimeValue("00:00:01")
           Call glhClipboardToTextFile

           SendKeys "{enter}": Application.Wait Now + TimeValue("00:00:20")
           SendKeys "{tab}": Application.Wait Now + TimeValue("00:00:01")
           SendKeys "{tab}": Application.Wait Now + TimeValue("00:00:01")
           SendKeys "{tab}": Application.Wait Now + TimeValue("00:00:01")
           SendKeys "^a": Application.Wait Now + TimeValue("00:00:01")
           SendKeys "^c": Application.Wait Now + TimeValue("00:00:02")
           Call glhClipboardToTextFile

           SendKeys "%{F4}": Application.Wait Now + TimeValue("00:00:03")
           SendKeys "{Down}": Application.Wait Now + TimeValue("00:00:01")

    Next x

    MsgBox "Capture Done"
End Sub

Public Sub glhClipboardToTextFile()
    '   reference to Microsoft Forms 2.0 Object Library
    '   VBEditor / Tools / References

    On Error Resume Next
    With New DataObject
        .GetFromClipboard
        Open "c:\temp\glhClipboard.txt" For Append As #1
          Print #1, .GetText
          Print #1, " "
          Print #1, " "

        Close #1
    End With
End Sub


text:
Q: can't bind to socket Code :
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <errno.h>
#include <string.h>
#include <netdb.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <sys/socket.h>
// #include <thread>
#include <arpa/inet.h>
#include <iostream>

using namespace std;

#define PORT 8888
#define BACKLOG 5

int main(int argc, char const *argv[]) {

    int status;
    struct addrinfo hints,
                    *res,
                    *temp;

    char ipstr [INET6_ADDRSTRLEN];
    int socket_fd;

    memset (&hints, 0, sizeof(hints));
    hints.ai_family = AF_UNSPEC;        // Allows both IPv4 and IPv6
    hints.ai_socktype = SOCK_STREAM;
    hints.ai_flags = AI_PASSIVE;        // Allows automatic fill-up of IP (allows using localhost)

    if ((status = getaddrinfo (NULL , "8000", &hints, &res)) != 0 ) {
        cout << "[-] Error: " << gai_strerror (status) << endl;
        exit (EXIT_FAILURE);
    }

    socket_fd = socket (res->ai_family, res->ai_socktype, res->ai_protocol);
    if (socket_fd == -1) {
        cout << "[-] Error : Socket couldn't be created" << endl;
        exit (EXIT_FAILURE);
    }

    if (bind (socket_fd, res->ai_addr, res->ai_addrlen) == -1 ) {
        cout << "[-] Error: Failed to bind to port" << endl;
        exit (EXIT_FAILURE);
    }

    if (connect (socket_fd, res->ai_addr, res->ai_addrlen) == -1) {
        cout << "[-] Error: Failed to connect to remote user" << endl;
        exit (EXIT_FAILURE);
    }

    freeaddrinfo (res);        // free the linked list returned by getaddrinfo ()
    return 0;
}

The code is returning :
[-] Error: Failed to bind to port
It doesn't matter if I put NULL on getaddrinfo ()'s first parameter (making it listen to localHost) or to provide some address, it isn't able to bind port to socket. The port is available as I have tried by changing the value of port. What is wrong with the code ?

A: The code is fine, so when the first time is executed everything works as expected. However, the subsequent execution of the same program will report
[-] Error: Failed to bind to port

If you run netstat --tcp --numeric | grep 8000 you will see that the socket on the port 8000 is in TIME_WAIT state:
bash-4.2$ netstat --tcp --numeric | grep 8000
tcp        0      0 127.0.0.1:8000          127.0.0.1:8000          TIME_WAIT

meaning that connection is closed, so it will be terminated in the timeout specified by the OS (four minutes by default). After the timeout expires, the program executes without the error (again only once).

A: Something here is not making sense. The shown code attempts to bind a socket to a port, then immediately connect() to the same port. So, even if the bind works, connect() will fail anyway, because nothing is listening on that port.
Now, the most likely reason why bind() is failing is because after a socket gets terminated unexpectedly, the kernel will not allow the same port to be reused for a minute or so, for a number of security-related reasons that are too boring to discuss. The first time this code runs, the bind should succeed, but connect() will fail, and the program will exit; then for the next minute or so, rerunning it will result in a bind() failure from the kernel refusing to reuse the port.
To prevent this, you must explicitly set the SO_REUSEADDR socket option. You will find plenty of examples in Google. This will allow you to rebind the same port immediately. Now, all you'll need to do is to figure out what exactly you hoped to accomplish with that connect() call...


text:
Q: Show that either $\mu(S) = 0$ or $\mu(G \setminus S) = 0$ Let $G$ be a locally compact group, $H \leq G$ be a dense subgroup  and $\mu$ be a Haar measure.
Let $S \subseteq G$ be a measurable subset such that for each $h \in H$ the sets $hS \cap (G \setminus S)$ and $S \cap (G \setminus hS)$ are both null-sets.
Then, show that either $\mu(S) = 0$ or $ \mu(G \setminus S) = 0$.
Any help with this question!

A: Fix a measurable subset $S$ in $G$, let $1_S$ denote the indicator function.
Since $1_S\in L^\infty(G)$ we can think about it as a functional on $L^1(G)$ given by
$$1_S (f) = \int_G 1_S(x) f(x)dx=\int_S f(x)dx$$
By assumption we have for every $h\in H$ that
$$\int_G 1_S(hx)f(x)dx-\int_G 1_S(x)f(x)dx = \int_G (1_S(hx)-1_S(x))f(x)dx=0$$
We explain the last equality:
$1_S(hx)-1_S(x)\not=0$ if and only if $x\in S\cap G\backslash hS$ or $x\in hS\cap G\backslash S$, By assumptions we have those are of measure zero. Hence the last equality follows.
We conclude that $$\int_G 1_S(x)f(h^{-1}x)dx=\int_G 1_S(hx)f(x)dx = \int_G 1_S(x)f(x)dx$$
where the first equation is just a change of variables.
Now the map $g\mapsto \int_S f(g^{-1}x) dx$ is continuous and trivial on $H$ hence trivial. Choosing $f$ wisely you would have that $\mu(S)=0,1$.


text:
Q: use LIKE in powerapp with % and _ Is there any eqivalent of LIKE option in PowerApp that allow use sql special characters like "%" or "_" in Search or Filter to find any records?
I would like to write in search: "DAP%55" and find all redords like:
DAPAAA55
DAPoooo55
... and so on...

*

*eqivalent to
SELECT * FROM sth WHERE name like 'DAP%55'

Is that possoble?
Thanks.

A: There are a couple of ways that you can do that:

*

*Filter(<data source name>, StartsWith(name, "DAP"), EndsWith(name, "55"))

*

*This case may work for the pattern in your example, but not for things more complex such as "D_P%55"

*Filter(<data source name>, IsMatch(name, "DAP.+55"))

*

*The IsMatch function is more generic and you can use any regular expressions. This function may not be delegated to the server, so it will be an issue if you need to filter over a large data source.


text:
Q: React useState array not resetting I have a functional component in which I use useState. I try to start with an empty array and it works fine when the component is rendered for the first time. But the component is often re-rendered and the array does not reset.
To give a bit of context, I have a page displaying customers data. I have a select component to change the customer. The data should of course change when I select another one.
My Component
const DataContainer = (props) => {
    const anotherProp = props.selectedInstallation;
    const initValues = props.initValues; // tried to use an empty array as prop
    const [arrValues,setArrayValues] = useState(initValues); // tried useState([]) as well
    console.log(props); // data here are correct and for the right customer
    console.log(anotherProp); // data here are correct and for the right customer
    console.log(initValues); // []
    console.log(arrValues); // should be empty but contains array from previous customer

    useEffect(() => {
        // code omitted
        // I use anotherProp to retrieve some data to use setArrayValues
        const interval = setInterval(() => {
            console.log("props");
            console.log(props);
        },10000);
    },[anotherProp]);

    return (
        <div>
            {(arrValues.length > 0 ? (
                arrValues.map((value,idx) => {
                    return (
                        <Chart value={value} />
                    )
                })) : ""
            )}
        </div>
    );
};

export default DataContainer;

Update
I added an interval that logs the props. I should have a result every 10s but I have one every 5s. Once it logs data from the previous user, once data from the selected user...
Update 2
For the arrValues I tried useState(initValues) where initValues
is an empty array and useState([]). It logs an array with the data from the previous customer and not an empty array.
I don't understand why my arrValues is not empty... The data in my props is correct so I know the switch from one customer to another works. The two methods I used to set arrValues as an empty array don't work.


text:
Q: Compare dataframe column to another dataframe column I have a dataframe column containing page paths (let's call it A):
pagePath
/text/other_text/123-string1-4571/text.html
/text/other_text/string2/15-some_other_txet.html
/text/other_text/25189-string3/45112-text.html
/text/other_text/text/string4/5418874-some_other_txet.html
/text/other_text/string5/text/some_other_txet-4157/text.html
/text/other_text/123-text-4571/text.html
/text/other_text/125-text-471/text.html

And I have another string dataframe column let's call it (B) (the two dataframes are different and they don't have the same number of rows).
Here's an example of my column in dataframe B:
names
string1
string11
string4
string3
string2
string10
string5
string100

What I want to do is to check if my page paths (A) are containing strings from my other dataframe (B).
I had difficulties because my two dataframes haven't the same length and the data are unorganized.
EXPECTED OUTPUT
I want to have this output as a result:
 pagePath                                                  names     exist
/text/other_text/123-string1-4571/text.html                string1   TRUE
/text/other_text/string2/15-some_other_txet.html           string2   TRUE
/text/other_text/25189-string3/45112-text.html             string3   TRUE
/text/other_text/text/string4/5418874-some_other_txet.html string4   TRUE
/text/string5/text/some_other_txet-4157/text.html          string5   TRUE
/text/other_text/123-text-4571/text.html                     NA      FALSE
/text/other_text/125-text-471/text.html                      NA      FALSE

If my question needs more clarification, please mention this.

A: We can generate the exist column with grepl()
# Collapse B$names into one string with "|"
onestring <- paste(B$names, collapse = "|")

# Generate new column
A$exist <- grepl(onestring, A$pagePath)

A: Not that nice, since containing a for loop:
names <- rep(NA, length(A$pagePath))
exist <- rep(FALSE, length(A$pagePath))

for (name in B$names) {
  names[grep(name, A$pagePath)] <- name
  exist[grep(name, A$pagePath)] <- TRUE
}

A: We can use str_extract_all from stringr package but NA are replaced with character(0) so we have to change it
df$names <- as.character(str_extract_all(df$pagePath, "string[0-9]+"))
df$exist <- df$names %in% df1$names
df[df=="character(0)"] <- NA
df
#                                                 pagePath       names   exist
#1                  /text/other_text/123-string1-4571/text.html string1  TRUE
#2             /text/other_text/string2/15-some_other_txet.html string2  TRUE
#3               /text/other_text/25189-string3/45112-text.html string3  TRUE
#4   /text/other_text/text/string4/5418874-some_other_txet.html string4  TRUE
#5 /text/other_text/string5/text/some_other_txet-4157/text.html string5  TRUE
#6                     /text/other_text/123-text-4571/text.html    <NA> FALSE
#7                      /text/other_text/125-text-471/text.html    <NA> FALSE

DATA
dput(df)
structure(list(pagePath = structure(c(1L, 5L, 4L, 7L, 6L, 2L,
3L), .Label = c("/text/other_text/123-string1-4571/text.html",
"/text/other_text/123-text-4571/text.html", "/text/other_text/125-text-471/text.html",
"/text/other_text/25189-string3/45112-text.html", "/text/other_text/string2/15-some_other_txet.html",
"/text/other_text/string5/text/some_other_txet-4157/text.html",
"/text/other_text/text/string4/5418874-some_other_txet.html"), class = "factor")), .Names = "pagePath", class = "data.frame", row.names = c(NA,
-7L))
dput(df1)
structure(list(names = structure(c(1L, 4L, 7L, 6L, 5L, 2L, 8L,
3L), .Label = c("string1", "string10", "string100", "string11",
"string2", "string3", "string4", "string5"), class = "factor")), .Names = "names", class = "data.frame", row.names = c(NA,
-8L))

A: Here is one way using apply:
df$exist <- apply( df,1,function(x){as.logical(grepl(x[2],x[1]))} )


text:
Q: Retornar ultima entrada de cada objeto no banco de dados Eu tenho duas tabelas:
               monitor_carro
id serial | setor_id |  modelo | ano | placa

               monitor_evento
id serial | lat | long | data | fkfuncionario_id | time | carro

A tabela monitor_evento só tem uma chave estrangeira que é funcionario e em ambas as tabelas a chave primaria é a id serial.
Supondo que eu tenha diversos carros inseridos na tabela monitor_carro e que tenha diversas entradas desses carros no meu bd. Gostaria de uma ajuda para retornar a ultima entrada de cada carro na tabela monitor_evento.
Alguém poderia me ajudar com isso?
Desde já agradeço.

A: select distinct on (carro) *
from monitor_evento
order by carro, id_serial desc


text:
Q: Как изменить цвет строки Treeview при выделении? Установил ttkthemes для использования одной темы. К сожалению в ней не реализовано изменение цвета строки при клике на неё. Как можно вручную это настроить?
То есть в самой теме не настроен фокус при нажатии на строку Treeview, из-за этого возникает ряд проблем. Надо как-то включить этот фокус, но я никак не могу понять что и где надо изменить. Помогите, пожалуйста.

A: Нашёл только один способ - лезть в tcl файлы темы и вручную менять.
Код(можно найти в файле ваша_тема.tcl, если нет, то надо вставить):
ttk::style map Treeview \
-background [list disabled $colors(-selectbg)\
        {!disabled !selected} $colors(-window) \
        selected $colors(-selectbg)] \
-foreground [list disabled $colors(-disabledfg) \
        {!disabled !selected} black \
        selected $colors(-selectfg)]

Код в первых [] реализует цвет заднего фона строки в Treeview. Вторые  [] реализуют установку цвета для текста в строках.
$colors(-...) - выбор цвета из списка, который присутствует в самом начале кода каждой темы, вместо этого можно вставить самому любой цвет в формате "#номер".


text:
Q: HM-10 iBeacon: Why is the AT+MEAS command not answered? I am trying to query an HM-10 iBeacon measured power using AT+MEAS? with no success. The module does not respond at all.
I have checked my HM-10 software version using AT+VERS? and it answers HMSoft V540. The datasheet says that the AT+MEAS command was added in V519 version, so this should be not the problem (except they removed it, but the datasheet does not say anything about the removal of the AT+MEAS command).
I am referring to this datasheet.
Also, I have tried to run the AT+MEAS? command before and after I enable iBeacon mode using AT+IBEA1, both with no success.
I run the commands in the Arduino Serial Monitor (no line ending, 9600 baud). The rest of the commands seem to work just fine, only AT+MEAS does not work, both for query (AT+MEAS?) and setting a value (ex. AT+MEAS0xFFE9).
Does anyone know how to query and set HM-10 iBeacon measured power, or to make the AT+MEAS command work?

A: Solved.
So apparently I referred to a "not so right" datasheet for my HM-10 module. After searching a little bit, I found this datasheet.
It turns out that to query and set my HM-10 iBeacon measured power, the commands are AT+MEA?? and AT+MEA[param] respectively.


text:
Q: JQuery Validate input file type I have a form that can have 0-hundreds of <input type="file"> elements. I have named them sequentially depending on how many are dynamically added to the page.
For example:
<input type="file" required="" name="fileupload1" id="fileupload1">
<input type="file" required="" name="fileupload2" id="fileupload2">
<input type="file" required="" name="fileupload3" id="fileupload3">
<input type="file" required="" name="fileupload999" id="fileupload999">

In my JQuery I want to validate these inputs on acceptable MIME/file type. Like this:
$("#formNew").validate({
    rules: {
        fileupload: {
            required: true,
            accept: "image/jpeg, image/pjpeg"
        }
    }

Immediately my problem is that the name attribute of the input file elements is dynamic. It has to be dynamic so that my web application can deal with each upload correctly. So obviously using "fileupload" isn't going to work in the rules section.
How do I set the rules for all inputs which have a name like "fileupload"?
This is the code that dynamically adds the inputs:
var filenumber = 1;
$("#AddFile").click(function () { //User clicks button #AddFile
    $('
<input type="file" name="FileUpload' + filenumber + '" id="FileUpload' + filenumber + '" required=""/> Remove
').prependTo("#FileUploader");
    filenumber++;
    return false;
});
$("#FileUploader").on('click', '.RemoveFileUpload', function () { //Remove input
    if (filenumber > 0) {
        $(this).parent('li').remove();
        filenumber--;
    }
    return false;
});

A: One the elements are added, use the rules method to add the rules
//bug fixed thanks to @Sparky
$('input[name^="fileupload"]').each(function () {
    $(this).rules('add', {
        required: true,
        accept: "image/jpeg, image/pjpeg"
    })
})

Demo: Fiddle

Update
var filenumber = 1;
$("#AddFile").click(function () { //User clicks button #AddFile
    var $li = $('
<input type="file" name="FileUpload' + filenumber + '" id="FileUpload' + filenumber + '" required=""/> Remove
').prependTo("#FileUploader");

    $('#FileUpload' + filenumber).rules('add', {
        required: true,
        accept: "image/jpeg, image/pjpeg"
    })

    filenumber++;
    return false;
});

A: So, I had the same issue and sadly just adding to the rules didn't work. I found out that accept: and extension: are not part of JQuery validate.js by default and it requires an additional-Methods.js plugin to make it work.
So for anyone else who followed this thread and it still didn't work, you can try adding additional-Methods.js to your  tag in addition to the answer above and it should work.

A: Simply use the .rules('add') method immediately after creating the element...
var filenumber = 1;
$("#AddFile").click(function () { //User clicks button #AddFile

    // create the new input element
    $('
<input type="file" name="FileUpload' + filenumber + '" id="FileUpload' + filenumber + '" /> Remove
').prependTo("#FileUploader");

    // declare the rule on this newly created input field
    $('#FileUpload' + filenumber).rules('add', {
        required: true,  // <- with this you would not need 'required' attribute on input
        accept: "image/jpeg, image/pjpeg"
    });

    filenumber++; // increment counter for next time

    return false;
});

*

*You'll still need to use .validate() to initialize the plugin within a DOM ready handler.

*You'll still need to declare rules for your static elements using .validate().   Whatever input elements that are part of the form when the page loads... declare their rules within .validate().

*You don't need to use .each(), when you're only targeting ONE element with the jQuery selector attached to .rules().

*You don't need the required attribute on your input element when you're declaring the required rule using .validate() or .rules('add').  For whatever reason, if you still want the HTML5 attribute, at least use a proper format like required="required".
Working DEMO:  http://jsfiddle.net/8dAU8/5/


text:
Q: Http content loaded in https connection My Webapp is running with a https connection / ssl certificate. I need to show pictures to the user. I get the links to the picture by an API request and link them afterwards. Sadly, the pictures address is http, so the browser shows that there are unsecure parts on the site, which mustn't be...
I could download the pictures and link to the proper picture afterwards, but I think this might be a little timeconsuming and not the best way to handle this.
Does somebody know a better solution for this? I'm using php, jquery and javascript.

A: You'll have to write a proxy on your server and display all the images through it. Basically your URLs should be like:
$url = 'http://ecx.images-amazon.com/images/I/51MU5VilKpL._SL75_.jpg';
$url = urlencode($url);

echo '<img src="/proxy.php?from=' . $url . '">';

and the proxy.php:
$cache = '/path/to/cache';
$url = $_GET['from'];

$hash = md5($url);
$file = $cache . DIRECTORY_SEPARATOR . $hash;
if (!file_exists($file)) {
    $data = file_get_contents($url);
    file_put_contents($file, $data);
}

header('Content-Type: image/jpeg');

readfile($file);

A: Ok, I've got a streaming example for you. You need to adapt it to your needs, of course.
Suppose you make a php file on your server named mws.php with this content:
if (isset($_GET['image']))
{
   header('Content-type: image/jpeg');
   header('Content-transfer-encoding: binary');
   echo file_get_contents($_GET['image']);
}

Look for any image on the web, for instance:
http://freebigpictures.com/wp-content/uploads/2009/09/mountain-stream.jpg

now you can show that image, as if it was located on your own secure server with this url:
https://<your server>/mws.php?image=http://freebigpictures.com/wp-content/uploads/2009/09/mountain-stream.jpg

It would of course be better to store the image locally if you need it more than once, and you have to include the correct code to get it from Amazon MWS ListMatchingProducts, but this is the basic idea.
Please don't forget to secure your script against abuse.


text:
Q: Create unique id on browser tab to keep content of page I'm generating unique id by
session_start();
$id = session_id();

then I'm saving content of web app in database, where primary key is equal to $id. I'm doing this to keep the content of page after refresh.
But when I open another tab, content of both pages is equal.
I red about sessionStorage but I need to generate specific id only when tab is opened for the first time and avoid this behaviour after refresh.
I would love to solve this problem via JavaScript or HTML5 because PHP is running on server side.

A: As your each page has different/unique url you can get that url at php side md5()-it and save to db your data with that unique key
$current_page_link = "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]";
$yourPageReleventUniqueId = md5($current_page_link); // string

documentation for md5 - http://php.net/manual/en/function.md5.php

A: It sounds like you are trying to implement some kind of caching.
Rather than store the page output using the session_id as a key, you could use the route e.g. '/foo'.  Or a combination of session_id and route.


text:
Q: Why does AllowExponent makes Decimal.Parse fail to parse normal numbers? I tried these
    Dim a = Decimal.Parse("0.00001", System.Globalization.NumberStyles.Any)
    Dim c = Decimal.Parse("0.00001")
    Dim cb = Decimal.Parse("0.00001", System.Globalization.NumberStyles.AllowExponent)

The first code works.
The second line works.
The third line doesn't work.
It seems that if I do not mention the numberstyles, the numberstyles default to something. Default to what?
It basically allow parsing normal number (".00001"). However, that ability is turned off if  System.Globalization.NumberStyles.AllowExponent is specified as parameter.
Why is this happening?
What is the default value of NumberStyles if we use the normal overload of Decimal.parse, without additional parameters?

A: You wouldn't write a number with exponent other than a whole number. See my comment above.
    Dim cb = Decimal.Parse("1e-5", System.Globalization.NumberStyles.AllowExponent)
    MessageBox.Show(cb.ToString)
    Dim ab = Decimal.Parse("1e-5", System.Globalization.NumberStyles.Any)
    MessageBox.Show(ab.ToString)

Both message boxes show .00001.

A: I just want to add that per Parsing decimal in scientific notation
System.Globalization.NumberStyles.AllowExponent

doesn't allow putting decimals.
It's probably unituitive.
Hence,
cb = Decimal.Parse("0.00001", System.Globalization.NumberStyles.AllowExponent)

will throw error because the parser cannot parse .
I have no idea why it's designed that way. So how are we going to parse 4.5e10, for example.
You need other options. AllowExponent seems to do exactly that. Allow Exponent and that's it.