Q:

Wrong Stack Size calculated by ASM library

I generate bytecodes using ASM library and 'Max stack size' for a method is left to be calculated automatically. During runtime,i found this value (max stack size) is not correct.
My source code is:
    ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
     ....
    MethodType initType = MethodType.methodType(void.class, clsList);
    mv = cw.visitMethod(ACC_PUBLIC, "<init>", initType.toMethodDescriptorString(), null, null);
    mv.visitCode();
    mv.visitVarInsn(ALOAD, 0);
    mv.visitMethodInsn(INVOKESPECIAL, "java/lang/invoke/BaseTemplate", "<init>", "()V", false);
    for(int i=0; i< list.size(); i++){
        mv.visitVarInsn(ALOAD, 0);
        mv.visitVarInsn(ALOAD, 1+i);
        mv.visitFieldInsn(PUTFIELD, className, list.get(i).name(), Utils.getFieldDesc(list.get(i).type()));
    }
    mv.visitInsn(RETURN);
    //mv.visitMaxs(2, 4);   //Verify succeeds if uncomment this line.
    mv.visitEnd();

     ....
    //Verify generated code before class loading..
    PrintWriter pw = new PrintWriter(System.out);
    CheckClassAdapter.verify(new ClassReader(cw.toByteArray()), true, pw);

 Class<?> expClass =defineClass(..);

Above code will generate bytecodes:
    Classfile /C:/temp/TGWD.class
  Last modified Mar 11, 2015; size 403 bytes
  MD5 checksum f58b96ad4cb0bc9e62f2ae5e11e63e90
public class TGWD extends java.lang.invoke.BaseTemplate
  minor version: 0
  major version: 51
  flags: ACC_PUBLIC, ACC_SUPER

Constant pool:
   #1 = Utf8               TGWD
   #2 = Class              #1             //  TGWD
   #3 = Utf8               java/lang/invoke/BaseTemplate
   #4 = Class              #3             //  java/lang/invoke/BaseTemplate
   #5 = Utf8               guard
   #6 = Utf8               Ljava/lang/invoke/MethodHandle;
   #7 = Utf8               trueTarget
   #8 = Utf8               falseTarget
   #9 = Utf8               <init>
  #10 = Utf8               (Ljava/lang/invoke/MethodHandle;Ljava/lang/invoke/MethodHandle;Ljava/lang/invoke/MethodHandle;)V
  #11 = Utf8               ()V
  #12 = NameAndType        #9:#11         //  "<init>":()V
  #13 = Methodref          #4.#12         //  java/lang/invoke/BaseTemplate."<init>":()V
  #14 = NameAndType        #5:#6          //  guard:Ljava/lang/invoke/MethodHandle;
  #15 = Fieldref           #2.#14         //  TGWD.guard:Ljava/lang/invoke/MethodHandle;
  #16 = NameAndType        #7:#6          //  trueTarget:Ljava/lang/invoke/MethodHandle;
  #17 = Fieldref           #2.#16         //  TGWD.trueTarget:Ljava/lang/invoke/MethodHandle;
  #18 = NameAndType        #8:#6          //  falseTarget:Ljava/lang/invoke/MethodHandle;
  #19 = Fieldref           #2.#18         //  TGWD.falseTarget:Ljava/lang/invoke/MethodHandle;
  #20 = Utf8               eval
  #21 = Utf8               Code
{
  final java.lang.invoke.MethodHandle guard;
    flags: ACC_FINAL

  final java.lang.invoke.MethodHandle trueTarget;
    flags: ACC_FINAL

  final java.lang.invoke.MethodHandle falseTarget;
    flags: ACC_FINAL

  public TGWD(java.lang.invoke.MethodHandle, java.lang.invoke.MethodHandle, java.lang.invoke.MethodHandle);
    flags: ACC_PUBLIC

    Code:
      stack=0, locals=4, args_size=4
         0: aload_0
         1: invokespecial #13                 // Method java/lang/invoke/BaseTemplate."<init>":()V
         4: aload_0
         5: aload_1
         6: putfield      #15                 // Field guard:Ljava/lang/invoke/MethodHandle;
         9: aload_0
        10: aload_2
        11: putfield      #17                 // Field trueTarget:Ljava/lang/invoke/MethodHandle;
        14: aload_0
        15: aload_3
        16: putfield      #19                 // Field falseTarget:Ljava/lang/invoke/MethodHandle;
        19: return

  public void eval();
    flags: ACC_PUBLIC

    Code:
      stack=0, locals=1, args_size=1
         0: return
}

The bytecode reports error:
org.objectweb.asm.tree.analysis.AnalyzerException: Error at instruction 0: Insufficient maximum stack size.
    at org.objectweb.asm.tree.analysis.Analyzer.analyze(Unknown Source)
    at org.objectweb.asm.util.CheckClassAdapter.verify(Unknown Source)
    at org.objectweb.asm.util.CheckClassAdapter.verify(Unknown Source)

because the construction method:
       stack=0, locals=4, args_size=4
The correct stack size is 2.
There is another thread ASM (from ObjectWeb) not calculating MaxStack correctly even though ClassWriter( COMPUTE_MAX + COMPUTE_STACK ) is set, indicating the max stack size can be wrongly calcucated if bytecode in other place is invalid.
So for me, the questions are:

Where is invalidate bytecodes in the generated file?
I still perfer avoiding call visitMax(). Becuase there are a number of generated bytecode methods and manual calucation of these values is not an easy job.

A:

You can’t omit the call to visitMax. From the documentation of ClassWriter.COMPUTE_MAXS:

If this flag is set, then the arguments of the visitMaxs method of the MethodVisitor returned by the visitMethod method will be ignored, and computed automatically from the signature and the bytecode of each method.

In other words, when you specify the flag, you may pass in whatever you want, e.g. call visitMax(-1,-1) to emphasize that you are not providing the actual values, but you still have to call the method to trigger the computation of the correct values.
By the way, since you create a class file of version 51 you should specify COMPUTE_FRAMES as I doubt that you want to create StackMapTable attributes manually. Note that COMPUTE_FRAMES implies COMPUTE_MAXS behavior.


Q:

AppleScript: Tell Google Chrome to activate/deactivate extension

I want to have AppleScript activate/deactivate a plugin, using a keyboard command.
I have set the keyboard command in Google Chrome > Settings > Extensions > Keyboard shortcuts and it works when I do it manually. For this example, I'm using Shift + Alt + U.
I've tried a few variants of this script.
tell application "Google Chrome" to activate
tell application "Google Chrome" to key code u using {option down, shift down}
delay(1)
tell application "Google Chrome" to keystroke "r" using command down

The last past refreshes the window, and it works – but not the second line which is supposed to toggle the extension. Again, I can toggle the extension manually with Shift + Alt + U, but the script won't do it,
I also tried this:
tell application "Google Chrome" to keystroke "u" using {option down, shift down}

Is the script actually supposed to work, making the problem reside somewhere else, or is there something wrong in it?

A:

Try this code instead.
tell application "Google Chrome" to activate
tell application "System Events" to keystroke "u" using {option down, shift down}
delay(1)
tell application "System Events" to keystroke "r" using command down

I actually ran this applescript along with yours. First time I did not test yours seeing you called for a key code but gave it a keystroke value. When I ran your code, it gave me syntax errors(even with proper key code and keystroke values). When I ran my code, it compiles properly and runs the script as intended.


Q:

Objects.hash(Object... values): How are hashes of values cambined?

How are the hashes of arguments combined when calculating Objects.hash(Object... values)?
Here is the javadoc which says it´s equivalent to Arrays.hashCode(Object[]). That opens up the question: how exactly does the latter calculate the hash?

A:

Indeed it is answered in the documentation for int hashCode() in List. (suggested by assylias).
  int hashCode = 1;
  for (E e : list)
      hashCode = 31*hashCode + (e==null ? 0 : e.hashCode());


Q:

Yii2 Advanced application Deployment Steps?

How to deploy Yii2 advanced application on server?
I've try steps given in these link but still by frontend/web/index.php show blank page?
I'm new in Yii2. Please give the steps for deployment.

A:

If you found the application is not deployed. then check or search for error_log file which is show you the exact error in which file.
Below is the path where error_log file will be find:

in your root application
in frontend/web/
in backend/web/


Q:

Make use of AppSettings from Web.config in AngulaJS

I guys, I'm converting asp.net c# application to AngularJS but the problem is how I can keep AppSettings from web.config in Angular.
<appSettings>

    <add key="AppID" value="pkDesk" />
    <add key="UserID" value="Prashanth" />
    <add key="UploadPath" value="\\pk\AttachmentsUpload\" />
</appSettings>

I want it to convert in pure AngularJS, I have found some of Answer on google they have mentioned to use Angular Constant, Angular Services.
How can i achieve this??

A:

Yes as you mentioned , you can use angular constant in your case
var mainApp = angular.module("mainApp", []);
mainApp.constant('AppID', 'pkDesk');
.....
etc

DEMO

var app = angular.module("constantApp", []);
    app.constant('AppID', "pkDesk");
    app.constant('UserID', "Prashanth");
    app.controller('constantController', function($scope, AppID, UserID) {
      console.log(UserID);
      $scope.appID = AppID;
      $scope.userId = UserID;
    });

  <title>Angular JS Services</title>

define constant in angularjs

URL: {{appID}}

Title : {{userId}}


Q:

Android Studio (3.1.2) problems with ADB-service

I'm using Linux Mint Sylvia on a pretty old laptop that do not support the emulators. Therefore I try to connect my Sony XA2 (pretty new with Oreo, 8.0)
I'm trying to detect my device but I seems to have some problem with Android Studio and the ADB-service.
In the log I get:
9:39 PM Unable to detect adb version, adb output: /home/fredrik/Android/Sdk/platform-tools/adb: 1: /home/fredrik/Android/Sdk/platform-tools/adb: Syntax error: "(" unexpected

If I run the lsusb I can find the device:
Bus 002 Device 011: ID 0fce:51f7 Sony Ericsson Mobile Communications AB

I tried to run the adb devices, but first I got this:
adb devices
The program 'adb' can be found in the following packages:
 * adb
 * android-tools-adb
Try: sudo apt install <selected package>

So I installed the adb with:
sudo apt install android-tools-adb

Then I could run the adb like:
adb devices
* daemon not running. starting it now on port 5037 *
* daemon started successfully *
List of devices attached
CQ3000KKV4  unauthorized

But still I got the error above in Android Studio.
Do you guys got any clue?
Best regards
Fredrik

A:

Adb after installation seems to run correct.
Your device is listed as unauthorized so I guess you did not turn on developer tools on your device, or on your device you did not accept debuging with connected computer.
To turn on developer options on device:

Open Settings on your Android O running device.
Select System » About phone.
Scroll down and tap seven times on the Build number entry.
Now go back to Settings » System » and select Developer options from there.

In these options you should allow usb debuging if it’s not on by default.
After connecting usb cable to your device and conputer you should see prompt on your device asking for permissions to allow debuging. If you accept that you should be able to run adb tools, logcat etc on your connected device.

EDIT
Looking at the error you described in comments, it looks like it is error specific for 32-bit version systems. So I see there two possible solutions:

reinstall your system for 64-bit version

or more likely:

downgrade your adb platform tools

How to downgrade adb platform tools:

Download platform tools from this archive:
https://dl-ssl.google.com/android/repository/platform-tools_r23.0.1-linux.zip
Go to your Android SDK folder (so in your case it will bee /home/fredrik/Android/sdk/)
Remove old platform-tools
Insert data from link downloaded above

Hope it will be your case. Please keep in mind that updates of Android Studio will probably restore that error again.


Q:

Skype keeps making me automatically invisible

