text:
Q: extjs4 : how to custom axis label in each word I'm using extjs 4 now, with its Ext.chart.axis.Category.
But how to custom the label in each word?
Say, I have 72 numbers in the label at the bottom of the axis, and I want bold 24 and 48 only.
I've checked the Ext.chart.Label, and did found there's a useful function called renderer. But it is only used for text change, not a style change.
My example code snippet:
{
    xtype: 'chart',
    id: 'monitorAmmeter72chart',
    animate: false,
    region: 'center',
    store:Ext.data.StoreManager.lookup('monitorAmmeter72Store'),
    axes: [
        {
            type: 'Category',
            fields: ['hourDis'],
            position: 'bottom',
            title: 'blablabla',
            grid: true,
            label:{
                renderer:function(v){
                    if(v == '24'){
                        return '<b>24</b>';//Note, this won't work.
                    }else{
                        return v;
                    }
                }
            }
        },
        {
            type: 'Numeric',
            fields: ['data'],
            position: 'left',
            title: 'another blablabla',
            grid: true,
            minimum: 0
        }
    ],
     series: [
        {
            type: 'column',
            axis: 'left',
            highlight: false,
            tips: {
              trackMouse: false,
              width: 50,
              height: 28,
              renderer: function(storeItem, item) {
                this.setTitle(storeItem.get('data') + ' xx');
              }
            },
            style: {
                fill: '#38B8BF'
            },
            gutter: 20,
            xField: 'hour',
            yField: 'data'
        }
    ]
}

A: i'm using extjs 4.2.1 and i'm doing :
label: {
 renderer: function(v) {
  if(v == 'Capitale-Nationale'){
   this.font = "bold 12px Arial, Helvetica, sans-serif";
   this.padding = 5;
  }
  else{
   this.font = "12px Arial, Helvetica, sans-serif";
   this.padding = 5;
  }
  return v;
 }
},

A: You could actually create a HTML string in the renderer and style it as you need. Isn't it an option?


text:
Q: React Native - Save data to AsyncStorage before the app closes/goes to background I am new to React Native, but I've started to use it to develop an app where users can upload Posts. On the Publish screen, there are two TextInput, one for the title, and another one for the body. I'd like the app to be able to save drafts in case the user closes the app, so the progress is not lost. I thought that a combination of AsyncStorage and AppState would do the job, but something is not working as it should.
export default class PublishScreen extends React.Component {

    constructor(props) {
        super(props);
        this.state = {
            title: '',
            body: ''
        };
        this._getData();
    }

    _getData = async () => {
        await this.setState({
            'title': await AsyncStorage.getItem('title') || '',
            'body': await AsyncStorage.getItem('body') || ''
        });
    };

    componentDidMount() {
        AppState.addEventListener('change', this._handleAppStateChange);
    }

    componentWillUnmount() {
        AppState.removeEventListener('change', this._handleAppStateChange);
    }

    _handleAppStateChange = async (nextAppState) => {
        if (this.state.appState.match(/inactive|background/) && nextAppState === 'active') {
            // App is going to be in the foreground
            this._getData()
        } else {
            // App is going to be closed/background, save the data
            await AsyncStorage.setItem('title', this.state.title);
            await AsyncStorage.setItem('body', this.state.body);
        }
        this.setState({appState: nextAppState});
    };
}

This approach seems to be working in dev mode, but as soon as I build the app in release mode, the data doesn't get saved or restored, I am not really sure where it is failing.
What am I doing wrong, am I doing the feature in the right way anyway?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to pass Eval parameter in Javascript onClientClick? Hello I saw some examples on how to this but unfortunately I end up with an error
**Description:** An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately.
Parser Error Message: The server tag is not well formed.

I want to use javaquery on a linkbutton placed in Gridview using the below code:
<asp:LinkButton ID="hlHierarchy" runat="server" OnClientClick= "return windowpop('~/../../..<%#Eval("NavigateURL") %>', 545, 433)">

<%# ((string)Eval("Name")).Replace("-", " ") %>

</asp:LinkButton>

Please help me rectify any syntax error if there is, below is the jquery:

A: So i figured out what was wrong, the corrected code:
<asp:LinkButton ID="hlHierarchy" runat="server" OnClientClick= <%# "return windowpop('../.."+((string)Eval("NavigateURL")).Replace("~", "") +"', 1024, 768)" %>>

<%# ((string)Eval("Name")).Replace("-", " ") %>

</asp:LinkButton>

Reference


text:
Q: Unable to install ADT plugin in Eclipse? I did everything in Windows XP 32bit-with 4GB RAM, but thought why not install all applications on my other computer with 8GB RAM and Windows 7 loaded in it.
I installed everything (relevant 64-bit software : Java SDK-64 bit, Eclipse-64bit and Android SDK) in that Win 7-64 bit, except 1 thing in Windows 7 - 64bit. Even Android is loading fine on the emulator.
But when I am installing the ADT plugin in eclipse from Help > Install New Software > https://dl-ssl.google.com/android/eclipse/ then only 2 options are coming, and eventually the setup fails with showing the error that

Cannot complete the install because one or more required items could not be found.   Software being installed: Android Hierarchy Viewer
    16.0.1.v201112150204-238534 (com.android.ide.eclipse.hierarchyviewer.feature.group
    16.0.1.v201112150204-238534)   Missing requirement: Android Hierarchy Viewer 16.0.1.v201112150204-238534
    (com.android.ide.eclipse.hierarchyviewer.feature.group
    16.0.1.v201112150204-238534) requires 'com.android.ide.eclipse.ddms 0.0.0' but it could not be found

I did everything correctly on Windows XP, but I am getting this problem on Win 7 - 64bit.
Can someone please let me know how to resolve this problem and successfully install the ADT plugin in Eclipse on Win 7 - 64 bit.
Thanks.

A: Change https://dl-ssl.google.com/android/eclipse/ to http://dl-ssl.google.com/android/eclipse/ .


text:
Q: Root user has no access to bucket policy I have created a new S3 bucket and I am following the below tutorial to host a static website. https://docs.aws.amazon.com/AmazonS3/latest/userguide/HostingWebsiteOnS3Setup.html#step3-edit-block-public-access
However when it comes to setting the bucket policy, it states that the root user has no access to manage bucket policy. If I follow the links and traverse to the IAM console, there are no other users but me the root user. How can the root user grant himself the bucket permissions?

A: It wont allow setting a bucket policy if you have not cleared the Block All Public Access button. I had not cleared that and it was resulting in this invalid permissions error.


text:
Q: Suggest a plan- We planning to Migrate SSIS-Oracle data warehouse workflows that run on stored pro to Pyspark AWS Redshift pipeline So we are planning migration from legacy SISS to big data pipeline using spark , I am bit confused how to migrate existing store procedures based SISS system to Pyspark/Airflow .. Should we convert all stored Procedures to pyspark scripts/Spark SQL or there is any way we can run them on Redshift using Pyspark .
Currently Planning to convert stored procedures to pyspark/spark SQL ...is it right the way ?


text:
Q: How to fix Exception: Failure deliviring result ResultInfo I have an application that displays a dialog with a listview. After the user chooses an option from the listview, I will change a record using the information that the user selects.
For this I thought about using the command setResult (RESULT_OK, intent); but my code is generating the following exception:
09-25 12:01:06.035: E/AndroidRuntime(8783): FATAL EXCEPTION: main
09-25 12:01:06.035: E/AndroidRuntime(8783): java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=0, result=-1, data=Intent { flg=0x20000000 cmp=com.sisteplantbrasil/.WorkOrderInfo (has extras) }} to activity {com.sisteplantbrasil/com.sisteplantbrasil.WorkOrderInfo}: android.os.NetworkOnMainThreadException
09-25 12:01:06.035: E/AndroidRuntime(8783):     at android.app.ActivityThread.deliverResults(ActivityThread.java:3182)
09-25 12:01:06.035: E/AndroidRuntime(8783):     at android.app.ActivityThread.handleSendResult(ActivityThread.java:3225)
09-25 12:01:06.035: E/AndroidRuntime(8783):     at android.app.ActivityThread.access$1100(ActivityThread.java:140)
09-25 12:01:06.035: E/AndroidRuntime(8783):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1275)
09-25 12:01:06.035: E/AndroidRuntime(8783):     at android.os.Handler.dispatchMessage(Handler.java:99)
09-25 12:01:06.035: E/AndroidRuntime(8783):     at android.os.Looper.loop(Looper.java:137)
09-25 12:01:06.035: E/AndroidRuntime(8783):     at android.app.ActivityThread.main(ActivityThread.java:4898)
09-25 12:01:06.035: E/AndroidRuntime(8783):     at java.lang.reflect.Method.invokeNative(Native Method)
09-25 12:01:06.035: E/AndroidRuntime(8783):     at java.lang.reflect.Method.invoke(Method.java:511)
09-25 12:01:06.035: E/AndroidRuntime(8783):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1006)
09-25 12:01:06.035: E/AndroidRuntime(8783):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:773)
09-25 12:01:06.035: E/AndroidRuntime(8783):     at dalvik.system.NativeStart.main(Native Method)
09-25 12:01:06.035: E/AndroidRuntime(8783): Caused by: android.os.NetworkOnMainThreadException
09-25 12:01:06.035: E/AndroidRuntime(8783):     at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1118)
09-25 12:01:06.035: E/AndroidRuntime(8783):     at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
09-25 12:01:06.035: E/AndroidRuntime(8783):     at libcore.io.IoBridge.connectErrno(IoBridge.java:144)
09-25 12:01:06.035: E/AndroidRuntime(8783):     at libcore.io.IoBridge.connect(IoBridge.java:112)
09-25 12:01:06.035: E/AndroidRuntime(8783):     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
09-25 12:01:06.035: E/AndroidRuntime(8783):     at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:459)
09-25 12:01:06.035: E/AndroidRuntime(8783):     at java.net.Socket.connect(Socket.java:842)
09-25 12:01:06.035: E/AndroidRuntime(8783):     at libcore.net.http.HttpConnection.<init>(HttpConnection.java:76)
09-25 12:01:06.035: E/AndroidRuntime(8783):     at libcore.net.http.HttpConnection.<init>(HttpConnection.java:50)
09-25 12:01:06.035: E/AndroidRuntime(8783):     at libcore.net.http.HttpConnection$Address.connect(HttpConnection.java:340)
09-25 12:01:06.035: E/AndroidRuntime(8783):     at libcore.net.http.HttpConnectionPool.get(HttpConnectionPool.java:87)
09-25 12:01:06.035: E/AndroidRuntime(8783):     at libcore.net.http.HttpConnection.connect(HttpConnection.java:128)
09-25 12:01:06.035: E/AndroidRuntime(8783):     at libcore.net.http.HttpEngine.openSocketConnection(HttpEngine.java:315)
09-25 12:01:06.035: E/AndroidRuntime(8783):     at libcore.net.http.HttpEngine.connect(HttpEngine.java:310)
09-25 12:01:06.035: E/AndroidRuntime(8783):     at libcore.net.http.HttpEngine.sendSocketRequest(HttpEngine.java:289)
09-25 12:01:06.035: E/AndroidRuntime(8783):     at libcore.net.http.HttpEngine.sendRequest(HttpEngine.java:239)
09-25 12:01:06.035: E/AndroidRuntime(8783):     at libcore.net.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:80)
09-25 12:01:06.035: E/AndroidRuntime(8783):     at org.ksoap2.transport.ServiceConnectionSE.connect(ServiceConnectionSE.java:76)
09-25 12:01:06.035: E/AndroidRuntime(8783):     at org.ksoap2.transport.HttpTransportSE.call(HttpTransportSE.java:146)
09-25 12:01:06.035: E/AndroidRuntime(8783):     at org.ksoap2.transport.HttpTransportSE.call(HttpTransportSE.java:95)
09-25 12:01:06.035: E/AndroidRuntime(8783):     at com.sisteplantbrasil.webservices.PrismaWebServices.getDateTimeNow(PrismaWebServices.java:144)
09-25 12:01:06.035: E/AndroidRuntime(8783):     at com.sisteplantbrasil.entities.LaborRecord.getCurrentDate(LaborRecord.java:120)
09-25 12:01:06.035: E/AndroidRuntime(8783):     at com.sisteplantbrasil.entities.LaborRecord.getLaborEndDate(LaborRecord.java:146)
09-25 12:01:06.035: E/AndroidRuntime(8783):     at com.sisteplantbrasil.queries.sql.LaborRecordDBQueries.insertLaborRecord(LaborRecordDBQueries.java:35)
09-25 12:01:06.035: E/AndroidRuntime(8783):     at com.sisteplantbrasil.entities.LaborRecord.offlineSave(LaborRecord.java:167)
09-25 12:01:06.035: E/AndroidRuntime(8783):     at com.sisteplantbrasil.WorkOrderInfo.onActivityResult(WorkOrderInfo.java:492)
09-25 12:01:06.035: E/AndroidRuntime(8783):     at android.app.Activity.dispatchActivityResult(Activity.java:5390)
09-25 12:01:06.035: E/AndroidRuntime(8783):     at android.app.ActivityThread.deliverResults(ActivityThread.java:3178)
09-25 12:01:06.035: E/AndroidRuntime(8783):     ... 11 more

