text:
Q: Mouse click is not working on winform application developed using VB6.0 in win 10 I need some inputs on a issue I am facing currently. Application randomly not responding to mouse click event and continue to behave until restart and mouse clicks works on other applications.
Brief about the application :
The application is developed in VB 6.0 some time back (i know VB 6.0 is not supported now), its working fine in Win7. The same application running on Win10 have this strange behaviour randomly.
The application is COM ActiveX Exe which as web browser control embedded on the form which is displaying html pages. the html displayed have button and user click on buttons using mouse and it navigates to other pages.
I am sure it not a driver issue.
Issue I am facing :
when a mouse is clicked on the button which is on html it navigates to next page. However, sometime the mouse clicked on the html will not be action i.e. it wont navigate to next point. I don't know what trigger this behaviour. until the application is restarted the behaviour continues.
i used spy++ tool to understand the message send to application and i see the windows messages are different in good case and bad case.
i started to notice a lot of WM_SETCURSOR messages
<00114> 000A0688 R WM_SETCURSOR fHaltProcessing:False [lResult:00000000]
<00115> 000A0688 S WM_SETCURSOR hwnd:000A0688 nHittest:FFFE wMouseMsg:WM_MOUSEMOVE [wParam:000A0688 lParam:0200FFFE]
<00116> 000A0688 R WM_SETCURSOR fHaltProcessing:False [lResult:00000000]
<00117> 000A0688 S WM_SETCURSOR hwnd:000A0688 nHittest:FFFE wMouseMsg:WM_MOUSEMOVE [wParam:000A0688 lParam:0200FFFE]
<00118> 000A0688 R WM_SETCURSOR fHaltProcessing:False [lResult:00000000]
<00119> 000A0688 S WM_SETCURSOR hwnd:000A0688 nHittest:FFFE wMouseMsg:WM_MOUSEMOVE [wParam:000A0688 lParam:0200FFFE]
<00120> 000A0688 R WM_SETCURSOR fHaltProcessing:False [lResult:00000000]
<00121> 000A0688 S WM_SETCURSOR hwnd:000A0688 nHittest:FFFE wMouseMsg:WM_MOUSEMOVE [wParam:000A0688 lParam:0200FFFE]
<00122> 000A0688 R WM_SETCURSOR fHaltProcessing:False [lResult:00000000]
<00123> 000A0688 S WM_SETCURSOR hwnd:000A0688 nHittest:FFFE wMouseMsg:WM_MOUSEMOVE [wParam:000A0688 lParam:0200FFFE]
<00124> 000A0688 R WM_SETCURSOR fHaltProcessing:False [lResult:00000000]
<00125> 000A0688 S WM_SETCURSOR hwnd:000A0688 nHittest:FFFE wMouseMsg:WM_MOUSEMOVE [wParam:000A0688 lParam:0200FFFE]
<00126> 000A0688 R WM_SETCURSOR fHaltProcessing:False [lResult:00000000]
<00127> 000A0688 S WM_SETCURSOR hwnd:000A0688 nHittest:FFFE wMouseMsg:WM_MOUSEMOVE [wParam:000A0688 lParam:0200FFFE]
<00128> 000A0688 R WM_SETCURSOR fHaltProcessing:False [lResult:00000000]
<00129> 000A0688 S WM_SETCURSOR hwnd:000A0688 nHittest:FFFE wMouseMsg:WM_MOUSEMOVE [wParam:000A0688 lParam:0200FFFE]
<00130> 000A0688 R WM_SETCURSOR fHaltProcessing:False [lResult:00000000]
<00131> 000A0688 S WM_SETCURSOR hwnd:000A0688 nHittest:FFFE wMouseMsg:WM_MOUSEMOVE [wParam:000A0688 lParam:0200FFFE]
<00132> 000A0688 R WM_SETCURSOR fHaltProcessing:False [lResult:00000000]
<00133> 000A0688 S WM_SETCURSOR hwnd:000A0688 nHittest:FFFE wMouseMsg:WM_MOUSEMOVE [wParam:000A0688 lParam:0200FFFE]
<00134> 000A0688 R WM_SETCURSOR fHaltProcessing:False [lResult:00000000]
<00135> 000A0688 S WM_SETCURSOR hwnd:000A0688 nHittest:FFFE wMouseMsg:WM_MOUSEMOVE [wParam:000A0688 lParam:0200FFFE]
<00136> 000A0688 R WM_SETCURSOR fHaltProcessing:False [lResult:00000000]
<00137> 000A0688 S WM_SETCURSOR hwnd:000A0688 nHittest:FFFE wMouseMsg:WM_MOUSEMOVE [wParam:000A0688 lParam:0200FFFE]
<00138> 000A0688 R WM_SETCURSOR fHaltProcessing:False [lResult:00000000]
<00139> 000A0688 S WM_SETCURSOR hwnd:000A0688 nHittest:FFFE wMouseMsg:WM_MOUSEMOVE [wParam:000A0688 lParam:0200FFFE]

<00140> 000A0688 R WM_SETCURSOR fHaltProcessing:False [lResult:00000000]
**<00141> 000A0688 S WM_SETCURSOR hwnd:000A0688 nHittest:FFFE wMouseMsg:WM_LBUTTONDOWN [wParam:000A0688 lParam:0201 FFFE]** ```

From the above message i see there is WM_LBUTTONDOWN message.
any pointer/guidance on how we can investigate and understand what is causing the issue?
Thanks in advance.
-- Updated with logs for good case.
00197> 00030808 S WM_WINDOWPOSCHANGING lpwp:0019BB64 [wParam:00000000 lParam:0019BB64]
<00198> 00030808 R WM_WINDOWPOSCHANGING lResult:00000000
<00199> 00030808 S WM_WINDOWPOSCHANGING lpwp:0019F08C [wParam:00000000 lParam:0019F08C]
<00200> 00030808 R WM_WINDOWPOSCHANGING lResult:00000000
<00201> 00030808 S WM_WINDOWPOSCHANGING lpwp:0019EDDC [wParam:00000000 lParam:0019EDDC]
<00202> 00030808 R WM_WINDOWPOSCHANGING lResult:00000000
<00203> 00030808 S WM_WINDOWPOSCHANGING lpwp:0019EC14 [wParam:00000000 lParam:0019EC14]
<00204> 00030808 R WM_WINDOWPOSCHANGING lResult:00000000
<00205> 00030808 S WM_CANCELMODE wParam:00000000 lParam:00000000
<00206> 00030808 R WM_CANCELMODE lResult:00000000
<00207> 00030808 S WM_ENABLE fEnable:False [wParam:00000000 lParam:00000000]
<00208> 00030808 R WM_ENABLE lResult:00000000
<00209> 00030808 S WM_ENABLE fEnable:True [wParam:00000001 lParam:00000000]
<00210> 00030808 R WM_ENABLE lResult:00000000
<00211> 00030808 S WM_NCACTIVATE fActive:False [wParam:00000000 lParam:00000000]
<00212> 00030808 R WM_NCACTIVATE fDeactivateOK:True [lResult:00000001]
<00213> 00030808 S WM_ACTIVATE fActive:WA_INACTIVE fMinimized:False hwndPrevious:(null) [wParam:00000000 lParam:00000000]
<00214> 00030808 R WM_ACTIVATE lResult:00000001
<00215> 00030808 S WM_ACTIVATEAPP fActive:False dwThreadID:000014CC [wParam:00000000 lParam:000014CC]
<00216> 00030808 R WM_ACTIVATEAPP lResult:00000000
<00217> 00030808 S WM_PARENTNOTIFY fwEvent:WM_LBUTTONDOWN xPos:881 yPos:581 [wParam:00000201 lParam:02450371]
<00218> 00030808 R WM_PARENTNOTIFY lResult:00000000
<00219> 00030808 S ...WM_MOUSEACTIVATE hwndTopLevel:00030808 nHittest:HTCLIENT uMsg:WM_LBUTTONDOWN [wParam:00030808 lParam:02010001] ```


text:
Q: Prevent event from parent element to child element in jquery I have bound event as below:
    $(document).delegate('.budget', 'click', function(e){
        if ($(this).hasClass('collapsed')) {
           $(this).removeClass('collapsed');
           $(this).addClass('expanded');
        }
        else if ($(this).hasClass('expanded')) {
           $(this).removeClass('expanded');
           $(this).addClass('collapsed');
        }
    });

Basically this toggles between expand and collapse.
I have another event bound as below:
    $('[id^="tree"]').delegate('.collapsed', 'click', function(e){
        var elementId = $(this).attr('id');
        hideChildElement(elementId);
    });

The elements bound by the second event binding are parents of elements binded by first event binding.
What happens is that on clicking on the element from the first binding event method also triggers the event bound by second event binding.
I want to prevent any events from binding from second event binding to 1st event binding method.
If element A is bound to click event from first event binding and B is bound to second event binding (A is inside B or A is child of B), I dont want any event of B to propagate to A.
Note I tried e.stopImmediatePropagation(); but did not worked

A: I think you want to prevent the event handler bound to [id^="tree"] to be triggered if a .budged element was clicked. In that case you can test where the click event originated from:
$('[id^="tree"]').delegate('.collapsed', 'click', function(e){
    if($(e.target).closest('.budget').length === 0) {
        // not from inside budget element
        var elementId = $(this).attr('id');
        hideChildElement(elementId);
    }
});

Alternatively, if you bind both event handlers to the same element, i.e. both to document or [id^="tree"] or any element in between, event.stopImmediatePropagation() will work just fine.
If this is not what you want, please clarify your question, it is not easy to understand.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to know a push message info if app is launched from background directly rather than from notification msg? I have properly registered for the push notification.
Implemented following method to receive notification.
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject])

Also used UIApplicationLaunchOptionsRemoteNotificationKey from func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool.
I'm able to receive notification when the app is active. I'm also able to see the notification if I open the app from the notification by selecting it from banner or alert.
But if app is not active, it could be alive or killed and if a notification arrives at that point. And I ignore the notification and open the app by directly selecting the app icon from the home screen, I'm not getting the notification information in the UIApplicationLaunchOptionsRemoteNotificationKey from func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject : AnyObject]?) -> Bool.
So what is the right way to handle this scenario? Should the app call server and get the recent messages it sent? Any help is much appreciated.

A: If the user will open you app directly from it's home screen, you would not get access to the push notification dictionary.
If you need the data sent in the push notification, so the proper way will be a server request as you suggested.

A: If user enter the app by click the icon or launch from the background, the push notification message can't deliver to you, the message is cached by system, the only way to get it is from notification center