I keep getting made invisible automatically by skype.  It doesn't even appear to happen at consistent intervals.  Sometimes it doesn't happen at all, sometimes it happens every 5 seconds.  I don't want this to happen, but I can't find an option to disable it.  Does anybody know if it's possible to disable the invisible status or prevent the timer at all?  Or is there a hotkey that I am inadvertently pressing that activates invisible mode?
Thanks.

A:

This could happen when you're logged into your account using multiple devices, so the statuses could be not in sync.
For workaround there are some cloud-based chat commands which allows you to see where you're logged in and you can logout from the remote sessions.

Create an empty conversation.
Type command in the message textbox:
/showplaces

Lists other endpoints that can receive push notifications for calls and IMs for this Skype account.

If you want to logout from remote online endpoints, then execute:
/remotelogout

Sign out all other instances except the current one. This will also stop push notifications on all other instances.


Q:

Asana Connect (OAuth) can not get token

when using the asana Oauth to get the Token
the https://app.asana.com/-/oauth_token return
Error

No route found

Any help?
Thanks!

A:

Create you application in asana

GET URL = 'https:// app.asana.com/-/oauth_authorize?client_id='+ setting.client_id
      + '&redirect_uri='  + setting.redirect_uri
      + '&response_type=' + setting.response_type

You get the code, POST code URL'https:// app.asana.com/-/oauth_token?grant_type=authorization_code'
            + '&client_id='     + setting.client_id
            + '&client_secret=' + setting.client_secret
            + '&code='          + query.code
            + '&redirect_uri='  + setting.redirect_uri

The access code is issued for an one hour. POST URL 'https:// app.asana.com/-/oauth_token?grant_type=refresh_token'
            + '&client_id='     + setting.client_id
            + '&client_secret=' + setting.client_secret
            + '&refresh_token=' + setting.refresh_token  ----- for refresh access co


Q:

Get the inner text by ID or any other way C#

Hello folks thanks for reading my question in advance. i have a webbrowser in my windows form application in c# and i am going to a website to get the innertext after a quick query. the HTML is the following.

Fall Semester 2015

<input type="hidden" name="WSS.COURSE.SECTIONS_1" value="Fall Semester 2015">

and i wanted to get the inner text by using the WSS_COURSE_SECTIONS_1, but i already have tried using the following code
HtmlElement s1 = webBrowser1.Document.GetElementById("WSS_COURSE_SECTIONS_1");
string s = s1.InnerText;

But when i check the containing values in the s1 it contains "null"
How can i get "Fall Semester 2015".
Thank you again folks.

A:

i wasnt getting the innertext because at the time that i was trying to get the data the webbrowser havent finished loading the webpage. I used that code webBrowser1.Document.GetElementById("WSS_COURSE_SECTIONS_1").Innertext; and it worked. Remeber to set the event handler to wait until the page loads


Q:

Upgraded to HTTPS and getting error from gtmetrix, unable to connect to the server

I just upgraded the settings in my server to use HTTPS and generate a free Let's Encrypt - Free SSL/TLS Certificates, I can access my website using the web browser (Chrome - Windows), however, when I try to test it using Pagespeed Insights (GTMetrix) I'm getting this error
Analysis Error
An error occurred fetching the page: HTTPS error: certificate verify failed
There may be a connectivity issue between your server and the GTmetrix test server. Try testing from another test location or try again later.

A:

Just missing CA Bundle (Contains Root And Intermediate Certificates)
In Direct admin go to  SSL Certificates under Advanced Features Section

on the bottom of the page click on paste a CA Root Certificate

paste CA Bundle on the box and check Use a CA Cert.

then click save.


Q:

Inverse image of sheaves

I am trying to prove the following:
$$f^{-1}(g^{-1}(\mathscr{H})) = (g \circ f)^{-1}(\mathscr{H})$$
where $\mathscr{H}$ is a presheaf on some topological space $Z$ and $f: X \rightarrow Y$, $g : Y \rightarrow Z$ are continuous maps between topological spaces. My definition of inverse image of a sheaf is the following: given $\mathscr{F}$ a sheaf on $Y$ and $f : X \rightarrow Y$ a continuous map between topological spaces we define
$$f^+\mathscr{F}(U) = \lim_{
\begin{array}{c}
\longrightarrow\\
V \supseteq f(U)\\
V \subseteq Y \text{ open}
\end{array}}
\mathscr{F}(V)
$$
and we define $f^{-1}\mathscr{F}$ to be the sheafification of $f^+\mathscr{F}$. I understand that $f^+(g^+(\mathscr{F})) = (g \circ f)^+(\mathscr{F})$, hence: $(g \circ f)^{-1}(\mathscr{F}) = \mathscr{G}$, where with $\mathscr{G}$ I mean the sheafification of $f^+(g^+(\mathscr{F})$. Now by the universal property of sheafification we obtain that $\mathscr{G} = f^{-1}(g^+(\mathscr{F}))$ and we have a natural morphism $f^{-1}(g^+(\mathscr{F})) \rightarrow f^{-1}(g^{-1}(\mathscr{H}))$ which is the map induced by $f^+(i)$, where $i: g^+(\mathscr{F}) \rightarrow g^{-1}(\mathscr{F})$ is the sheafification map. I don't understand why that map must be an isomorphism (I can't use the characterization of the stalks of the presheaf $f^+(-)$ or of $f^{-1}(-)$) and I don't find another way to show the isomorphism at the beginning.
Thank you.

A:

I find proving equalities like this way more "intuitive" using the universal properties. You might want to take the following approach.
Given $f:X\to Y$ and a sheaf $\mathscr{F}$ on $X$, the \emph{direct image} sheaf $f_*\mathscr{F}$ (on $Y$) is defined as $f_*\mathscr{F}(U)=\mathscr{F}(f^{-1}U)$. In the language of category theory the functor $f^{-1}$ (that you defined) is the left-adjoint to direct image functor $f_*$. More explicity, given any sheaf $\mathscr{F}$ on $X$ and any sheaf $\mathscr{G}$ on $Y$ one has a natural bijection of sets:
$$
\alpha: \mathrm{Hom}_Y(\mathscr{G}, f_*\mathscr{F})\to \mathrm{Hom}_{X}(f^{-1}\mathscr{G}, \mathscr{F})
$$
where by $\mathrm{Hom}_X(\mathscr{F_1}, \mathscr{F}_2)$ I mean the set of morphisms of sheaves from $\mathscr{F}_1$ to $\mathscr{F}_2$. You might want to first find such $\alpha$. This is called the adjoint property (I'll provide hints on how to do this at the end.
Using the adjoint property prove that thre is a natural bijection
$$
\beta:\mathrm{Hom}_X (f^{-1}(g^{-1}\mathscr{H}), \mathscr{F)}\to
\mathrm{Hom}_X ((f\circ g)^{-1}\mathscr{H}, \mathscr{F})
$$
for any sheaf $\mathscr{H}$ on $Z$ and any sheaf $\mathscr{F}$ on $X$. In particular let $\mathscr{F}=f^{-1}(g^{-1}\mathscr{H})$, with its bijeciton
$$
\beta:\mathrm{Hom}_X (f^{-1}(g^{-1}\mathscr{H}), f^{-1}(g^{-1}\mathscr{H}))\to
\mathrm{Hom}_X ((f\circ g)^{-1}\mathscr{H}, f^{-1}(g^{-1}\mathscr{H}))
$$
Now choose the identity morephism $\mathrm{id}\in \mathrm{Hom}_X (f^{-1}(g^{-1}\mathscr{H}), f^{-1}(g^{-1}\mathscr{H}))$. What is $\beta(\mathrm{id})$ now? What does say about $(f\circ g)^{-1}$ and $f^{-1}\circ g^{-1}$?
Adjoint property: Consider a morphism $\phi: \mathscr{G}\to f_*\mathscr{F}$, meaning for each open set $V\subset Y$, one has $\phi(V): \mathscr{G}(V)\to \mathscr{F}(f^{-1}(V))$ compatible with restriction. Take an open set $U\subset X$, and suppose $V\subset Y$ is such that $f(U)\subset V$, then $U\subset f^{-1}(V)$, therefore using a restriction map we have a function $\mathscr{F}(f^{-1}(V))\to \mathscr{F}(U)$. Gathering all of this you will find a family of maps
$$
\psi_V: \mathscr{G}(V)\to \mathscr{F}(U)
$$
for all $V\supset f(U)$. By universal property of direct limit then there exists a map, compatible with all these maps,
$$
\omega(U): f^+\mathscr{G}(U)\to \mathscr{F}(U)
$$
I leave it to you to check this naturally extends to a morphism $\omega: f^{-1}\mathscr{G}\to \mathscr{F}$ (use universal propert of sheafification). Define $\alpha(\phi)=\omega$.
Going in the reverse direction, take a morphism $\omega(U): f^{-1}\mathscr{G}(U)\to \mathscr{F}(U)$. Take an open set $V\subset Y$ and let $U=f^{-1}(V)$. Then $f^{-1}\mathscr{G}(U)=\mathscr{G}(V)$, and using $\omega$, we a map $\phi(V): \mathscr{G}(V)\to f_*\mathscr{F}(V)$. Show that $\phi$ is indeed a morphism of sheaves. Then prove that this map is inverse to $\alpha$.


Q:

Android XML graphical layout viewer - cannot instantiate custom view, class not found?

I have a very simple custom view that tries to draw an OvalShape, a.k.a. android.graphics.drawable.shapes.OvalShape. So it's native to the SDK.
This is the error title:
com.dan.test.ui.ArcButton failed to instantiate.

This is the error body:
java.lang.ClassNotFoundException: android.graphics.drawable.shapes.OvalShape
at com.android.ide.eclipse.adt.internal.resources.manager.ProjectClassLoader.findClass(ProjectClassLoader.java:105)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.ClassLoader.loadClass(Unknown Source)
at java.lang.Class.getDeclaredConstructors0(Native Method)
at java.lang.Class.privateGetDeclaredConstructors(Unknown Source)
at java.lang.Class.getConstructor0(Unknown Source)
at java.lang.Class.getConstructor(Unknown Source)
at com.android.ide.eclipse.adt.internal.editors.layout.ProjectCallback.instantiateClass(ProjectCallback.java:327)
at com.android.ide.eclipse.adt.internal.editors.layout.ProjectCallback.loadView(ProjectCallback.java:166)
at com.android.layoutlib.bridge.android.BridgeInflater.loadCustomView(BridgeInflater.java:205)
at com.android.layoutlib.bridge.android.BridgeInflater.createViewFromTag(BridgeInflater.java:133)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:623)
at android.view.LayoutInflater.rInflate(LayoutInflater.java:626)
at android.view.LayoutInflater.inflate(LayoutInflater.java:408)
at android.view.LayoutInflater.inflate(LayoutInflater.java:296)
at com.android.layoutlib.bridge.impl.RenderSessionImpl.inflate(RenderSessionImpl.java:279)
at com.android.layoutlib.bridge.Bridge.createSession(Bridge.java:318)
at com.android.ide.common.rendering.LayoutLibrary.createSession(LayoutLibrary.java:325)
at com.android.ide.eclipse.adt.internal.editors.layout.gle2.RenderService.createRenderSession(RenderService.java:372)
at com.android.ide.eclipse.adt.internal.editors.layout.gle2.GraphicalEditorPart.renderWithBridge(GraphicalEditorPart.java:1361)
at com.android.ide.eclipse.adt.internal.editors.layout.gle2.GraphicalEditorPart.recomputeLayout(GraphicalEditorPart.java:1115)
at com.android.ide.eclipse.adt.internal.editors.layout.gle2.GraphicalEditorPart.activated(GraphicalEditorPart.java:941)
at com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditorDelegate.partActivated(LayoutEditorDelegate.java:477)
at com.android.ide.eclipse.adt.internal.editors.layout.LayoutEditorDelegate.partBroughtToTop(LayoutEditorDelegate.java:487)
at org.eclipse.ui.internal.PartListenerList$2.run(PartListenerList.java:87)
at org.eclipse.core.runtime.SafeRunner.run(SafeRunner.java:42)
at org.eclipse.core.runtime.Platform.run(Platform.java:888)
at org.eclipse.ui.internal.PartListenerList.fireEvent(PartListenerList.java:57)
at org.eclipse.ui.internal.PartListenerList.firePartBroughtToTop(PartListenerList.java:85)
at org.eclipse.ui.internal.PartService.firePartBroughtToTop(PartService.java:208)
at org.eclipse.ui.internal.WorkbenchPagePartList.firePartBroughtToTop(WorkbenchPagePartList.java:76)
at org.eclipse.ui.internal.WorkbenchPagePartList.fireActiveEditorChanged(WorkbenchPagePartList.java:52)
at org.eclipse.ui.internal.PartList.setActiveEditor(PartList.java:162)
at org.eclipse.ui.internal.WorkbenchPage.makeActiveEditor(WorkbenchPage.java:1355)
at org.eclipse.ui.internal.WorkbenchPage.setActivePart(WorkbenchPage.java:3629)
at org.eclipse.ui.internal.WorkbenchPage.requestActivation(WorkbenchPage.java:3159)
at org.eclipse.ui.internal.PartPane.requestActivation(PartPane.java:279)
at org.eclipse.ui.internal.EditorPane.requestActivation(EditorPane.java:98)
at org.eclipse.ui.internal.PartPane.setFocus(PartPane.java:325)
at org.eclipse.ui.internal.EditorPane.setFocus(EditorPane.java:127)
at org.eclipse.ui.internal.PartStack.presentationSelectionChanged(PartStack.java:837)
at org.eclipse.ui.internal.PartStack.access$1(PartStack.java:823)
at org.eclipse.ui.internal.PartStack$1.selectPart(PartStack.java:137)
at org.eclipse.ui.internal.presentations.util.TabbedStackPresentation$1.handleEvent(TabbedStackPresentation.java:133)
at org.eclipse.ui.internal.presentations.util.AbstractTabFolder.fireEvent(AbstractTabFolder.java:269)
at org.eclipse.ui.internal.presentations.util.AbstractTabFolder.fireEvent(AbstractTabFolder.java:278)
at org.eclipse.ui.internal.presentations.defaultpresentation.DefaultTabFolder.access$1(DefaultTabFolder.java:1)
at org.eclipse.ui.internal.presentations.defaultpresentation.DefaultTabFolder$2.handleEvent(DefaultTabFolder.java:88)
at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1053)
at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1077)
at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1062)
at org.eclipse.swt.widgets.Widget.notifyListeners(Widget.java:774)
at org.eclipse.swt.custom.CTabFolder.setSelection(CTabFolder.java:2746)
at org.eclipse.swt.custom.CTabFolder.onMouse(CTabFolder.java:1433)
at org.eclipse.swt.custom.CTabFolder$1.handleEvent(CTabFolder.java:257)
at org.eclipse.swt.widgets.EventTable.sendEvent(EventTable.java:84)
at org.eclipse.swt.widgets.Widget.sendEvent(Widget.java:1053)
at org.eclipse.swt.widgets.Display.runDeferredEvents(Display.java:4165)
at org.eclipse.swt.widgets.Display.readAndDispatch(Display.java:3754)
at org.eclipse.ui.internal.Workbench.runEventLoop(Workbench.java:2701)
at org.eclipse.ui.internal.Workbench.runUI(Workbench.java:2665)
at org.eclipse.ui.internal.Workbench.access$4(Workbench.java:2499)
at org.eclipse.ui.internal.Workbench$7.run(Workbench.java:679)
at org.eclipse.core.databinding.observable.Realm.runWithDefault(Realm.java:332)
at org.eclipse.ui.internal.Workbench.createAndRunWorkbench(Workbench.java:668)
at org.eclipse.ui.PlatformUI.createAndRunWorkbench(PlatformUI.java:149)
at org.eclipse.ui.internal.ide.application.IDEApplication.start(IDEApplication.java:123)
at org.eclipse.equinox.internal.app.EclipseAppHandle.run(EclipseAppHandle.java:196)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.runApplication(EclipseAppLauncher.java:110)
at org.eclipse.core.runtime.internal.adaptor.EclipseAppLauncher.start(EclipseAppLauncher.java:79)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:344)
at org.eclipse.core.runtime.adaptor.EclipseStarter.run(EclipseStarter.java:179)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.eclipse.equinox.launcher.Main.invokeFramework(Main.java:622)
at org.eclipse.equinox.launcher.Main.basicRun(Main.java:577)
at org.eclipse.equinox.launcher.Main.run(Main.java:1410)
at org.eclipse.equinox.launcher.Main.main(Main.java:1386)