My code:
public void onClickEndLabor(View v) {
    if (selectedNextWorkOrderState != null) {
        Intent intent;

        if (showNotes) {
            EditText txtNotes = (EditText) findViewById(R.id.txtNotes);
            intent = IntentFactory.createWorkOrderInfo(
                    WorkOrderStateWorkflow.this,
                    selectedNextWorkOrderState, txtNotes.getText()
                            .toString(), Intent.FLAG_ACTIVITY_SINGLE_TOP);
        } else {
            intent = IntentFactory.createWorkOrderInfo(
                    WorkOrderStateWorkflow.this,
                    selectedNextWorkOrderState, "",
                    Intent.FLAG_ACTIVITY_SINGLE_TOP);
        }

        setResult(RESULT_OK, intent);

        finish();
    }
}

WorkOrderInfo Activity:
protected void onActivityResult(int requestCode, int resultCode,
        Intent intent) {
    if (resultCode == RESULT_OK) {
        super.onActivityResult(requestCode, resultCode, intent);

        Bundle extras = intent.getExtras();
        if (extras != null) {
            WorkOrderState nextWOState = (WorkOrderState) extras
                    .getSerializable("workOrderState");

            nextState = nextWOState.getWorkOrderState();
            String notes = extras.getString("notes");
            WorkOrder workOrder = Application.getInstance().getWorkOrder();

            previousWOState = new WorkOrderState(
                    workOrder.getWorkOrderState(),
                    workOrder.getWorkOrderStateName());

            if (Application.getInstance().useLaborRecord()) {
                lre.setWorkOrder(workOrder);
                lre.setNotes(notes);

                progress = ProgressDialog.show(this, getResources()
                        .getString(R.string.Wait), getResources()
                        .getString(R.string.EndingLabor));

                if (Application.getInstance().getStatus() == AppStatus.ONLINE) {
                    lre.asyncSave(endHandler);
                    lre.getWorkOrder().offlineSave(false);
                    lre.offlineSave(false, false);
                } else {
                    if (lre.offlineSave(true, false)
                            && lre.getWorkOrder().offlineSave(false)) {
                        endHandler.sendEmptyMessage(0);
                    } else {
                        Message msg = new Message();
                        msg.obj = new QueryException(getResources()
                                .getString(R.string.ErrorSaving));

                        endHandler.sendMessage(msg);
                    }
                }
            } else {

                ChangeWOState changeState = new ChangeWOState(
                        WorkOrderInfo.this);
                changeState.execute();

            }
        }
    }
}

Can someone tell me what is wrong with the code?
Thank´s for your attention!!!

A: NetworkOnMainThreadException: The exception that is thrown when an application attempts to perform a networking operation on its main thread.
http://android-developers.blogspot.in/2009/05/painless-threading.html
here is link that illustrates how to use asynctask
http://developer.android.com/reference/android/os/AsyncTask.html
android.os.NetworkOnMainThreadException with android 4.2
http://developer.android.com/reference/android/os/NetworkOnMainThreadException.html
http://blog.vogella.com/2012/02/22/android-strictmode-networkonmainthreadexception/


text:
Q: How to replicate a UNABLE_TO_LOCK_ROW error in a unit test We've been seeing the UNABLE_TO_LOCK_ROW issue in our prod org. I've created a retry for DML actions facing this issue to sleep for a certain number of milliseconds between each try and try for a certain number of times.
I'm unable to replicate the error within my unit tests. I'd like to know if it's possible to purposefully produce the UNABLE_TO_LOCK_ROW error in the unit test so I can test the retry logic?

A: You cannot intentionally cause this to happen, because you need at least two threads in order for this to actually get thrown. Two parallel tests running at once can accidentally cause this problem, but parallel testing is disabled for deployments, so those tests wouldn't pass correctly, even if you could coordinate two specific tests to run in parallel on purpose.
In other words, this is one of those times when you would need dependency injection or Stub API mocking. Either way, you'd have to have either a DML or SOQL class to inject code in to during testing. As I've advised before, it's best to probably just assume it works and leave out the coverage. In most cases, this shouldn't even drop you 1% of your total coverage if you're doing it right.


text:
Q: Add category while adding product in OpenCart2.x I'm working on a webshop using OpenCart2.x. I would like to add category while I'm adding product and assign product to that category.
Just to clarify... Let's say I want to add "HTC One" to category "Android". I would like to go to Catalog > Product > Add Product, enter "HTC One" details and
if category "Android" dosen't exist OC should offer to create new category.
It is possible in wordpress/woocommerce so I hope it is possible in OC2.
Sorry if the question is not for this site.
Thank you!

A: No, this is unfortunately not possible in vanilla OpenCart. However, I did find somewhat of a trick to make this process a tad bit more convenient.
If you open your OpenCart admin panel in 2 different browser instances that use different sets of cookies (different browser or incognito/no cookie mode) you can make your categories in one instance and then the category auto complete list in your product creation page will instantly update. Not exactly the desired functionality but definitely better than having to switch back and forth.


text:
Q: how to get touch event after a button click in iphone? I have a UIButton in my project and after a button click I am showing a UIView on the top of that button in such a way that the button remains hidden that time. I want to get a touchesmoved event on that time when I keep that button pressed and move finger over the overlapped UIView. As far as I did is like the following:
-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event{

 UITouch *touch = [touches anyObject];

    if ([touch view] == uiview)
    {

        NSLog(@"Touches moved");
    }

but it doesnt get called when I keep the button pressed that is hidden when the UIView comes up and the uiview goes hidden when I release the button. Any suggestion please?

A: I don't quiet understand what your trying to do but I would suggest you use UIGestureRecognizers and add Gestures Recognizers to your button.
Try using this code. I've used this in a card game i developed. moving cards around using long press gestures. Hope i helps.
 UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(addLongpressGesture:)];
 [longPress setDelegate:self];
 [YOUR_BUTTON addGestureRecognizer:longPress];