A: Answering my question:
It is possible for the app in the background to receive push notification.
To do so send content-available in the aps dictionary of push notification.
Enable background mode of the app from the Background modes section of the Capabilities tab in your Xcode project.
Implement application:didReceiveRemoteNotification:fetchCompletionHandler: in the app delegate.
References:
See section 'Notification Payload' in https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/ApplePushService.html
See section 'Using Push Notifications to Initiate a Download' in
https://developer.apple.com/library/prerelease/ios/documentation/iPhone/Conceptual/iPhoneOSProgrammingGuide/BackgroundExecution/BackgroundExecution.html
However if app is killed then the appdelegate's application:didReceiveRemoteNotification:fetchCompletionHandler: is not getting called.
According to Will iOS launch my app into the background if it was force-quit by the user? post on iOS8.0 it is possible to do it using PushKit. But I have not tested it. And also if VOIP is not used then I dont know if it is possible for app to receive push notification information if it is killed.


text:
Q: Python: Handling variables as text to include into directories I came across a problem in my script. Let's say I have an if-loop and a variable that is constantly increased by 1, like this:
i=0
if __name__ == "__main__":
   try:
      while True
         file.open('example>i<.txt', 'a')
         file.write('some text')
         i+=1

...
In the first step, I want the file to be named example0.txt, then example1.txt in the next run and so on.
How do I convert my control variable i into string/text to e.g. include it into a directory ?
Thanks in advance
Steve

A: Python 3.6 introduces format strings.
> i = 0
> f'example{i}.txt'
example0.txt

A: You can use the .format method. So in your case it will be:
i=0
if __name__ == "__main__":
   try:
      while True
         file.open('example{}.txt'.format(i), 'a')
         file.write('some text')
         i+=1

A: You just need to consutruct the string with the control variable value substituted in it.
i=0
if __name__ == "__main__":
   try:
      while True
         file.open("example"+str(i)+".txt", "a")
         file.write('some text')
         i+=1


text:
Q: How to add multiple signers on a single document using docusign REST API Embedded Signing I have a web application developed which we want to sign a sales contract pdf from the end customer. It's a responsive web application which can be used from desktop/laptop, tablet or mobile phones.
I am trying to implement Embedded Signing with multiple signer using docusign REST API.
So the flow in my app is the following:-

*

*Dealer goes to the sold to party and sold to party will sign.

*Dealer goes to the payer and payer will sign.

*And finally dealer will do the final signing and all the signer will receive the signed document via mail.

My app status-

*

*I have successfully created signing url for first signer and signing is completed and returning to my web page.

*But for the second signer i want to sign on the first signer url.But it is redirecting to web page.

My scenario is -
Is this possible without opening three recipients views - one for the sold to party, one for the payer and one for dealer? Can we achieve this just by opening one view where all recipients can sign the order with mobile verification authentication?
In one signing url all the signer will complete the sign process with mobile verification authentication.
I tried to add a single recipient with three signing boxes with mobile verification authentication. But after complete the first signer it is returning to main web page.
Please check this scenario also-
My question is is there any way this is possible? I am assuming that it isn't since each envelope id can really only relate to a single signer. It doesn't even make sense to me how a second signer could sign the same document with the same envelope id and put in different data and it maintain the integrity of both signers since envelope id seems to be a sort of session for the document.
Please help me Thanks.

A: No, you have to open separate signing ceremonies for each signer.  Each captive recipient (for embedded signing) is defined by their email, name, and clientUserId.  ClientUserId needs to be unique to each individual, such as a customerId in your system.  If you don't have a unique identifier for each person, then simply use their email address.
You should also consider how you will validate the identity of the person signing and link it to the DocuSign signing, since DocuSign is not sending an email link for validating who was invited in.  You can link that data using the additional parameters for the createRecipient Envelope View API call, i.e. assertionId, authenticationInstant, authenticationMethod, and securityDomain.


text:
Q: Extracting latitude, longitude and altitude using C++ NMEAParser I am currently working on a project to calculate the true bearing of a particular object.
So far I have been able to

*

*calculate the magnetic declination using a C++ library and code, by manually plugging in the latitude and longitude values.

*extract latitude, longitude and altitude from a GPS module using a python library and script

But, now I need to feed the GPS live data to the declination calculation function in order to calculate the live declination.
And since the declination calculation is based on a C++ library, I need to transform that python script into a C++ code.
Library details:

*

*used pynmea2 library to parse GPS data in the python script

https://pypi.org/project/pynmea2/

*came across C++ NMEAParser library

https://sourceforge.net/projects/cppnmeaparser/files/latest/download
I am not sure on how to use the C++ NMEAParser in order to get the above mentioned metrics.
Any help regarding how to use this library or what alternative options are there in order to achieve the same function would be highly appreciated.


text:
Q: how to save edittext when back pressed to previous activity may be my question wrong.but when i click on item in listview i open other activty to edit the item name text after that when i back press it was saving but not renaming to the listview.so please help me.
listview class:
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.settings_view);

    listView=(ListView)findViewById(R.id.listView);
    listView.invalidateViews();
    BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();

    final List<String> s = new ArrayList<String>();
    for(BluetoothDevice bt : pairedDevices)
       s.add(bt.getName());
    listView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, s));
    //listView.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
    //listView = getListView();
    listView.setOnItemClickListener(new OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> paramAdapterView, View paramView, int paramInt,
                long paramLong) {
       // TextView select_text=(TextView)viewClicked.findViewById(R.id.select_text);

            String name=s.get(paramInt);
            Intent i = new Intent(SettingOptionActivity.this, EditPreview.class);
            i.putExtra("name", name);
            startActivityForResult(i,0);

            //Log.v("____string name________", "__________"+name);
            //loadSavedPreferences(s.get(paramInt));
    }

    });

}

and the following class is to edit the name of item
   protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.edit_layout);
    edittext=(EditText)findViewById(R.id.device_text);

  //  edittext.setText(val);
    loadSavedPreferences();

}
private void loadSavedPreferences() {
    /*SharedPreferences sharedPreferences = PreferenceManager
            .getDefaultSharedPreferences(this);
*/   Intent i = getIntent();
       String val = "";

       if(i.hasExtra("name"))
             val = i.getStringExtra("name");

    edittext.setText(val);
    Log.v("___________edittext", "_______________"+edittext.getText());
    }
    private void savePreferences(String key, String value) {
    //SharedPreferences sharedPreferences = PreferenceManager
      //      .getDefaultSharedPreferences(this);
    SharedPreferences   sharedPreferences=this.getSharedPreferences(
                  "com.example.app", Context.MODE_PRIVATE);
    Editor editor = sharedPreferences.edit();
    editor.putString(key, value);
     Log.v("__________key", "_______________"+key);
     Log.v("___________value", "_______________"+value);
    //edittext.setText(editor.toString());
     Intent intent=new Intent();
        intent.putExtra("name", edittext.getText().toString());
        setResult(RESULT_OK, intent);
        finish();
    editor.commit();
    }
    public void saveData(){
    savePreferences("name", edittext.getText().toString());
     Log.v("___________edittext", "_______________"+edittext.getText().toString());
    }
    @Override
    public void onBackPressed(){
        saveData();

    super.onBackPressed();
    }

so please check and help me.

A: You may try another way, instead of SharedPreference.
// First Save the Text
@Override
public void onSaveInstanceState( Bundle outState )
{
      super.onSaveInstanceState( outState );
      outState.putInt( "textValue", editText.getText().toString() );
}

// Load the Text
@Override
public void onCreate ( Bundle savedInstanceState )
{
      ....

      if ( savedInstanceState != null )
      {
           editText.setText ( savedInstanceState.getString ( "textValue" ) );
      }

      ....
}

A: I'm not quite sure but you could make your
final List<String> s = new ArrayList<String>();

=> public static List<String> s; (Before the constructor)

and your ListView Activity's onCreate()
s = new ArrayList<String>();

In your EditName Activity you modify the ListView.s. -listitems name attribute and then on your ListView's onResume method you call:
Edit 2:
Before onCreate:
private ArrayAdapter<String> aa;

In onCreate:
this.aa = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, s));
listView.setAdapter(this.aa);

In onResume:
this.aa.notifyDataSetChanged();

A: try this in listview class:
listView.setOnItemClickListener(new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> paramAdapterView, View paramView, int   paramInt,
            long paramLong) {
   // TextView select_text=(TextView)viewClicked.findViewById(R.id.select_text);

        String name=s.get(paramInt);
        Intent i = new Intent(SettingOptionActivity.this, EditPreview.class);
        i.putExtra("name", name);
        i.putExtra("position", paramInt);
        startActivityForResult(i,0);

        //Log.v("____string name________", "__________"+name);
        //loadSavedPreferences(s.get(paramInt));
}

});

and implement callback method :
onActivityResult(int requestCode, int resultCode, Intent data) {
     if(requestCode == 0 && resultCode == RESULT_OK) {
        int position = data.getIntExtra("position", 0);
        String newName = data.getIntExtra("name");
        s.get(0).replace(oldname, newName );
        yourAdapterObject.notifyDatasetChanged();
     }

}
And in your name edit class pass position as you have got from intent.


text:
Q: How to send a parameter over http request using an anchor tag I want to send a parameter value over http using  tag but I do not want it to be set in the href attribute.
Is there a way to do just that so that I could receive that value on the server side?
Thanks.

A: Either use JS to submit a (hidden) form.
<form id="foo" method="post" action="servletURL">
    <input type="hidden" name="yourParamName" value="yourParamValue" />
</form>
link

Or use CSS to style the default submit button to look like a link.
<form id="foo" method="post" action="servletURL">
    <input type="hidden" name="yourParamName" value="yourParamValue" />
    <input type="submit" value="link" class="link" />
</form>

with
input[type=submit].link {
    margin: 0;
    border: 0;
    background: transparent;
    color: blue;
    text-decoration: underline;
    cursor: pointer;
    overflow: visible;
}


text:
Q: C++ как вернуть массив типа char из функции Не могу разобраться с возвратом массива из функции. Код:
loadData.cpp
#include "SaveText.h"

#include <fstream>
#include <iostream>

char* SaveText::loadData(char point[]) {
  std::ifstream load;

  load.open(point ios::out | ios::app);

  if(!load) {
    std::cout<<"ERROR!"<<std::endl;
  }

  char* out_file = new char[200];
  while(1) {
    load.getline(out_file, sizeof(out_file));
    if(load.eof()) break;
  }

  return out_file;//не могу вернуть массив
}

main.cpp
#include "SaveText.h"

int main() {
  char *text_in_file[200];

  SaveText data;
  text_in_file = data.loadData("C://Users//...");
  data.saveData(text_in_file, "C://Users//...");

  return 0;
}

По замыслу эта функция будет открывать файл и считывать от туда данные, после эти данные функция вернёт, а потом я буду решать что с ними делать.
Но при компиляции мне выдаёт ошибку:
main.cpp:8:16: error: incompatible types in assignment of 'char*' to 'char* [200]'
   text_in_file = data.loadData("C://Users//SilentiumNoxe//Documents//Projects//noteCoin//data//savedata.txt");
                ^