This is a piece of my layout XML:
<com.dan.test.ui.ArcButton
android:id="@+id/btn_arc"
android:layout_width="100dip"
android:layout_height="75dip"
android:layout_gravity="center"
/>

This is my onDraw code in the ArcButton class:
@Override
protected void onDraw(Canvas canvas)
{
    super.onDraw(canvas);

    // SETUP
    int r = (int) radius;

    // BG WHITE
    int cx = this.getWidth() / 2, cy = this.getHeight() / 2;
    Paint bg_paint = new Paint();
    bg_paint.setAntiAlias(true);
    bg_paint.setARGB(255, 255, 255, 255);
    ShapeDrawable bg = new ShapeDrawable(new OvalShape()); // If removed, then ArcShape causes the same CNFE error
    canvas.drawCircle(cx, cy, r, bg_paint);

    // ROTATING ARC
    ShapeDrawable drawable = new ShapeDrawable(new ArcShape(-90, s));
    drawable.getPaint().setColor(0xff74AC23);
    drawable.setBounds(cx - (r-2), cy - (r-2), cx + (r-2), cy + (r-2));
    drawable.draw(canvas);

    invalidate();
}

EDIT: Also, I have these constructors already in place. Even so, error still occurring:
public ArcButton(Context context, AttributeSet attrs, int defStyle)
{
    super(context, attrs, defStyle);
}

public ArcButton(Context context, AttributeSet attrs)
{
    super(context, attrs);
}

public ArcButton(Context context)
{
    super(context);
}

A:

find my code, maybe you have some difference and also clean project.
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.drawable.ShapeDrawable;
import android.graphics.drawable.shapes.ArcShape;
import android.graphics.drawable.shapes.OvalShape;
import android.util.AttributeSet;
import android.view.View;

public class Button1 extends View
{
    private int radius = 100;

     /**
     * @param context
     * @param attrs
     */
    public Button1(Context context, AttributeSet attrs)
    {
        super(context, attrs);
    }

    @Override
    protected void onDraw(Canvas canvas)
    {
        super.onDraw(canvas);

        // SETUP
        int r = (int) radius ;

        // BG WHITE
        int cx = this.getWidth() / 2, cy = this.getHeight() / 2;
        Paint bg_paint = new Paint();
        bg_paint.setAntiAlias(true);
        bg_paint.setARGB(255, 255, 255, 255);
        ShapeDrawable bg = new ShapeDrawable(new OvalShape()); // If removed, then ArcShape causes the same CNFE error
        canvas.drawCircle(cx, cy, r, bg_paint);

        // ROTATING ARC
        ShapeDrawable drawable = new ShapeDrawable(new ArcShape(-90, 60));
        drawable.getPaint().setColor(0xff74AC23);
        drawable.setBounds(cx - (r-2), cy - (r-2), cx + (r-2), cy + (r-2));
        drawable.draw(canvas);

        invalidate();
    }
}


Q:

writing the console result into textfile

I wrote this code to convert binary data to ascii , now I want to write the console result into a textfile output.txt . it runs but the problem is it prints the first line into console and start writing the output to textfile from the second line , on other words it skip the fisr line !
public static void main(String args[])
  {
  try{
  // Open the file that is the first
  // command line parameter
  FileInputStream fstream = new FileInputStream("textfile.txt");
  // Get the object of DataInputStream
  DataInputStream in = new DataInputStream(fstream);
  BufferedReader br = new BufferedReader(new InputStreamReader(in));
  String strLine;
  //Read File Line By Line
  while ((strLine = br.readLine()) != null)   {

      String input = br.readLine();
            String output = "";
            for(int i = 0; i <= input.length() - 8; i+=8)
            {
                int k = Integer.parseInt(input.substring(i, i+8), 2);
                output += (char) k;
            }

                System.out.println("string: " + output);
          orgStream = System.out;
          fileStream = new PrintStream(new FileOutputStream("d:/output.txt",true));

          // Redirecting console output to file
          System.setOut(fileStream);

              }
  //Close the input stream
  in.close();
    }catch (Exception e){//Catch exception if any
  System.err.println("Error: " + e.getMessage());
  }
  }
}

these line are responsible for writing the result into output.txt:
 System.out.println("string: " + output);
          orgStream = System.out;
          fileStream = new PrintStream(new FileOutputStream("d:/output.txt",true));

          // Redirecting console output to file
          System.setOut(fileStream);

how can I save output in eclipse to be able to use that again ? now I save in D drive

A:

the code
System.err.println("Error: " + e.getMessage()); will write to the error stream and not the out stream..
          System.setOut(out);

here you are setting the out stream, the err stream still defaults to the console.


Q:

Alternative to ForEach?

I have the class Exam with the following attributes:
package logic;

import java.util.ArrayList;

public class Exam {

    private int number;
    private Professor professor;
    private ArrayList<Question> questions = new ArrayList<Question>();
    private ArrayList<Test> tests = new ArrayList<Test>();

    ... // getters, setters, etcetera

}

My question is about the constructor:
public Exam(Professor professor, ArrayList<Question> questions) {

    this.professor = professor;

    for(Question question : questions) // <---
        this.questions.add(question); // <---

}

Is there any alternative to foreach in order to add the questions? For example, using a while or another cycle? How could it be? I've been trying but couldn't make it work.

A:

How about a simple List#addAll()?
this.questions.addAll(questions);

Note, it would help if you explained why your current code is not working for you, and how it fails (compile error? runtime exception? something else?).


Q:

Disadvantages of HTTP GET/POST Flooding Attack?

I asked about What is HTTP GET/POST Flooding Attack? recently and I got a few detailed answers about what they are and how they work.
Now I want to find out what are the disadvantages of them.

A:

Main disadvantages (for the attacker) of that kind of flooding attack are:

Traces. If the attacker is doing the HTTP requests himself, then he must first establish a working TCP connection, i.e. one where he can receive response packets. Therefore, his IP address will appear in the logs of the target server. (Alternative is to predict TCP sequence numbers for new connections, which is nigh infeasible with modern operating systems which use decent random generators for that.) Launching the attack while avoiding retribution implies using many relay systems, which are expensive to gather, especially since most will be "burned" (revealed as relays) in the process. This contrasts with SYN floods in which the attacker can use fake, random, non-incriminating source addresses for his packets.
Scale. Serving a typical HTTP request is not very expensive for a Web server, which does that all day long. To drown it under the influx of requests, the attacker has to muster a substantial workforce, especially with regards to network bandwidth; he will not flood the server with 3 or 4 PC, rather 300 or 400 at least. Flooding is about who, between target and attacker, will have the biggest network and the fastest CPU.
Duration. As soon as the attack ceases, the target server becomes fully operational again. It is hard to obtain long-lasting effects. But the longer the attack runs, the easier it becomes for law enforcement agencies to pinpoint the perpetrator.
Cheesiness. Flooding is the level zero of attacks. It is brutal and inelegant. It has no finesse. If the attacker runs the attack in order to gain some prestige among his fellow attackers, this might backfire (floods are for script kiddies).