- (void)addLongpressGesture:(UILongPressGestureRecognizer *)sender {

UIView *view = sender.view;

CGPoint point = [sender locationInView:view.superview];

if (sender.state == UIGestureRecognizerStateBegan){

      // GESTURE STATE BEGAN

}
else if (sender.state == UIGestureRecognizerStateChanged){

     //GESTURE STATE CHANGED/ MOVED

    CGPoint center = view.center;
    center.x += point.x - _priorPoint.x;
    center.y += point.y - _priorPoint.y;
    view.center = center;

    // This is how i drag my views
  }

 else if (sender.state == UIGestureRecognizerStateEnded){

      //GESTURE ENDED
 }

A: You need to set view.userInteractionEnabled = NO for your overlapped UIView.
This will send action to button.


text:
Q: How to pass multiple lines to clipboard? Is there a way to send multiple lines of text to the clipboard?
I've used following commands but didn't work for me:
import os
text = """sample one \r\n sample two \r\n sample three"""
command = 'echo ' + text.strip() + '| clip'.
os.system(command)

I want o/p as
sample one

sample two

sample three

A: Use the clipboard module:
import clipboard
clipboard.copy("line1\nline2")  # now the clipboard content will be string "line1\nline2"
clipboard.copy("line3") # add line3
text = clipboard.paste()  # text will have the content of clipboard

Right, so @Reman said the clipboard copy command overrides it, instead of appending. So, let's do the appending ourselves.
line = '\n'.join(line, new_line)
clipboard.copy(line)
text = clipboard.paste() # now all lines separated by newline will be on the clipboard.


text:
Q: Hide Menu using jQuery Im new to jQuery and need a litte help.
I have created a nav menu that I want to completely disappear upwards after "3 seconds" once  a user lands on the page. From this an arrow will be in its place hiding the original nav menu.
When a user clicks on the "arrow" the menu will come back into view and stay there for now 20 seconds.
I have some code in this jsFiddle but it doesn't seem to be doing anything. Can anyone help out there?
http://jsfiddle.net/headex/AsjMz/1/
Any info passed on will be much appreciated.
Cheers

A: You have to use the correct selectors for your  <div/> Elements and supply the MenuOut()
 Function as an object, not a string.
$(function() {
    setTimeout(MenuOut /*don't supply this parameter as a string*/, 3000); /* 3000 represent 3000 milliseconds, so 3 seconds */
});

function MenuOut() { /* The sample code I put on top */
    $('#nav'/*it's an id (#), here you have to use a string*/).slideUp();
}

A: The error in your live example it's that you're passing the name of the function to the setTimeOut function with "" in other words
you have this
  setTimeout("MenuOut", 3000);

Change for this
  setTimeout(MenuOut, 3000);

Here's your live example with that change Demo

A: Instead of using animate, look at using jQuery's slideUp and slideDown.
You'll want to animate like so: setTimeout("$('#nav').slideUp()", 3000);

A: You had a few errors with your JS.
setTimeout requires a function callback, not a string.
You also used $(nav) instead of $("#nav")
http://jsfiddle.net/AsjMz/9/


text:
Q: parsing HTML in C# ASP.net here's my sample HTML...

                Invoice ID:

                    1622579

                Code:

                    20475

there's no ID so ican't use SelectNodes()
    How can i get the Code: 20475 using HTMLAgilitypack or regex?

A: Using latest HtmlAgilityPack, just using the document structure - this will not be very resilient to changes in the HTML - you should strongly consider adding appropriate ids (if this is your html anyway):
HtmlDocument doc = new HtmlDocument();
doc.Load(@"test.html");

var tds = doc.DocumentNode.Descendants("td").ToArray();
string codeValue = "";

for (int i = 1; i < tds.Length; i++)
{
    if (tds[i - 1].Element("b").InnerText == "Code:")
        codeValue = tds[i].Element("b").InnerText;
}


text:
Q: Intent and Edit Text Issues I am basically trying to create an application which consists of 2 activities.
In activity 1 , user can enter 2 values in 2 separate edit text fields and I have provided a spinner drop down item , using which user can select either of 2 values.
If user selects option as 1 and clicks on Submit button , user will be displayed a second activty with value displayed as per the id selected in spinner object in previous activity.
Like if user selects 1 , value in first edit text box gets shown and if he selects 2 , then second edit text box value is displayed.
Also, when user clicks on submit button in second activity , based on value he enters in edit text field of second activity , it will get displayed in either edit text box 1 or edit text box 2 of previous activity .
I am having issues understanding why my app is showing bizarre behaviour. Please guide me.
FIRST ACTIVITY FILE:
package spinnner.intents.understand;

    import android.app.Activity;
    import android.content.Context;
    import android.content.Intent;
    import android.os.Bundle;
    import android.view.View;
    import android.view.inputmethod.InputMethodManager;
    import android.widget.AdapterView;
    import android.widget.ArrayAdapter;
    import android.widget.EditText;
    import android.widget.Spinner;
    import android.widget.TextView;
    import android.widget.Toast;
    import android.widget.AdapterView.OnItemSelectedListener;

    public class TwoAppsActivity extends Activity {
        /** Called when the activity is first created. */
        String [] items = {"1","2"};
        //String ch;
        TextView tv;
        EditText et1,et2;
        Spinner spinner;
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);

             tv=(TextView) findViewById(R.id.txt);
            et1=(EditText) findViewById(R.id.edittxt1); // value 1
            et2=(EditText) findViewById(R.id.edittxt2); // value 2
            spinner=(Spinner) findViewById(R.id.spin1); // select

            //

            Intent i3 = getIntent();
            if(i3.getStringExtra("spinner.intents.understand.value1")!=null)
            {
                et1.setText(i3.getStringExtra("spinner.intents.understand.value1"));
            }
            else if(i3.getStringExtra("spinner.intents.understand.value2")!=null)
            {
                et2.setText(i3.getStringExtra("spinner.intents.understand.value2"));
            }
            else
            {
                Toast.makeText(getApplicationContext(), "Enter some text ", Toast.LENGTH_LONG).show();
            }

         // spinner logic
            ArrayAdapter<String> as1 = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, items);
            as1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
            spinner.setAdapter(as1);
            spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

                public void onItemSelected(AdapterView<?> arg0, View arg1,
                        int arg2, long arg3) {
                    // TODO Auto-generated method stub
                    tv.setText(items[arg2]);
                    Toast.makeText(getApplicationContext(), " You selected : "+items[arg2],Toast.LENGTH_LONG).show();
                }

                public void onNothingSelected(AdapterView<?> arg0) {
                    // TODO Auto-generated method stub
                    Toast.makeText(getApplicationContext(), "You selected nothing", Toast.LENGTH_LONG).show();
                }
            });

            //
        }

        public void Submit(View v)
        {
            Intent i = new Intent(this,Second.class);
            startActivity(i);

            //str1 = et1.getText().toString();
            //Toast.makeText(getApplicationContext(), str1, Toast.LENGTH_LONG).show();

        //  str2 = et2.getText().toString();
            //Toast.makeText(getApplicationContext(), str2, Toast.LENGTH_LONG).show();

            //

            if(spinner.getSelectedItem().toString()=="1")
            {
                Toast.makeText(getApplicationContext(), "I am in 1st option", Toast.LENGTH_LONG).show();
                i.putExtra("spinner.intents.understand.value1", et1.getEditableText().toString());
                i.putExtra("spinner.intents.understand.Id1", "1");
            }
            else if(spinner.getSelectedItem().toString()=="2")
            {
                Toast.makeText(getApplicationContext(), "I am in 2nd option", Toast.LENGTH_LONG).show();
                i.putExtra("spinner.intents.understand.value2", et2.getEditableText().toString());
                i.putExtra("spinner.intents.understand.Id2", "2");
            }
            else
            {
                Toast.makeText(getApplicationContext(), "You selected nothing!!!", Toast.LENGTH_LONG).show();
            }

        }
    }

SECOND ACTIVITY FILE
  package spinnner.intents.understand;

    import android.app.Activity;
    import android.content.Intent;
    import android.os.Bundle;
    import android.view.View;
    import android.widget.EditText;
    import android.widget.TextView;
    import android.widget.Toast;

    public class Second extends Activity{
          /** Called when the activity is first created. */
            TextView Tv;
            EditText Et;
            @Override
            public void onCreate(Bundle savedInstanceState) {
                super.onCreate(savedInstanceState);
                setContentView(R.layout.second);
                //
                Tv=(TextView) findViewById(R.id.txtS1);
                Et=(EditText) findViewById(R.id.edittxtS1);
                //

                Intent i1 = getIntent();

                if((i1.getStringExtra("spinner.intents.understand.Id1"))=="1")
                {
                    Toast.makeText(getApplicationContext(), "I am in value 1", Toast.LENGTH_LONG).show();
                    Et.setText(i1.getStringExtra("spinner.intents.understand.value1"));
                }
                else if((i1.getStringExtra("spinner.intents.understand.Id2"))=="2")
                {
                    Toast.makeText(getApplicationContext(), "I am in value 2", Toast.LENGTH_LONG).show();
                    Et.setText(i1.getStringExtra("spinner.intents.understand.value2"));
                }
                else
                {
                    Toast.makeText(getApplicationContext(), "Some mismatch", Toast.LENGTH_SHORT).show();
                }

            }

            public void submit(View v)
            {
                Intent i2 = new Intent(this,TwoAppsActivity.class);
                startActivity(i2);
                if(i2.getStringExtra("Id1")=="1")
                {
                    i2.putExtra("spinner.intents.understand.value1", Et.getEditableText().toString());

                }
                else if(i2.getStringExtra("Id2")=="2")
                {
                    i2.putExtra("spinner.intents.understand.value2", Et.getEditableText().toString());

                }
                else
                {
                    Toast.makeText(getApplicationContext(), "No data to display", Toast.LENGTH_LONG).show();
                }
            }
    }

MAIN.XML
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/txt"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

    <TextView
        android:id="@+id/txt1"
        android:text="Enter value 1:"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <EditText
        android:id="@+id/edittxt1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>

    <TextView
        android:id="@+id/txt2"
        android:text="Enter value 2:"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <EditText
        android:id="@+id/edittxt2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>

    <TextView
        android:id="@+id/txt3"
        android:text="Select"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

    <Spinner
        android:id="@+id/spin1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/btnsubmit1"
        android:text="Submit"
        android:onClick="Submit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</LinearLayout>

SECOND ACTIVITY XML FILE
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/txtS1"
        android:text="Value:"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>

    <EditText
        android:id="@+id/edittxtS1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"/>

    <Button
        android:id="@+id/btnsubmit2"
        android:text="Submit"
        android:onClick="submit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</LinearLayout>

ANDROID MANIFEST XML FILE
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="spinnner.intents.understand"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="15" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".TwoAppsActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".Second">
        </activity>
    </application>

</manifest>

I am also willing to mail my project if my code appears too messed up.

A: You shouldn't use == nor != to compare two strings. Use equals instead:
if(spinner.getSelectedItem().toString().equals("1"))

Regards.


text:
Q: Compactness theorem
Let $\Sigma$ be a set of theorems, such that for every $\varphi\in\Sigma$ exists an arbitrarily large (<--- edited) finite model $\mathcal{M}$, with $\mathcal{M}\models\varphi$.
Show: It exists an infinite modell $\mathcal{M}$ with $\mathcal{M}\models\varphi$ for every $\varphi\in\Sigma$.

Hello,
I want to proof this statement, and might need some help. I think the compactness theorem is needed.
My idea ist the following:
I want to extend $\Sigma$, such that it has an infinite carrier set $M$ and conclude that for the resulting model $\mathcal{M}=(M,\dotso )\quad\mathcal{M}\models\varphi$ by using the compactness theorem. The actuall proof seems to be trivial:
Let $\Sigma':=\Sigma\cup\{v_i\neq v_j: i\neq j\}$.
By assumption every finite $\overline{\Sigma}\subset\Sigma$ is satisfiable.
Therefor $\Sigma'$ is satisfiable by the compactness theorem and has obviously an infinite carrier set, since we added an infinite amount of variables.
My thoughts do not need that $\Sigma$ contains theorems (hence formulas without free variables) and not general formulas.
Am I mistaken with my proof?
Thanks in advance for your comments.

A:
Theorem: Let $\Sigma$ be a set of sentences such that every finite set of sentences from $\Sigma$ has arbitrarily large finite models. Then there is an infinite model of $\Sigma$.