main.cpp:9:107: error: no matching function for call to 'SaveText::saveData(char* [200], const char [75])'
   data.saveData(text_in_file, "C://Users//SilentiumNoxe//Documents//Projects//noteCoin//data//outfile.txt");
                                                                                ^

Как правильно вернуть в данной ситуации массив и что значит "Нет подходящей функции для вызова"?
P.S. string, vector и пр. не предлагать. Спасибо.

A: Вот это -
char *text_in_file[200];

массив из 200 указателей на char, причем сама переменная text_in_file не может получить никакое иное значение, кроме определенного выше.
Вы же пытаетесь присвоить ей другой указатель, но не просто другой, а указатель на массив char.
В лучшем случае можно сделать
text_in_file[0] = data.loadData(...);

но это явно не то, что вы хотите...
Можно объявить так:
char *text_in_file;

и тогда ваше присваивание будет логично и понятно :)
Только не забудьте потом вызвать
delete[] text_in_file;


text:
Q: Get Pyrebase HTTPError information Using the pyrebase wrapper for Firebase Authentication, when attempting to create a new user that is already a user pyrebase wraps the google API response in an HTTPError message. But when I try to capture this exception it doesn't recognize HTTPError as an exception. I can access the exception by using expect Exception as e show in greater detail below.
Code:
config = {
  "apiKey": os.environ.get('WEB_API_KEY'),
  "authDomain": "project.firebaseapp.com",
  "databaseURL": "https://project.firebaseio.com",
  "storageBucket": "project.appspot.com",
  "serviceAccount": os.environ.get('FIREBASE_APPLICATION_CREDENTIALS')
}

firebase = pyrebase.initialize_app(config)

auth = firebase.auth()

# Attempt to register a user that already exists
try:
    user = auth.create_user_with_email_and_password('myemail@email.com', 'mypassword')
except HTTPError as e:
    print('Handling HTTPError:', e)

This will output:
Traceback (most recent call last):
  File "<console>", line 3, in <module>
NameError: name 'HTTPError' is not defined

I can catch the error if i take a more general approach and use:
try:
    user = auth.create_user_with_email_and_password('myemail@email.com', 'mypassword')
except Exception as e:
    print(e.args)

This will then gracefully print the exception:
(HTTPError('400 Client Error: Bad Request for url: https://www.googleapis.com/identitytoolkit/v3/relyingparty/signupNewUser?key=<WEB_API_KEY>'), '{\n  "error": {\n    "code": 400,\n    "message": "EMAIL_EXISTS",\n    "errors": [\n      {\n        "message": "EMAIL_EXISTS",\n        "domain": "global",\n        "reason": "invalid"\n      }\n    ]\n  }\n}\n')

This gives me the info, but it is a string.
How do I access the response JSON that is shown in the Exception message?
Thanks!

A: json.loads(e.args[1])['error']['message']

this will give you as a result : EMAIL_EXISTS

A: For your case, try it, with firebase-admin==6.0.0:
import firebase_admin

try:
    user = auth.create_user_with_email_and_password('myemail@email.com', 'mypassword')
except firebase_admin._auth_utils.EmailAlreadyExistsError as e:
    print('Handling HTTPError:', e)


text:
Q: In Dynamics NAV, how do I link the Production BOM Where-Used page to display the associated Prod BOM Header Notes? If it makes a difference, we are using Dynamics NAV 2013R2.
In the Prod BOM Where-Used page, I would like to display the associated Production BOM Header record Notes as displayed in the Prod BOM page. However, I am having difficulty linking things up correctly. By calling the following code from the OnAfterGetRecord event, I can see the data that I want, but I can't get it to link properly to display in the Notes. When I make the notes visible they display as blank.
Procedure ReadNotes(ItemNo : Code[20])
CLEAR(Item);
Item.RESET;
IF Item.GET(ItemNo) THEN
BEGIN
  IF Item."Replenishment System" = Item."Replenishment System"::"Prod. Order" THEN
  BEGIN
    IF Item."Production BOM No." <> '' THEN
    BEGIN
      CLEAR(ProdBOMHeader);
      ProdBOMHeader.RESET;
      IF ProdBOMHeader.Get(Item."Production BOM No.") THEN
      BEGIN
        RecRef.GETTABLE(ProdBOMHeader);
        RecordLink.SETRANGE("Record ID", RecRef.RECORDID);
        IF RecordLink.FINDLAST THEN
        BEGIN
          REPEAT
            RecordLink.CALCFIELDS(Note);
            IF RecordLink.Note.HASVALUE THEN
            BEGIN
              Count += 1;
              CLEAR(NoteText);
              RecordLink.Note.CREATEINSTREAM(Stream);
              NoteText.READ(Stream);
              NoteText.GETSUBTEXT(NoteText, 2);
              IF STRPOS(FORMAT(NoteText), 'ECN') > 0 THEN
              BEGIN
                Finished := TRUE;
                MESSAGE('%3 PSSI Test ItemNo: ''%1'', ProdBOMNo: ''%2''\%4 %5', ItemNo, Item."Production BOM No.", Count, RecordLink.Created, FORMAT(NoteText));
              END;
            END;
          UNTIL (RecordLink.NEXT(-1) = 0) OR (Finished);
        END;
      END;
    END;
  END;
END;


text:
Q: Add circle around a div I have this div that looks like a big square but I would like to add a little circle on the top of the div (keeping the style) with an icon inside (I mean something like Font Awesome) so people will know what category of content it is.
How can I do that using css ?
Thank you

.le_quiz {
  position: relative;
  width: 350px;
  background-color: white;
  height: 400px;
  margin-top: 45px;
  border-bottom: 1px solid lightgrey;
  box-shadow: 0px 2px #40c8d6;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.01), 0 2px 5px 0 rgba(0, 0, 0, 0.19);
}

.le_quiz .post-title {
  position: absolute;
  top: 60%;
  left: 2%;
  font-size: 22px;
  color: #404040;
}

.le_quiz .postbody {
  margin-top: 40px;
  font-size: 22px;
}

.le_quiz .postbody a:visited {
  margin-top: 40px;
  font-size: 22px;
  color:#404040;
}
.le_quiz .cta {
  position: absolute;
  top: 90%;
  left: 15px;
  font-weight: bold;
  font-size: 14px;
  color:#38C8D6;
}
.le_quiz .cta:visited {
  color:#38C8D6;
}

This is what I'd like : Circle

A: You could use 2 pseudo elements. One to put the circle up top, and the other to cover the bottom half of the circle.

.le_quiz {
  position: relative;
  width: 350px;
  background-color: white;
  height: 400px;
  margin-top: 60px;
  border-bottom: 1px solid lightgrey;
  box-shadow: 0px 2px #40c8d6;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.01), 0 2px 5px 0 rgba(0, 0, 0, 0.19);
}

.le_quiz .post-title {
  position: absolute;
  top: 60%;
  left: 2%;
  font-size: 22px;
  color: #404040;
}

.le_quiz .postbody {
  margin-top: 40px;
  font-size: 22px;
}

.le_quiz .postbody a:visited {
  margin-top: 40px;
  font-size: 22px;
  color:#404040;
}
.le_quiz .cta {
  position: absolute;
  top: 90%;
  left: 15px;
  font-weight: bold;
  font-size: 14px;
  color:#38C8D6;
}
.le_quiz .cta:visited {
  color:#38C8D6;
}

.le_quiz:before, .le_quiz:after {
  content: '';
  position: absolute;
  background: #fff;
  top: 0;
}

.le_quiz:before {
    left: 0;
    right: 0;
    height: 60px;
    z-index: 2;
}

.le_quiz:after {
    left: 50%;
    transform: translate(-50%,-50%);
    box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.01), 0 2px 5px 0 rgba(0, 0, 0, 0.19);
    z-index: 1;
    width: 100px;
    height: 100px;
    border-radius: 50%;
}

A: You can add another div and set boder-radius to 50% to make it a circle.

.le_quiz, .circle {
  position: relative;
  width: 350px;
  background-color: white;
  height: 400px;
  margin-top: 45px;
  border-bottom: 1px solid lightgrey;
  box-shadow: 0px 2px #40c8d6;
  box-shadow: 0 4px 8px 0 rgba(0, 0, 0, 0.01), 0 2px 5px 0 rgba(0, 0, 0, 0.19);
}

.le_quiz .post-title {
  position: absolute;
  top: 60%;
  left: 2%;
  font-size: 22px;
  color: #404040;
}

.le_quiz .postbody {
  margin-top: 40px;
  font-size: 22px;
}

.le_quiz .postbody a:visited {
  margin-top: 40px;
  font-size: 22px;
  color:#404040;
}
.le_quiz .cta {
  position: absolute;
  top: 90%;
  left: 15px;
  font-weight: bold;
  font-size: 14px;
  color:#38C8D6;
}
.le_quiz .cta:visited {
  color:#38C8D6;
}
.circle {
  width:100px;
  height:100px;
  border-radius:50%;
  top: 100px;
  left: 120px;
}