Q:

JBoss EJB 3 issue DeploymentException

I am deploying a EJB3 Jar with several beans in it. The jar works fine on other instances and is deployed correctly. However if I try that on my machine, I get the DeploymentException.
I am on JBoss 5.1.0
Please help!!
Here is the stack trace:

*** DEPLOYMENTS IN ERROR: Name -> Error
vfszip:/D:/jboss-5.1.0.GA/server/default/deploy/Enhanced-QC-ejb.jar/ -> org.jboss.deployers.spi.DeploymentException: org.jboss.deployers.spi.DeploymentException: Error deploying: Factory$org.jboss.aspects.remoting.InvokeRemoteInterceptor
DEPLOYMENTS IN ERROR:
  Deployment "vfszip:/D:/jboss-5.1.0.GA/server/default/deploy/Enhanced-QC-ejb.jar/" is in error due to the following reason(s): java.lang.IllegalStateException: Factory$org.jboss.aspects.remoting.InvokeRemoteInterceptor is already installed.
    at org.jboss.deployers.plugins.deployers.DeployersImpl.checkComplete(DeployersImpl.java:993)
    at org.jboss.deployers.plugins.deployers.DeployersImpl.checkComplete(DeployersImpl.java:939)
    at org.jboss.deployers.plugins.main.MainDeployerImpl.checkComplete(MainDeployerImpl.java:873)
    at org.jboss.system.server.profileservice.repository.MainDeployerAdapter.checkComplete(MainDeployerAdapter.java:128)
    at org.jboss.system.server.profileservice.hotdeploy.HDScanner.scan(HDScanner.java:369)
    at org.jboss.system.server.profileservice.hotdeploy.HDScanner.run(HDScanner.java:255)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:441)
    at java.util.concurrent.FutureTask$Sync.innerRunAndReset(FutureTask.java:317)
    at java.util.concurrent.FutureTask.runAndReset(FutureTask.java:150)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$101(ScheduledThreadPoolExecutor.java:98)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.runPeriodic(ScheduledThreadPoolExecutor.java:181)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:205)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
    at java.lang.Thread.run(Thread.java:619)

A:

Try to clean the tmp directory (D:/jboss-5.1.0.GA/server/default/tmp in your case) and restart JBoss.


Q:

Как верно высчитать прошедшее время?

Сразу пример
http://jsbin.com/uFUSOZOJ/1/edit?js,output
Я хочу вывести точно сколько прошло лет, месяцев и дней с определённой даты, ибо запись "234234 дней" кажется мне чудовищной. Попробовал выводить отдельно года, месяца и дни, но столкнулся с ошибкой в подсчётах.
Метод getTime() выводит точно, но я не знаю, как верно его дату превратить в годы, месяца и дни, чтоб учесть, что в феврале 28 дней (в високосный год 29), что в нечётном месяце 31 день, а в чётном - 30.
Помогите, пожалуйста, реализовать подсчёт.
p.s. решение, что в астрономическом месяце (365 + 365 + 365 + 366) / 48 = 30.4375 дней мне не нравится ввиду такой же своей неточности.

A:

Попробуйте так, хотя и без проверок
function leapyear(y) {
    if (y%400 == 0) return 1;
    if (y%100 == 0) return 0;
    else if(y%4 == 0) return 1;
    else return 0;
}
var months = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
function diff(d2, d1) {
    var y1, m1, d1, y2, m2, d2, o;
    y1 = d1.getFullYear();
    m1 = d1.getMonth();
    d1 = d1.getDate();
    y2 = d2.getFullYear();
    m2 = d2.getMonth();
    d2 = d2.getDate();
    o = new Object();
    if (d2 < d1) {
        o.d = d2 + months[(m2+11)%12] - d1;
        if(leapyear(y2) && m2 == 2) o.d++; // март на дворе
        m2--;
    } else o.d = d2 - d1;
    if (m2 < m1) {
        o.m = m2 + 12 - m1;
        y2--;
    } else o.m =  m2 - m1;
    o.y = y2 - y1;
    return o;
}

Надеюсь, даты до Рождества Христова Вас не интересуют.
UPD
Добавлена проверка на кратность года 400, как указал @Gurylev. Но выражение из его комментария гораздо симпатичней.


Q:

org.springframework.context.ApplicationContextException: Failed to start bean 'org.springframework.kafka.config.internalKafkaListenerEndpointRegistry