Proof. Let $\pi_n$ be the assertion that our structure has at least $n$ distinct elements, and let $\Pi$ be the set of all the $\pi_n$. Since $\Pi$ has only infinite models, it is sufficient to show that $\Sigma \cup \Pi$ is consistent. By compactness, it is sufficient to show that $\Sigma \cup \Pi$ is finitely consistent.
Assume we are given a finite subset of $\Sigma \cup \Pi$. That is, we are given $\Sigma_0$ a finite subset of $\Sigma$ and $\Pi_0$ a finite subset of $\Pi$. Since $\Pi_0$ is finite, it can only include sentences $\pi_n$ up to some finite maximum $n_\max$. Therefore, to be a model of $\Pi_0$, it is sufficient to have size at least $n_\max$. By assumption, we can find $M \models \Sigma_0$ of size at least $n_\max$. Therefore $M \models \Sigma_0 \cup \Pi_0$. By previous statements, we have shown the desired result.

Note that it is necessary to strengthen the hypothesis to talk about finite sets of sentences from $\Sigma$, rather than just individual sentences. Otherwise, as @James mentioned in a comment, we obtain a counterexample whenever we allow $\Sigma$ to contain two sentences that contradict each other. Also, that's how compactness works: you need to know that $\Sigma$ is finitely consistent, not just that every sentence of $\Sigma$ is consistent.
We also have to allow that that every finite set of sentences has arbitrarily large finite models: it doesn't work if you just require $\Sigma$ to be finitely consistent and that each individual sentence has arbitrarily large finite models. Let $\varphi$ be a sentence such that both $\varphi$ and $\neg \varphi$ have arbitrarily large finite models. Then let $\Sigma$ consist of the following two sentences:

*

*"either the structure has exactly one element or $\varphi$ holds"

*"either the structure has exactly one element or $\neg\varphi$ holds."

Then $\Sigma$ is consistent, its only models have exactly one element, and each sentence in $\Sigma$ has arbitrarily large finite models.


text:
Q: What means "public static {}" in bytecode generated by clojure compiler? When I generate a class in clojure (through gen-class), I get the following definition upon inspection via javap:
public class foo.bar extends java.lang.Object implements java.io.Serializable{
    public final java.lang.Object state;
    public static {};
    public foo.bar();
    ...
}

I wonder what the construct public static {} means as I never saw something like this before …
Can someone please enlighten me?

A: The static section contains code which runs during static class initialization (before any instances of the class are created).
Think of having namespace-level code with side effects in Clojure -- those side effects take place as soon as anyone requires or uses the namespace, even if they don't actually call any functions. This is a comparable situation.

A: If you take a look at full output of javap (with javap -c ...) you'll see that it's just a bunch of code that clojure compiler put to be executed ahead of first class access. Usually it is interning of vars which are used later and so on.

A: sounds like a static initialization block on the class.
You can use that block to initialize all static variables of the class. However, I had never seen the "public" qualifier before it.
Try this in Java so you see the order of invocation
public class StaticTest {

  {
    System.out.println("Anonymous Block.");
  }

  static {
    //probably equivalent to that public {} you see on your code.
    System.out.println("Static Block.");
  }

  public StaticTest() {
     System.out.println("Constructor.");
  }

  public static void main(String[] args) {

    StaticTest test = new StaticTest() {
            {
                System.out.println("Anonymous block in instance.");
            }
    };
  }
}

when you execute this it prints the following:
> $ java StaticTest
> Static Block.
> Anonymous Block.
> Constructor.
> Anonymous block in instance.


text:
Q: Get response body 401 spring I'm consuming a service using Spring's Rest Template. I'm getting error 401 in response: [no body]. But I'm doing the same query by postman, and I get the body. can anybody help me?
code:

private static List<AcervoMarcSecao> assinar(List<AcervoMarcSecao> acervosMarcSecao, byte[] imgAssinatura) throws ClientException, IOException  {
        restTemplate = new RestTemplate();

        ResponseEntity<String> response = null;

        HttpEntity<?> request = getHttpEntity(acervosMarcSecao, imgAssinatura);

        try {
            response = restTemplate
                .exchange(parametros.get("SERVICE_HUB2_BASE_URL") + "/fw/v1/pdf/kms/lote/assinaturas",
                        HttpMethod.POST, request, String.class);

            if(response.getBody() != null) {
                LoteAssinaturaDTO loteAssinatura = new Gson().fromJson(response.getBody(), LoteAssinaturaDTO.class);
                for(int i = 0; i < acervosMarcSecao.size(); i++) {
                    byte[] documentoAssinado = ImageRecover.recoverImageFromUrl(loteAssinatura.getDocumentos().get(i)
                            .getLinks().get(0).getHref());
                    if(documentoAssinado != null)
                        if(acervosMarcSecao.get(i).getVinculo() == null)
                            acervosMarcSecao.get(i).setVinculo(new Vinculos());
                        acervosMarcSecao.get(i).getVinculo().setArquivoAssinado(documentoAssinado);
                        acervosMarcSecao.get(i).getVinculo().setDataGravacao(new Date());
                }
            }

            return acervosMarcSecao;

        } catch (RestClientResponseException e) {
            ErrorDTO error = new Gson().fromJson(e.getResponseBodyAsString(), ErrorDTO.class);
            if(error.getChave().equals("excecao.hub.perfil")) {
                throw new AlertaException(resourceBundle.getString("lblTipoAssinaturaDigitalInvalida"));
            }
            throw new AlertaException(error.getMessage());
        } catch (Exception e) {
            throw new AlertaException(resourceBundle.getString("txtErroCertificarArquivo"));
        }
    }

postman:


text:
Q: Venn Diagram Conditional Probability Questions Solution I was having a go at this question, I got an answer of $\frac{2}{29}$, not sure if this is correct, I would appreciate if someone could explain the solution to it.

A: You are correct, please include your working next time.
From the definition of conditional probability we have $$P(B\cap A'|C)=\frac{P(B\cap A'\cap C)}{P(C)}$$
$$=\frac{\frac{x}{5}}{x+\frac{x}{5}+\frac{x}{2}+2x^2+x}=\frac{\frac{x}{5}}{\frac{27}{10}x+2x^2}=\frac{\frac{1}{5}}{\frac{27}{10}+2x}.$$
But the sum of the probabilities must be $1$ so we have $$x+x+x^2+2x+\frac{x}{2}+x+\frac{x}{5}+2x^2+x+13x-1=1 $$
$$3x^2+\frac{197}{10}x-2=0$$
and solving gives $x=\frac{1}{10}$ and $x=-\frac{20}{3}$, but $x$ cannot be negative.
Thus we have $$P(B\cap A'|C)=\frac{\frac{1}{5}}{\frac{27}{10}+\frac{1}{5}}=\frac{\frac{1}{5}}{\frac{29}{10}}=\frac{2}{29}.$$


text:
Q: Populating IAuthSession with data from the database So I've created a custom CredentialsAuthProvider using ServiceStack as per the examples located here:
https://github.com/ServiceStack/ServiceStack/wiki/Authentication-and-authorization
I have the authentication side of things working but I'm not sure how I populate the session with data from the database in the OnAuthenticated method. In the example they show the following:
     //Fill the IAuthSession with data which you want to retrieve in the app eg:
    session.FirstName = "some_firstname_from_db";

In the TryAuthenticate method I have the username/password, which I can use to authenticate the user against the database, but once it goes to the OnAuthenticated method, how/what do I use to access/retrieve the user information from the database?

A: I know this is an older thread but it may still be relevant because unfortunately not much has improved since Sep of 2012 in terms of availability of ServiceStack documentation, clarity of examples or even comments in the code. (@mythz: It would be very helpful if you guys could add meaningful summaries to all your classes and methods.)
I struggled with the same dilemma until I looked at the actual code of CredentialsAuthProvider (which in general is pretty much the only way to understand how things work in ServiceStack). The OnAuthenticated is called right after TryAuthenticate inside the Authenticate method, so I figured it's not necessary to make all your DB calls in OnAuthenticated as @mythz suggests in his examples. Instead I placed the code that populates the IAuthSession object right into my implementation of TryAuthenticate, like so:
public override bool TryAuthenticate(IServiceBase authService, string userName, string password)
{
    try
    {
        // Use my own repo to authenticate the user.
        var userRepo = authService.TryResolve<IUserRepository>();
        var user = userRepo.Authenticate(userName, password);

        // Populate session properties with data from my user POCO.
        var session = authService.GetSession();
        session.Id = user.CurrentSession.ID.ToString();
        session.IsAuthenticated = true;
        session.CreatedAt = DateTime.UtcNow;
        session.DisplayName = session.FirstName = session.LastName = user.FullName;
        session.UserAuthName = session.UserName = user.Username;
        session.UserAuthId = user.ID.ToString();
    }
    catch (Exception ex)
    {
        // Log the exception, etc....
        return false;
    }
    return true;
}

However, you still have to override OnAuthenticated in order to save the cookie in HTTP response (which I assume is required for subsequent requests from the same browser to be authenticated) because the base implementation only sets the cookie if it finds IUserAuthRepository in the IOC container, which in my case won't happen because I use my own repository. So my implementation now looks like this:
public override void OnAuthenticated(IServiceBase authService, IAuthSession session, IOAuthTokens tokens, Dictionary<string, string> authInfo)
{
    try
    {
        // Save the browser cookie.
        var httpRes = authService.RequestContext.Get<IHttpResponse>();
        if (httpRes != null)
        {
            httpRes.Cookies.AddPermanentCookie(HttpHeaders.XUserAuthId, session.UserAuthId);
        }

        // Save the user session object (ServiceStack stores it in the in-memory cache).
        authService.SaveSession(session, SessionExpiry);
    }
    catch (Exception ex)
    {
        // Log the exception, etc....
    }
}

@mythz: Please let me know if the above makes sense or not.

A: Another good example of a ServiceStack's CustomUserSession is in the SocialBootstrapApi project. Rather than pulling information out of the data, it extracts the information out of the UserSession and populates its own Custom User Table using the registered DB Factory resolved from the AppHost IOC:
authService.TryResolve<IDbConnectionFactory>().Run(db => db.Save(user));

Rather than using it to extract and save data from the user's session, you can also use any of your registered dependencies to fetch data and populate the session with:
public override void OnAuthenticated(
    IServiceBase authService,
    IAuthSession session,
    IOAuthTokens tokens,
    Dictionary<string, string> authInfo)
{
    using (var db = authService.TryResolve<IDbConnectionFactory>().OpenDbConnection())
    {
        var user = db.Id<MyUser>(session.UserId);
        session.FirstName = user.FirstName;
    }
}


text:
Q: C# immutability.. a lie? It is one ideal practice in a multithreaded environment to clone objects (eg: a list) to promote immutability. However if we do so it can be a lie to the API users. What I'm saying is that..
Consider the following code:
public class Teacher {

    public List<Student> Students = new List<Student>();

    public Student GetStudent(int index) {
        return Students[index].Clone();
    }
}

public class Student {
    public DateTime LastAttended { get; set; }
}

and the users of the API could have done so:
var teacher = new Teacher();
var student3 = teacher.GetStudent(3);

student3.LastAttended = DateTime.Now;

Without proper documentation the user could not have known the student object he is getting is actually a cloned object and in which case all changes made to the object will not reflect the original one.
How can the code above be improved in a way for the user to know intuitively that the GetStudent is meant only for reading and not for modification? Is there any way to force / restrict from modifying the Student object returned from the GetStudent method?

A: Your Student object isn't immutable at all. If you want immutability, make an immutable object:
public sealed class Student {
    private readonly DateTime _lastAttended;
    public DateTime LastAttended { get { return _lastAttended; } }

    public Student(DateTime lastAttended)
    {
        _lastAttended = lastAttended;
    }
}

If you don't want someone to set the value of a property, then do not expose a setter, only a getter.
This of course requires architecting the application around this. If you actually need to update the LastAttended time, you would do that e.g. through a Repository that updates the Database and returns a new Student object. Also, many ORMs can't automatically handle immutable objects and need some translation code.
Note that your issue is super-common when people cache objects in Memory and then pass them along, e.g. to View Models which manipulate them, unknowingly modifying the master-object in the cache. This is why cloning is often recommended for Caches. Cloning protects you from code making modifications to "your" objects - every time someone asks, they get a new instance of your master object. Cloning does not prevent the caller to mess up his own version.
Note that declaring a Field as readonly doesn't do much if the Type of the Field is a mutable type - I could still do e.g. Student.Course.Name = "Test"; even if Course were readonly - I cannot change the reference in the Student object, but I can access any property setters.
True immutability is a bit of a pain in C# as it's a lot of typing and a lot of factory methods. At some point, it may be okay to just leave a normal mutable Get/Set and trust that callers know what to do as they can only mess up themselves, not you. That said, anything that actually manipulates the data in the database needs proper security/business rule checks.


text:
Q: Object must be set to an instance (Array using Monogame) So I'm trying to draw a grid to the screen with monogame using an array, but it keeps giving me the error "object reference must be set to instance of object". I've initialized the grid as you can see, so I don't know whats causing the problem. The exception is being thrown on the Globals.Spritebatch.draw line, and when I change the grid[i,j] to new Rectangle(), it works just fine, but I would prefer to use the grid. Here's my code, any help/explanation of what I'm doing wrong would be appreciated.
public class Grid
    {
        Rectangle[,] grid;
        public Grid()
        {
        Rectangle[,] grid = new Rectangle[12, 8];
        for (int i = 0; i <= 11; i++)
        {
            for (int j = 0; j <= 7; j++)
            {
                grid[i, j] = new Rectangle(new Point(100 + 50 * i, 100 + 50 * j), new Point(50, 50));
            }
        }
    }
        public void Update()
        {
        }
        public void Draw()
        {
           for(int i = 0; i <= 11; i++)
            {
                for (int j = 0; j <= 7; j++)
                {
                    Globals.spriteBatch.Draw(Globals.content.Load<Texture2D>("2d\\GridRect"), grid[i, j], Color.White);
                }
            }
        }
    }


text:
Q: Why is success block being called with incorrect path? I accidentally mistyped the post path and noticed that although it's being wrong, the success block is called:
[[APIClient sharedInstance]
 postPath:@"api_url"
 parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
     NSLog(@"Result: Success %@",[responseObject description]);

 } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
     //handle error
     NSLog(@"Result: Failure + %@",error.userInfo);

  }];