text:
Q: Spring mvc portlet @sessionAtribute Hello would need a little help.
I'm working with Spring and portlets, my problem is that I have 2 tabs handled by two different controller with 2 beans. What I need is to display data from the bean of the first controller in the render phase of the second controller.
I try to do as follows:
This is the controller for the first tab where I collect the necessary values and generated a request with them.
@Controller
@RequestMapping(ServletContextKeys.SC_VIEW_MODE)
//This is my bean session
@SessionAttributes(salarioBean)
public class AltaSalarioFSOPortletController extends BaseController {

private SalarioBean salarioBean;

//With this method generated the request to display the data in the other controller jsp
@RequestMapping(params = ACTION_CAMBIA_TAB)
public final String doRenderTab(@ModelAttribute(value = "SalarioBean") SalarioBean salario, Errors errors, RenderRequest renderrequest, PortletSession portletSession) {

    //retrieve the bean managed by Spring in session
    SalarioBean salarioSessionBean = (SalarioBean) portletSession.getAttribute(salarioBean);

    ImputacionBean imputacionBean = new ImputacionBean();
    ....Insert data on imputacionBean

    //generated the request to display data in jsp handled by another controller
    renderrequest.setAttribute(imputacionBean,imputacionBean);

    //redirected to jsp
    return jsp_tab2;
}

With this controller with it to display data in jsp, but my problem comes when trying to generate the same data when click-on the other tab. So I try to do with this method render in another controller:
@Controller
@RequestMapping(ServletContextKeys.SC_VIEW_MODE)
@SessionAttributes(imputacionBean)
public class AsociarCostesSalarioAlumnoPortletController extends BaseController {

private ImputacionBean imputacionBean;

@RequestMapping(params = ACTION_ASOC_COSTES_SALARIO)
public final String doRender(@ModelAttribute(value = "ImputacionBean") ImputacionBean imputacionSalarioAlumno,Errors errors, RenderRequest renderrequest,SessionStatus status) {

    justifSessionBean = (SalarioBean) renderrequest.getPortletSession().getAttribute(salarioBean);

    ImputacionBean imp=(ImputacionBean) justifSessionBean.getImputaciones().get(0);

renderrequest.getPortletSession().setAttribute(imputacionBean,imp);

    setJustificanteAsociarCostesSalarioAlumno(imp);

    setRequestParameters(renderrequest, imp);

    return jsp_tab2;
}

@Override
public final void setRequestParameters(RenderRequest renderrequest, Object object) {

    ImputacionBean imputacionSalarioAlumno = (ImputacionBean) object;

    renderrequest.setAttribute(imputacionBean, imputacionSalarioAlumno);

      renderrequest.getPortletSession().setAttribute(imputacionBean,imputacionSalarioAlumno);
}

public final void setJustificanteAsociarCostesSalarioAlumno(ImputacionBean imputacionSalario) {
    this.imputacionBean = imputacionSalario;
}

The first time the bean that handles spring is object empty. My question is: how I can set the session bean that handles Spring from the first controller? so when generating the request this bean contains data.
I need change the bean that handles Spring to generate the new request whit this data.
Thanks for the help. If there is something you do not understand I will try to explain it better.

A: I did not quite understand what you are looking for, from your statement - The first time the bean that handles spring is object empty. - I guess you would be hitting a null pointer or exception says that the session attribute is null.
Usually, when you declare anything as session attribute e.g. @SessionAttributes("salarioBean"), then on submission or the very first time when the portlet is rendered, the framework assumes that the session attribute is already created and available in session.
In order to get rid of the issue - The first time the bean that handles spring is object empty. - all you would need to make sure is to have the attribute already available. For this you can add a method which creates a model attribute using the annotation @ModelAttribute e.g. in your case it would be
@ModelAttribute("salarioBean")
public SalarioBean getSalarioBean(){
    return new SalarioBean();
}

What happens is that when a method is annotated with @ModelAttribute, it is always called before render/action method is invoked everytime and sets the attribute in the Model object so that it is available. However, when the same attribute (e.g. "salarioBean") is also set in the @SessionAttribute, it would be set in the session as soon as it is created and the further calls to the getSalarioBean() will not be triggered before render/action method is invoked and is always available in the session.
Hope it helps.


text:
Q: difference between options and originalOptions in jquery What is the difference between options and originalOptions in ajaxPrefilter ? I read the docs but I am still confused about the difference.

A: options are the request options, while originalOptions are the original options you passed in to $.ajax.
$.ajaxPrefilter(function( options, originalOptions, jqXHR ) {

    // here options will have all the request information
    {url : 'test.html',
     type: "GET",
     isLocal: false,
     global: true,
     processData: true,
     hasContent: false,
     jsonp: "callback",
     jsonpCallback: function () { ... },
     responseFields: ......
      …  and a lot more

    // while originalOptions will be exactly the same as the object passed
    // to $.ajax below
    {url : 'test.html', dataType: 'html'}
});

$.ajax({
    url : 'test.html',
    dataType: 'html'
});


text:
Q: Python3 dbus import error: undefined symbol: _Py_ZeroStruct I am trying to use python-mbus for python 3, i have installed it with
sudo apt-get install python3-dbus

However the import fails with:
asdf@asdf:~$ python3
Python 3.6.3 (default, Oct  3 2017, 21:16:13)
[GCC 7.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import dbus
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python3.6/dist-packages/dbus/__init__.py", line 77, in <module>
    import dbus.types as types
  File "/usr/local/lib/python3.6/dist-packages/dbus/types.py", line 6, in <module>
    from _dbus_bindings import (
ImportError: /usr/local/lib/python3.6/dist-packages/_dbus_bindings.so: undefined symbol: _Py_ZeroStruct

I have also installed it with:
pip3 uninstall dbus-python

But i still get the same error:
asdf@asdf:~$ python3
Python 3.6.3 (default, Oct  3 2017, 21:16:13)
[GCC 7.2.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import dbus
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/asdf/.local/lib/python3.6/site-packages/dbus/__init__.py", line 77, in <module>
    import dbus.types as types
  File "/home/asdf/.local/lib/python3.6/site-packages/dbus/types.py", line 6, in <module>
    from _dbus_bindings import (
ImportError: /home/asdf/.local/lib/python3.6/site-packages/_dbus_bindings.so: undefined symbol: _Py_ZeroStruct

This is in sys.path:
>>> print (sys.path)
['', '/usr/lib/python36.zip', '/usr/lib/python3.6', '/usr/lib/python3.6/lib-dynload', '/home/asdf/.local/lib/python3.6/site-packages', '/usr/local/lib/python3.6/dist-packages', '/usr/lib/python3/dist-packages', '/usr/lib/python3.6/dist-packages']

Im runnin on Debian GNU/Linux buster/sid
Any idea of what am I doing wrong?

A: I'm not exactly sure how I fixed this (can't comment), but I had the exact same problem and I did:
sudo pip3 uninstall dbus-python
sudo aptitude update && sudo aptitude upgrade
sudo aptitude -f

After which aptitude alerted me of some dependency issues with Python, and I "downgraded" a version of Python I had installed on Ubuntu Xenial to the default package provided by Artful. Now, import dbus on Python 3.6.3 doesn't pass any errors. Don't know if it actually works well, though.
Maybe you'll be able to fix it in a similar fashion, since Debian and Ubuntu packages are usually the same.


text:
Q: Custom configuration section with keys and an attribute I need to make a config section like appsettings but with an attribute on the surrounding element, eg:
<userSettings>
    <machine name="my-machine">
        <setting key="Site" value="http://localhost" />
        <setting key="Online" value="true" />
    </machine>
    <!-- more machines -->
</userSettings>

I have the collection of machines and collections of settings working ok as per examples, but I can't get the name attribute on machine to work in conjunction with settings collection.
Here is my Machine class
public class Machine : ConfigurationElementCollection
{
    [ConfigurationProperty("name", IsRequired = true)]
    public string Name
    {
        get
        {
            // This line doesn't compile, cannot convert SettingElement to string
            return (string)this["name"];
        }
    }

    protected override ConfigurationElement CreateNewElement()
    {
        return new SettingElement();
    }

    protected override object GetElementKey(ConfigurationElement element)
    {
        return ((SettingElement)element).Key;
    }

    // this method is the problem but I want to be able to do
    // something like
    // section.Machines[Environment.MachineName][settingKey].Value
    public new SettingElement this[string index]
    {
        get { return (SettingElement)BaseGet(index); }
        set
        {
            if (BaseGet(index) != null)
            {
                BaseRemoveAt(BaseIndexOf(BaseGet(index)));
            }
            BaseAdd(value);
        }
    }
}

And Setting
public class SettingElement : ConfigurationElement
{
    [ConfigurationProperty("key", IsRequired = true, IsKey = true)]
    public string Key
    {
        get { return this["key"].ToString(); }
    }

    [ConfigurationProperty("value", IsRequired = true)]
    public string Value
    {
        get { return this["value"].ToString(); }
    }
}


text:
Q: Problem with Maven plugin :maven-enforcer-plugin:3.0.0-M3:enforce Some Enforcer rules have failed A little bit of context:
Im working as a FE developer for an AEM project. The project is a SPA AEM as cloud service. I am running the author instance from the command line.
My pc specs are:

*

*CPU: Intel(R) Core(TM) i5-7400 CPU @ 3.00GHz   3.00 GHz

*RAM: 24.0 GB

*SSD: 476 GB

*OS: Windows 10 Pro

For the AEM Project we are using

*

*Java sdk 11

*Maven 3.6.3

I have already set up everything, the path variables, JAVA_HOME, mvn. All of them work fine, even trying to build other type of projects with "older" versions of AEM like 6.5 build perfectly. I don't have a problem with them. But with this version of AEM I am getting this error
[WARNING] Rule 9: org.apache.maven.plugins.enforcer.RequireFileChecksum failed with message:
There have been changes detected in a file which is supposed to be immutable according to https://docs.adobe.com/content/help/en/experience-manager-cloud-service/implementing/content-delivery/disp-overview.html#file-structure: src/conf.dispatcher.d/renders/default_renders.any
[WARNING] Rule 10: org.apache.maven.plugins.enforcer.RequireFileChecksum failed with message:
There have been changes detected in a file which is supposed to be immutable according to https://docs.adobe.com/content/help/en/experience-manager-cloud-service/implementing/content-delivery/disp-overview.html#file-structure: src/conf.dispatcher.d/virtualhosts/default_virtualhosts.any
[INFO] ------------------------------------------------------------------------
[INFO] Reactor Summary for xxxxxx 1.0.0-SNAPSHOT:
[INFO]
[INFO] xxxxxx ................................. SUCCESS [  0.270 s]
[INFO] xxxxxx - Core .......................... SUCCESS [ 59.232 s]
[INFO] xxxxxx - UI Frontend ................... SUCCESS [ 19.876 s]
[INFO] xxxxxx - UI Frontend React ............. SUCCESS [ 39.613 s]
[INFO] xxxxxx - Repository Structure Package .. SUCCESS [  0.991 s]
[INFO] xxxxxx - UI apps ....................... SUCCESS [ 12.990 s]
[INFO] xxxxxx - UI content .................... SUCCESS [  4.178 s]
[INFO] xxxxxx - UI config ..................... SUCCESS [  0.314 s]
[INFO] xxxxxx - All ........................... SUCCESS [  1.052 s]
[INFO] xxxxxx - Integration Tests ............. SUCCESS [ 12.166 s]
[INFO] xxxxxx - Dispatcher .................... FAILURE [  0.030 s]
[INFO] xxxxxx - UI Tests ...................... SKIPPED
[INFO] xxxxxx - Project Analyser .............. SKIPPED
[INFO] ------------------------------------------------------------------------
[INFO] BUILD FAILURE
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  02:34 min
[INFO] Finished at: 2021-08-22T15:11:20-05:00
[INFO] ------------------------------------------------------------------------
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-enforcer-plugin:3.0.0-M3:enforce (enforce-checksum-of-immutable-files) on project xxxxxxx.dispatcher.cloud: Some Enforcer rules have failed. Look above for specific messages explaining why the rule failed. -> [Help 1]
[ERROR]
[ERROR] To see the full stack trace of the errors, re-run Maven with the -e switch.
[ERROR] Re-run Maven using the -X switch to enable full debug logging.
[ERROR]
[ERROR] For more information about the errors and possible solutions, please read the following articles:
[ERROR] [Help 1] http://cwiki.apache.org/confluence/display/MAVEN/MojoExecutionException
[ERROR]
[ERROR] After correcting the problems, you can resume the build with the command
[ERROR]   mvn <args> -rf :xxxxxx.dispatcher.cloud

I've been searching in sites, some of the answers for this problem haven't work for me.

*

*I tried to run everything from the "gitbash"
command line and I had the same problem.

*I tried to change the version in the pom.xml, didnt work.

*I tried to build the project using eclipse IDE and all the build-in tools, I get an error that org.apache.maven.plugins:maven-enforcer-plugin:3.0.0-M3:enforce is missing

*Disable firewall and antivirus, nope

*Use other versions of maven like 3.8.2

*Delete the .m2 directory and download again all the plugins, not working

One of many answers tell me to comment out the dispatcher module in the pom.xml and after I did that builds fine. Other is doing the same and upload the ui.apps/target/*.zip with the crx package manager I did it but im not sure if the result is the "best".
To end, I installed the same project in a Mac Pro and i did without a problem. I hope someone can help me with this. Thanks for reading.

A: [WARNING] Rule 9: org.apache.maven.plugins.enforcer.RequireFileChecksum failed with message:
There have been changes detected in a file which is supposed to be immutable according to https://docs.adobe.com/content/help/en/experience-manager-cloud-service/implementing/content-delivery/disp-overview.html#file-structure: src/conf.dispatcher.d/renders/default_renders.any

The Maven Enforcer Plugin is checking for some files to have an specific checksum using requireFileChecksum rule
Somewhere in your pom.xml the Enforcer Maven plugin should be declared, so  you will be able to see the rule and the hash it is applying. This xml snippet is from the maven plugin documentation.
<requireTextFileChecksum>
  <file>E:\java-workspace\apache-maven-enforcer\maven-enforcer\target\checkout\enforcer-rules\target\classes/foo.txt</file>
  <checksum>d41d8cd98f00b204e9800998ecf8427e</checksum>
  <type>md5</type>
</requireTextFileChecksum>

Check that hash against the hash of the file of your filesystem. Maybe when you change aem version, you need to upgrade some of those files.

A: As discussed here: https://github.com/adobe/aem-guides-wknd/pull/202
Adobe have reported the issue and the fix to Adobe AEM WKND project:
Some Windows users experience a Maven enforcer issue where it appears that default dispatcher files have been modified. Unclear if this is a result of differences between Mac and Windows or something that occurs during the checkout process. Most users simply want to install the code base to a local environment and this check is unnecessary. Removing the enforcement for windows builds.
so you can :
Skips Dispatcher enforcement plugin for users on windows environments.
doing a change you dispatcher/pom.xml
with the commit reported here:
https://github.com/adobe/aem-guides-wknd/pull/202/commits/bebcf5d2236c75a95055d5ff71ea58f66379f271
replacing the line:
<goal>enforce</goal>

with:
<goal>display-info</goal>


text:
Q: When I enter the word "ma'am", the program doesn't count it as a palindrome I have here a program that outputs the number of palindromes in a sentence. Case insensitive and ignores comma and periods when for instance the palindrome happens to be the last word in a sentence.
#include <iostream>
#include <string>

using namespace std;

char toUpper(char c) {
    if (c >= 'a' && c <= 'z')
        return c - 'a' + 'A';
    else
        return c;
}

char isLetter(char c) {
    return (toUpper(c) >= 'A' && toUpper(c) <= 'Z');
}

int findNextLetter(string& s, int start) {
    // find first letter at or after 'start'
    for (int i = start; i < s.length(); ++i) {
        if (isLetter(s[i])) return i;
    }
    return s.length();
}

int findNextPunct(string& s, int start) {
    // find first non-letter character at or after 'start'
    for (int i = start; i < s.length(); ++i) {
        if (!isLetter(s[i])) return i;
    }
    return s.length();
}

bool isPalindrome (const string& s, int start, int stop) {
    // look for palindrome in the range (start) to (stop - 1)
    for (int i = 0; i < (stop-start)/2; ++i) {
        if (toUpper(s[start + i]) != toUpper(s[stop - 1 - i])) {
            return false;
        }
    }
    return true;
}

int main() {
    string line;
    int counter=0;
    cout << "Please input a sentence." << endl;
    getline(cin, line);
    int wordStart = findNextLetter(line, 0);
    int wordEnd = findNextPunct(line, wordStart);
    while (wordStart != line.length()) {
        if (isPalindrome(line, wordStart, wordEnd))
            ++counter;
        wordStart = findNextLetter(line, wordEnd); // find start of next word
        wordEnd = findNextPunct(line, wordStart); // find end of next word
    }
    cout << "Number of Palindromes: " << counter << endl;
}

The program runs properly except when there is a word "ma'am". For example, when "Hello, ma'am! I'm Aya." is entered, the program just outputs 1, which means one palindrome: Aya. "ma'am" was not included because of the apostrophe.
I will be so happy if you show me a concrete code so it will be easy for me to figure out what to change. But still, I thank you for any kinds of help. :)

A:
wordStart = findNextLetter(line, wordEnd); // find start of next word
wordEnd = findNextPunct(line, wordStart); // find end of next word

define a word as a run of letter characters.

if (isPalindrome(line, wordStart, wordEnd))

is checking whether a word is a palindrome.  "ma'am" is not a word because it does not consist solely of letter characters.  "ma'am" is two words "ma" and "am" separated by a punctuation character, "'".

A: Your code already ignores commas and periods; extend it to include apostrophes, colons, semi-colons, and all other forms of punctuation.


text:
Q: Handle Socket Timeout Exception with Jsoup what I´m doing is this:
Document page = Jsoup.connect(url).timeout(0).get();
Elements elements= pageSubforum.select(elements);

Sometimes this is working, but often I get a
java.net.SocketTimeoutException

How can I handle this?

A: I could actually solve it. The problem was not the connection, it was the parsing method.
int timeout = 0;
Jsoup.parse(url, timeout);

The timeout has to be set to zero, so Jsoup interprets it as an infinite timeout.
Hope I can help someone with this in the future.


text:
Q: Where is the Excel Object Library file I'm looking for the Excel Object Library file to import it into LabVIEW.  I have MS Office 2013 installed and can find MSACC.olb, MSOUTL.olb, MSPPT.olb, and MSWORD.olb but can't figure out which file (.olb or .dll) to import in order to manipulate Excel files in LabVIEW.

A: The Excel team does it differently. The Excel object library is the executable:
Office 2013:
C:\Program Files (x86)\Microsoft Office\Office15\EXCEL.EXE

Office 2016:
C:\Program Files (x86)\Microsoft Office\root\Office16\EXCEL.EXE


text:
Q: How can I upgrade my Diablo 3 account? So I am a World of Warcraft player and received a free copy of the game because of that promotion they were running. I have however purchased the collectors edition of the game. Do I have to start a new account to play this one or can I upgrade my existing game to the collector's edition and not have to start over again?

A: You should be able to just register your CE serial key with your account, even if you already have Diablo 3 registered to it. Upon logging into the game in Diablo 3, the game should ask you which of your games within your account you want to play on. That is basically an "upgrade". You just have to select your CE registration when you log in.


text:
Q: Repeatable Read isolation level SELECT vs UPDATE...WHERE maybe you can shed light on something for me here:
DB = MySQL 5.7
Storage engine: InnoDB
Isolation level: Repeatable Read
Following table:
---------------
|   MyTable   |
---------------
| PK | Concur |
---------------
| 3  |   2    |
---------------

I have no transaction going at this point in time and I select this record like
SELECT * FROM MyTable WHERE PK = 3
and store the result in my program.
I start now a DB transaction.
An outside process increments Concur for the record with PK = 3 from 2 to 3 after my transaction has started.
I have not yet read again from that table inside my transaction.
I issue the following query from inside my transaction:
UPDATE MyTable SET Concur = 3 WHERE PK = 3 AND Concur = 2
This will succeed with 0 records affected. So clearly, it evaluates against the data that has been altered AFTER my transaction has started.
Still in the transaction I subsequently query:
SELECT * FROM MyTable WHERE PK = 3
which will return me the record with PK = 3 and Concur = 2 which are the values from before the transaction.
Why do SELECT and UPDATE ... WHERE behave differently, what am I missing?
I would have expected that the UPDATE ... WHERE statement either fails directly instead of succeeding with 0 records affected, or alternatively it succeeds there with 1 record affected and then blows at the COMMIT afterwards, but not this mix and match.
Any insight here?

A: https://dev.mysql.com/doc/refman/8.0/en/innodb-consistent-read.html

A consistent read means that InnoDB uses multi-versioning to present to a query a snapshot of the database at a point in time. The query sees the changes made by transactions that committed before that point of time, and no changes made by later or uncommitted transactions. The exception to this rule is that the query sees the changes made by earlier statements within the same transaction. This exception causes the following anomaly: If you update some rows in a table, a SELECT sees the latest version of the updated rows, but it might also see older versions of any rows. If other sessions simultaneously update the same table, the anomaly means that you might see the table in a state that never existed in the database.

The important condition is if you change the rows, your consistent read is "refreshed" so it includes the change you just made.
But if you UPDATE, it's always made to the most recent version of the row, not the version your transaction's consistent read can view. Therefore your UPDATE may have no net effect, if another transaction has already made that change. That's the situation you observed.
Therefore your transaction issued an UPDATE but didn't change the row.
This is perhaps not how you would like InnoDB to behave, but it is nevertheless how it does behave.

A: Signal your intent with FOR UPDATE:
BEGIN;
SELECT ... FOR UPDATE;
...
(no other thread can change that row until you `COMMIT` or `ROLLBACK`)
...
COMMIT;

On the other hand...
BEGIN;
...
(At this point another thread modifies the row...)
...
SELECT ... FOR UPDATE;  -- you are blocked until they COMMIT or ROLLBACK

A: To get affected by the Repeatable Read isolation level, you must be inside the same transaction. This means that your two selects must be inside a transaction, so they are not afected by wherever you change in your DB from an external transaction.
So, as you say, I have no transaction going at this point in time and I select this record like SELECT * FROM MyTable WHERE PK = 3 and store the result in my program. you are making a transaction with just one statement.
After that, you start a transaction with your Update.
What you should do is
 START TRANSACTION
      SELECT * FROM MyTable WHERE PK = 3
      ------                                        START TRANSACTION
      -----                                             UPDATE MyTable SET Concur = 3 WHERE PK = 3 AND Concur = 2
      -------                                       END TRANSACTTION
      -------
      -------
      SELECT * FROM MyTable WHERE PK = 3
 END TRANSACTION

In the left side, you have your select transaction, and in the right side your update. The left transaction is not afected by the update in this way.


text:
Q: How can I insert at the start of a line a string dependent on two other string values that define beginning and end locations using python note++ How to use Python plugin for note++ for the example below...please advice
So for example, I have
First
x
y
z
Second
a
b
c
Third
d
e
f
The result I would like to achieve is;
First
Q1 x
Q1 y
Q1 z
Second
Q2 a
Q2 b
Q2 c
Third
Q3 d
Q3 e
Q3 f


text:
Q: Call child's method or cast parent to child in Rails I have some STI structure like following:

class Assignment < ActiveRecord::Base
  has_many :criteria, :class_name => "Criterion", :order => :position
end

class Criterion < ActiveRecord::Base
  # Represents a criterion used to mark an assignment that
  # being the super class for all different criterias
  set_table_name "criteria" # set table name correctly
  belongs_to  :assignment
  validates_associated :assignment, :message => 'association is not strong with an assignment'
  validates_presence_of :assignment_id
  validates_numericality_of :assignment_id, :only_integer => true, :greater_than => 0, :message => "can only be whole number greater than 0"
  validates_uniqueness_of :criterion_name, :scope => :assignment_id, :message => 'is already taken'
  validates_presence_of :criterion_name,:assignment_id
end

class FlexibleCriterion < Criterion
  has_one :flexible_criterion_attribute, :class_name => "FlexibleCriterionAttribute"
  accepts_nested_attributes_for :flexible_criterion_attribute
  default_scope :include => :flexible_criterion_attribute
end

class FlexibleCriterionAttribute < ActiveRecord::Base
  belongs_to  :criterion, :class_name => "FlexibleCriterion"
  validates_presence_of :max
  validates_numericality_of :max, :message => "must be a number greater than 0.0", :greater_than => 0.0

  DEFAULT_MAX = 1

end

Alright, I have uploaded my current working codes. So basically the problem is:
When I use a method like criterion = assignment.criteria.find_or_create_by_criterion_name("AAA"), I will get an object of criterion. But I want cast this object to flexiblecriterion so that I can assign the value of criterion.flexible_criterion_attribute
Thx in advance!

A: *

*If assignment.criteria.find_or_create_by_criterion_name("AAA") returns a record in which type column has value FlexibleCriterion, it will automatically cast the object to FlexibleCriterion.

*If you want to ensure that only FlexibleCriterion is returned, modify your finder like this: assignment.criteria.find_or_create_by_criterion_name_and_type("AAA", 'FlexibleCriterion')


text:
Q: C# event problems I have some problems with my application. Heres the thing I have web cam that feeds the pictures into function wich calculate if there were any movements and where. But the problem is (my opinion) that event trigered by the new frames from camera are so often that the code doesnt have time to finish. So where could i put some semaphores or something if this is my code: (i tried many things nothing succsessful) :
 private void button1_Click(object sender, EventArgs e)
    {
        FinalVideoSource = new VideoCaptureDevice(VideoCaptureDevices[comboBox1.SelectedIndex].MonikerString);

        FinalVideoSource.NewFrame += new NewFrameEventHandler(FinalVideoSource_NewFrame);

        FinalVideoSource.Start();

        ImageEfects.drawGrid(detectionImage, 40);
    }

    public void FinalVideoSource_NewFrame(object sender, NewFrameEventArgs eventArgs)
    {
            image = (Bitmap)eventArgs.Frame.Clone();
            #region demoInit
            if (initalization)
            {
                image1 = image;
                initalization = false;
            }
            #endregion demoInit

            ImageProcessing.calculateDiferences(ref image, ref image1, ref detectionImage);

            screen1.Image = image;
            screen2.Image = detectionImage;
    }

A: Just don't compare each and every frame. I would store a frame, than wait (count) a specified number of frames and than compare the current frame and the stored frame (in a separate thread). And store the current frame for the next comparison.
The number of frames to wait is up to you, that depends on which time lap is acceptable for you to overlook a movement.

A: I would use a flag set at the beginning of FinalVideoSource_NewFrame which if set will let the function return. Toggle this flag at the beginning and end of your FinalVideoSource_NewFrame. That way you will never incurr in a queue if ever a computation cycle takes longer.


text:
Q: How to source a Windows batch script For example, I have a simple batch script get_path.bat
@echo off
echo C:\Software\dt

Also, I have another simple batch script switch_dir.bat
@echo off
get_path.bat > target.tmp
set /p TARGET=<target.tmp
cd %TARGET%

Now, what I want to accomplish is that when I invoke in cmd.exe the batch file switch_dir.bat, my current working directory changes to C:\Software\dt.
As of now, the scripts work but they run in a process spawned from cmd.exe so my current working directory stays the same. What is missing? Basically, we need Unix-like source or . here.

A: Well, there are many possible solutions:
Start your script with cmd /c:
All you have to write in cmd is:
cmd /c switch_dir.bat

Using popd/pushd in your batch file:
In your switch_dir.bat add:
@echo off
pushd dir\you\want\to\remain\
get_path.bat > target.tmp
set /p TARGET=<target.tmp
cd %TARGET%
rem [code...]
popd

An additional note: A better way to find directory specified in get_path.bat is to use a for /f loop like this:
@echo off
pushd dir\you\want\to\remain\
for /f "delims=" %%A IN ('get_path.bat') do set TARGET=%%A
cd %TARGET%
rem [code...]
popd


text:
Q: Remove reference to raster layer object PyQGIS I am developing a plugin to load a set of raster files on QGIS. When there is a large number of files to be loaded, the main UI freezes. So I use QgsTask to move the creation of raster layers to a thread. This thread then returns a list of raster layer objects. I was able to load these layers on QGIS.
When I remove the layers from canvas by using QGIS UI or QgsProject.instance().removeMapLayers(), the layers are removed. However, it seems that the raster layer objects still exist. I cannot move or remove the source raster files on disk. It says that the files are still being used by qgis.bin. This did not happen when I did not use the thread.
Here is my code:
Create raster layers task:
task = QgsTask.fromFunction('Load images', createRasterLayers, params = [result["files"]], on_finished=self.load_layers)
task.progressChanged.connect(lambda: self.dlg.he_progress.setValue(task.progress()))
task.taskTerminated.connect(lambda: self.dlg.he_progress.reset())
QgsApplication.taskManager().addTask(task)

The function that creates a list of raster layers, but not load yet:
def createRasterLayers(task, params):

    # extract parameters
    images = params[0]

    n_photos = len(images)

    # set task progress
    task.setProgress(1)

    # then reload the photos
    count = 0
    n_processed = 0
    rlayers = list()
    rt = QgsRasterTransparency()
    rt.initializeTransparentPixelList(0,0,0)
    for img in images:
        fileInfo = QFileInfo(img)
        path = fileInfo.filePath()
        basename = fileInfo.baseName()
        r = QgsRasterLayer(path, basename)
        crs = r.crs()
        crs.createFromId(4326)
        r.setCrs(crs)
        # set transparent for the image
        r.renderer().setRasterTransparency(rt)

        if r.isValid():
            rlayers.append(r)
            count = count + 1

        # set progress
        n_processed = n_processed + 1
        percent = float(n_processed/n_photos) * 100
        task.setProgress(percent)

        if task.isCanceled():
            raise Exception('Task canceled!')

    return {'rlayers': rlayers, 'task': task.description()}

And finally, the function that loads the layers on map:
def load_layers(self, exception, result=None):

    if exception is None:
        for r in result['rlayers']:
            QgsProject.instance().addMapLayer(r, addToLegend=True)

A: Try to move the QgsRasterLayer to the Core Thread.
if r.isValid():
    r.moveToThread(QCoreApplication.instance().thread())
    rlayers.append(r)
    count = count + 1

I had issues with QgsVectorLayers loading from QgsTask and that helped.


text:
Q: jenkinsfile docker agent get access to private repositories & composer I'm trying to use a declarative pipline in the Jenkinsfile to build my php app. My jenkins is running in a docker container, as I want to use this server for other services as well.
My issue is now, that I have to install also private packages from bitbucket over public key authentication with composer. For composer I'm using the docker container from official composer on docker hub.
This is my Jenkinsfile:
pipeline {
    environment {
        BUILD_VERSION = new java.text.SimpleDateFormat('yyyyMMddHHmmss').format(new Date())
    }

    options {
        buildDiscarder(logRotator(numToKeepStr: '3'))
    }

    agent any

    stages {

        stage('composer install') {
            agent {
                docker {
                    image 'composer:latest'
                    args "--volume /tmp:/app --volume /etc/passwd:/etc/passwd:ro --volume /etc/group:/etc/group:ro -u 1000"
                }
            }

            steps {
                sshagent(credentials: ['jenkins_ssh_key']){
                    sh 'composer install -d /app'
                }
            }

            post {
                success {
                    echo 'Composer compiled successfully :)'
                }

                failure {
                    echo 'Composer throw an error :('
                }
            }
        }
    }

    post {
        always {
            echo 'Cleaning up'
            deleteDir() /* clean up our workspace */
        }
        success {
            echo 'Build successful finished :)'
        }
        failure {
            echo '[FAILURE] Build was not successful :('
        }
    }
}

If I'm using sh 'composer install' within sshagent(...){...}, like in my file above, it fails with the information that no composer.json was found.
If I'm using sh 'composer install' without the sshagent, composer runs like expected, but fails for private repositories.
Hope anyone can help me to solve this issue.
Thank you


text:
Q: Randomly constructing a probability distribution for simulation For a simulation, I want to construct the probability distribution of a random variable $X_k$ that takes only finite number of values $x_1, \cdots, x_N$. I have to assign values to each probability: $Pr(X=x_1), \cdots, Pr(X=x_N)$, and of course they should sum to one: $\sum_{i=1}^{N} Pr(X=x_i)$. I have two ways in my mind:
1) I generate $N$ values using a continuous uniform random number generator, and then divide each by the total.
2) I generate $N-1$ values using a continuous uniform(0,1) random number generator, sort them out and treat these numbers as cut points for the probabilities.
What can I say about these two ways? Are they equivalent in the sense that the distributions of the generated probabilities are the same? If different, is there any reason to choose one over the other?

A: The methods are not equivalent. To see this, let us pick $N=2$, denote the random probabilities by $(P_1,P_2)$ and compute
\begin{equation}
\mathbb{P}\left(P_1 \leq \frac{2}{3}\right).
\end{equation}
for both methods.
Method 1
Method 1 in the $N=2$ case works as follows. $X_1,X_2$ are iid.  $\mathrm{Uniform}(0,1)$ random variables and
\begin{equation}
P_1 = \frac{X_1}{X_1 + X_2}
\end{equation}
Therefore,
\begin{equation}
\mathbb{P}\left(P_1 \leq \frac{2}{3}\right) = \mathbb{P}\left(\frac{X_1}{X_1+X_2} \right) = \mathbb{P}\left(X_1 \leq 2X_2 \right).
\end{equation}
There are various straightforward ways to evaluate the last expression. For example, $(X_1,X_2)$ is uniform in the unit square $[0,1]\times[0,1]$, so the probability is simply the area where $X_1\leq X_2$. Alternatively, let us decompose it into two conditional probabilities conditioning on whether $X_2\leq\frac{1}{2}$:
\begin{equation}
=\mathbb{P}(X_2\leq \frac{1}{2}) \mathbb{P}\left(X_1 \leq 2X_2 \mid X_2 \leq \frac{1}{2}\right) + \mathbb{P}(X_2 > \frac{1}{2}) \mathbb{P}\left(X_1 \leq 2X_2 \mid X_2 > \frac{1}{2}\right)
\end{equation}.
Conditional on $X_2 \leq\frac{1}{2}$, $2X_2$ is uniform in $[0,1]$ and thus for symmetry reasons $\mathbb{P}\left(X_1 \leq 2X_2 \mid X_2 \leq \frac{1}{2}\right) = \frac{1}{2}$. If $X_2 > \frac{1}{2}$, $2X_2 > 1$ and therefore $X_1 < X_2$. Thus $\mathbb{P}\left(X_1 \leq 2X_2 \mid X_2 > \frac{1}{2}\right) = 1$. Finally, $\mathbb{P}(X_2\leq \frac{1}{2}) = \mathbb{P}(X_2 > \frac{1}{2}) = \frac{1}{2}$. Plugging these values into the expression, we get
\begin{equation}
= \frac{1}{2}\times \frac{1}{2} + \frac{1}{2} \times 1 = \frac{3}{4}.
\end{equation}
Method 2
In the $N=2$ case there is only one cutpoint uniform in $[0,1]$ and this cutpoint directly equals $P_1$. Thus $P_1 \sim \mathrm{Uniform}(0,1)$ and
\begin{equation}
\mathbb{P}\left(P_1 \leq \frac{2}{3} \right) = \frac{2}{3},
\end{equation}
which is not equal to the value obtained with Method 1.
Which one  to use
As kjetil b halvorsen pointed out in comments, it is impossible to judge which is better for your use case without knowing more details about your use case. Besides these approaches, you may also want to investigate Dirichlet distribution which is often used in Bayesian statistics to define probability distributions over discrete probability distributions (just as the methods described in the question). The Dirichlet distribution has $N$ parameters which you could tune to obtain distributions closer to desired behavior. On the other hand, the use of the Dirichlet distribution is mainly  motivated by its useful computational properties in the Bayesian context, which may be totally irrelevant in your use case.
Another suggestion is to do your simulations using various distributions over the probabilities. If the conclusions you are interested in do not change, good, if they change, you need to think more about which distribution you should use.


text:
Q: Restrict TFS 2010 access by work item type In TFS 2010, is it possible to give a group of users the ability to update certain work item types, but restrict to read-only access on all others?

A: One way you can do it is by adding required field to work item types you want to control.
What you need to do:

*

*Export WI type definition xml using witadmin:
witadmin.exe exportwitd /collection:http://localhost:8080/tfs/DefaultCollection /p:<project name> /n:<WI type name> /f:C:\type.xml

*Modify WI type xml by adding new field definition to the FIELDS node:
<FIELD name="Block" refname="Test.Block" type="String" reportable="dimension">
  <ALLOWEDVALUES>
      <LISTITEM value="NotUsed" />
  </ALLOWEDVALUES>
  <REQUIRED for="[Project]\RestrictedUsers" />
  <DEFAULT for="[Project]\RestrictedUsers" from="value" value="You don't have permissions to create work items of this type."/>
</FIELD>

*Import updated xml back to the server:
witadmin.exe importwitd /collection:http://localhost:8080/tfs/DefaultCollection /p:<project name> /f: C:\type.xml

*Now members of the RestrictedUsers project group won't be able to create/update work items of this type. When they try to save the work item of this type, they'll get an error saying:
The field 'Block' contains the value 'You don't have permissions to create work items of this type.' that is not in the list of supported values.

A: No I don't believe this is possible to do by Work Item Type.  You can restrict access to Work Items based on which Area they are in however.  But the security by Area permissions would apply equally to all Work Item Types in that area.


text:
Q: Avoid accuracy problems while computing the permanent using the Ryser formula Task
I want to calculate the permanent P of a NxN matrix for N up to 100. I can make use of the fact that the matrix features only M=4 (or slightly more) different rows and cols. The matrix might look like
A1 ... A1 B1 ... B1 C1 ... C1 D1 ... D1   |
...                                       | r1 identical rows
A1 ... A1 B1 ... B1 C1 ... C1 D1 ... D1   |
A2 ... A2 B2 ... B2 C2 ... C2 D2 ... D2
...
A2 ... A2 B2 ... B2 C2 ... C2 D2 ... D2
A3 ... A3 B3 ... B2 C2 ... C2 D2 ... D2
...
A3 ... A3 B3 ... B3 C3 ... C3 D3 ... D3
A4 ... A4 B4 ... B4 C4 ... C4 D4 ... D4
...
A4 ... A4 B4 ... B4 C4 ... C4 D4 ... D4
---------
c1 identical cols

and c and r are the multiplicities of cols and rows. All values in the matrix are laying between 0 and 1 and are encoded as double precision floating-point numbers.
Algorithm
I tried to use the Ryser formula to calculate the permanent. For the formula, one needs to first calculate the sum of each row and multiply all the row sums. For the matrix above this yields
 S0 = (c1 * A1 + c2 * B1 + c3 * C1 + c4 * D1)^r1 * ...
    * (c1 * A4 + c2 * B4 + c3 * C4 + c4 * D4)^r4

As a next step the same is done with col 1 deleted
 S1 = ((c1-1) * A1 + c2 * B1 + c3 * C1 + c4 * D1)^r1 * ...
    * ((c1-1) * A4 + c2 * B4 + c3 * C4 + c4 * D4)^r4

and this number is subtracted from S0.
The algorithm continues with all possible ways to delete single and group of cols and the products of the row sums of the remaining matrix are added (even number of cols deleted) and subtracted (odd number of cols deleted).
The task can be solved relative efficiently if one makes use of the  identical cols (for example the result S1 will pop up exactly c1 times).
Problem
Even if the final result is small the values of the intermediate results S0, S1, ... can reach values up to N^N. A double can hold this number but the absolute precision for such big numbers is below or on the order of the expected overall result. The expected result P is on the order of c1!*c2!*c3!*c4! (actually I am interested in P/(c1!*c2!*c3!*c4!) which should lay between 0 and 1).
I tried to arrange the additions and subtractions of the values S in a way that the sums of the intermediate results are around 0. This helps in the sense that I can avoid intermediate results that are exceeding N^N, but this improves things only a little bit. I also thought about using logarithms for the intermediate results to keep the absolute numbers down - but the relative accuracy of the encoded numbers will be still bounded by the encoding as floating point number and I think I will run into the same problem. If possible, I want to avoid the usage of data types that are implementing a variable-precision arithmetic for performance reasons (currently I am using matlab).


text:
Q: Node js Get Status I get data in node js like this
var no_ktp = req.body.cust_noktp
request({
   uri : 'https://evodms-dev.client.com/evoDMM/api/api_customer_all.php?cust_noktp='+no_ktp,
   auth: {
      'bearer': '71D55F995678929'
   },
   rejectUnauthorized: false,//add when working with https sites
   requestCert: false,//add when working with https sites
   agent: false,//add when working with https sites

   }, function(error, rows) {
     if (error) {
       console.log(error);
     } else {
       console.log(rows);
     }

 });

and the log is like this

but i want to get the status : false, when i try console.log(rows.body.status) the log show undefined. how to write it so I get the status?
Thank you for any help...

A: You could access the status using this way rows.body.statusif and only if your body is an object !
However, in the log, your object is actually a string, so, you need to first use JSON.parse(rows.body) in order to transform your object-string into an actual javascript object. Then you will be able to access any properties using the normal syntax
let body = JSON.parse(rows.body);
console.log(body.status) // 'False'

UPDATE
SO, I just read the readme for the request nodejs package https://www.npmjs.com/package/request
And you can see that the request's callback take actually 3 arguments :
(error, response, body)

The response arguments si what you called 'rows', so you can, instead of using my method (JSON.parse) you can use instead the third argument provided to the callback function, no need to parse, you can use it directly :)