I am developing Spring Boot + Apache Kafka + Apache Zookeeper example. I've installed/setup Apache Zookeeper and Apache Kafka on my local windows machine. I've taken a reference from link: https://www.tutorialspoint.com/spring_boot/spring_boot_apache_kafka.htm and executed code as is:
Setup: https://medium.com/@shaaslam/installing-apache-kafka-on-windows-495f6f2fd3c8
Error:
org.springframework.context.ApplicationContextException: Failed to start bean 'org.springframework.kafka.config.internalKafkaListenerEndpointRegistry'; nested exception is org.apache.kafka.common.errors.TimeoutException: Timeout expired while fetching topic metadata
    at org.springframework.context.support.DefaultLifecycleProcessor.doStart(DefaultLifecycleProcessor.java:185) ~[spring-context-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.context.support.DefaultLifecycleProcessor.access$200(DefaultLifecycleProcessor.java:53) ~[spring-context-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.context.support.DefaultLifecycleProcessor$LifecycleGroup.start(DefaultLifecycleProcessor.java:360) ~[spring-context-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.context.support.DefaultLifecycleProcessor.startBeans(DefaultLifecycleProcessor.java:158) ~[spring-context-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.context.support.DefaultLifecycleProcessor.onRefresh(DefaultLifecycleProcessor.java:122) ~[spring-context-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.finishRefresh(AbstractApplicationContext.java:879) ~[spring-context-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.context.support.AbstractApplicationContext.refresh(AbstractApplicationContext.java:549) ~[spring-context-5.1.3.RELEASE.jar:5.1.3.RELEASE]
    at org.springframework.boot.SpringApplication.refresh(SpringApplication.java:775) [spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE]
    at org.springframework.boot.SpringApplication.refreshContext(SpringApplication.java:397) [spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:316) [spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1260) [spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE]
    at org.springframework.boot.SpringApplication.run(SpringApplication.java:1248) [spring-boot-2.1.1.RELEASE.jar:2.1.1.RELEASE]
    at com.tutorialspoint.SpringKafkaTutorialspointApplication.main(SpringKafkaTutorialspointApplication.java:21) [classes/:na]
Caused by: org.apache.kafka.common.errors.TimeoutException: Timeout expired while fetching topic metadata

Logs from Zookeeper server:
2018-12-14 22:16:35,352 [myid:] - INFO  [NIOServerCxn.Factory:0.0.0.0/0.0.0.0:2181:NIOServerCnxn@1040] - Closed socket connection for client /127.0.0.1:60197 (no session established for client)
2018-12-14 22:16:36,260 [myid:] - INFO  [NIOServerCxn.Factory:0.0.0.0/0.0.0.0:2181:NIOServerCnxnFactory@215] - Accepted socket connection from /127.0.0.1:60200
2018-12-14 22:16:36,260 [myid:] - WARN  [NIOServerCxn.Factory:0.0.0.0/0.0.0.0:2181:NIOServerCnxn@383] - Exception causing close of session 0x0: null
2018-12-14 22:16:36,262 [myid:] - INFO  [NIOServerCxn.Factory:0.0.0.0/0.0.0.0:2181:NIOServerCnxn@1040] - Closed socket connection for client /127.0.0.1:60200 (no session established for client)
2018-12-14 22:16:37,473 [myid:] - INFO  [NIOServerCxn.Factory:0.0.0.0/0.0.0.0:2181:NIOServerCnxnFactory@215] - Accepted socket connection from /127.0.0.1:60204
2018-12-14 22:16:37,473 [myid:] - WARN  [NIOServerCxn.Factory:0.0.0.0/0.0.0.0:2181:NIOServerCnxn@383] - Exception causing close of session 0x0: null
2018-12-14 22:16:37,476 [myid:] - INFO  [NIOServerCxn.Factory:0.0.0.0/0.0.0.0:2181:NIOServerCnxn@1040] - Closed socket connection for client /127.0.0.1:60204 (no session established for client)
2018-12-14 22:16:38,383 [myid:] - INFO  [NIOServerCxn.Factory:0.0.0.0/0.0.0.0:2181:NIOServerCnxnFactory@215] - Accepted socket connection from /127.0.0.1:60207
2018-12-14 22:16:38,384 [myid:] - WARN  [NIOServerCxn.Factory:0.0.0.0/0.0.0.0:2181:NIOServerCnxn@383] - Exception causing close of session 0x0: null
2018-12-14 22:16:38,388 [myid:] - INFO  [NIOServerCxn.Factory:0.0.0.0/0.0.0.0:2181:NIOServerCnxn@1040] - Closed socket connection for client /127.0.0.1:60207 (no session established for client)
2018-12-14 22:16:39,494 [myid:] - INFO  [NIOServerCxn.Factory:0.0.0.0/0.0.0.0:2181:NIOServerCnxnFactory@215] - Accepted socket connection from /127.0.0.1:60211
2018-12-14 22:16:39,494 [myid:] - WARN  [NIOServerCxn.Factory:0.0.0.0/0.0.0.0:2181:NIOServerCnxn@383] - Exception causing close of session 0x0: null
2018-12-14 22:16:39,497 [myid:] - INFO  [NIOServerCxn.Factory:0.0.0.0/0.0.0.0:2181:NIOServerCnxn@1040] - Closed socket connection for client /127.0.0.1:60211 (no session established for client)
2018-12-14 22:16:40,506 [myid:] - INFO  [NIOServerCxn.Factory:0.0.0.0/0.0.0.0:2181:NIOServerCnxnFactory@215] - Accepted socket connection from /127.0.0.1:60214
2018-12-14 22:16:40,507 [myid:] - WARN  [NIOServerCxn.Factory:0.0.0.0/0.0.0.0:2181:NIOServerCnxn@383] - Exception causing close of session 0x0: null
2018-12-14 22:16:40,509 [myid:] - INFO  [NIOServerCxn.Factory:0.0.0.0/0.0.0.0:2181:NIOServerCnxn@1040] - Closed socket connection for client /127.0.0.1:60214 (no session established for client)
2018-12-14 22:16:41,519 [myid:] - INFO  [NIOServerCxn.Factory:0.0.0.0/0.0.0.0:2181:NIOServerCnxnFactory@215] - Accepted socket connection from /127.0.0.1:60217
2018-12-14 22:16:41,519 [myid:] - WARN  [NIOServerCxn.Factory:0.0.0.0/0.0.0.0:2181:NIOServerCnxn@383] - Exception causing close of session 0x0: null
2018-12-14 22:16:41,525 [myid:] - INFO  [NIOServerCxn.Factory:0.0.0.0/0.0.0.0:2181:NIOServerCnxn@1040] - Closed socket connection for client /127.0.0.1:60217 (no session established for client)

KafkaProducerConfig.java
@Configuration
public class KafkaProducerConfig {

    @Bean
    public ProducerFactory<String, String> producerFactory(){
        Map<String, Object> configProps = new HashMap<>();
        configProps.put(ProducerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
        configProps.put(ProducerConfig.KEY_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        configProps.put(ProducerConfig.VALUE_SERIALIZER_CLASS_CONFIG, StringSerializer.class);
        return new DefaultKafkaProducerFactory<>(configProps);
    }

    @Bean
    public KafkaTemplate<String, String> kafkaTemplate() {
        return new KafkaTemplate<>(producerFactory());
    }
}

KafkaConsumerConfig.java
@EnableKafka
@Configuration
public class KafkaConsumerConfig {
    @Bean
    public ConsumerFactory<String, String> consumerFactory() {
        Map<String, Object> props = new HashMap<>();
        props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:2181");
        props.put(ConsumerConfig.GROUP_ID_CONFIG, "group-id");
        props.put(ConsumerConfig.KEY_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        props.put(ConsumerConfig.VALUE_DESERIALIZER_CLASS_CONFIG, StringDeserializer.class);
        return new DefaultKafkaConsumerFactory<>(props);
    }

    @Bean
    public ConcurrentKafkaListenerContainerFactory<String, String> kafkaListenerContainerFactory() {
        ConcurrentKafkaListenerContainerFactory<String, String> factory = new ConcurrentKafkaListenerContainerFactory<>();
        factory.setConsumerFactory(consumerFactory());
        return factory;
    }
}

SpringKafkaTutorialspointApplication.java
@SpringBootApplication
public class SpringKafkaTutorialspointApplication implements CommandLineRunner{

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    public void sendMessage(String message) {
        kafkaTemplate.send("tutorialspoint", message);
    }

    public static void main(String[] args) {
        SpringApplication.run(SpringKafkaTutorialspointApplication.class, args);
    }

    @Override
    public void run(String... args) throws Exception {
        sendMessage("Hi Welcome to Spring For Apache Kafka @@@@@@@@@");
    }

    @KafkaListener(topics = "tutorialspoint", groupId = "group-id")
    public void listen(String message) {
        System.out.println("Received Messasge in group - group-id: " + message);
    }
}

Note: Pls let me know if you need any other details.
Any quick help ?

A:

After spending many hours I found that I should be using below in KafkaConsumerConfig too.
With the below changes code works fine.
props.put(ConsumerConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");


Q:

C# asp.net web api returning List how to keep Mongodb serializer from adding Name Value fields?

Web api function that is generating a List that the web api is returning via Telerik DataSourceResult
List<BsonDocument> objs = _mongoStore.GetData(id, newTime);
DataSourceResult result = objs.ToDataSourceResult(request);
return Json(result);

When I look in a debugger at the objs variable I see it represented in the following way; which is how we want the Json returned web api data:
{ "Computer" : "Computer1", "OSVersion" : "Windows" }

However when the Json() function serializes the objs object it is adding Name Value fields such as the following:
[[{"Name":"Computer","Value":"Computer1"},{"Name":"OSVersion","Value":"Windows"}]]

This expansion to Name, Value, fields is breaking future Json parsing APIs we use. How do we serialize this so that it just uses the actual values for Name and Value vs. it adding a specific Name and Value field? I.E. We want the returned Json to resemble like what the debugger is seeing:
{ "Computer" : "Computer1", "OSVersion" : "Windows" }

I know that one could do something like:
string rawjson = objs.ToJson(new JsonWriterSettings {OutputMode = JsonOutput.Strict});

But not sure how one would use something like that globally so if you were to be returning a Telerik DataSourceResult such as:
DataSourceResult result = objs.ToDataSourceResult(request);
return Json(Result);

Would cause the serialization that happens to return proper Json without the Name Value added fields.
Thank you!

A:

It looks like you can actually just take the result DataSourceResult object and perform Mongo .ToJson against it then return the web api as raw json string content.
So fixed up it would be something like
List<BsonDocument> objs = _mongoStore.GetData(id, newTime);
DataSourceResult result = objs.ToDataSourceResult(request);
var finalResult=result.ToJson(new JsonWriterSettings { OutputMode = JsonOutputMode.Strict });
return Content(finalResult);

Not sure if there is a better way but this seems to work. If someone else knows a better way happy to change that to the Answer.


Q:

Raspberry Pi Camera Rev 1.3 is not detected

I'm using an RPi 2 Model B and I have connected a Raspberry Pi Camera Rev 1.3 to it.
I have checked to make sure that the connection is correct (the power LED on the camera is on).
I've run:
rpi-update
apt-get update
apt-get upgrade

I have the following configuration in /boot/config.txt:
start_x=1
gpu_mem=128
start_file=start_x.elf
fixup_file=fixup_x.dat

I've gone to raspi-config and tried to enable my camera with no success. When I try to enable it exits back to main config page but when I go back to the camera configuration page its still at disable. I tried entering enable and restarting anyways.
Each time I run raspistill -o image.jpg I get the following error:
mmal: mmal_vc_component_create: failed to create component 'vc.ril.camera' (1:ENOMEM)
mmal: mmal_component_create_core: could not create component 'vc.ril.camera' (1)
mmal: Failed to create camera component
mmal: main: Failed to create camera component
mmal: Camera is not detected. Please check carefully the camera module is installed correctly

Not sure where my problem is. Does anyone have any insight on this?

A:

I just had this same problem. Here is what eventually worked after reading this (From the comments it looks like you had the same issue as I did):

vcgencmd get_camera (Returned supported=1 detected=0)
Check to make sure ribbon was facing the right way (it was)
Check to make sure ribbon is all the way in the connector slot (it was)
Check to make sure ribbon is in proper connector slot: the one between the ethernet port and the HDMI port (it was NOT!)
Reconnect camera in the proper slot
vcgencmd get_camera (now returns supported=1 detected=1)
Good to go!


Q:

Writing about sets (especially subsets and supersets) in terms of their elements

I am currently working through some set-theory-texts, trying to prove different basic theorems. Therefore, i often replace the notation for the set as a whole with the rules that apply to an element of the set. (example: $A\cup B = \{x | x \in A \lor x \in B \} $).
I do the same when the statement involves a subset: $A \subset B = \{x|x\in A \land x\in B \} $.
For the statement to hold true, this rule would indeed have to apply, but of course it doesn't really reflect the statement. $A\subset B$ feels more like it should translate into the implication: $x\in A \implies x\in B$.
In some cases this might however not be as easy to work with as the above form.
Really even the equal-sign after $A \subset B$ feels misplaced, as the subset-expression doesn't seem to be a set in itself (in contrast to the union of two sets), but rather just information about a set, and can therfore not be equal to $A \subset B = \{x|x\in A \land x\in B \} $.
So i guess my question is: What is the common way to translate the notion of a subset (or superset) into a statement applying to an element x, instead of to the set as a whole.

A:

What you want is

$A \subset B \equiv \forall x(x \in A \to x \in B)$

(i) '$\equiv$' expresses the equivalence between the proposition on the left and the one on the right (or you can equally use '$\leftrightarrow$').
(ii) And plainly you need a conditional on the right, not a conjunction  -- $A$ is a subset of $B$ if and only if for any $x$, IF $x$ is in $A$ THEN $x$ is in $B$.


Q:

How can I supply report parameters to ancillary reports from a "base" SSRS report?

I need to have several (four) reports that are identical except for the value of a particular parameter. I don't want the user to have to enter all parameters manually, though.
When they enter the following parameters:
BEATLES
-------
BegDate: 1962
EndDate: 1970
Unit: Beatles

I want four reports to run, using these parameters:
LENNON
------
BegDate: 1962
EndDate: 1970
Unit: John Lennon

MCCARTNEY
---------
BegDate: 1962
EndDate: 1970
Unit: Paul McCartney

HARRISON
--------
BegDate: 1962
EndDate: 1970
Unit: George Harrison

STARR
-----
BegDate: 1962
EndDate: 1970
Unit: Ringo Starr

So when the user enters the three parameters, the first two ("date") parameters and also the appropriate-for-the-ancillary-report "Unit" parameter ("John Lennon" to the first, "Paul McCartney" to the second, etc.) are passed.
The report "robot" says to itself after the person enters "Beatles" for Unit: "Oh, he entered 'Beatles'! So I'll pass 'John Lennon' as the Unit parameter to the first report, 'Paul McCartney' as the Unit parameter to the second report, " (etc.).
I tried doing this by supplying literal values inside practically-the-same Stored Procedures (as expounded on to some extent here, but it didn't work at all.
So I'm looking for some other way to put multiple related but distinct reports on the same surface. The ultimate goal is to see to it that, when ran and exported as Excel, each report (LENNON, MCCARTNEY, etc.) all display on their own sheet in the Excel file.
For now, though, I just need to know how to pass the appropriate parameters from one report ("BEATLES") to the others ("LENNON", etc.). I'm thinking of these as distinct reports all embedded in one report project/page, but perhaps they needed to be a report and then a bunch of subreports (if you're reading this, you probably know better than I do the inner workings and vagaries of SSRS).
So, how can I supply report parameters to ancillary (sub-?) reports from a "base" SSRS report - or is there another/better way to accomplish this?

A:

Based on what is written here, this is how I accomplished this:
I added a Subreport and then dragged the existing report onto it. Then I selected the context menu item "Subreport Properties" and added a parameter ("Unit"), providing it with a "hard-coded/baked-in" value ("CHOPHOUSE") different from the one to be provided by the user for the main report.
Then, since I want to keep the same date values from the existing report, I added two more parameters to the subreport and set them to use the same values for the date range as those used there in the main report by selecting the "formula" ("fx") button and 2-clicking the appropriate parameter to be used as the passed-in (tramp) value:

That works.
I provided more detail at the answer to the similar question here.


Q:

Understanding React props

Looking at Facebook's react example here, I found this code showing how to use mixins to set intervals. I am confused as to what is happening with this.intervals. I understand that state holds render-altering data, and props handle data handed down from a parent component, ideally. I would have used this.props.intervals instead, but what is the difference between the two?
      var SetIntervalMixin = {
      componentWillMount: function() {
        this.intervals = [];
      },
      setInterval: function() {
        this.intervals.push(setInterval.apply(null, arguments));
      },
      componentWillUnmount: function() {
        this.intervals.forEach(clearInterval);
      }
    };

    var TickTock = React.createClass({
      mixins: [SetIntervalMixin], // Use the mixin
      getInitialState: function() {
        return {seconds: 0};
      },
      componentDidMount: function() {
        this.setInterval(this.tick, 1000); // Call a method on the mixin
      },
      tick: function() {
        this.setState({seconds: this.state.seconds + 1});
      },
      render: function() {
        return (
          <p>
            React has been running for {this.state.seconds} seconds.
          </p>
        );
      }
    });

    ReactDOM.render(
      <TickTock />,
      document.getElementById('example')
    );

A:

When you use props, you know for 100% certainty the value should will be coming from it's immediate parent component (as a property).
When you see state, you know the value is being born/created within that component it's self.
The key, when state changes, every child below will render if any of their received props change.
Your Mixin is not a normal React class. It is simply an object, so this in the case of this.interval, is a reference to the scope of the object in which the method is being executed - TickTock.


Q:

Proving Euclid's Lemma using basic axioms of Z.

I'm attempting to prove Euclid's Lemma in class, and while there are many proofs available on the internet which use Bezout's Identity and greatest common divisors and the Linear Diophantine equation, my class was specifically instructed to prove Euclid's Lemma only using basic axioms for the set of integers and properties of equality. As such, I was thinking that I could present a sketch of the proof I have in mind, and I hope that I could receive some feedback as to whether it is correct or if there are any problems and how to fix them if they exist. Thanks!
Statement: $\forall a,b \in \mathbb{Z}$, If $p\mid ab$, then $p \mid a$ or $p \mid b$, where $p$ is a prime integer.
Proof: (By Contradiction)
Let $p,a,b \in \mathbb{Z}$ where $p$ is a prime integer.
Suppose that $p \mid ab$ and $p \nmid a$
In order to prove the statement, it must be shown that $p \mid b$
Assume that $p \nmid b$
If $p \nmid b$, then $pk \neq b$ for some $k \in \mathbb{Z}$
Observe that $pk \neq b => pak \neq ab$
Since $\mathbb{Z}$ is closed under multiplication and $a,k \in \mathbb{Z}$, $ak = r$ where $r \in \mathbb{Z}$
Therefore, $pr \neq ab$ which implies that $p \nmid ab$
This is a contradiction since we were given $p \mid ab$
Thus, it must  be true that $p \mid b$
Q.E.D.
Any thoughts?

A:

If $p\not \mid b$ then $pk \ne b$ for all $k$ not just one $k$.  (For example $3*k \ne 21$ for some $k$ i.e. for $k=6$, $3*k =18 \ne 21$.  And yet somehow, $3|21$.)
So if we use that $p\ne ak$ for all $k$ we can say that $pak \ne ab$ for any $k$.
We can't say $r =ak$ because we don't have any specific $k$ in mind. But we can so that $pr \ne ab$ for any $r$ *that is a multiple of $a$.
But so far it could very possibly be that $ps = ab$ for some $s$ that is not a multiple of $a$.
I think you are doomed.
FWIW it's probably not a good idea to use the double negative that $pk \ne b$ for all$k$.  It's better to say: there does not exist any $k$ so that $pk = b$.


Q:

how to use sed command in batch file

I had written a shell script with the following commands :
if [[ $(echo $FILE_NAME | awk -F"_" '{print $3}') == "IMAGE" ]];
    then
echo "in if of f_name"
     F_NAME=`echo $FILE_NAME | sed 's/IMAGE/UCM/'`
echo $F_NAME
    else
echo "in else of f_name"
    F_NAME=`echo $FILE_NAME | sed 's/FUSION_CONFIGURATION_1/UCM/'`
    fi

This searched for the FILENAME which was the parameter and then go into this if else and then give the result. How can this LOGIC be used in the batch file ?
This is giving an internal or external error in batch file

A:

This is my try to translate/interpret your bash code to batch.
@Echo off&SetLocal EnableExtensions EnableDelayedExpansion
Set FILE_NAME=one_two_IMAGE_four
:: Set FILE_NAME=one_two_FUSION_CONFIGURATION_1_four

:: This replaces your awk
For /f "tokens=3 Delims=_" %%A in (
 'echo:%File_Name%'
) Do Set Token3=%%A

:: Variable content is refered to by enclosing the var name in %
:: DelayedExpansion is neccessary because inside a (code block)
:: You have to use the exclamation mark instead of the percent then
If "%Token3%"=="IMAGE" (
  Set F_NAME=!FILE_NAME:IMAGE=UCM!
) Else (
  Set F_NAME=!FILE_NAME:FUSION_CONFIGURATION_1=UCM!
)
Echo FILE_NAME=%FILE_NAME%
Echo Token3   =%Token3%
Echo F_NAME   =%F_NAME%

The output
FILE_NAME=one_two_IMAGE_four
Token3   =IMAGE
F_NAME   =one_two_UCM_four

FILE_NAME=one_two_FUSION_CONFIGURATION_1_four
Token3   =FUSION
F_NAME   =one_two_UCM_four

EDIT
To renove the extension .zip from a string each of these lines will do:
Set F_NAME=%F_NAME:.zip=%
For %%A in ("%F_NAME%") Do Set F_NAME=%%~nA
Set F_NAME=%F_NAME:~0,-4%


Q:

Misunderstood Compiler Error on glGenerateMipmap(GL_TEXTURE_2D);

error: there are no arguments to 'glGenerateMipmap' that depend on a template parameter, so a declaration of 'glGenerateMipmap' must be available [-fpermissive]
I have #include <GL/glext.h> included and can see the declaration of the function in the header, however I get the compiler error above. I am on Ubuntu 13.04 with the most up-to-date nvidia drivers installed. I would assume that this function would be defined.
My use of the function is:
  if (mipmapped) {
    glGenerateMipmap(GL_TEXTURE_2D);
  }

Why is my compiler choking on this function? What does that error mean in this context?

A:

The glext.h header does by default not declare those functions, you have to
#define GL_GLEXT_PROTOTYPES

before including that file if you really want to. But you should be warned that just declaring that function is does not mean that you can successfully link on any platform, as the GL lib is not required to export that function. On Linux, it is likely to work, though, but the closest to a standard is the OpenGL Application Binary Interface for Linux which just guarantees that all OpenGL 1.2 core functions are exported.
You should consider using the OpenGL extension mechanism, either manually via glXGetProcAddress[ARB]() or by using a convenient library like GLEW or GL3W.


Q:

Google Apps Script - Sheets - Conditional Formatting - X = highlight

I have a sheet with over 100,000 cells (will soon be 300,000+ cells) used as a Gantt Chart. Each cell has an IF formula which returns the letter X if the corresponding column's header (a date) is between the row's start and end date.
But what's slowing down the sheet dramatically is the conditional formatting behind it. The conditional formatting says if the cell's value is an X, then change the cell's background color and font color to green. If no X, the background color should be white. Since conditional formatting, as I understand it, is recalculated any time you make any edit to the sheet, the performance is drastically poor. So my thought is to remove the conditional formatting and add it as a Script, with a menu button that I can click any time I want it ran, as opposed to conditional formatting running every time I make an edit to the sheet.
Here is where I've gotten with the script, which doesn't work. I've tried a couple dozen variations of this, but can't find something that works - sometimes I get it to run with no error, sometimes there is an error. Is my context wrong somewhere?
function formatting() {

  var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Sheet 1");
  var range = ss.getRange("A1:A100");
  var cellValue = range.getValues();
  if (cellValue === 'X') {
    ss.range.setBackgroundColor('#000000'); }
  else {
    cellValue.setBackgroundColor('#ffffff'); }
}

A:

Here's an approach using the batch function Range.setBackgrounds(). This function takes a 2D array of values as it's argument, allowing you to set all of the cell backgrounds for a range in a single API call.
Also note that the function Range.getValues() returns a 2D array of values. To inspect each individual cell value you need to loop through the arrays.
Since you're dealing with a 2D array as both an input and an output, the logic for building the output array of background values mirrors the logic you need to use to check the current cell values. Therefore, you can build the 2D array of backgrounds values while you are looping through the cell values.
function setCellBackgrounds() {
  // The name of the sheet to process.
  var sheetName = "Sheet1";
  // The range of cells to inspect.
  var range = "A1:Z100";

  var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(sheetName);
  var range = sheet.getRange(range);
  var values = range.getValues();
  var colors = [];
  for (var x = 0; x < values.length; x++) {
    colors[x] = [];
    for (var y = 0; y < values[x].length; y++) {
       if (values[x][y] == 'X') {
         colors[x][y] = '#999999';
       } else {
         colors[x][y] = '#ffffff';
       }
    }
  }
  range.setBackgrounds(colors);
}

Using batch functions, instead of repeated calls to the non-batch version, is a documented Apps Script best practice.


Q:

How could I use VBA to change a button's picture to one of the embedded default images?

I'm trying to get a button to change from the "Arrow Left" to "Arrow Right" picture when I click it, but I'm not sure how to assign the images through VBA. I tried Me!btnCollapseUnscheduled.Picture = "Arrow Left", but I get an error message this way.

A:

In Access 2010 or later, you can store images in the MSysResources system table.  Then choose Shared for your command button's Picture Type property, and select one of those shared images.
Afterward, it's easy to toggle between the shared images from the command buttons's click event.  I named my command button "cmdArrow" and the shared images "Arrow Left" and "Arrow Right" ...
Option Compare Database
Option Explicit

Private Sub cmdArrow_Click()
    Dim strDirection As String

    If Me!cmdArrow.Picture Like "*Left" Then
        strDirection = "Right"
    Else
        strDirection = "Left"
    End If
    Me!cmdArrow.Picture = "Arrow " & strDirection
    Me!txtImage.Value = Me!cmdArrow.Picture
End Sub

Private Sub Form_Load()
    Me!txtImage.Value = Me!cmdArrow.Picture
End Sub

Screenshots:

The biggest challenge was loading the images into MSysResources.  I created a throwaway form and added a command button.  Next I chose Embedded as the button's Picture Type property and selected Arrow Left from the available choices.  Then I changed Picture Type from Embedded to Shared, which added a row to MSysResources with the image data in an attachment field and my command button's name in the Name field.  So I opened the table, changed Name to "Arrow Left" and closed the table.  Note MSysResources will not be visible in the Navigation pane unless you enable "Show System Objects" in the Navigation Options.
I repeated those steps for "Arrow Right".  It may sound fiddly, but it's not really a huge hurdle.


Q:

Why does my Activity get destroyed upon adding a fragment (#2)?

I want to make it clear that this question will look very similar to one I asked earlier, but that I'm not asking exactly the same thing.
In my previous question, I got a RuntimeException/IllegalStateException, which told me my Activity got destroyed upon adding a new fragment.
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.tim.timapp
    /com.example.tim.timapp.MainActivity}: java.lang.IllegalStateException:
    Activity has been destroyed

In that case, it turned out it had to do with me creating new instances of MainActivityin an invalid way:
MainActivity ma = new MainActivity();
(PSA: Don't do the above, use MainActivity ma = (MainActivity) getActivity(); instead.)
I have now corrected this in my entire project, and am getting almost exactly the same error. Let me be clear: I (think I) know the original error was fixed, because I got a different error in between these two RE's, which I was able to fix myself.
To reiterate on my gibberish: Got the first RE, fixed it with the answer on my question, got a different error, fixed that myself, got almost exactly the same RE.
I have searched through my entire project to see if I had anything similar to the error I made before, but I can't find anything, so here I am. So basically, the answer I got on my previous question fixed my issue, temporarily. That answer however, does not help me with this new error I'm getting, that's why I'm asking this question.
TL;DR: Answer on Q1 fixed my issue at first(which makes it a working answer), but it does not fix the issue I'm having right now, which is almost the same.
The actual question
So, now we've got that bit out of the way, let's get on with my issue. So, I'm getting a RuntimeException/IllegalStateExcetion:
java.lang.RuntimeException: Unable to start activity
    ComponentInfo{com.example.tim.timapp/com.example.tim.timapp.MainActivity}:
    java.lang.IllegalStateException: Activity has been destroyed

(PS. It's only a RE because I have my app navigate to the GeneralSettings fragment on startup, for debugging ease.)
I've read up on this kind of error, but nothing I could find that applies on my project.
So, what is causing this RuntimeException/IllegalStateException?
Full log
04-05 14:17:53.140 23411-23411/? I/art: Not late-enabling -Xcheck:jni (already on)
04-05 14:17:53.190 23411-23411/com.example.tim.timapp W/System: ClassLoader referenced unknown path: /data/app/com.example.tim.timapp-1/lib/x86_64
04-05 14:17:53.210 23411-23411/com.example.tim.timapp D/TEST DBHandler: sInstance == null
04-05 14:17:53.370 23411-23411/com.example.tim.timapp D/AndroidRuntime: Shutting down VM
04-05 14:17:53.370 23411-23411/com.example.tim.timapp E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.tim.timapp, PID: 23411
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.tim.timapp/com.example.tim.timapp.MainActivity}: java.lang.IllegalStateException: Activity has been destroyed
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2416)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
        at android.app.ActivityThread.-wrap11(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:5417)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
     Caused by: java.lang.IllegalStateException: Activity has been destroyed
        at android.app.FragmentManagerImpl.enqueueAction(FragmentManager.java:1433)
        at android.app.BackStackRecord.commitInternal(BackStackRecord.java:687)
        at android.app.BackStackRecord.commit(BackStackRecord.java:663)
        at com.example.tim.timapp.MainActivity.DrawVariableFragments(MainActivity.java:276)
        at com.example.fragments.Settings.GeneralSettingsFragment.onCreateView(GeneralSettingsFragment.java:58)
        at android.app.Fragment.performCreateView(Fragment.java:2220)
        at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:973)
        at android.app.FragmentManagerImpl.moveToState(FragmentManager.java:1148)
        at android.app.BackStackRecord.run(BackStackRecord.java:793)
        at android.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:1535)
        at android.app.FragmentController.execPendingActions(FragmentController.java:325)
        at android.app.Activity.performStart(Activity.java:6252)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2379)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2476)
        at android.app.ActivityThread.-wrap11(ActivityThread.java)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1344)
        at android.os.Handler.dispatchMessage(Handler.java:102)
        at android.os.Looper.loop(Looper.java:148)
        at android.app.ActivityThread.main(ActivityThread.java:5417)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)

MainActivity (Snippet)
package com.example.tim.timapp;

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    private static boolean isMainShown = false;
    private static boolean isSettingsShown = false;
    private static boolean doSavePopup = false;
    private static String backTitle = "";
    private String tag = "TEST MA";
    DBHandler dbHandler;

    Menu menu;

    public void DrawVariableFragments(String base,String token){
//        FragmentManager fm = getFragmentManager();
        ArrayList<String> Data;
        dbHandler = DBHandler.getInstance(this);

        int AmountOfEntries;
        int SettingsContainer;
        String SettingsTag;
        Fragment SettingsVariableFragment;
        Fragment SettingsEmptyFragment;

        if (base.equalsIgnoreCase("StuffManager")) {
            Data = new ArrayList<String>() {{add("StuffManager"); add("name"); add("tag"); }};
            SettingsContainer = R.id.FragmentContainer2;
            SettingsTag = getString(R.string.navdrawer_stuffmanager);
            SettingsVariableFragment = new StuffManagerVariableFragment();
            SettingsEmptyFragment = new StuffManagerEmptyFragment();
        } else if (base.equalsIgnoreCase("GeneralSettings")) {
            Data = new ArrayList<String>() {{add("GeneralSettings"); add("name"); add("ip"); add("port"); add("username"); add("pass"); }};
            SettingsContainer = R.id.FragmentContainerGeneralSettings;
            SettingsTag = getString(R.string.navdrawer_generalsettings);
            SettingsVariableFragment = new GeneralSettingsVariableFragment();
            SettingsEmptyFragment = new GeneralSettingsEmptyFragment();
        } else {
            Log.e(tag, "String Base not recognised");
            return;
        }
        AmountOfEntries = dbHandler.returnArray(base, Data.get(1)).size();

        FragmentManager fm = getFragmentManager().findFragmentByTag(SettingsTag).getChildFragmentManager();

        if ((dbHandler.returnArray(base, Data.get(1))).size() == 0 ) {
//            Log.d(tag, "SettingsContainer1: " + String.valueOf(SettingsContainer) + ";  SettingsEmtpyFragment1: " + SettingsEmptyFragment + ";  Base1: " + base);
            fm.beginTransaction().add(SettingsContainer, SettingsEmptyFragment, (base + "EmptyFragment")).commit();
            fm.executePendingTransactions();
            return;
        }

        if (AmountOfEntries > 0) {
            String EmptyFragName = (base + "EmptyFragment");
            if ((fm.findFragmentByTag(EmptyFragName)) != null) {
                fm.beginTransaction().remove(fm.findFragmentByTag(EmptyFragName)).commit();
                fm.executePendingTransactions();
            }
            for (int i = 0; i < AmountOfEntries; i++) {
                ArrayList<String> fragmentData = new ArrayList<>();
                for (int k=1; k < Data.size(); k++) {
                    int j=k-1;
                    fragmentData.set(j, (dbHandler.returnArray(base, Data.get(k)).get(j)));
                }

                if (token.equalsIgnoreCase("edit")) {
                    LinearLayout linearLayout = (LinearLayout) findViewById(SettingsContainer);
                    linearLayout.removeAllViews();
                    DrawVariableFragments(base ,"draw");
                } else if (token.equalsIgnoreCase("add")) {
                    if (fm.findFragmentByTag(fragmentData.get(i)) == null) {
                        fm.beginTransaction().add(SettingsContainer, SettingsVariableFragment, fragmentData.get(0)).commit();
                        fm.executePendingTransactions();
                        if (base.equalsIgnoreCase("StuffManager")) {
                            ((StuffManagerVariableFragment) fm
                                    .findFragmentByTag(fragmentData.get(i)))
                                    .setText(fragmentData.get(0), fragmentData.get(1));
                        } else if (base.equalsIgnoreCase("GeneralSettings")) {
                            ((GeneralSettingsVariableFragment) fm
                                    .findFragmentByTag(fragmentData.get(i)))
                                    .setText(fragmentData.get(0), fragmentData.get(1), fragmentData.get(2), fragmentData.get(3));
                        }
                    }
                } else if (token.equalsIgnoreCase("draw")) {
                    fm.beginTransaction().add(SettingsContainer, SettingsVariableFragment, fragmentData.get(0)).commit();
                    fm.executePendingTransactions();
                    if (base.equalsIgnoreCase("StuffManager")) {
                        ((StuffManagerVariableFragment) fm
                                .findFragmentByTag(fragmentData.get(i)))
                                .setText(fragmentData.get(0), fragmentData.get(1));
                    } else if (base.equalsIgnoreCase("GeneralSettings")) {
                        ((GeneralSettingsVariableFragment) fm
                                .findFragmentByTag(fragmentData.get(i)))
                                .setText(fragmentData.get(0), fragmentData.get(1), fragmentData.get(2), fragmentData.get(3));
                    }
                }
            }
        } else {
            Log.d("TEST", "WTF, nameArray.size != 0 && !> 0");
        }
    }
}

GeneralSettingsFragment (Snippet)
package com.example.fragments.Settings;

public class GeneralSettingsFragment extends Fragment {

    MainActivity ma;
    DBHandler dbHandler;
    private static Menu optionsMenu;
    public static boolean hideDeleteAllButton = false;
    LinearLayout linearLayout;
    View rootView;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        rootView = inflater.inflate(R.layout.fragment_generalsettings, container, false);
        ma = (MainActivity) getActivity();
        linearLayout = (LinearLayout) rootView.findViewById(R.id.FragmentContainerGeneralSettings);

        if (linearLayout == null) {
            Log.e("GMF", "Layout is null");
        } else if (linearLayout.getChildCount() == 0) {
            GeneralSettingsInitialInputDialog GSIID = new GeneralSettingsInitialInputDialog();
            GSIID.show(getFragmentManager(), "dialog");
            hideDeleteAllButton = true;
        } else {
            hideDeleteAllButton = false;
        }
        ma.DrawVariableFragments("GeneralSettings", "draw");

        return rootView;
    }
}

A:

You are still doing things in an unsupported way. In MainActivity.DrawVariableFragments() you are creating a new GeneralSettingsVariableFragment() and then call getChildFragmentManager() on it and attempt to commit a fragment.
The GeneralSettingsFragment has not yet been attached to an Activity so it does not have a host. This throws the IllegalStateException("Activity has been destroyed") exception you are seeing when you try to commit the FragmentTransaction.
It is unclear why you are creating a new GeneralSettingsVariableFragmentwhen you are already inside a new instance of one.
To properly lookup an existing fragment use getFragmentManager().findFragmentByTag(...) or getFragmentManager().findFragmentById(...).


Q:

Operator '-' cannot be applied to operands of type string and string

I want to create a new variable using two string variables. But I keep getting the error message

"operator '-' cannot be applied to operands of type string and string c#".

string query3 = "SELECT Quantity FROM Supplier WHERE [Supplier ID]='"+supplierid+"'";
string query4 = "SELECT Quantity FROM Supplier WHERE [Book ID] = '" + bookid + "'";
SqlCommand cmd3 = new SqlCommand(query3, con);
SqlCommand cmd4 = new SqlCommand(query4, con);
con.Open();
string temporaryquantity = cmd3.ExecuteScalar().ToString();
string temporaryquantitystocks = cmd4.ExecuteScalar().ToString();
string totalcostforstocks = (temporaryquantitystocks-temporaryquantity + quantity) * buyingpriceperbook;

"quantity" is in int type
"buyingpriceperbook" is in double type
Can anyone help me with this?

A:

You can not apply arithmetic operators to strings.  Change to double or integer:
string query3 = "SELECT Quantity FROM Supplier WHERE [Supplier ID]='" + supplierid + "'";
string query4 = "SELECT Quantity FROM Supplier WHERE [Book ID] = '" + bookid + "'";

SqlCommand cmd3 = new SqlCommand(query3, con);
SqlCommand cmd4 = new SqlCommand(query4, con);
con.Open();
double temporaryquantity = Convert.ToDouble( cmd3.ExecuteScalar());
double temporaryquantitystocks = Convert.ToDouble(cmd4.ExecuteScalar());
double totalcostforstocks = (temporaryquantitystocks - temporaryquantity + quantity) * buyingpriceperbook;


Q:

Insertion of transmission lines and effects on reflection coefficient

I have a doubt on a step usually performed in matching network design. Consider a load ZL: a method for getting impedance matching (for instance with an amplifier) is that of inserting a transmission line in order to modify its impedance, like in the following picture:

This operation can be seen also in terms of reflection coefficient. Precisely, I found this relation:

where ΓL is the reflection coefficient of the Load. My question is a bout a generic case in which ZL may be also another transmission line, a port etc
where does this relationship come from? Are there any assumption (for instance that the transmission line must have the same characteristic impedance of ZL - in case is a transmission line - , or it must be a no loss line etc) for it?

A:

where does this relationship come from?

It comes from the fact that if you have a forward travelling wave at \$z=-l_1\$, then it will travel forward a distance \$l_1\$, then reflect off the load, then travel in reverse distance \$l_1\$ again before you see the reverse travelling wave at your measurement point.

Are there any assumption (for instance that the transmission line must have the same characteristic impedance of ZL - in case is a transmission line - , or it must be a no loss line etc) for it?

As shown in the diagram, the transmission line must have characteristic impedance \$Z_0\$ (it must be matched to the system impedance), and propagation constant \$\beta\$.
If it was matched to the load (it had characteristic impedance numerically equal to \$Z_L\$), then the reflection coefficient at \$z=-l_1\$ would just be \$\Gamma_L\$, since a transmission line terminated with a matched load just "looks like" a lumped impedance equal to its characteristic impedance.
You are correct that this formula only applies to a lossless line. If it were a lossy line, the magnitude of the reflection constant at \$z=-l_1\$ would be less than \$|\Gamma_L|\$.


Q:

Converting an AudioBufferList to a CMSampleBuffer Produces Unexpected Results

I'm trying to convert an AudioBufferList that I get from an Audio Unit into a CMSampleBuffer that I can pass into an AVAssetWriter to save audio from the microphone.  This conversion works, in that the calls I'm making to perform the transformation don't fail, but recording ultimately does fail, and I'm seeing some output in the logs that seems to be cause for concern.
The code I'm using looks like this:
- (void)handleAudioSamples:(AudioBufferList*)samples numSamples:(UInt32)numSamples hostTime:(UInt64)hostTime {
    // Create a CMSampleBufferRef from the list of samples, which we'll own
    AudioStreamBasicDescription monoStreamFormat;
    memset(&monoStreamFormat, 0, sizeof(monoStreamFormat));
    monoStreamFormat.mSampleRate = 48000;
    monoStreamFormat.mFormatID = kAudioFormatLinearPCM;
    monoStreamFormat.mFormatFlags = kAudioFormatFlagIsSignedInteger | kAudioFormatFlagsNativeEndian | kAudioFormatFlagIsPacked | kAudioFormatFlagIsNonInterleaved;
    monoStreamFormat.mBytesPerPacket = 2;
    monoStreamFormat.mFramesPerPacket = 1;
    monoStreamFormat.mBytesPerFrame = 2;
    monoStreamFormat.mChannelsPerFrame = 1;
    monoStreamFormat.mBitsPerChannel = 16;

    CMFormatDescriptionRef format = NULL;
    OSStatus status = CMAudioFormatDescriptionCreate(kCFAllocatorDefault, &monoStreamFormat, 0, NULL, 0, NULL, NULL, &format);
    if (status != noErr) {
        // really shouldn't happen
        return;
    }

    CMSampleTimingInfo timing = { CMTimeMake(1, 48000), kCMTimeZero, kCMTimeInvalid };

    CMSampleBufferRef sampleBuffer = NULL;
    status = CMSampleBufferCreate(kCFAllocatorDefault, NULL, false, NULL, NULL, format, numSamples, 1, &timing, 0, NULL, &sampleBuffer);
    if (status != noErr) {
        // couldn't create the sample buffer
        PTKLogError(@"Failed to create sample buffer");
        CFRelease(format);
      return;
    }

    // add the samples to the buffer
    status = CMSampleBufferSetDataBufferFromAudioBufferList(sampleBuffer,
                                                            kCFAllocatorDefault,
                                                            kCFAllocatorDefault,
                                                            0,
                                                            samples);
    if (status != noErr) {
        PTKLogError(@"Failed to add samples to sample buffer");
        CFRelease(sampleBuffer);
        CFRelease(format);
        return;
    }

    NSLog(@"Original sample buf size: %ld for %d samples from %d buffers, first buffer has size %d", CMSampleBufferGetTotalSampleSize(sampleBuffer), numSamples, samples->mNumberBuffers, samples->mBuffers[0].mDataByteSize);
    NSLog(@"Original sample buf has %ld samples", CMSampleBufferGetNumSamples(sampleBuffer));

As I mentioned, the code doesn't seem to be failing, per se, but AVAssetWriter doesn't like it, and the CMSampleBuffer that I'm creating seems to have size 0, based on the fact that the following log entries are being logged:
2015-07-09 19:34:00.710 xxxx[1481:271334] Original sample buf size: 0 for 1024 samples from 1 buffers, first buffer has size 2048
2015-07-09 19:34:00.710 xxxx[1481:271334] Original sample buf has 1024 samples

Oddly, the sample buffer reports that it has 1024 samples, but size 0.  The original AudioBufferList has 2048 bytes of data, which is what I'd expect for 1024 2-byte samples.
Am I doing something wrong in terms of the way I'm initializing and populating the CMSampleBuffer?

A:

It turns out that the fact that the sample size was coming back as 0 was a red herring.  Once I cleaned up a few things--notably, I set the timestamp correctly, like so:
uint64_t timeNS = (uint64_t)(hostTime * _hostTimeToNSFactor);
CMTime presentationTime = CMTimeMake(timeNS, 1000000000);
CMSampleTimingInfo timing = { CMTimeMake(1, 48000), presentationTime, kCMTimeInvalid };

recording started working.
So, in the event that someone else is thrown off by the reportedly 0 sample buffer size, be aware that this is OK, at least in the case in which you're feeding the data into an AVAssetWriter.


Q:

How to register a user event defined in a SUB VI(LabVIEW)

I created a SUB VI and defined a user event in it.
Then I created another VI, let's call it MAIN VI.
I put a SUB VI in the MAIN VI,and I want to register the user event created in the SUB VI to the Event Case in the MAIN VI, what should I do?

A:

You can do this, but it takes effort. What you are attempting to do is generally a bad idea -- as you can see from how much fighting against LabVIEW you have to do in the steps below. But because it is sometimes (rarely) necessary, I'll tell you how to do it. In general, though, when you have to fight this much, you may want to reconsider and let the caller VI be the one that allocates the event refnum and then pass it into the subVI, and only let the subVI generate the events.
Anyway... here's what you're asking for...
Option 1
Step one: In the caller VI, use "Obtain Queue" and create a queue of the user event type (that means you need to drop a constant of the desired event refnum type wired to the "Obtain Queue" element type terminal).
Step two: Add the queue to the connector pane of the subVI and wire your created queue to the new terminal on the subVI.
Step three: Modify the subVI so that after you create the user event, use "Enqueue Element" to enqueue that user event into the queue.
Step four: Back in the caller VI, in parallel to the call to the subVI, do a "Dequeue Element". Now you have the user event in the caller.
Step five: Use Release Queue in the caller VI to release the queue.
Step six: In the caller VI, use "Register For Events" to register the user event. Now you are ready to receive the event in an Event structure.
NOTE: The above process gives no guarantee that the caller VI will register the event before the subVI starts sending events. If the subVI starts sending events before the Register For Events node is called, you'll miss those initial events. You need a second signaling mechanism to tell the subVI "ok, it's safe to proceed".
Option 2
Step one: Put a giant case structure around all the code in your subVI. Wire the ? terminal of the case structure with a Boolean control. Add that Boolean control to the connector pane of the subVI. Now all the code for the subVI is in the TRUE case of the structure.
Step two: In the FALSE case, put the code to create the user event. Create an indicator of the user event and put it on the connector pane.
Step three: Use a Feedback Node outside of the case structure to store the user event. Do not provide any initialization of the Feedback Node.
Step three: In the caller, call the subVI with a FALSE wired to its input. The subVI will allocate the event refnum and return it to you. It will also store the refnum in the Feedback Node.
Step four: Use the Register For Events node to register the event in the caller VI.
Step five: Call the subVI a second time, this time passing TRUE. It will get the value of the user event refnum from the Feedback Node.
NOTE: This version DOES provide protection against missing the first events.


Q:

Resizing dynamic stack allocations in C++

I'm writing a small ray tracer using bounding volume hierarchies to accelerate ray tracing.
Long story short, I have a binary tree and I might need to visit multiple leafs.
Current I have a node with two children left and right, then during travel() if some condition, in this example intersect(), the children are visited:
class BoundingBoxNode{
    BoundingBoxNode* left, *right;
    void travel(param &p);
    inline bool intersect(param &p){...};
};

void BoundingBoxNode::travel(param &p){
    if(this->intersect(p)){
        if(left)
            left->travel(p);
        if(right)
            right->travel(p);
    }
}

This approach uses recursive methods calls, however, I need to optimized this code as much as possible... And according to Optimization Reference Manual for IA-32, function calls deeper than 16 can be very expensive, so I would like to do this using a while loop instead of recursive calls.
But I do NOT wish to do dynamic heap allocations as these are expensive. So I was thinking that maybe I could use that fact that every time a while loop starts over the stack will be in the same position.
In the following very ugly hack I rely on alloca() to always allocate the same address:
class BoundingBoxNode{
    BoundingBoxNode* left, right;
    inline void travel(param &p){
        int stack_size = 0;
        BoundingBoxNode* current = this;
        while(stack_size >= 0){
            BoundingBoxNode* stack = alloca(stack_size * 4 + 2*4);
            if(current->intersect(p)){
                if(current->left){
                    stack[stack_size] = current->left;
                    stack_size++;
                }
                if(current->right){
                    stack[stack_size] = current->right;
                    stack_size++;
                }
            }
            stack_size--;
            current = stack[stack_size];
        }
    };
    inline bool intersect(param &p){...};
};

However surprising it may seem this approach does fail :)
But it does work as long as the stack is smaller than 4 or 5... I'm also quite confident that this approach is possible, I just really think I need some help implementing it correctly.
So how can I manipulate the stack manually from C++, is it possible that I can use some compiler extension... Or must I do this is assembler, and if so, how do I write assembler than can be compiled with both GCC and ICC.
I hope somebody can help me... I don't need a perfect solution, just a hack, if it works it's good enough for this purpose :)
Regards Jonas Finnemann Jensen

A:

So, you've got a recursive function that you want to convert to a loop. You correctly work out that your function is not tail call so you have to implement it with a stack.
Now, why are you worried about the number of times that you allocate your "scratch space" stack? Is this not done once per traversal? -- if not then pass the scratch area in to the traverse function itself so it can be allocated once and then re-used for each traversal.
If the stack is small enough to fit in the cache it will stay hot and the fact that it isn't on the real C++ stack won't matter.
Once you've done all of that profile it both ways and see if it made any difference -- keep the faster version.


Q:

"Undefined control sequence." when using autocite and biblatex-chicago

I've wrestled for days with this problem for days, and have looked at the forum for answers, but to no avail.
I have in my preamble:
\usepackage[utf]{inputenc}
\usepackage[english]{babel}
\usepackage[babel]{csquote}
\usepackage[notes,backend=bibtex]{biblatex-chicago}
\addbibresource{Bibliography.bib}

For the bibliography output I have:
\printbibliography

However, I keep getting this error:

Package hypperref Warning: Return to get /pagelabels entry.
(./main.bbl
./main.bbl:20: undefined control sequence.
\blx@slist@name ->\cms @choose/global/
l.20 \entry{*****}{article}{}
?

When I click on "Go to error", it takes me to my main.bbl file,
\sortlist[entry]{\cms@choose/global/}
\entry{*****}{article}{}
\field{labeltitlesource}{title}

\field{sortinit}{2}

\field{sortinithash}{2}

\field{title}{XTITLEOFARTICLEX}

\field{journaltitle}{{XJOURNALNAMEX}}

\field{month}{08}

\field{year}{2010}

\endentry
I'd be grateful for any help. I apologise if my question has not been posted in proper format, this is my first ever question.

A:

biblatex-chicago sets the sorting with
 \ExecuteBibliographyOptions{...,sorting=\cms@choose,...}

With bibtex as backend the command \cms@choose ends up unexpanded in the control-file (a special bib created by biblatex) and then also in the bbl.
When the bbl is read at the begin of document LaTeX chokes on the @ in the command name and gives an error. The error could be avoided by activating \makeatletter but this wouldn't resolve the problem that bibtex didn't get the correct sorting name.
With the biber backend there is no problem.
As a conclusion I would avoid the bibtex backend with biblatex-chicago and switch to biber. A link how to do this is Biblatex with Biber: Configuring my editor to avoid undefined citations.


Q:

backbone.js view id tag using information from model

I am using backbone.js,
I have a model that is formatted like this:
{
  username:"name",
  id:"1",
  picture:"image.jpg"
}

I want to have a view like this:

    name

from this template:

but I get stuck when it comes to putting the users id into the views id attribute.
UserView = Backbone.View.extend({

    id: this.model.id, //this is what I have tried but it doesnt work

    initialize: function(){
        this.template = _.template($('#users-template').html());
    },

    render: function(){
        ...
    }
})

does anyone know how put the current models id into the id attribute?

A:

I use that
id : function () {
    return this.model.get("id");
}

U can get the model's data only using ".get()"

Properties like tagName, id, className, el, and events may also be defined as a function, if you want to wait to define them until runtime. @from Backbonejs.org

A:

First of all, your model has picture but your template uses image, they should be the same or you'll get a "missing variable" error from your template.
The id attribute on a view is supposed to be the DOM id of an existing element; Backbone won't add it to the el, Backbone uses it to find the el. Besides, this won't be a view when id: this.model.id is executed (this will probably be window or some other useless thing) and the model property isn't set until the view is instantiated anyway.
The view's el is:

created from the view's tagName, className, id and attributes properties, if specified. If not, el is an empty div.

So drop the id from your view and use the default
 for the el. Then, in your render method, you can set the id attribute on this.el; also, using a numeric id attribute causes trouble with some browsers so you should usually prefix it the id with something non-numeric:
render: function() {
    this.el.id = 'v' + this.model.get('id');
    this.$el.append(this.template(this.model.toJSON()));
    return this;
}

Demo: http://jsfiddle.net/ambiguous/ZBE5z/
Open your console when running the demo and you'll be able to see the HTML that ends up in your view's this.el.