Of course the data are not being sent to server and the transaction is not processed, but I want to know why it's not the failure block which is supposed to be called in case the path is wrong? Thanx.

A: Failure is called if the requestOperation has an associated error after finishing. Reasons for an error include the response having the incorrect Content-Type, not having an acceptable status code (2XX range, by default), or an error processing the downloaded data.
Why your server returned a 200 response with the correct content type is a question only something you can determine.


text:
Q: Drag and drop column data to another column In Flex, using AdvancedDataGrid, I'm trying to achieve a drag and drop of one row's column data to another row's column or the same row but different column.  Is this even possible?  I've been googling for hours and all I can find are drag and drop whole columns just to rearrange their view order.

A: You have two options to make columns draggable.
First is to make all the columns draggable in the DataGrid.  You can do this using the draggableColumns property on the DataGrid class.  Set its value to true.
The second is to set the draggable property on the DataGridColumn class.
In both cases, you would drag the columns using the column header.
If you want to be able to drag a single cell, there is no way to do this that I know of.


text:
Q: getting a servlet to print from a csv file to an xhtml page/PluginExecutionException I need to pull data from a csv file that is on my computer and print it to a web page via a servlet. The data needs to read one line at a time and refresh every second, then when it hits the end of the csv file, start again at the top. I feel like I'm close, but when I try to build the program nothing outputs to the web page. It's highly possible that something is misplaced in the code. Any help you can give would be greatly appreciated, I completely suck at programming and am just trying to get through this class. I have added code from all 3 parts. I am using netbeans IDE 8.2 and glassfish server.
main.xthml:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <title>Ivan's HTTP ETF</title>
  <link rel="stylesheet" type="text/css" href="resources/css/default.css" />

Ivan's HTTP ETF

            Ticker
            IGH

            Date
            --

            Time
            --

            Price
            --

            Volume
            --

            52-weekHigh
            --

            52-weekLow
            --

DukeETFServlet.java:

package javaeetutorial.web.dukeetf;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Queue;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.servlet.AsyncContext;
import javax.servlet.AsyncEvent;
import javax.servlet.AsyncListener;
import javax.servlet.ServletConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(urlPatterns={"/dukeetf"}, asyncSupported=true)
public class DukeETFServlet extends HttpServlet {
    private static final Logger logger = Logger.getLogger("DukeETFServlet");
    private static final long serialVersionUID = 2114153638027156979L;

    private Queue<AsyncContext> requestQueue;
    @EJB private PriceVolumeBean pvbean;

    @Override
    public void init(ServletConfig config) {
        /* Queue for requests */
        requestQueue = new ConcurrentLinkedQueue<>();
        /* Register with the bean that provides price/volume updates */
        pvbean.registerServlet(this);
    }

    /* PriceVolumeBean calls this method every second to send updates */
    public void send(String date, String time, String price, String volume, String weekHigh, String weekLow) {
        /* Send update to all connected clients */
        requestQueue.forEach((acontext) -> {
            try {
                String msg = String.format(date, time, price, volume, weekHigh, weekLow);
                PrintWriter writer = acontext.getResponse().getWriter();
                writer.write(msg);
                logger.log(Level.INFO, "Sent: {0}", msg);
                /* Close the connection
                * The client (JavaScript) makes a new one instantly */
                acontext.complete();
            } catch (IOException ex) {
                logger.log(Level.INFO, ex.toString());
            }
        });
    }

    /* Service method */
    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("text/html");

        /* Put request in async mode. */
        final AsyncContext acontext = request.startAsync();
        /* Remove from the queue when done */
        acontext.addListener(new AsyncListener() {
            @Override
            public void onComplete(AsyncEvent ae) throws IOException {
                requestQueue.remove(acontext);
                logger.log(Level.INFO, "Connection closed.");
            }
            @Override
            public void onTimeout(AsyncEvent ae) throws IOException {
                requestQueue.remove(acontext);
                logger.log(Level.INFO, "Connection timeout.");
            }
            @Override
            public void onError(AsyncEvent ae) throws IOException {
                requestQueue.remove(acontext);
                logger.log(Level.INFO, "Connection error.");
            }
            @Override
            public void onStartAsync(AsyncEvent ae) throws IOException { }
        });
        /* Add to the queue */
        requestQueue.add(acontext);
        logger.log(Level.INFO, "Connection open.");
    }
}

PriceVolumeBean.java:

package javaeetutorial.web.dukeetf;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.ejb.Singleton;
import javax.ejb.Startup;
import javax.ejb.Timeout;
import javax.ejb.TimerConfig;
import javax.ejb.TimerService;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;

/* Updates price and volume information every second */
@Startup
@Singleton
public class PriceVolumeBean {
  private static final Logger logger = Logger.getLogger("PriceVolumeBean");
  private final String csvFile = "/Users/ivanhurdimac/glassfish5/docs/javaee-tutorial/examples/web/servlet/dukeetf/project4input.csv";

  /* Use the container's timer service */
  @Resource TimerService tservice;

  private BufferedReader reader = null;
  private DukeETFServlet servlet;

  @PostConstruct
  public void init() {
    try {
      reader = new BufferedReader(new FileReader(csvFile));
    } catch (IOException e) {
      throw new RuntimeException("Failed to read the CSV file [" + csvFile + "].", e);
    }

    /* Intialize the EJB and create a timer */
    logger.log(Level.INFO, "Initializing EJB.");
    tservice.createIntervalTimer(1000, 1000, new TimerConfig());
  }

  public void registerServlet(DukeETFServlet servlet) {
    /* Associate a servlet to send updates to */
    this.servlet = servlet;
  }

  @Timeout
  public void timeout() {

    String line;
    try {
      line = reader.readLine();

      // Once we are done, just return
      if (line == null) {
        return;
      }

    } catch (IOException e) {
      throw new RuntimeException("Failed to read a line from the CSV file [" + csvFile + "].", e);
      } finally {
        if (reader != null){
            try{
                reader.close();
            }catch (IOException e){
             throw new RuntimeException("CSV file didn't close [" + csvFile + "].", e);
            }
        }
        }

    String[] parts = line.split(",");

    /* Adjust price and volume and send updates */
    String date = parts[0];
    String time = parts[1];
    String price = parts[2];
    String volume = parts[3];
    String weekHigh = parts[4];
    String weekLow = parts[5];

    if (servlet != null) {
      servlet.send(date, time, price, volume, weekHigh, weekLow);
    }
  }
}


text:
Q: Uploading file via Axios config I want to change my axios setup to upload multiple files within it
I am trying to pass it to data if the req.file exist
But it does not work
Is there any way to access request file by req.file
What if it is defined in backend?
(Like code below)
 axios({
    url: URL + req.url,
    method: req.method,
     ...(
        (!req.file)
        ? { data: req.body }
        : { data: req.file }
    ),
})