A: It looks like your body response is not in JSON format but string. You must convert it to JSON by
var no_ktp = req.body.cust_noktp
request({
   uri : 'https://evodms-dev.client.com/evoDMM/api/api_customer_all.php?cust_noktp='+no_ktp,
   auth: {
      'bearer': '71D55F995678929'
   },
   rejectUnauthorized: false,//add when working with https sites
   requestCert: false,//add when working with https sites
   agent: false,//add when working with https sites

   }, function(error, rows) {
     if (error) {
       console.log(error);
     } else {
       const body = JSON.parse(rows.body); // parse string to JSON
       console.log(body.status);
     }

 });


text:
Q: Does $\left|A\right|=\left|\mathbb{N}\right|$ and $\left|\mathbb{N}\right|=\left|\mathbb{Z}^+\right|$ imply $\left|\mathbb{Z}^+\right|=\left|A\right|$ Suppose $A$ is a countably infinite set. Is it true that if $\left|A\right|=\left|\mathbb{N}\right|$ and $\left|\mathbb{N}\right|=\left|\mathbb{Z}^+\right|$, then $\left|\mathbb{Z}^+\right|=\left|A\right|$?
It can be show by the Cantor-Bernstein theorem that $|\mathbb{N}|=|\mathbb{Z}^+|$, as
\begin{align}
f&:\mathbb{N}\hookrightarrow\mathbb{Z}^+, \ \text{as} \ f(x)=x+1\implies \left|\mathbb{N}\right|\leq\left|\mathbb{Z}^+\right| \\
g&:\mathbb{Z}^+\hookrightarrow\mathbb{N}, \ \text{as} \ g(x)=x-1\implies \left|\mathbb{Z}^+\right|\leq\left|\mathbb{N}\right|.
\end{align}
If we know $\left|A\right|=\left|\mathbb{N}\right|$ and $\left|\mathbb{N}\right|=\left|\mathbb{Z}^+\right|$, can we deduce that $\left|\mathbb{Z}^+\right|=\left|A\right|$?

A: Yes: generally, if you know $\lvert A\rvert=\lvert B\rvert$ and $\lvert B\rvert=\lvert C\rvert$, you can conclude $\lvert A\rvert=\lvert C\rvert$ because if $f:A\to B$ is a bijection and $g:B\to C$ is a bijection, then $g\circ f:A\to C$ is a bijection.


text:
Q: I did not manually acknowledge a message, then rabbitmq give it again after 1min, can i extend this time? In my python3 code. When i get the a message, first i need to do a long-time job. So i want to acknowledge the message when the job done. But if i dont acknowledge the message right now, it will consume the same message after 1min. So, i want to know can i set this time longer?
my code:
def do_work(body, tag):
    print(datetime.datetime.now(), 'I get body:', body, tag)
    # simulate a long time job
    time.sleep(70)
    # ack the message
    channel.basic_ack(tag)

if __name__ == '__main__':
    for method, properties, body in channel.consume('dolphin'):
    t = Thread(target=do_work, args=(body, method.delivery_tag))
    t.start()

""" console output:
2019-04-16 17:32:02.200645 I get body: b'2019-04-16 17:31:31.440033' 1
2019-04-16 17:33:05.879708 I get body: b'2019-04-16 17:31:31.440033' 2
2019-04-16 17:34:10.885120 I get body: b'2019-04-16 17:31:31.440033' 3
"""