A: Add the file to a formData object, and set the Content-Type header to multipart/form-data.
var formData = new FormData();
var imagefile = document.querySelector('#file');
formData.append("image", imagefile.files[0]);
axios.post('upload_file', formData, {
    headers: {
      'Content-Type': 'multipart/form-data'
    }
})

Reference HERE


text:
Q: Select parent and child attribute value I have an xml file like below:
<tag>
   <file name="name1">
      <error message="error1"/>
      <error message="error2"/>
   </file>
   <file name="name2">
      <error message="error1"/>
      <error message="error2"/>
   </file>
</tag>

I hope to get a next result:
name1: error1, error1;
name2: error1, error1

I'm trying to do something like this:
*//file/@name | //file/error/@message*

But this, of course, does not work. Can I implement a map?

A: With XPath 3.1,
string-join(/tag/file ! (@name || ': ' || string-join(error/@message, ', ')), '#')

where # represents a newline character escaped according to the conventions of your host language, e.g. \n for Java,
 for XSLT.
For XPath 2.0 replace A!B by for $a in A return B and replace A||B by concat(A, B)
XPath 1.0: not possible without host language support.

A: This is only possible with XPath-2.0 or above. You can use the following expression to create a string as a result. It uses the appropriate delimiters , and LF
.
for $nam in /tag/file/@name, $msg in $nam/../error return concat(if (generate-id($msg) = generate-id($nam/../error[1])) then concat($nam,': ',$msg/@message) else $msg/@message, if (generate-id($msg) = generate-id($nam/../error[last()])) then ';
' else ',')

The output is:
name1: error1, error2;
name2: error1, error2;

This output differs a little bit from your desired output above (error2 instead of error1) and a trailing ;. If you need to get rid of the last ;, you can do so by implementing the same principle like with the line-feeds.
P.S.: The approach for checking for the first and last elements seems to be sub-optimal, so there's probably room for improvement.


text:
Q: How to include edittext in appwidget like Google search widget I was trying to include an editText in appwidget..later I came to know that it is not possible to include edittext
But if I check Google search appwiget I can see they are using a view similar to edittext..
How can I create a view like edittext for widget

A: Dianne Hackborn explains on this thread:
http://groups.google.com/group/android-developers/browse_thread/thread/a50a2aff0c8c754d/
that the Google search widget is a "special case", built right into the home screen (not a true widget), so they are obviously able to take some liberties.  Pretty sure you're not going to be able to do this, at least not pre-3.0.

A: I have used TextView instead of EditText  with custom background.. and onClick it will take to the desired screen ..
This looks similar to Twitter and Facebook search widget :)


text:
Q: Groovy: Cannot cast object 'true' with class 'java.lang.Boolean' to class 'java.io.File' I don't understand why I am getting the following error. Any thoughts?
I am getting error:
Cannot cast object 'true' with class 'java.lang.Boolean' to class 'java.io.File'
This is the code producing the error at line 'if (envProp.exists()...':
static private File envProp = new File('env.properties')
static private File envPropBak = new File('env.properties.bak')

@BeforeClass
static void beforeAll() {
    if (envProp.exists()) {
        envPropBak.write( envProp.text )
    }
}

I don't understand why envProp.exists() is trying to cast anything as another object. Method .exists() should just return a boolean.
Thanks

A: I had the same problem today, but in my case was:
org.codehaus.groovy.runtime.typehandling.GroovyCastException: Cannot cast object 'true' with class 'java.lang.Boolean' to class 'java.util.List'

The thing is that if your have something like this:
public List<Foo> method(){
    methodThatReturnsTrue()
}

Because Groovy uses the last sentence's return as the method's return value, it tries to cast true to <some_not_boolean_type> and so the error you and I are getting.

A: For the sake of completeness I need to say that I got a similar message:

Cannot cast object 'true' with class 'java.lang.Boolean' to class
  'java.util.List'

When I invoked:
final List<String> reportedChangedFiles = linesOfChangedFiles.removeAll([null])

I was expecting removeAll() to return a new collection but I forgot that it modifies the current collection and returns a boolean instead. So it was as easy as:
linesOfChangedFiles.removeAll([null])

A: That was a bug and got fixed in newer versions (2.3.2):
https://issues.apache.org/jira/browse/GROOVY-6810


text: Q: Confusion over summation Before Someone marks this duplicate, this is from an answer just given in this site for another question. But I'm unable to follow this step, how choosing $q<2^n$ forces summation to go on from $k \geq n+1$?


text:
Q: Performance in CUDA I can't seem to figure out the underlying factors that affect my kernels' performance. I implemented two simple kernels, one that loads two images and adds them, pixel by pixel, and one that loads two images and ANDS them, in the bitwise sense. Now, I've templatized them so that the kernels can take 8- and 32-bit images, as well as 1-, 3-, and 4-channel images.
So, initially I had both kernels loading the global memory as uchar3 and float3, along with uchar4 etc. I wasn't too sure about using the triples, however, because of coalescing, so I thought I'd give it a profiling run. I figured that since the operations were independent of channel number, I could just as well read the image as if it were a 1-channel uchar image of triple the width, rather than the uchar3 image that it really was.
In fact, the uchar3 global loads were much, much slower than the uchar loads. My efforts were vindicated. But, alas, this only happened with the arithmetic kernel. The bitwise AND operation showed the exact opposite result!
Now, I know I could just load the image data as uints rather than uchars, for the bitwise operation, which should take care of the coalescing perfectly. But let's assume I simply want to learn and understand what is going on.
And let's forget about float3s and float4s, etc. My problem is with the uchar versions of the kernels. So, in a nutshell, why is the uchar load sometimes faster than the uchar3 load, and sometimes not?
I'm using a GTX 470, compute capability 2.0.
PS. According to the CUDA programming guide, logical operations and add operations have the same throughput. (My kernel actually has to first convert the uchars to uints, but that should be happening in both kernels.) So the execution length should amount to much the same thing, from what I gather.
The arithmetic add kernel (uchar version):
__global__ void add_8uc1(uchar* inputOne, uchar* inputTwo, uchar* output, unsigned int width, unsigned int height, unsigned int widthStep)
{
    const int xCoordinateBase = blockIdx.x * IMAGE_X * IMAGE_MULTIPLIER + threadIdx.x;
    const int yCoordinate = blockIdx.y * IMAGE_Y + threadIdx.y;

    if (yCoordinate >= height)
        return;

#pragma unroll IMAGE_MULTIPLIER
    for (int i = 0; i < IMAGE_MULTIPLIER && xCoordinateBase + i * IMAGE_X < width; ++i)
    {
        //  Load memory.
        uchar* inputElementOne = (inputOne + yCoordinate * widthStep + (xCoordinateBase + i * IMAGE_X + threadIdx.x));
        uchar* inputElementTwo = (inputTwo + yCoordinate * widthStep + (xCoordinateBase + i * IMAGE_X + threadIdx.x));

        //  Write output.
        *(output + yCoordinate * widthStep + (xCoordinateBase + i * IMAGE_X + threadIdx.x)) = inputElementOne[0] + inputElementTwo[0];
    }
}

The bitwise AND kernel:
__global__ void and_8uc1(uchar* inputOne, uchar* inputTwo, uchar* output, unsigned int width, unsigned int height, unsigned int widthStep)
{
    const int xCoordinateBase = blockIdx.x * IMAGE_X * IMAGE_MULTIPLIER + threadIdx.x;
    const int yCoordinate = blockIdx.y * IMAGE_Y + threadIdx.y;

    if (yCoordinate >= height)
        return;

#pragma unroll IMAGE_MULTIPLIER
    for (int i = 0; i < IMAGE_MULTIPLIER && xCoordinateBase + i * IMAGE_X < width; ++i)
    {
        //  Load memory.
        uchar* inputElementOne = (inputOne + yCoordinate * widthStep + (xCoordinateBase + i * IMAGE_X + threadIdx.x));
        uchar* inputElementTwo = (inputTwo + yCoordinate * widthStep + (xCoordinateBase + i * IMAGE_X + threadIdx.x));

        //  Write output.
        *(output + yCoordinate * widthStep + (xCoordinateBase + i * IMAGE_X + threadIdx.x)) = inputElementOne[0] & inputElementTwo[0];
    }
}

The uchar3 versions are the same except that the load/store lines are now as follows:
        //  Load memory.
    uchar3 inputElementOne = *reinterpret_cast<uchar3*>(inputOne + yCoordinate * widthStep + (xCoordinateBase + i * IMAGE_X + threadIdx.x) * 3);
    uchar3 inputElementTwo = *reinterpret_cast<uchar3*>(inputTwo + yCoordinate * widthStep + (xCoordinateBase + i * IMAGE_X + threadIdx.x) * 3);

    //  Write output.
    *reinterpret_cast<uchar3*>(output + yCoordinate * widthStep + (xCoordinateBase + i * IMAGE_X + threadIdx.x) * 3)
        = make_uchar3(inputElementOne.x + inputElementTwo.x, inputElementOne.y + inputElementTwo.y, inputElementOne.z + inputElementTwo.z);

Similarly for the AND kernel. (I'm not sure I remember the kernels exactly, to be honest... I'll confirm that tomorrow).

A: uchar3 loads are split by the compiler into separate loads as there are no 24-bit loads in the SM's instruction set. As such, they are never coalesced. To a certain degree, the cache is going to mitigate this.
However, depending on the exact execution configuration there might only be about 10.7 bytes of cache per thread (your example will probably come close to that value as the kernel is simple, so a lot of threads can run concurrently on one SM). As the cache is not fully associative, the number of usable bytes per thread might be a lot smaller before thrashing occurs. When exactly that happens depends on a lot of factors including the exact scheduling of instructions, which might be different even for instructions that have the same documented throughput.
You can compare the output of cuobjdump -sassexecutable for both versions to see whether the static scheduling by the compiler is the same. How the dynamic scheduling at runtime works out is basically unobservable however.
As you have noticed, all channels of the image are processed in the same way, so it doesn't matter how you distribute them between threads. The best option you have is to use uchar4 instead of uchar3 or uchar, which (assuming suitable alignment of the image) will give you coalesced accesses independent of the cache. This should result in both shorter and more consistent execution times.


text:
Q: $A^3$ is similar to $B^3$ but $A^2$ is not similar to $B^2$ Find an example of $A,B$ such that $A^3$ is similar to $B^3$, and $A^2$ is not similar to $B^2$, and $A$ is not similar to $B$.
I only have some clues that $p_{A^2}(x) \neq p_{B^2}(x)$ and $p_{A}(x) \neq p_{B}(x)$
I first wanted to start from $A^3 = S^{-1} B^3 S$
Then let $S$ and $B$ to be some arbitrary matrices, where $S$ is invertiable, so that I could obtain $A^3$ which is similar to $B^3$. Thus, $A = \sqrt[\leftroot{-3}\uproot{3}3]{A^3}$
However, I realize I don't know how to find square root or cube root of matrices.