A: When you ask a question, you must provide the name and version of all software you are using. In this case, what version of RabbitMQ, Erlang, Python and what Python library you are using.

But if i dont acknowledge the message right now, it will consume the
  same message after 1min.

This is probably because your sleep call blocks heartbeat messages and RabbitMQ thinks your client application has died. RabbitMQ will close the connection and re-enqueue the message.
If you are using the Pika library, your code is not correct. You can't acknowledge a message from another thread.
Please see this example code for how to correctly acknowledge a message from another thread.

NOTE: the RabbitMQ team monitors the rabbitmq-users mailing list and only sometimes answers questions on StackOverflow.


text:
Q: Different FileOpenModes using design automation for AutoCAD I seem to have issues sometimes opening a drawing database.  In the past, I used: MyDb.ReadDwgFile(DrawingName, IO.FileShare.ReadWrite, True, Nothing), with the IO.Fileshare.ReadWrite being the point of interest.  But, I started having issues with it when I moved to Design Automation.  I Later, I found a different file open mode enum of FileOpenMode.OpenForReadAndAllShare and started using it.
I understand both enums are from different libraries (system.io vs autodesk.autocad.databaseservices), but why do I have off and on success using one versus the other?  Could it be because of the .dwg version, or because AEC libraries are being loaded?  I switched to the autodesk enum and was having success for a while, but now I have some files that pass though and others that don't.  For right now, my plan is to try one, check for a failure, then try the other.  Is anybody else running into this?