A: HINT: Can you think of an example where both cubes are the zero matrix but one square is not?

A: Let $\omega:=e^{\frac{2\pi i}{3}}$.
Then
$$
A=\begin{pmatrix}
\omega & 0\\
0 &\omega
\end{pmatrix}
\text{  and  }
B=\begin{pmatrix}
\omega & 0\\
0 &1\\
\end{pmatrix}
$$
will do the trick.

A: I want to argue that, in some sense, the examples already given are the only things that can go wrong.
First, we consider the case when $A$ and $B$ are diagonalizable.  Diagonalizable matrices are determined (up to similarity) by their eigenvalues and multiplicities.  Let us group the eigenvalues together based on the value of $\lambda^3$.  For a given value of $\lambda$, the equation $x^3-\lambda^3=0$ has 3 solutions, $\lambda, \omega \lambda, \omega^2\lambda$, where $\omega$ is a primitive cube root of unity.  e.g., $\omega=e^{2\pi i/3}$.  For example, if $A=\operatorname{diag}(1,\omega, \omega, \omega^2, 2, 2\omega)$, we would break the eigenvalues into two multi-sets, $\{1,\omega, \omega, \omega^2\}$ and $\{2, 2\omega\}$
Each group of eigenvalues can contain up to 3 different eigenvalues in it, and we see that as long as the multiplicities are different for $A$ and $B$, $A$ and $A^2$ will not be similar to $B$ and $B^2$.
For a simple (rational!) example of this type, consider $A=I$, $B=\begin{pmatrix} 0 & 1 & 0 \\ 0 & 0 & 1 \\ 1 & 0 & 0 \end{pmatrix}.$  For a $2\times 2$ real (but not rational) example, again consider $A=I$ and $B$ a rotation of angle $2\pi/3$.
The thinking here actually gives a nice way to take square roots of diagonalizable matrices: diagonalize, then replace  every eigenvalue with one of its possible cube roots.  If $A$ is $n\times n$ and has no repeated eigenvalues, there are $3^n$ ways to do this.  However, repeated eigenvalues mean we can take multiple different eigenbases, which yield different cube roots.  For example, if $A=I_3$, pick any axis and and the rotation about that axis of angle $2\pi/3$ will be a cube root.  This method also does not allow for the possibility of non-diagonalizable square roots.

So one problem is that $A$ and $B$ can have different eigenvalues even though $A^3$ and $B^3$ have the same eigenvalues.  But what if they have identical characteristic polynomials? It isn't too hard to construct examples which are nilpotent, but that is essentially all that can go wrong, at least over $\mathbb C$.  This follows from the following result.
Lemma: If $A=J_n(\lambda)$ is an $n\times n$ Jordan block with eigenvalue $\lambda$, and $\lambda\neq 0$, then $A^{3}$ is similar to $J_n(\lambda^3)$.
Proof. Note that $(A-\lambda I)^n=0$ but $(A-\lambda I)^{n-1}\neq 0$ uniqutely characterizes $A$ up to similarity.  Since $A$ and $I$ commute, we can factor $(A^3-\lambda^3 I)=(A-\lambda I)(A-\omega\lambda I)(A-\omega^2 \lambda I)$, factors of which all commute with each other, and since $\lambda$ is the only eigenvalue of $A$, the latter two factors are invertible.  Then $(A^3-\lambda^3 I)^k=(A-\lambda I)^k(A-\omega\lambda I)^k(A-\omega^2 \lambda I)^k$.  Since the latter two terms are invertible, if $k<n$, the overall expression is not $0$, and if $k=n$, then the first factor is already $0$ so the entire expression is as well.
This shows that if $A$ and $B$ are invertible and $A^3$ and $B^3$ are similar, then we can pair off the Jordan blocks of $A$ and $B$ in such a way that corresponding blocks will have the same size and the ratio of corresponding eigenvalues is a cube root of unity.
This also says how to find all the cube roots of an invertible matrix $A$.  First, write the JNF of $A$ as a sum of Jordan blocks.  Second, replace the eigenvalue for each block with one of its 3 cube roots. Call this matrix $B$  Then $B^3$ is similar to $A$, and for every $P$ such that $PB^3P^{-1}=A$, we get $PBP^{-1}$ is a cube root of $A$.
For non-invertible matrices, we can canonically break them up as the sum of an invertible and nilpotent matrix, and it is a fun (but involved) combinatorial problem to understand what the square or cube roots of a nilpotent matrix are.


text:
Q: Is it possible to generate multi audience claim JWT token using Azure Identity? I'm reading about JWT token and understands that a single token can have multiple audiences claims so that the same token can be used with multiple resource servers. But I'm not able to find out a way to generate such token in Azure Active Directory Authentication Libraries (ADAL).
If you look at the AcquireTokenAsync function which is part of AuthenticationContext class, all its implementations just takes a single resource parameter. But I'm not able to find any written doc which says ADAL doesn't supports multi audience token.
Does anyone know whether its possible in ADAL or not?

A: Unfortunately this is not allowed. Azure AD issues a token for a certain resource (which is mapped to an Azure AD app). When we call AcquireTokenAsync, we need to provide a single resourceID. The result is the token can only be used for resource matching the supplied identifier.


text:
Q: Best Practice: How to realize a browsergame "building system"? i am developing a browser game and stuck on a "theory problem".
I want to make the user to "level" specific buildings to gain better stats.
Example:

*

*Coal Mine: Lvl 1  (If user clicks on "upgrade" it will upgrade after X hours to lvl2 and so on)

Now my question is, whats the best solution to handle it in the mysql database?
What table setup's would you prefer and how to mange the "lvling" thing?
Would it be good to make a table called "buildings" and another one with "user_buildings" where a link to "buildings" is with actual level?
Or are there better solutions?
Please help me with a good brainstorming :)

A: in the buildings table I would keep the buildings "definition" like hours needed to upgrade from lvl 1 to2 is X, from 2 to 3 is Y...
in user_buildings I would keep the users curent building, like: Coal Mine, located apt partition of map z, built started at u, current level u...

A: Im making a Browsergame and Just finished the building System for the Resources and I made something that Adds a Timestamp to A Database and process / upgrade the Building AFTER the user logges in, using Real-Time Handling..
I'm Using A simple logic script that calculates the time depending on Server Speed and Bulding LVL.


text:
Q: Offline to Online database synchronization programmatically using PHP and MySQL I am working on a project in which the client requires an online as well as an offline application. Offline application data will be manually synced to online database linked to the web application.
Database is MySQL, some of the functions need to be available online as well as offline. Suppose any user who does not have internet access will use the offline application. Once he is done with his work, and has internet access, he will sync all his work/data to the online database with single click.
I know how to push the data to the online database, but the complexity here is how to maintain the indexes/primary keys of the records in sequence, without losing any data or mismatching any data.
How do I maintain the primary keys in sequence if a user syncs his offline data to online?

A: Plan A:  You charge your client an arm an leg to develop code to keep track of diffs, avoid dup keys, upload data, etc.
Plan B:  Multi-source replication (available at least in MariaDB).
With Multi-source, each offline laptop can be a "Master".  The "online server" is a Slave.  All writes must be done on the Master(s).  Not being able to write to the online Slave should not be an issue, just add a extra, centralized, offline Master in HQ if needed.
As for dup keys -- You must design the schema to avoid any issues like that.  This probably means no AUTO_INCREMENT or FOREIGN KEYS.  It may mean each offline Master has separate tables (or separate a database) for anything that can't live without things that will cause trouble.  But then, that means having some sort of resolution code after each connect.  (The upload is merely Replication doing its thing.)
Plan C:  NDB Cluster.  This is a significantly different Engine available under MySQL.  The set up is complex.  However, it provides a different model for replication -- "eventual consistency".  Rather than hanging on a dup key (etc), you provide rules for what to do in such situations.  These rules are automatically applied when replication leads to a conflict.
Plan D:  Galera Cluster (built into MariaDB 10.x; manually installable on MySQL) -- With this clustering technology, "nodes" can come and go; when they reconnect they automatically get back in sync.  But...  There needs to always be a quorum, that is more than 50% online.  Although you can write to any node, you cannot write to nodes that are not part of the quorum.
Plan E:  Convince the client to stay connected.  Or not do any writes when disconnected.  In this case, the offline machine can be a readonly Slave.  Writes must wait for connection to the remote Master.
Note:  In any case, you should write the application with an explicit eye to what app actions need writes versus what can be readonly.  Suggest you go as far as to have two separate connections -- one for writes and associated reads, one for plain reads.  This will facilitate whatever Plan you pick.
Which do I recommend?  I have not heard enough about your situation to say which.


text:
Q: Trying to have Excel VBA return a 0 when dividing Trying to get Excel VBA to return a number 0 in Cell D16(Conversion Rate) if cell D7 (Submissions) is a zero when dividing cell D13 (Hires) / D7 (Submissions). We sometimes don't have submissions but have hires from previous submissions (that we aren't allowed to record as a submission twice). The user clicks on a convert button to get the conversion rate, but the user keeps getting a Run-time error '11': Division by zero. We know that we have to occasionally put a zero in cell D7, but the user can't access the conversion rate box to manually type in the zero and can't leave D7 blank when submitting the form.
My current code for the division is:
Private Sub CommandButton2_Click()
Range("D16") = Range("D13") / Range("D7")
End Sub

Can anyone help?
User Form
With Zero

A: You can better solve this in the cell and not by code like:
=if (D7 = 0, 0, D13/D7)

We first check if D7 = zero and if so the cell gets filled wiht zero else with your formula.
if you want to do it in code:
if Range("D7").value = 0 or IsEmpty(Range("D7").value) then
    Range("D16").value = 0
else
    Range("D16").value = Range("D13").value / Range("D7").value
end if


text:
Q: Basic definition of variables for use in resume I'm working on writing my resume in a LaTeX and hoping to implement some commands to automate section styles (though I am by no means planning to write an entire class).  For example, I'd like to include some simple commands for contact information in the preamble that I could then use to build up the header.  It would ideally look something like this (I've included resume_config.tex at the bottom of this post):
% =============================================================================
%                                   Preamble
% =============================================================================
% Checks for correct LaTeX usage (no out of data packages, poor syntax etc.)
\RequirePackage[l2tabu,orthodox]{nag}
% -----------------------------------------------------------------------------
\documentclass[letterpaper,11pt]{article}
\input{resume_config.tex}

% =============================================================================
%                                    Inputs
% =============================================================================
\name{C. Gonzalez}
\email{myemail@gmail.com}
\address{000 E 0th St, Austin, TX 12345}
\phone{(000)111-2222}

% =============================================================================
%                                     Body
% =============================================================================
\begin{document}
\makeheader
% \input{resume_education.tex}
% \input{resume_publications.tex}
\input{resume_experience.tex}
% \input{resume_coursework.tex}
% \input{resume_technical.tex}
% \input{resume_other.tex}
\end{document}

I've been studying the .cls file of a template (awesome-cv) and found that they seem to implement this sort of thing with the following code:
% Define writer's address
% Usage: \address{<address>}
\newcommand*{\address}[1]{\def\@address{#1}}

My question is, what does this code mean exactly?  First, from what I've read, it sounds like \def is the same thing as \newcommand*, no?  Second, is \@varname{#1} syntax for defining a variable, as in \@varname = #1?  I've read elsewhere on tex.stackexchange and can't seem to figure out exactly what \@ is used for.  Third, the compiler doesn't seem to like that I'm using these commands before \begin{document}, but I'm unsure if that is related....
All of that said, for my use, would it be the same to just write the following in my "Inputs" section?
\def\@name{C. Gonzalez}
\def\@email{myemail@gmail.com}
\def\@address{000 E 0th St, Austin, TX 12345}
\def\@phone{(000)111-2222}

resume_config.tex:
% ----------------------------------------------------------- Load packages ---
% geometry - easier to change margine and page setup
\usepackage[letterpaper,margin=1in]{geometry}
\usepackage{amsfonts,amssymb,amsmath,amsthm}
\usepackage[english]{babel}
\usepackage{booktabs}
\usepackage[usenames,dvipsnames]{color}
% multirow - merge table cells vertically (\multirow{nrows}{width}{content})
\usepackage{multirow}
\usepackage{graphicx}
\usepackage{subcaption}
\usepackage{microtype}
\usepackage{siunitx}
\usepackage[colorlinks=true,linkcolor=blue,citecolor=blue,pdfborder={0 0 0}]{hyperref}
\usepackage{enumitem}
\usepackage{titlesec}

% --------------------------------------------------------- Change commands ---
\renewcommand{\arraystretch}{1.1}

% --------------------------------------------------------- Config booktabs ---
\newcolumntype{L}[1]{>{\raggedright\let\newline\\\arraybackslash\hspace{0pt}}m{#1}}
\newcolumntype{C}[1]{>{\centering\let\newline\\\arraybackslash\hspace{0pt}}m{#1}}
\newcolumntype{R}[1]{>{\raggedleft\let\newline\\\arraybackslash\hspace{0pt}}m{#1}}

% --------------------------------------------------------- Config titlesec ---
% Used for sections of resume (education, experience etc.)
\titleformat{\section}  % Customise the \section command
  {\Large\raggedright}  % Make the \section headers large (\Large) and left aligned (\raggedright)
  {}{0em}               % Can be used to give a prefix to all sections, like 'Section ...'
  {}                    % Can be used to insert code before the heading
  [\titlerule]          % Inserts a horizontal line after the heading

% Used for subsections of resume (experience 1, experience 2 etc.)
\titleformat{\subsection}
  {\large\raggedright}
  {}{0em}
  {}

% ------------------------------------------------------------ Add commands ---
% Basic Information
\newcommand{\name}[1]{\def\@name{#1}}
\newcommand{\address}[1]{\def\@address{#1}}
\newcommand{\email}[1]{\def\@email{#1}}
\newcommand{\phone}[1]{\def\@phone{#1}}

\newcommand{\makeheader}[1]{
  \centerline{\Huge{\name}}} \\
  \centerline{\Large{\address \textperiodcentered \email \textperiodcentered \phone}}
}

% Create a subsection with a date (written so that date will not show in table of contents)
\newcommand{\datedsubsection}[2]{%
  \subsection[#1]{#1 \hfill #2}%
}


text:
Q: Able to run Django server on PyCharm but not on command line? I configured my virtual environment with virtualenvwrapper and I can run the server when I hit the run button on PyCharm. But when I type in manage.py runserver on my command line, I get this error message.
raise ImproperlyConfigured("The SECRET_KEY setting must not be empty.")
django.core.exceptions.ImproperlyConfigured: The SECRET_KEY setting must not be empty.
I'm using the PyCharm .env plug-ins to export my variables. And my .env file is sitting on the root of my project folder.

A: You'll need some tooling to read in that .env file outside PyCharm, then.

*

*https://pypi.org/project/envparse/ is a good all-around solution for just getting an .env file into os.environ.

*https://pypi.org/project/django-environ/ a similar one with better support for certain Django features such as configuring database URLs, etc.


text:
Q: Import .target file could not dynamic loading to my project I have a .target file, which imports to my project:
<Project xmlns="http://schemas.microsoft.com/developer/msbuild/2003" DefaultTargets="CreateInstaller">
  <Import Project="$(PathToTargetFile)\My.target" />
<Project>

The .target is build by another target:
  <Target Name="MyCustomTarget" DependsOnTargets="$(OtherTargets)">
    <MSBuild Projects="$(PathToTargetFile)\My.target" />
  </Target>

The target MyCustomTarget is called several time, each time the content of My.target would be changed. But My.target seems that not imported anymore rather than the first time. How to resolve this problem?

A:
How to resolve this problem?

Visual Studio caches all imported .target files. That is the reason why you My.target seems that not imported anymore rather than the first time.
To resolve this issue, you can use a temp .target file with different name, this will force VS to reload .target file:
  <Target Name="AfterBuild">
    <PropertyGroup>
      <TempProjectFile>My.$([System.Guid]::NewGuid()).target</TempProjectFile>
    </PropertyGroup>
    <Copy SourceFiles="My.target" DestinationFiles="$(TempProjectFile)" />
    <MSBuild Projects="$(TempProjectFile)" />
    <Delete Files="@(TempProjectFile)" />
  </Target>

You can refer to the similar issue for detail info.
Hope this help you.


text:
Q: How to get button values inside a foreach using jquery and codeigniter? In my view i have a foreach loop like below
<?php foreach($wishes as $wish) { ?>
    <input id="delete" type="button" value="<?= $wish->id ?>">
<?php } ?>

button value will be diffrent in each buttons
if I use a method like below it only take the first button click and its value other buttons do nothing
what did I do wrong
$(document).ready(function() {

    $("#delete").click(function(event) {
        event.preventDefault();

        var id = $("#delete").val();

        console.log('delete');
        console.log(id);

    });

});

A: Use classes instead of ids. Because an id has to be unique. Since your id values are dynamic you can listen to the button click event by using the button's class.
<?php foreach($wishes as $wish) { ?>
   <input class="delete" type="button" value="<?= $wish->id ?>">
<?php } ?>

$(document).ready(function() {

  $(".delete").click(function(event) {
      event.preventDefault();

      var id = $(this).val();
      console.log(id);

  });

});

A: <?php foreach($wishes as $wish) { ?>
   <input class="delete" type="button" value="<?= $wish->id ?>">
<?php } ?>

Method 1
Use class instead of id for click event
$(document).ready(function() {

  $(".delete").click(function() {

      var IdValue = $(this).val();
      alert(IdValue);

  });

});

Method 2
Function can be call on button click onclick="function_name()" and pass the id as a parameter
<?php foreach($wishes as $wish) { ?>
   <input class="delete" type="button" value="<?= $wish->id ?>" onclick="GetId(<?= $wish->id ?>)" >
<?php } ?>

function GetId(IdValue){
    alert(IdValue)
}

A: add to your code class for events
<?php foreach($wishes as $wish) { ?>
    <input id="<?= $wish->id ?>" class="action" type="button" >
<?php } ?>

$wish->id  --> id must be uniq, and server must provide this
$(document).ready(function() {

    $(".action").click(function(event) {
        event.preventDefault();

        var id = event.target.id;

        console.log('delete');
        console.log(id);

    });

});


text:
Q: How can I activate the Friendly Service in eXo platform? Ive been trying a few days to activate the FriendlyService in exo-platfom 3.5.x but have been unsuccessful so far.
In the section:
administration > management
There is a service called Friendly Service which allows eXo to rewrite a request URL to another URL (in a more readable format). However, this service is inactivated.
Can someone tell me how activate it?

A: 1.When starting server, you need to enable the profile 'friendly':
  Example: ./start_eXo.sh -Dfriendly
2.When registering FriendlyService, you need to provide parameter enable as true:
<component>
  <key>org.exoplatform.services.wcm.friendly.FriendlyService</key>
  <jmx-name>exo-service:type=FriendlyService</jmx-name>
  <type>org.exoplatform.services.wcm.friendly.impl.FriendlyServiceImpl</type>
  <init-params>
    <value-param>
      <name>enabled</name>
      <value>true</value>
    </value-param>
    </init-params>
</component>

Hope it helps..


text:
Q: Setting breakpoints on final methods for subclasses Is there any way to set a breakpoint in Eclipse JDT on a final method in a superclass that is only triggered, when the method gets invoked on a specific subclass?
For example I'd like to have a breakpoint on MyClass#notify() that gets triggered as soon as any thread invokes
MyClass test...
synchronized (test) {
    test.notify();
}

But the breakpoint should only be triggered for instances of MyClass and not for any Object.
Is there perhaps a way to filter breakpoints on Object#notify() e.g. by using a conditional breakpoint? I already tried conditions like this instanceof somepackage.TestNotifyBreakpoint.MyClass and this.getClass().getName().equals("somepackage.TestNotifyBreakpoint.MyClass") but with no luck: the first condition gives me a somepackage cannot be resolved to a type error and the second condition an Attempt to send a message to a non object value error.

Here is a simple example - the breakpoint should trigger when test.notify(); gets executed.
package somepackage;

import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class TestNotifyBreakpoint {
    public static class MyClass {}

    public static void main(String[] args) {
        MyClass test = new MyClass();
        Thread t = new Thread(){
            @Override
            public void run() {
                System.out.println("waiting for notify");
                try {
                    Thread.sleep(5000);
                } catch (InterruptedException e) {
                }
                synchronized (test) {
                    System.out.println("About to notify");
                    test.notify(); // should trigger the brakepoint
                }
                System.out.println("Notify done");
            }
        };
        t.start();
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                JFrame frame = new JFrame("Test");
                frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                frame.setSize(200, 200);
                frame.setVisible(true);
            }
        });
    }
}