A: I don't think this is specific to Design Automation. I think the same DWG file will behave the same on your machine too. I suspect what's going on is that you have some unreadable objects in the drawing. ReadWrite will engage the "lazy loading" code path: only the objects that you open are loaded from disk. "...AllShare" will load every object from disk since you want others to be able to access the drawing simultaneously.


text:
Q: RoR Devise - create related new object after User creation I have been stuck on this problem for way too long now.
Using Devise for the first time, I am trying to combine new user sign up with the automatic joining of a group, based on the existence of an invitation token in the params. (E.g. Email invitation to join a group, so when they follow signup link and complete signup, they are automatically a member of the invited group)
Following tutorials, I have been able to customise the Devise controller, with the User being created successfully when an invitation token exists, however I cannot then use the ID from the new user object to create a group membership - the membership is created successfully, with group_id added, but the user_id always remains nil.
Below is my customised Devise controller, and relevant models:
class Users::RegistrationsController < Devise::RegistrationsController

  def create

    super do
      newUser = User.create(resource_params)
      token = params[:invite_token]

      if token != nil
        group = Invite.find_by_token(token).group
        newUser.groups.push(group)
        Membership.create(:user_id => newUser.id, :group_id => group.id)
      end
    end

  end

end

class Membership < ActiveRecord::Base
  belongs_to :user
  belongs_to :group
end

class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable, :omniauthable

  has_many :memberships
  has_many :groups, :through => :memberships
  has_many :gifts
  has_many :posts
  has_many :votes
  has_many :invitations, :class_name => 'Invite', :foreign_key => 'recipient_id'
  has_many :sent_invites, :class_name => 'Invite', :foreign_key => 'sender_id'
end

class Group < ActiveRecord::Base
  has_many :memberships
  has_many :users, :through => :memberships
  has_many :invites
  has_many :gifts
  has_many :posts
  has_one :user
end

Does anyone know how I might be able to successfully create the Membership object, containing both User_id and Group_id, after the User creation?
Thank you all in advance,

A: The call to super will create the user.  Pass a block to the super call that accepts the newly created resource/user and create the membership:
class Users::RegistrationsController < Devise::RegistrationsController
  def create
    super do |user|
      token = params[:invite_token]

      if token.present?
        invite = Invite.find_by_token(token)

        if invite.present?
          Membership.create(user_id: user.id, group_id: invite.group.id)
        end
      end
    end
  end
end

There's an example of this here: http://www.rubydoc.info/github/plataformatec/devise/#Configuring_controllers


text:
Q: Java: looking for a better resize method I wrote this little resize method to scale .png pictures:
    public BufferedImage resize(BufferedImage img, int newW, int newH) {
    int w = img.getWidth();
    int h = img.getHeight();
    BufferedImage dimg = new BufferedImage(newW, newH, img.getType());
    Graphics2D g = dimg.createGraphics();
    g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    g.drawImage(img, 0, 0, newH, newW, 0, 0, w, h, null);
    g.dispose();
    return dimg;
}

I want to make my .png picture at least 8 times bigger, but this fcks up the resolution of the image. Does anyone know how to solve this?
Thanks.

A: What you could do if you wish to is use the Image.getscaledinstance then render it. For example
resizedimage = image.getScaledInstance(newW, newH, Image.SCALE_SMOOTH));

Only thing is you would have to change you method to work with a Image instead of a BufferedImage but that is easily done.

A: you can try this :
BufferedImage createResizedCopy(BufferedImage img, int newW, int newH)
{
    BufferedImage scaledBI = new BufferedImage(newW, newH, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g = scaledBI.createGraphics();
    g.setComposite(AlphaComposite.Src);
    g.drawImage(img, 0, 0, newW, newH, null);
    g.dispose();
    return scaledBI;
}

Or go see here , an other people have the same issue.


text:
Q: How to simply deactivate a button? I've connected the button with my ViewController.swift.
@IBAction func buttPressed(sender: AnyObject) {
   //DO THINGS
}

When it's job get done, how to simply deactivate it? The other answers suggested that:
button.enabled = false

But I can't figured out how to use it, so how to handle this?
Thanks a lot!

A: Just cast the sender of the message to an UIButton and then set the enable property as other suggests, something like this:
@IBAction func buttPressed(sender: AnyObject) {
    //DO THINGS
    if let button = sender as? UIButton {
        button.enabled = false
    }
}

the optional casting is not necessary if you can guarantee that the sender will always be an UIButton, but it is safer to use. You can also change the data type of the sender, like this:
@IBAction func buttPressed(button: UIButton) {
    //DO THINGS
    button.enabled = false
}

A: You just have to create a Referencing Outlet for your button:
@IBOutlet weak var button: UIButton!

A: First you should make an IBOutlet too. At the moment you've only a function which will be executed, if you touch on it.
So connect the Button to your UIViewcontroller and choose Outlet:

then in one of your methods you can set the enabled property to false:
yourButton.enabled = false


text:
Q: Airpods with SpeechRecognizer is not working Is there an option to connect headphones to the phone with SFSpeechRecognizer enabled?
I am trying to build an application. in that mono will use a speech recognizer for text with the headphones turned on.
I have gone through a lot of links about problems with connecting headphones to the phone due to AVAudioeSession configurations, and it seems that I have tried everything
This is how my configs are
let audioSession = AVAudioSession.sharedInstance()
audioSession.setCategory(.playAndRecord, mode: .videoChat, options: [.allowBluetoothA2DP, .defaultToSpeaker])
try audioSession.setActive(true)

I found a small preset description for the type here: documentation
Bluetooth is already known and present in options and much more, but we managed to connect sound through airpods
In fact, I would like the sound to be redirected to the airpods
project example link from Apple


text:
Q: Virtual (fake) primary monitor in Windows 10? I have a bunch of automated UI tests that currently require a physical monitor to run. Can I somehow create a virtual monitor in Windows 10 that functions like a real monitor to the OS? I want to run the UI tests in a remote cloud environment without screens.
I think I heard sometime that VR-development (Virtual Reality) have had similar problems in that VR also need a physical monitor attached (except the VR-headset) and that this was perhaps solved by Nvidia/Intel? with a fake monitor driver or similar? Or was it virtual desktops in VR? I can't find the source for any of this anymore...

A: The easiest way is to use the Spacedesk utility:
https://spacedesk.net/
Spacedesk server part is installed on your PC.
The client part (viewer) will also be required - any device on Android/Windows in same LAN segment.
Small hack:
You can also install Windows Client on Spacedesk server PC and manually assign client IP from another subnet. As a result, you will assume real Windows fake display )...


text:
Q: Undefined method `has_attached_file` with Paperclip and Rails I'm having some trouble getting Paperclip working on my VPS. It works fine locally and on my first VPS, but when I try to rake db:migrate on the second VPS, I get the following output:
root@Test:/home/rails# rake db:migrate
==  CreateGroups: migrating ===================================================
-- create_table(:groups)
   -> 0.0019s
-- add_column(:discussions, :group_id, :integer)
   -> 0.0007s
-- add_column(:memberships, :memberships_id, :integer)
   -> 0.0006s
-- has_attached_file(:photo, {:styles=>{:original=>"400x200>", :tile=>"200x200#"}, :url=>"/assets/images/groups/:id/:style/:basename.:extension", :path=>":rails_root/public/assets/images/groups/:id/:style/:basename.:extension", :default_url=>"/assets/:style/missing-group-image.jpg"})
rake aborted!
An error has occurred, this and all later migrations canceled:

undefined method `has_attached_file' for #<CreateGroups:0x0000000342cbf8>/usr/local/rvm/gems/ruby-1.9.3-p429/gems/activerecord-3.2.8/lib/active_record/migration.rb:465:in `block in method_missing'
...

What I've done so far to set up this second VPS is:

*

*set up Unicorn + Nginx (they seem to be working fine)

*apt-get install git

*apt-get install imagemagick

*bundle install (and Paperclip is in my Gemfile)

*restarted my shell

*rebooted the VPS

After all of this, I'm still getting the above error whenever I try to migrate. Any ideas of what to do next?

A: I think you didn't quite follow Paperclip installation guide. You should have following migration (copied from Paperclip readme so may slightly differ for you)
class AddAvatarColumnsToUsers < ActiveRecord::Migration
  def self.up
    add_attachment :users, :avatar
  end

  def self.down
    remove_attachment :users, :avatar
  end
end

and you apparently put there something that should be in you MODEL.

A: It turns out that my issue had more to do with incomplete code than my environment. Turns out that a teammate of mine had pushed some incomplete code to our GitHub repository, and I hadn't noticed it.
By doing git logs, choosing the right commit, and then git checkout (...), I was able to migrate and seed my database and run my application as expected.
I feel very silly for spending over an hour trying to figure that out, but hopefully it helps someone else. :)