text:
Q: Python attribute that holds other existing attributes in a list I am currently working on a python-sqlite project, and i am novice to both.
I have created a class that has some attributes declared inside the __init__ method. I need another attribute that will be a list or array, that will contain some of the already declared attributes of the class. What i want is my list to contain just a reference of the original attributes.
I need this structure in order to be able to call these attributes together, to iterate on them, but i want to be able to call them separately, too.
At first I tried to create that list attribute inside the __init__ method, after the rest declarations. When I create an instance, however, and change the initial value of one of the attributes, the attribute in the list is not updated.
Then I tried to create that same list attribute inside another method of the class, instead of inside the init, and call it from inside my code, and it did what I wanted to.
Why does the different approach has different results?
Here is the code at both cases:
Case #1
class Tools():
    def __init__(self):
        self.name = "defaultname"
        self.manufacturer = "defaultmanuf"
        self.tooldetails = [self.name, self.manufacturer]

    def get_details(self):
        return self.tooldetails

Case #2
class Tools():
    def __init__(self):
        self.name = "defaultname"
        self.manufacturer = "defaultmanuf"

    def _set_detail_list(self):
        self.tooldetails = [self.name, self.manufacturer]

    def get_details(self):
        _set_detail_list()
        return self.tooldetails

And when I create an instance:
tool1 = Tools()
tool1.name = 'abc'
tool1.get_details()

The first case gives me ["defaultname", "defaultmanuf"] while the second gives me ["abc","defaultmanuf"].
My question is what is the reason python gives me different output for each case? It seems like I miss something important about how initialization is working..
dir() and other similar functions or magic methods could be able to give me what i want, but i think they are not flexible enough if you want many different lists with different sets of attributes. Unluckily, introspection doesn't work very well with sqlite string-formatted commands..
Plus i am curious of the way python works, which I believe is very important..
Thanks!!

A: Case #1
When your list is created within __init__, it contains pointers to 2 strings. But the link between name and tooldetails is irrevocably broken once your list is created. If you update name, tooldetails will not dynamically update, unless you tell Python to explicitly update tooldetails with new data.
Case #2
Here you explicitly tell Python to reconstruct tooldetails via the method _set_detail_list, which is called within get_details. You update name and then tell Python to rebuild the tooldetails list. Therefore, if you update name followed by get_details, your list will be updated.


text:
Q: Get active processname in vc++ Am working on a background appliation in vc++
How can i get the Process Name of the current Application for example "Iexplore" for Using Internet Explorer, "Skype" for window with tile "Skype - username", "Explorer" for using windows explorer ?
i referred this link but am getting Null error :        http://www.codeproject.com/Articles/14843/Finding-module-name-from-the-window-handle

A: This can be done using the following code:
bool GetActiveProcessName(TCHAR *buffer, DWORD cchLen)
{
    HWND fg = GetForegroundWindow();
    if (fg)
    {
        DWORD pid;
        GetWindowThreadProcessId(fg, &pid);
        HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid);
        if (hProcess)
        {
            BOOL ret = QueryFullProcessImageName(hProcess, 0, buffer, &cchLen);
            //here you can trim process name if necessary
            CloseHandle(hProcess);
            return (ret != FALSE);
        }
    }
    return false;
}

and then
TCHAR buffer[MAX_PATH];
if(GetActiveProcessName(buffer, MAX_PATH))
{
    _tprintf(_T("Active process: %s\n"), buffer);
}
else
{
    _tprintf(_T("Cannot obtain active process name.\n"));
}

Note though that QueryFullProcessImageName function is only available since Windows Vista, on earlier systems you could use GetProcessImageFileName (it is similar, but requires linkage with psapi.dll and returns device path instead of usual win32 path)

A: I used this code in my QT5/C++ project to get the currently active process name and window title successfully, based on some research (thanks @dsi). Just wanted to share the code so that someone else would benefit from it.
# Put this two declarations in the top of the CPP file
#include <windows.h>
#pragma comment(lib, "user32.lib")

And put the following into a method:
// get handle of currently active window
HWND hwnd = GetForegroundWindow();
if (hwnd) {
    // Get active app name
    DWORD maxPath = MAX_PATH;
    wchar_t app_path[MAX_PATH];
    DWORD pid;
    GetWindowThreadProcessId(hwnd, &pid);
    HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, FALSE, pid);
    if (hProcess) {
        QueryFullProcessImageName(hProcess, 0, app_path, &maxPath);
        // here you can trim process name if necessary
        CloseHandle(hProcess);
        QString appPath = QString::fromWCharArray(app_path).trimmed();
        QFileInfo appFileInfo(appPath);
        windowInfo.appName = appFileInfo.fileName();
    }

    // Get active window title
    wchar_t wnd_title[256];
    GetWindowText(hwnd, wnd_title, sizeof(wnd_title));
    windowInfo.windowTitle = QString::fromWCharArray(wnd_title);
}

This code may not be compiled directly, because windowInfo is a parameter in my program. Please feel free to let me know in case you encountered any issues when trying this code.

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to confirm password from the keyboard in kotlin android studio? what I mean by the title is by pressing enter from the keyboard instead of pressing a button.

I want the user to have another option of confirming the password  from the keyboard
Edit:grammar fixed


text:
Q: Using MergeCursor and a SimpleCursorAdapter, What's Missing? No matter what I do, the following throws an error that one of the columns contained in the cursor_counterparty does not exist. When I checked the merge_cursor, I can find the column in there, here's my code, what am I doing wrong?
cursor_invoices = Invoices.getInvoicesCursor(counterparty.getId());
    Cursor cursor_counterparty = Counterparties
            .getCounterpartyCursor(counterparty.getId());
    startManagingCursor(cursor_invoices);
    startManagingCursor(cursor_counterparty);

    /* Joins cursors akin to doing an SQL join */

    MergeCursor merge_cursor = new MergeCursor(new Cursor[] {
            cursor_invoices, cursor_counterparty });
    merge_cursor.moveToFirst();

    int[] listview_columns = new int[] { R.id.textview_invoice_number,
            R.id.textview_counterparty_name, R.id.textview_amount,
            R.id.textview_account_name, R.id.textview_invoice_date,
            R.id.textview_date_paid };
    String[] listview_fields = new String[] { App.INVOICENUMBER,
            App.COUNTERPARTYNAME, counterparty_amount_field,
            App.ACCOUNTNAME, App.INVOICEDATE, App.DATEPAID };

    SimpleCursorAdapter cursor_adapter_invoices = new SimpleCursorAdapter(
            this, R.layout.listview_invoice_item, merge_cursor,
            listview_fields, listview_columns);

The error I get is:

java.lang.IllegalArgumentException: column 'counterparty_name' does not exist

When I debug the App, I can see 'counterparty_name' as a column in one of the cursors in the merge_cursor.
Any help would be great, thanks!

A: Are you wanting to join the cursors vertically (adding rows) or horizontally (adding columns)?
This is theory, as I haven't peeked at the code, but it makes sense to me...
MergeCursor concatenates cursors vertically (fact), one after another.  So for part of the cursor you have one set of columns and for the other you have a different set of columns (supposition).
Your adapter is trying to find a column that doesn't exist in one portion or the other for the row being displayed.
If you changed to a CursorJoiner, which concatenates the columns, I think it would work more like you expect, although how you would line up the rows appropriately I don't know.
A good explanation here
EDIT
I see you use the same ID to fetch each cursor, so my concern about lining them up is irrelevant.  I think you do want CursorJoiner rather than MergeCursor.


text:
Q: Verify signature of Private key by Public key between Sender and Receiver in PHP I create a Signature() function for the sender to sign his/her private key and then return the $signature
use phpseclib\Crypt\RSA;

public function Signature(Request $request)
{
  $agent_code = $request->agent_code;
  $private_key = $request->private_key;
  $private_passphrase = $request->private_passphrase;

  $string = $agent_code;

  $private_key = File::get($private_key);

  $rsa = new RSA();
  $rsa->setPassword($private_passphrase);
  $rsa->loadKey($private_key); // private key

  $signature = base64_encode($rsa->sign($string));
  return $signature;
}

After that, the $signature is passed to Verify() function for the receiver to verify the signature using his/her public key
 public function Verify(Request $request)
 {
  $agent_code = $request->agent_code;
  $public_key = $request->public_key;
  $signature = $request->signature;

  $string = $agent_code;

  $public_key = File::get($public_key);

  $rsa = new RSA();
  $rsa->loadKey($public_key); // public key
  echo $rsa->verify($string, base64_decode($signature)) ? 'verified' : 'unverified';

}

Then, I test both function on Postman
Photo 1 - 3 is for the Signature() function
Photo 4 - 6 is for the Verify() function
Photo 1 : This url will call the Signature() function. The agent_code and private_passphrase param is filled. agent_code  is the string to be signed by private key whereas private_passphrase  is the passphrase for the private key.

Photo 2 : The private key is attached in body form as file format

Photo 3 : The $signature is returned

Photo 4 : This url will call the Verify() function. The agent_code and signature param is filled. the signature is copied from Signature() function that used to verified by the public key

Photo 5 : The public key is attached in body form as file format

Photo 6 : Invalid signature error

I have no idea why it return Invalid Signature, because if I write the signature and verify code in one function, it will echo 'verified' for me. The key pairs is correct and the $signature is copied correctly.
All the guidance and correction is appreciated.

A: I am converting my comment into an answer.
I believe that your issue is caused by the + signs in the query parameter(s) - they are being recognized as URL-encoded spaces. If you were using POST instead of GET there would not be any issue.
In order to avoid the problem with URL-encoding caused by the usual Base64 encoding my advice is to use Base64URL encoding. It uses - instead of + and _ instead of / compared to the normal Base64 encoding.


text:
Q: Updating text in a tkinter label from motion bind event I'm able to move data from one class frame to another, unfortunately, I can't update the text in the new frame.   I can only pack the new data below the original pack
class LabelApp(tk.Frame):
    def __init__(self, master, xy_motion=[-1,-1]):
        tk.Frame.__init__(self, master )
        self.pack()
        print('LapApp: ' + str(xy_motion[0]))
        self.master = master
        self.xy_motion=xy_motion
        self.xlabel = tk.Label(text=self.xy_motion[0])
        self.xlabel.pack()

    def update_label(self, xy_motion ):
        self.xlabel.config(text=xy_motion[0])

the print statement above shows correct data
code that is passing over data
class VideoDisplayApp(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)
        self.pack()
        self.master = master
        self.image_label = tk.Label(master=self.master)  # label for the vide.
..
.
.

def motion(self, event):
    x, y = event.x, event.y
    self.xy_motion = [x,y]
    print('{}, {}'.format(x, y))
    self.motion=tk.Frame(self.master)
    self.app = LabelApp(self.motion, self.xy_motion )

Main window
class MainWindow(tk.Frame):
    def __init__(self, master):
        tk.Frame.__init__(self, master)
        self.pack(padx=15, pady=15)
        self.master.title("Mob")
        self.master.resizable(False, False)
        self.master.tk_setPalette(background='#e6e6e6')

        frame_video = tk.Frame(self)
        frame_video.grid(row=0, column=0)
        # frame_video.geometry("200x200")
        VideoDisplayApp(frame_video)
        #
        frame_bottom = tk.Frame(self)
        frame_bottom.grid(row=1, column=0)
        LabelApp(frame_bottom)
        #
        frame_left = tk.Frame(self)
        frame_left.grid(row=0, column=1)
        ClickOnFrame(frame_left)


text:
Q: conditional queries do not work on a single select form filterbar Sorry for my approximately english,
I have created a filter bar to list my courses by selected category. Here is the form
<form id="formFilter" method="get">
    <select name="thematique" id="thematique">
       <? if (isset($_GET['thematique'])) : ?>
            <option value="all">Toutes les formations</option>
            <? foreach ($thematiques as $term) : ?>
               <? if ($_GET['thematique'] === $term->slug) : ?>
                  <option value="<? echo $term->slug ?>" selected><? echo $term->name ?></option>
               <? else : ?>
                   <option name="<? echo $term->slug ?>" value="<? echo $term->slug ?>"><? echo $term->name ?></option>
               <? endif ?>
            <? endforeach; ?>
        <? else : ?>
            <option value="all" selected>Toutes les formations</option>
            <? foreach ($thematiques as $term) : ?>
              <option name="<? echo $term->slug ?>" value="<? echo $term->slug ?>"><? echo $term->name ?></option>
            <? endforeach; ?>
        <? endif; ?>
   </select>
   <input type="submit" value="Filtrer">
</form>

When I click on a category, everything works and I only have the courses of the selected category.  But when I click on All courses I don't see my page from the beginning where there are all the courses
Here is the link if you want test http://cedille-formation.ftalps.fr/formations/
I tried this for now but it doesn't work
if (isset($_GET['thematique'])) {
    for ($i = 0; $i < sizeof($thematiques); $i++) :
        if ($_GET['thematique'] !== $thematiques[$i]->slug) :
            $my_posts = new WP_Query(array('post_type' => 'formations'));
        else :
            $my_posts = new WP_Query(array(
                'post_type' => 'formations',
                'thematique' => $_GET['thematique']
            ));
        endif;
    endfor;
} else {
    $my_posts = new WP_Query(array('post_type' => 'formations'));
}

I check if my variable $_GET['thematique'] isset, if it exists I browse my category array and I check if $_GET is strictly equal to the slug of my category. If it is not part of my category array then my query is a general query that retrieves all my formations otherwise I launch a query with the name of the chosen category.
I enter in my condition if it is not part of my table but I have an error as nothing was found while it is the same request when we arrive on the page all the formations.
I also tried to check if $_GET['thematique'] isset && $_GET['thematique'] !== "all" but I have the same result.
So I want to do is that when the filter bar has already been used on a category (displays only the courses of this category) when I sort on All courses I want to display all courses again.
Thanks for your help


text:
Q: Transform an object recursively in JavaScript I've been struggling with that problem for a few days. I have to transform an object into another object with a different structure.
from this:
{
  "a1" : "key",
  "a2" : {
    "b1" : "key",
    "b2" : {
      "c1" : "key"
    }
  }
}

to this:
{
  "key" : {
    "a1" : null,
    "a2" : [
      {
        "b1" : null,
      },
      {
        "b2" : [
          "c1" : null
        ]
      }
    ]
  }
}

For better understanding, a1, a2, b1, b3 etc. would represent css selectors. null will be the value applied to the node. But for now, this shouldn't matter.
My current (non working) function looks like this:
var json = {};
var obj = {};

function build(objA){
  for(var a in objA){
    var key = objA[a];

    if(key instanceof Object){
      obj = {}; obj[a] = key;
      build(key);
    } else {
      json[key] = json[key] || {};

      if(obj == undefined){
        json[key][a] = null;
      } else {
        var p = firstKeyOf(obj);
        var key = obj[p][a];
        json[key][p] = json[key][p] || [];

        var selector = {};
        selector[a] = null;

        json[key][p].push(selector);
      }
    }
  }
}

which produces:
{
  "key" : {
    "a1" : null,
    "a2" : [
      {
        "b1" : null
      }
    ],
    "b2" : [
      {
        "c1" : null
      }
    ]
  }
}

What did i miss? I appreciate any help, thanks!

A: Try this
var Converter = (function() {

var pic;

function _rec(a, o) {
    for(var k in o){
        var s = o[k];
        var arr = a.slice();
        arr.push(k);
        if (s instanceof Object) { _rec(arr, s); }
        else {
            if ("string" == typeof s) { arr.unshift(s); _attach(pic, arr); }
            else console.log('Invalid key type');
        }
    }
}

function _attach(p, m) {
    var k = m.shift();
    if ( ! p.hasOwnProperty(k)) p[k] = (m.length == 0) ? null : {};
    if (m.length > 0) p[k] = _attach(p[k], m);
    return p;
}

function _reverse(obj) {
    if ( ! (obj instanceof Object)) console.log('First parameter need to be an Object');
    else { pic = {}; _rec([], obj); return pic; }
    }
return {
    reverse: _reverse,
    attach: _attach
}
})();


text:
Q: Postfix not sending emails to external domains from mailing client I have just finished setting up postfix and dovecot on my virtual server. I am able to send emails to external email addresses from my Linux console using mailx but when I try to set up mail account on outlook or any other email client then the server returns the below error:
454 4.7.1 <info@some-external-domain.com>: Relay access denied

Below is my postconf -n
alias_database = hash:/etc/aliases
alias_maps = hash:/etc/aliases
command_directory = /usr/sbin
compatibility_level = 2
daemon_directory = /usr/libexec/postfix
data_directory = /var/lib/postfix
debug_peer_level = 2
debugger_command = PATH=/bin:/usr/bin:/usr/local/bin:/usr/X11R6/bin ddd $daemon_directory/$process_name $process_id & sleep 5
html_directory = no
inet_interfaces = all
inet_protocols = ipv4
mail_owner = postfix
mail_spool_directory = /var/spool/mail
mailq_path = /usr/bin/mailq.postfix
manpage_directory = /usr/share/man
meta_directory = /etc/postfix
mydestination = $myhostname, localhost.$mydomain, localhost
mydomain = mail.example.com #hiding the actual server name
myhostname = example.com #hiding the actual server name
mynetworks = 192.168.30.0/24, 127.0.0.0/8
myorigin = $mydomain
newaliases_path = /usr/bin/newaliases.postfix
queue_directory = /var/spool/postfix
readme_directory = /usr/share/doc/postfix/README_FILES
relayhost =
sample_directory = /usr/share/doc/postfix/samples
sendmail_path = /usr/sbin/sendmail.postfix
setgid_group = postdrop
shlib_directory = /usr/lib64/postfix
smtp_tls_CAfile = /etc/pki/tls/certs/ca-bundle.crt
smtp_tls_CApath = /etc/pki/tls/certs
smtp_tls_security_level = may
smtpd_sasl_auth_enable = yes
smtpd_tls_cert_file = /etc/pki/tls/certs/postfix.pem
smtpd_tls_key_file = /etc/pki/tls/private/postfix.key
smtpd_tls_security_level = may
unknown_local_recipient_reject_code = 550

What am I doing wrong here?

A: First, comment "relayhost =" line at main.cf
Then if it continues failing, provide more logs.
Regards


text:
Q: Динамический файл с переменными для python Подскажите способ создания файла с переменными для кода на питоне который можно будет редактировать и сохранять в ходе действия кода. Я чет ваще не нашел никакой инфы, может руки уже искривились гуглить нормально.
К примеру, у меня есть чат-бот с фильтром запрещенных слов, он естественно эти запрещенный слова берет из списка, ну к примеру
bad_words = [
    'редиска', 'картофель', 'баклажан'
]

@client.event
async def on_message(message):
    for i in bad_words:
        if i in message.content.lower():
            await message.delete()

просто пример, так вот как можно сделать отдельный файл в котором будет этот список запрещенных слов bad_words чтобы и питон с ним хорошо работал и его можно было редактировать в ходе работы кода (добавить/удалить слова) и вместить в него прочие настройки которые будут динамичными.
Вручную редачить это же не вариант вовсе а сохранять все в оперативной памяти которая очищается после закрытия кода это...

A: Например, можно использовать файл в формате JSON:
Код:
import json

# ... там, где это нужно
with open('bad_words.json', 'r') as f:
    bad_words = json.loads(f.read())

Файл:
["редиска", "картофель", "баклажан"]

Но учтите, что по стандарту JSON в файле кавычки должны быть двойными, а в конце списка не должно быть запятой. Если хочется больше вольности, то можно использовать eval(), который парсит питоновские значения:
# ... там, где это нужно
with open('bad_words.data', 'r') as f:
    bad_words = eval(f.read())

Файл в таком случае может быть более свободного формата, но учтите, что это не JSON:
["редиска", 'картофель', 'баклажан', ]


text:
Q: Microsoft Word Can't do "Save As" I have a Word file, I want to create a PDF file. For that, I need the "Save As" dialog. I click on File/Save As — and nothing happens. No dialog. It just returns to the screen I had before I clicked File.
What's wrong? How do I fix it?

A: I still don't know what went wrong, but I found online discussion where people had fixed this problem by deleting all the registry entries containing Word preferences. I tried it and it works. Go here for detailed instructions and a automated tool that works very well.


text:
Q: Android Map - Skipped frames! The application may be doing too much work on its main thread I'm working on a E-com app, and I have to get the location of the user. I was using Google Maps' Places Picker API for the tasks. Things were fine for a while, but now I suddenly receive this error message:

I/Choreographer(691): Skipped 55 frames! The application may be doing too much work on its main thread

The first two activities are working fine and the error message comes only at the starting of the map activity. The map screen starts flashing and app returns to the main activity. The error happens randomly, and doesn't happen all of the time. Sometimes it's working fine and sometimes it's giving issues.
Here I'm putting my whole map code:
  public class LocationActivity extends AppCompatActivity implements OnMapReadyCallback,GoogleApiClient.OnConnectionFailedListener{

        ArrayList<Products> products_list;
        //products_list =

SharedPrefManager.getInstance(getApplicationContext()).GetCart();

@Override
public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {

}

@Override
public void onMapReady(GoogleMap googleMap) {
    Log.i(TAG, "onMapReady: Map is ready");
    Toast.makeText(this, "Map is Ready", Toast.LENGTH_SHORT).show();
    mMap = googleMap;

    if (mLocationPermissionGranted) {
        getDeviceLocation();

        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {

            return;
        }
        mMap.setMyLocationEnabled(true);
        mMap.getUiSettings().setMyLocationButtonEnabled(false);
        Init();
    }
}

private static final String TAG = "MapActivity";
private static final String FINE_LOCATION=Manifest.permission.ACCESS_FINE_LOCATION;
private static final String COARSE_LOCATION=Manifest.permission.ACCESS_COARSE_LOCATION;
private static final int mLocationPermissionRequestCode = 1234;
private static final float DEFAULT_ZOOM = 15f;
protected GeoDataClient mGeoDataClient;
private static final LatLngBounds LAT_LNG_BOUNDS = new LatLngBounds(new LatLng(5,79),new LatLng(10,82));
private static final int PLACE_PICKER_REQUEST = 1;

//widgets
private AutoCompleteTextView mSearch_text;
private ImageView mGps,mPicker;
private Button button;

//vars
private Boolean mLocationPermissionGranted = false;
private GoogleMap mMap;
private FusedLocationProviderClient mFusedLocationProviderClient;
private PlaceAutocompleteAdapter placeAutocompleteAdapter;
private GoogleApiClient mGoogleApiClient;
private LatLng selectedLatLng;
private String selectedname;

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

    // Construct a GeoDataClient.
    mGeoDataClient = Places.getGeoDataClient(this, null);

    button=findViewById(R.id.btn_confirm);
    mSearch_text = findViewById(R.id.search_text);
    mGps = findViewById(R.id.ic_gps);
    mPicker = findViewById(R.id.ic_picker);

    getPermissionAccess();

}

private void Init(){
    Log.i(TAG, "Init: Initializing");

    mGoogleApiClient = new GoogleApiClient
            .Builder(this)
            .addApi(Places.GEO_DATA_API)
            .addApi(Places.PLACE_DETECTION_API)
            .enableAutoManage(this, this)
            .build();

    mSearch_text.setOnItemClickListener(mAutocompleteAdapterViewListener);

    placeAutocompleteAdapter = new PlaceAutocompleteAdapter(this,mGeoDataClient,LAT_LNG_BOUNDS,null);

    mSearch_text.setAdapter(placeAutocompleteAdapter);

    mSearch_text.setOnEditorActionListener(new TextView.OnEditorActionListener() {
        @Override
        public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
            if(actionId == EditorInfo.IME_ACTION_SEARCH
                    || actionId == EditorInfo.IME_ACTION_DONE
                    || event.getAction() == event.ACTION_DOWN
                    || event.getAction() == event.KEYCODE_ENTER){
                //Method for search
                geoLocate();

            }
            return false;
        }
    });
    mGps.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Log.i(TAG, "onClick: gps icon clicked");
            getDeviceLocation();
        }
    });

    mPicker.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            PlacePicker.IntentBuilder builder = new PlacePicker.IntentBuilder();

            try {
                startActivityForResult(builder.build(LocationActivity.this), PLACE_PICKER_REQUEST);
            } catch (GooglePlayServicesRepairableException e) {
                e.printStackTrace();
            } catch (GooglePlayServicesNotAvailableException e) {
                e.printStackTrace();
            }
        }
    });

    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            NextActivity();
        }
    });

}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (requestCode == PLACE_PICKER_REQUEST) {
        if (resultCode == RESULT_OK) {
            Place place = PlacePicker.getPlace(this,data);
            String toastMsg = String.format("Place: %s", place.getName());
            Toast.makeText(this, toastMsg, Toast.LENGTH_LONG).show();

            PendingResult<PlaceBuffer>  placeResult = Places.GeoDataApi.getPlaceById(mGoogleApiClient,place.getId());
            placeResult.setResultCallback(mUpdatePlaceDetailsCallback);
        }
    }
}

private void geoLocate(){
    Log.i(TAG, "geoLocate: geolocating");
    String searchstring = mSearch_text.getText().toString();
    Geocoder geocoder = new Geocoder(LocationActivity.this);
    List<Address> list = new ArrayList<>();
    try{
        list = geocoder.getFromLocationName(searchstring,1);
    }catch (IOException e)
    {
        Log.i(TAG, "geoLocate: IOException"+ e.getMessage());
    }
    if(list.size()>0){
        Address address = list.get(0);
        Log.i(TAG, "geoLocate: Found LocationActivity"+ address.toString());
        MoveCamera(new LatLng(address.getLatitude(),address.getLongitude()),DEFAULT_ZOOM,
                address.getAddressLine(0));

    }
}

private void getDeviceLocation(){
    Log.i(TAG, "getDeviceLocation: Getting Device LocationActivity");
    mFusedLocationProviderClient = LocationServices.getFusedLocationProviderClient(this);
    try{
        if(mLocationPermissionGranted){
            Task location =mFusedLocationProviderClient.getLastLocation();
            location.addOnCompleteListener(new OnCompleteListener() {
                @Override
                public void onComplete(@NonNull Task task) {
                    if(task.isSuccessful()){
                        Log.i(TAG, "onComplete: LocationActivity Found");
                        android.location.Location currentLocation = (android.location.Location) task.getResult();

                        MoveCamera(new LatLng(currentLocation.getLatitude(),currentLocation.getLongitude()),DEFAULT_ZOOM
                                ,"My LocationActivity");

                    }
                    else {
                        Log.i(TAG, "onComplete: LocationActivity Null");
                        Toast.makeText(LocationActivity.this, "Unable to get LocationActivity", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }

    } catch (SecurityException e){
        Log.i(TAG, "getDeviceLocation: SecurityException: "+e.getMessage());
    }

}

private void MoveCamera(LatLng latLng , float zoom, String title){
    Log.i(TAG, "MoveCamera: Moving Camera to lat: "+latLng.latitude+" ,lng: "+latLng.longitude);
    mMap.moveCamera(CameraUpdateFactory.newLatLngZoom(latLng,zoom));

    mMap.clear();

    if(!title.equals("My LocationActivity")){
        MarkerOptions markerOptions = new MarkerOptions()
                .position(latLng)
                .title(title);
        mMap.addMarker(markerOptions);
    }

}

private void InitMap(){
    Log.i(TAG, "InitMap: Initilizing Map");
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
    mapFragment.getMapAsync(LocationActivity.this);
}

private void getPermissionAccess(){
    Log.i(TAG, "getPermissionAccess: Getting LocationActivity permissions");
    String[] permissions = {FINE_LOCATION,COARSE_LOCATION};
    if(ContextCompat.checkSelfPermission(this.getApplicationContext(),FINE_LOCATION) == PackageManager.PERMISSION_GRANTED){
        if(ContextCompat.checkSelfPermission(this.getApplicationContext(),COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED){
            mLocationPermissionGranted = true;
            InitMap();
        } else {
            ActivityCompat.requestPermissions(this,permissions,mLocationPermissionRequestCode);
        }
    } else {
        ActivityCompat.requestPermissions(this,permissions,mLocationPermissionRequestCode);
    }

}

@Override
public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
    Log.i(TAG, "onRequestPermissionsResult: Called");
    mLocationPermissionGranted = false;
    switch (requestCode){
        case mLocationPermissionRequestCode:{
            if(grantResults.length>0){
                for(int i=0; i<grantResults.length; i++){
                    if(grantResults[i]!= PackageManager.PERMISSION_GRANTED){
                        mLocationPermissionGranted=false;
                        Log.i(TAG, "onRequestPermissionsResult: Permission Denied.");
                        Log.i(TAG, "onRequestPermissionsResult:"+grantResults[i]);
                        return;
                    }
                }
                mLocationPermissionGranted=true;
                Log.i(TAG, "onRequestPermissionsResult: Permission Granted");
                //initialization of Map
                InitMap();
            }
        }
    }
}

/*
 google places api auto complete */

private AdapterView.OnItemClickListener mAutocompleteAdapterViewListener = new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

        final AutocompletePrediction item = placeAutocompleteAdapter.getItem(position);
        final String placeid = item.getPlaceId();

        PendingResult<PlaceBuffer> placeResult = Places.GeoDataApi.getPlaceById(mGoogleApiClient,placeid);
        placeResult.setResultCallback(mUpdatePlaceDetailsCallback);

    }
};

private ResultCallback<PlaceBuffer> mUpdatePlaceDetailsCallback = new ResultCallback<PlaceBuffer>() {
    @Override
    public void onResult(@NonNull PlaceBuffer places) {

        if(!places.getStatus().isSuccess()){
            Log.i(TAG, "onResult: Place query did not complete"+places.getStatus().toString());
            places.release();
        }
        final Place place = places.get(0);
        Log.i(TAG, "onResult: Name:"+place.getName());
        Log.i(TAG, "onResult: Latitude:"+place.getLatLng().latitude);
        Log.i(TAG, "onResult: Longtitude:"+place.getLatLng().longitude);

        selectedname=place.getName().toString();
        selectedLatLng=place.getLatLng();

        MoveCamera(selectedLatLng,DEFAULT_ZOOM,selectedname);
        places.release();
        Log.i(TAG, "onResult: Name:"+selectedname);
        Log.i(TAG, "onResult: Selected LAtLng"+selectedLatLng);
    }

};

private void NextActivity(){
    if(selectedLatLng!=null && !selectedname.equals("")){
        Intent intent = new Intent(getApplicationContext(),CheckoutActivity.class);
        SharedPrefManager.getInstance(getApplicationContext()).SaveLocation(selectedname,selectedLatLng);
        startActivity(intent);
    }
    else{
        showErrorMsg("Location Cannot be Empty");
    }
}
public void showErrorMsg(String message){
    new AlertDialog.Builder(this)
            .setTitle("Oops")
            .setMessage(message)
            .setPositiveButton(android.R.string.ok,null)
            .show();
}
}

A: This is where you need to start doing some digging around to find where there is heavy lifting in your activity and make a Thread/AyscTask/Worker do the work instead of your main thread. This is a warning/error because your main thread handles rendering the GUI of your application and your telling it to do a lot of calculations which make the application look like it's frozen.
Once you find where there is a lot of work your main thread is doing you can create something like a Thread and Runnable that the Thread will be running on.
private Thread thread = null;
private final Runnable thread_DoWork = new Runnable() {
    @Override public void run() {
        // Your code here or call some function to run for the thread
        someHeavyLiftingFunction();
    }
};

Below is how you create and tell the Thread to start working on the Runnable you gave it.
// Check if already created/started
if (thread == null) {
    // Create new thread
    thread = new Thread(thread_DoWork);
    // Start Thread in background
    thread.start();
}

That is pretty much it. Your main Thread will be freed up. There are some other types of workers/threads that have more build in functionality like a callback function that gets called when the thread is done doing work (AsyncTask Android example).


text:
Q: socket io client not connecting to server using ipv4 address I'm having a problem with testing the connection when I use https://localhost:3000/ it connects successfully but I want to use socket Io client on a different device on android application to be precise I searched it up and turns out localhost wont work I have to connect using ipv4 address well I tried it but didnt work - like this http http://192.168.XX.XX:3000 for example so what is the problem why doesnt it connect please help
server code:
var cors = require("cors");
const express = require("express");
const app = express();
const port = process.env.PORT || 3000 ;
const server = app.listen(port, () => {
    console.log(`started on ${port}`);
})

const io = require('socket.io')(server, {
    cors: { origin: "*" }
});

io.on('connection', (socket) => {
    console.log('a user connected');

    socket.on('message', (message) =>     {
        console.log(message);
        io.emit('message', `${socket.id.substr(0,2)} said ${message}` );
    });
});

require("dotenv").config();
app.use(express.json());
app.use(cors());

//routes setup
const homeGetRoute = require("./routes/test.js");
app.use("/home", homeGetRoute);
app.use(cors());


text:
Q: How can I use terminal commands as pattern in grep or any other program? I've been writing a small script, and one of its functionalities is to register the computer in landscape. To do so, I have to first install landscape and then run this line with the following data:
sudo landscape-config --computer-title "**DEVICE NAME**" --account-name ******** --registration-key ***********

If I'm not wrong, I must get the device name with some sort of embedded command (I guess hostname should be what I'm looking for), that way it should work for every device.
So my question is how do I get a command to fill that field? I believe it involves the $ sign, but I really don't know. Thank you in advance if you answer!!


text:
Q: Existing spring project to maven project Earlier at the time of development my project have not consider the requirement of Maven. Since now project size is quite large and having a lot of dependencies so we have to change our existing spring project to maven project .
can any body suggest me the steps by step implementation of converting spring project to maven project. I'm using Spring, JPA, EJB, Apache CXF.

A: *

*Change the project directory structure to adapt maven standard directory structure

*Change the classpath provider (if you are using) to maven

*Change project configuration in eclipse to get it detected as maven project

*configure maven plugins for your build requirement


text:
Q: Statistical test to use to compare subgroups with each other I don't have a stats background, so I apologize in advance if my question is dummy. I sent a quiz to several people and I would like to run some statistics' tests on it (I'm using R).
Essentialy I asked question like :

*

*Man or woman?

*Age? < 20 yo, 20-40 yo, 40-60 yo, > 60 yo

*Work? Engineer, Lawyer, Teacher, Doctor.

*When do you use means of transports? Never, Rarely, From time to time, Frequently.

*...

I would like to run a statistical test to see whether the there is a (statistical) difference between men and women regarding the frequency at which they use means of transports. I would like to answer the same question with age and work.
My problem is that I don't know which test should be used to answer these questions. All I can find in my old courses are t-test and chi2 test which are not really suited for that matter.
I suspect it should be quite frequent for researchers to want to do that, but unfortunately I couldn't find a clear answer to that, hence my cry for guidance.
Cheers! :)


text:
Q: Get String from json with nested json object and nested json arrays with multiple json object, in Android I need to access as String all the single parameters contained in a complex Json.
for example String people=...;
             String idPeople=...;   etc.
I have tried to use the JSONTokeners, as I have tried to search for similar question, and for simple json I haven't problem but I don't know how to get the parameters correctly from this:
{"id":1,"error":null,"result":
  {"nPeople":2,
    "people":[
            {"namePeople":"Inca",
             "power":"1235",
             "location":"asdfghjja",
             "idPeople":189,
             "mainItems":"brownGem",
             "verified":false,
             "description":"Lorem impsum bla bla",
             "linkAvatar":"avatar_12.jpg",
             "longitude":16.2434263,
             "latitude":89.355118},

            {"namePeople":"Maya",
             "power":"1235",
             "location":"hcjkjhljhl",
             "idPeople":119,
             "mainItems":"greenstone",
             "verified":false,
             "description":"Lorem impsum bla bla",
             "linkAvatar":"avatar_6.jpg",
             "longitude":16.2434263,
             "latitude":89.3551185}]
    }
}

NB the numbers of object in the array people is not always 2... and may contains 4 or more people object

A: I've not tried.
But i guess it may work.
    JSONObject obj = new JSONObject(jsonString);
    String id = obj.getString("id");
    String error = obj.getString("error");
    JSONObject result = obj.getJSONObject("result");
    int nPeople = result.getInt("nPeople");
    JSONArray people = result.getJSONArray("people");
    for(int i = 0 ; i < people.length() ; i++){
        JSONObject p = (JSONObject)people.get(i);
        String namePeople = p.getString("namePeople");
        ...
    }

A: if we call the json you post myJsonString,
JSonObject obj = new JSonObject(myJsonString);
JSonObject result = obj.getJSONObject("result");
JSonArray people = result.getJSONArray("people");
int numOfPeople = result.getInt("nPeople");


text:
Q: Query That Returns First Results from Subquery I'm trying to create a query that returns the results from a subquery in the result set.
Here are the tables I'm using:
Orders       OrderDetails
-------      -----------
orderId      orderDetailId
(other data) orderId
             productName

I'd like to get the first two order details for each order (Most orders have only one or two details). Here's an example of the desired result set:
orderId   (other order data)   productName1   productName2
-------   ------------------   ------------   ------------
1         (other order data)   apple          grape
2         (other order data)   orange         banana
3         (other order data)   apple          orange

This is what I tried so far:
SELECT o.orderid,
       Max(CASE WHEN detail = 1 THEN oi.productname END) AS ProductName1,
       Max(CASE WHEN detail = 2 THEN oi.productname END) AS ProductName2
FROM orders AS o
    OUTER apply (SELECT TOP 2 oi.*,
                     Row_number() OVER (ORDER BY orderdetailid) AS detail
                FROM orderdetails AS oi
                WHERE oi.orderid = o.orderid) AS oi
GROUP BY o.orderid

I'm doing this in the custom reporting module of a hosted ecommerce solution and getting the following unhelpful syntax error: SQL Error: Incorrect syntax near '('.
Unfortunately I don't know what version of SQL Server I'm using. Customer support knows nothing and select @@Version doesn't work.
Note, it appears the row_number() function is not properly supported even though error messages reference the function by name.
Thanks for the help!

A: Here is an alternative that does not use cross apply. Your ranking was correct but I added a partition by the order.
SELECT
*
FROM
(
    SELECT
        o.orderid,
        ProductName=oi.productcode,
        RowNumber=ROW_NUMBER() OVER (PARTITION BY o.orderid ORDER BY oi.orderdetailid)
    FROM
        orders as o
        INNER JOIN orderdetailid oi ON oi.orderid=o.orderid
)AS X
WHERE
    RowNumber=1

without using row_number
SELECT
    orderdetails.*
    Q1.*
FROM
(
    SELECT
        o.*,
        FirstOrderDetailID=(SELECT MIN(orderdetails.orderdetailsid) FROM orderdetails WHERE orderid=o.orderid)
    FROM
        orders o
)AS Q1
LEFT OUTER JOIN orderdetails oi ON oi.orderdetailsid=Q1.FirstOrderDetailID

A: If you are just selecting orderid and the product, you don't need the join at all:
select orderid, productcode
from (SELECT oi.orderid, oi.productcode,
             row_number() over (partition by oi.orderid order by oi.orderdetailid) as seqnum
      FROM orderdetails oi
     ) oi
where seqnum = 1;

This may not fix the problem if row_number() is not working, but it simplifies the query.  You can do this with the min() method as well:
select orderid, productcode
from orderdetails oi
where oi.orderdetailid in (select min(orderdetailid) from orderdetails group by orderid);


text:
Q: Hw to prevent Google chrome from loading old javascript after writing a meaningless command in the console? I wrote some code that didn't work so I wanted to try running specific parts of the code to find the wrongs but I accidentally copied all my code and it makes my program act weird now whenever I write anything in the console.
More specifically I'm making a program that draws by placing pictures at mouse pointer but I made it so whenever I write something in the console it makes it so I draw far more than normally.
I have tried reloading the page, closing chrome and opening it again as well as restarting my computer. I have also tried clearing the console with console.clear() but none of my attempts have worked.
Here is the code that I use to draw with:
function tegn() {
  if(MusTilstand == 1) { //this is the drawing function
    var x = event.clientX;
    var y = event.clientY;
    var coor = "X coords: " + x + ", Y coords: " + y;
    document.getElementById("demoo").innerHTML = coor;

    pnktArrayX[counter2].push(x);
    pnktArrayY[counter2].push(y);

    var img = document.createElement("img");
    img.src = "https://www.astrology-zodiac-signs.com/images/cancer.jpg";
    img.width = 50;
    img.height = 50;
    img.style.zIndex = -1;
    img.alt = "Image";
    img.id = ("idd" + counter);

    document.body.appendChild(img);

    var y = document.getElementById("idd" + counter);
    y.style.position = "absolute";
    y.style.left = (event.pageX - 25 + 'px');
    y.style.top = (event.pageY - 25 + 'px');

    counter = (counter + 1);

  }
}

Don't know if its relevant but here is some more of the code for drawing:
document.getElementsByTagName("BODY")[0].addEventListener("mousedown", mouseDown);
function mouseDown() {
  if(MusTilstand == 0) {
    MusTilstand = 1;
    pnktArrayX.push([]);
    pnktArrayY.push([]);
  } else {
    MusTilstand = 0;
    counter2 = counter2 + 1;
  }

}

Here are some links to show the difference between drawing the way my code works normally and the way it works after I have written something in the console:

This image is when I draw normally

This is what happens after I have written a command in the console

A: Ctrl + F5 to reload page while ignoring cache.


text:
Q: Arquivo de configuração para formulários Existe alguma maneira de criar um arquivo onde eu posso definir por exemplo, uma cor com o nome 'Fundo' e adicionar o valor '#fff', depois usar ela em todos os meus forms, semelhante a um style do CSS, para que caso eu precise mudar essa cor eu não precise trocar em todos os forms um a um?
Eu vi algo sobre Singleton, mas não sei se seria o ideal para o que eu preciso, que é apenas informar uma cor ou texto.

A: Talvez, tem duas formas de pensar isso. pelo que está dizendo, sim, tem.
Chama-se orientação a objetos. Algo que as pessoas dizem que fazem, mas desconhecem totalmente o que seja, como se aplica.
O mecanismo exclusivo da orientação a objetos é a herança, algo que praticamente nunca vi alguém fazer no Windows Forms e é onde OOP melhor se aplica.
Você cria um controle com certas características e sempre que precisa de um controle semelhante que mantenha as mesmas características você herda deste controle, assim todos os herdados recebem estas características. O que provavelmente já sabe é que este controle pode, e provavelmente deve herdar de um controle já existente. E pode ser que este novo controle pode ser abstrato, só para organizar. Pode deixar as classes descendentes modificar o valor ou não, o que pode ser um pouco diferente do que quer.
Se quiser que a mudança ocorra de forma dinâmica, e o CSS não trabalha assim, onde pode mudar na hora e seja transferi automaticamente para os descendentes, aí precisa de um mecanismo que faça isto, provavelmente com eventos onde as descendentes assinam eventos da ascendente, talvez até automaticamente.
Por outro lado pode estar falando não de formulários e sim de controles que são aninhados uns dentro dos outros. Isto não tem nada pronto e geralmente faz pouco sentido no WinForms e provavelmente em outros formas, salvo algo muito restrito e específico. Neste caso os controles que são filhos de outros, ou seja, são vinculados dentro do controle já existente, algo como colocar um label ou um textbox dentro de um form. As propriedades de um form costumam ser diferentes. Mesmo as que são iguais tem motivações diferenças, não faz muito sentido querer que a cor de fundo do formulário seja automaticamente replicada no textbox. O que pode fazer é estabelecer cor transparente por exemplo em um label e isso significa que a cor de fundo será a mesma do formulário porque não é pra ter um cor, não é branco, ou preto, é sem cor, isso é feito.
Não consigo imaginar onde Singleton entra nisso, alias me parece ser o oposto do que precisa. A não ser que a pergunta seja sobre outra coisa completamente diferente.
A pergunta é bem geral e a resposta foi na mesma linha.

A: Como Maniero falou, no Windows Forms, você utiliza a herança. Um Singleton, ou criar "um arquivo onde eu posso definir ... uma cor com o nome 'Fundo' e adicionar o valor '#fff'" pode até funcionar, mas será gambiarra. Imagine só em todo construtor de Form você ter que ir lá e colocar: this.BackColor = minhaClasseStylesSingleton.Fundo;
Essa utilização seria viável, mas para pontos específicos, por exemplo, definir mensagens, ou cores de certos objetos.
Voltando à herança do WinForms, é bem simples (Basta não querer resolver tudo em um único formulário):
Você cria um Form com as características que serão aplicadas a todos os forms do projeto:

(não foi alterado nada no código do Form)
Agora, nos próximos Forms, basta você trocar a herança:
namespace WindowsFormsApplication
{
    public partial class FormFilho : FormBase
    {
        public FormFilho()
        {
            InitializeComponent();
        }
    }
}

Pronto:

Repare que as propriedades são carregadas com o valor padrão do Form Pai (FormBase).

Observações:

Você ainda pode alterar esses propriedades no Form filho e elas serão aplicadas apenas nele.
Você pode ter um terceiro Form, que herde o FormFilho e assim sucessivamente.
Cuidado ao querer resolver tudo em um Form só, adicionar um controle no Forms pai por exemplo, ele estará disponível em todos os Forms filhos e não será possível removê-lo. Removê-lo do Form pai, trará problemas aos Forms filhos.
Para acessar os controles de Forms superiores nos Forms Filhos, basta você alterar a propriedade Modifiers para o valor desejado.


text:
Q: How can I subset a data frame for unique rows using repeating values from a column in another data frame in python? I have 2 data frames. I want to subset df_1 based on df_2 so that the rows in the resulting data frame correspond to the rows in df_2. Here are two example data frames:
df_1 = pd.DataFrame({
    "ID": ["Lemon","Banana","Apple","Cherry","Tomato","Blueberry","Avocado","Lime"],
    "Color": ["Yellow","Yellow","Red","Red","Red","Blue","Green","Green"]})

df_2 = pd.DataFrame({"Color": ["Red","Blue","Yellow","Green","Red","Yellow"]})

My desired output is df_3, where the "Color" column is the same as in df_2:
df_3 = pd.DataFrame({
    "ID": ["Apple","Blueberry","Lemon","Avocado","Cherry","Banana"],
    "Color": ["Red","Blue","Yellow","Green","Red","Yellow"]})

When I merge df_1 and df_2, I get duplicated rows because most of the rows in df_2 have multiple matches in df_1.
merged = df_2.merge(df_1, how="left", on="Color")

Dropping duplicates works properly for the "Yellow" color because it has a 2:2 ratio of values in df_2 and options in df_1, but it doesn't work properly for "Red" or "Green" because they have a 2:3 ratio and a 1:2 ratio respectively, resulting in extra rows.
no_duplicates = merged.drop_duplicates(subset = "ID")

Is there a way to subset df_1 where the first occurrence of "Red" in df_2 pulls out the first occurrence of "Red" in df_1, the second occurrence of "Red" in df_2 pulls out the second occurrence of "Red" in df_1, etc.? I would rather not use a loop unless I have no other choice. Thank you.

A: Try adding an indicator column to both df_1 and df_2 with groupby cumcount to get position as well:
df_1['i'] = df_1.groupby('Color').cumcount()
df_2['i'] = df_2.groupby('Color').cumcount()

df_1:
          ID   Color  i
0      Lemon  Yellow  0
1     Banana  Yellow  1
2      Apple     Red  0
3     Cherry     Red  1
4     Tomato     Red  2
5  Blueberry    Blue  0
6    Avocado   Green  0
7       Lime   Green  1

df_2:
    Color  i
0     Red  0
1    Blue  0
2  Yellow  0
3   Green  0
4     Red  1
5  Yellow  1

Then merge on both the indicator and the Color then drop the indicator column:
merged_df = df_1.merge(df_2, how='right', on=['Color', 'i']).drop('i', axis=1)

merged_df:
          ID   Color
0      Apple     Red
1  Blueberry    Blue
2      Lemon  Yellow
3    Avocado   Green
4     Cherry     Red
5     Banana  Yellow

Alternatively create pass the series directly to merge (this leaves df_1 and df_2 unaffected):
merged_df = df_1.merge(
    df_2, how='right',
    left_on=['Color', df_1.groupby('Color').cumcount()],
    right_on=['Color', df_2.groupby('Color').cumcount()]
).drop('key_1', axis=1)

merged_df:
          ID   Color
0      Apple     Red
1  Blueberry    Blue
2      Lemon  Yellow
3    Avocado   Green
4     Cherry     Red
5     Banana  Yellow


text:
Q: J Oliver EventStore V2.0 questions I am embarking upon an implementation of a project using CQRS and intend to use the J Oliver EventStore V2.0 as my persistence engine for events.
1) In the documentation, ExampleUsage.cs uses 3 serializers in "BuildSerializer".  I presume this is just to show the flexibility of the deserialization process?
2) In the "Restart after failure" case where some events were not dispatched I believe I need startup code that invokes GetUndispatchedCommits() and then dispatch them, correct?
3) Again, in "ExampleUseage.cs" it would be useful if "TakeSnapshot" added the third event to the eventstore and then "LoadFromSnapShotForward" not only retrieve the most recent snapshot but also retrieved events that were post snapshot to simulate the rebuild of an aggregate.
4) I'm failing to see the use of retaining older snapshots.  Can you give a use case where they would be useful?
5) If I have a service that is handling receipt of commands and generation of events what is a suggested strategy for keeping track of the number of events since the last snapshot for a given aggregate.  I certainly don't want to invoke "GetStreamsToSnapshot" too often.
6) In the SqlPersistence.SqlDialects namespace the sql statement name is "GetStreamsRequiringSnaphots" rather than "GetStreamsRequiringSnapShots"

A: 1) There are a few "base" serializers--such as the Binary, JSON, and BSON serializers.  The other two in the example--GZip/Compression and Encryption serializers are wrapping serializers and are only meant to modify what's already been serialized into a byte stream.  For the example, I'm just showing flexibility.  You don't have to encrypt if you don't want to.  In fact, I've got stuff running production that uses simple JSON which makes debugging very easy because everything is text.
2) The SynchronousDispatcher and AsychronousDispatcher implementations are both configured to query and find any undispatched commits.  You shouldn't have to do anything special.
3) Greg Young talked about how he used to "inline" his snapshots with the main event stream, but there were a number of optimistic concurrency and race conditions in high-performance systems that came up.  He therefore decided to move them "out of band".  I have followed this decision for many of the same reasons.
In addition snapshots are really a performance consideration when you have extrememly low SLAs.  If you have a stream with a few thousand events on it and you don't have low SLAs, why not just take the minimal performance hit instead of adding additional complexity into your system.  In other words, snapshots are "ancillary" concepts.  They're in the EventStore API, but they're an optional concept that should be considered for certain use cases.
4) Let's suppose you had an aggregate with tens of millions of events and you wanted to run a "what if" scenario from before your most recent snapshot.  It's a lot cheaper to go from another snapshot forward.  The really nice thing about snapshots being a secondary concept is that if you wanted to drop older snapshots you could and it wouldn't affect your system at all.
5) There is a method in each implementation of IPersistStreams called GetStreamsRequiringSnapshots.  You provide a threshold of 50, for example which finds all streams having 50 or more events since their last snapshot.  This can (and probably should) be done asynchronously from your normal processing.
6) "Snapshots" is the correct casing for that word.  Much like "website" used to be "Web site" but because of common usage it became "website".


text:
Q: Spring security @PostFilter in combination with maxResults I am using Spring security for my web services. I'm using annotations to specify the security conditions. Right now I'm facing the following problem. Consider the following service method:
@Override
@PostFilter("hasPermission(filterObject, 'read')")
@Transactional(readOnly = true)
public List<UserDTO> listUsers(int firstResult, int maxResults, String orderBy, boolean ascending) {

//Retrieve users and put them in a collection
}

Post filtering works after the method is invoked, but the contract of the method is to return a collection of size #maxResults if at least that many users exist. How do I achieve this, because objects may be filtered out after the method has been invoked. Of course I could revert to manual access checking inside the method, but I thought that there maybe would be a more elegant way of doing this.


text:
Q: unexpected '' (T_ENCAPSED_AND_WHITESPACE), expecting identifier (T_STRING) or variable (T_VARIABLE) or number (T_NUM_STRING) in PHP MYSQL I get the above error when i run the code. Please tell me where i've gone wrong.
I'm trying to get the values and encode them with JSON and save them into the database. Then later on i'm gonna retrieve the data from the database, decode it, and send it to the client end.
Following is my php code.
    <?php

    $name = $_POST['fname'];
    $email = $_POST['email'];
    $comment =$_POST['comment'];
    $website = $_POST ['website'];
    $rate = $_POST['rate'];

    $conn = mysqli_connect("localhost","root","","webtech");
    if(!$conn){
        die("Connection Failed : ".mysqli_connect_error());
    } else{
        echo "Connection Succesful ";
    }

    $jsonDb = array
    (
        'name' => $name,
        'email'=> $email,
        'comment'=> $comment,
        'website'=> $website,
        'rate'=> $rate
        );

    $jsonArray = array
    (
        'name' => $name,
        'email'=> $email,
        'comment'=> $comment,
        'website'=> $website,
        'rate'=> $rate
         );

$encodeDatabase = json_encode($jsonDb);

$encodeArray = json_encode($jsonArray);
mysql_query("INSERT INTO comments VALUES ("."'".$jsonDb['name']."'"."," ."'".$jsonDb['email']."'".","."'".$jsonDb['website']."'".","."'".$jsonDb['comment']."'".","."'".$jsonDb['rate']."'".")");

    echo $encodeDatabase;

?>

A: You have used mysqli to connect the DB but you are using mysql_query() to execute the insert query.
Please use mysqli_query() instead of mysql_query() to execute the Insert Query.

A: mysql_query("INSERT INTO comments VALUES ('$jsonDb[name]','$jsonDb[email]','$jsonDb[website]','$jsonDb[comment]','$jsonDb[rate]')");

That is what it should look like.

A: As others have pointed out you need to use mysqli_query instead of mysql_query in this case.
A couple more suggestions:

*

*With large string concatenation as in your query string it can become hard to read and easy to make mistakes with all of the single and double quotation marks. Another option is to use curly braces for interpolation, although this is mostly a stylistic choice:

"INSERT INTO comments VALUES ('{$jsonDb['name']}', '{$jsonDb['email']}',
    '{$jsonDb['website']}', '{$jsonDb['comment']}', '{$jsonDb['rate']}')"

*This code is vulnerable to sql injection. Instead of inserting variables into the database using string concatenation for the query it would be much safer to use prepared statements.


text:
Q: java:S2189: "Add an end condition to this loop.". Could you please help me? I'm trying to solve this Sonarqube issue regarding this piece of code
private void processEvents() {
    long nextSequence = sequence.get() + 1L;

    long groupCounter = 0;
    long msgsInGroup = 0;

    long groupLastNs = 0;

    long l2dataLastNs = 0;
    boolean triggerL2DataRequest = false;

    final int tradeEventChainLengthTarget = sharedPool.getChainLength();
    MatcherTradeEvent tradeEventHead = null;
    MatcherTradeEvent tradeEventTail = null;
    int tradeEventCounter = 0; // counter

    while (true) {
        try {

            // should spin and also check another barrier
            long availableSequence = waitSpinningHelper.tryWaitFor(nextSequence);

            if (nextSequence <= availableSequence) {
                while (nextSequence <= availableSequence) {

                    OrderCommand cmd = ringBuffer.get(nextSequence);
                    nextSequence++;

                    // some commands should trigger R2 stage to avoid unprocessed state in events
                    if (cmd.command == OrderCommandType.RESET
                            || cmd.command == OrderCommandType.PERSIST_STATE_MATCHING
                            || cmd.command == OrderCommandType.BINARY_DATA) {
                        groupCounter++;
                        msgsInGroup = 0;
                    }

                    cmd.eventsGroup = groupCounter;

                    cmd.serviceFlags = 0;
                    if (triggerL2DataRequest) {
                        triggerL2DataRequest = false;
                        cmd.serviceFlags = 1;
                    }

                    // cleaning attached events
                    if (EVENTS_POOLING && cmd.matcherEvent != null) {

                        // update tail
                        if (tradeEventTail == null) {
                            tradeEventHead = cmd.matcherEvent; //?
                        } else {
                            tradeEventTail.nextEvent = cmd.matcherEvent;
                        }

                        tradeEventTail = cmd.matcherEvent;
                        tradeEventCounter++;

                        // find last element in the chain and update tail accourdingly
                        while (tradeEventTail.nextEvent != null) {
                            tradeEventTail = tradeEventTail.nextEvent;
                            tradeEventCounter++;
                        }

                        if (tradeEventCounter >= tradeEventChainLengthTarget) {
                            // chain is big enough -> send to the shared pool
                            tradeEventCounter = 0;
                            sharedPool.putChain(tradeEventHead);
                            tradeEventTail = null;
                            tradeEventHead = null;
                        }

                    }
                    cmd.matcherEvent = null;

                    // TODO collect to shared buffer
                    cmd.marketData = null;

                    if (cmd.command == OrderCommandType.NOP) {
                        // just set next group and pass
                        continue;
                    }

                    msgsInGroup++;

                    // switch group after each N messages
                    // avoid changing groups when PERSIST_STATE_MATCHING is already executing
                    if (msgsInGroup >= msgsInGroupLimit && cmd.command != OrderCommandType.PERSIST_STATE_RISK) {
                        groupCounter++;
                        msgsInGroup = 0;
                    }

                }
                sequence.set(availableSequence);
                groupLastNs = System.nanoTime() + GROUP_MAX_DURATION_NS;

            } else {
                final long t = System.nanoTime();
                if (msgsInGroup > 0 && t > groupLastNs) {
                    // switch group after T microseconds elapsed, if group is non empty
                    groupCounter++;
                    msgsInGroup = 0;
                }

                if (t > l2dataLastNs) {
                    l2dataLastNs = t + L2_PUBLISH_INTERVAL_NS; // trigger L2 data every 10ms
                    triggerL2DataRequest = true;
                }
            }

        } catch (final AlertException ex) {
            if (running.get() != RUNNING) {
                break;
            }
        } catch (final Throwable ex) {
            sequence.set(nextSequence);
            nextSequence++;
        }
    }
}

The problem is about that while(true) loop with a try catch inside. I've tried to put while(true) into the try block but this created huge compilation error.
This code has not been written by me, but it is a project given me by my teacher for the exam.

A: Introduce a variable so that instead of
while (true) {
    ...
}

You can control it from within the loop
boolean running = true;
...
while (running) {
    ...
    if (condition) {
        running = false;
    }
}

Or alternatively create a method to validate whatever criteria are necessary if the loop is to keep iterating:
while (isValid(input)) {
    ...
}

And define the method
boolean isValid( ... method args here ... ) {
    ...
}

If for example the loop should keep going for as long as nextSequence is not 0, this can all be simplified to
while (nextSequence != 0) {
    ...
}

Note that you can't use a compile time constant in this case. If it were set to false you would get an error due to unreachable code.


text:
Q: How to fetch jsonb column through jpa springboot? I have one table which contains one column 'details' as jsonb data type. The content is
{
     "name": "username",
     "value": "user1",
     "is_required": true
}

for one row.
I want to write one jpa hibernate query in spring boot to fetch this record when name == username for details column.
Something like this:
select details->>'value' from table where details->>'name' = 'username';

This syntax does not work in spring boot hibernate query.

A: I got the answer. Use
@Query(value="select details->>'value' from table where details->>'name' = 'username'", nativeQuery=true)


text:
Q: SPO: Storage Metrics via PS without Admin site access and no Graph How can we get the storage metric details via powershell for SP online (without Admin access).
I can access the GUI page on storman.aspx
like here: https://myDom123.sharepoint.com/sites/mySite1232/_layouts/15/storman.aspx
GUI example:
But can't figure out how to use PS to get such info.
Seem that Graph API and PnP to admin Site has some of this information.
here my PnP PS attempt (without Admin site)
Get-PnPTenantSite -Url https://rkodev1.sharepoint.com/sites/wgive `
| select Title, StorageQuota, StorageQuotaType , StorageQuotaWarningLevel , StorageUsageCurrent , `
ResourceQuota , ResourceQuotaWarningLevel , ResourceUsageAverage , ResourceUsageCurrent


text:
Q: Пробел после точки или запятой в регуляярном выражении Есть гугл форма с проверкой текста в ответе с помощью регулярно выражения. Сейчас оно проверяет, чтобы в ответе использовался только английский язык и цифры, пробелы, двоеточия, тире, двойные кавычки, точки, запятые, восклицательный и вопросительные знаки и скобки. Кроме этого заставляет начинать ответ с заглавной буквы или цифры, а заканчивать точкой или знаками '!?'. А как сделать так, чтобы точка или запятая в тексте использовались только с пробелом после них?
^[A-Z0-9][0-9a-zA-Z\s:\-".,!?()]*[\.!?]$

A: Используйте
^[A-Z0-9]([0-9a-zA-Z\s:"!?()-]|[.,]\s)*[.!?]$

Подробности

*

*^ - начало строки

*[A-Z0-9] - буква или цифра из набора символов ASCII

*( - начало захватывающей подмаски:

*

*[0-9a-zA-Z\s:"!?()-] - буква или цифра из набора символов ASCII, пробельный символ или один из символов :"!?()-

*| - или

*[.,]\s - точка или запятая, после которых следует один пробельный символ

*)* - конец подмаски, ноль или более повторов

*[.!?] - ., ! или ?

*$ - конец строки.


text:
Q: Ошибка при деплое spring-boot на websphere У меня есть spring-boot приложение, которое пытаюсь задеплоить на webspere.
Локально проект нормально собирается в war и работает если запускать на внешнем tomcat.
Код pom.xml  :
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>MyApp</groupId>
    <artifactId>MyApp</artifactId>
    <version>1.0</version>
    <packaging>war</packaging>

    <parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.4.RELEASE</version>
    </parent>

    <properties>
        <java.version>1.8</java.version>
        <spring.boot.version>2.0.4.RELEASE</spring.boot.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot</artifactId>
        </dependency>
        <!--Spring-boot dependencies-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
            <exclusions>
                <exclusion>
                    <groupId>org.springframework.boot</groupId>
                    <artifactId>spring-boot-starter-tomcat</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-data-jpa</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
        </dependency>
        <!--deploy on tomcat-->
        <!-- <dependency>
             <groupId>org.springframework.boot</groupId>
             <artifactId>spring-boot-starter-tomcat</artifactId>
             <scope>provided</scope>
         </dependency>-->
        <!-- swagger to provide list available rests-->
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger2</artifactId>
            <version>2.7.0</version>
        </dependency>
        <dependency>
            <groupId>io.springfox</groupId>
            <artifactId>springfox-swagger-ui</artifactId>
            <version>2.7.0</version>
        </dependency>
        <!--database connector-->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <scope>runtime</scope>
        </dependency>
        <!--json to xml provider-->
        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-xml</artifactId>
        </dependency>
    </dependencies>

    <build>
        <finalName>SBRiskDataSvcs</finalName>
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <filtering>true</filtering>
            </resource>
        </resources>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
                <executions>
                    <execution>
                        <goals>
                            <goal>repackage</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
            <!--provide to split it and ut test-->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.19.1</version>
                <configuration>
                </configuration>
            </plugin>
        </plugins>
    </build>
</project>

Но получаю такую ошибку в логах:

criptor count = 1048576
  ************* End Display Current Environment ************* [9/20/18 18:35:17:893 MSK] 00000089 ecs           W
  com.ibm.ws.ecs.internal.scan.context.impl.ScannerContextImpl scanJAR
  unable to open input stream for resource
  META-INF/versions/9/org/apache/logging/log4j/util/ProcessIdUtil.class
  in archive WEB-INF/lib/log4j-api-2.10.0.jar
                                   java.lang.IllegalArgumentException
          at org.objectweb.asm.ClassReader.(Unknown Source)
          at org.objectweb.asm.ClassReader.(Unknown Source)
          at org.objectweb.asm.ClassReader.(Unknown Source)
          at com.ibm.ws.ecs.internal.scan.impl.ClassScanner.scanInputStream(ClassScanner.java:147)
          at com.ibm.ws.ecs.internal.scan.impl.ClassScanner.scanInputStream(ClassScanner.java:124)
          at com.ibm.ws.ecs.internal.scan.impl.ClassScanner.scanInputStream(ClassScanner.java:120)
          at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:463)
          at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleNewRequest(HttpInboundLink.java:530)
          at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.processRequest(HttpInboundLink.java:316)
          at com.ibm.ws.http.channel.inbound.impl.HttpICLReadCallback.complete(HttpICLReadCallback.java:88)
          at com.ibm.ws.ssl.channel.impl.SSLReadServiceContext$SSLReadCompletedCallback.complete(SSLReadServiceContext.java:1833)
          at com.ibm.ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:175)
          at com.ibm.io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:217)
          at com.ibm.io.async.AsyncChannelFuture.fireCompletionActions(AsyncChannelFuture.java:161)
          at com.ibm.io.async.AsyncFuture.completed(AsyncFuture.java:138)
          at com.ibm.io.async.ResultHandler.complete(ResultHandler.java:204)
          at com.ibm.io.async.ResultHandler.runEventProcessingLoop(ResultHandler.java:775)
          at com.ibm.io.async.ResultHandler$2.run(ResultHandler.java:905)
          at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1892)
[9/20/18 18:35:17:904 MSK] 00000089 ecs           W
  com.ibm.ws.ecs.internal.scan.context.impl.ScannerContextImpl scanJAR
  unable to open input stream for resource
  META-INF/versions/9/org/apache/logging/log4j/util/StackLocator.class
  in archive WEB-INF/lib/log4j-api-2.10.0.jar
                                   java.lang.IllegalArgumentException
          at org.objectweb.asm.ClassReader.(Unknown Source)
          at org.objectweb.asm.ClassReader.(Unknown Source)
          at org.objectweb.asm.ClassReader.(Unknown Source)
          at com.ibm.ws.ecs.internal.scan.impl.ClassScanner.scanInputStream(ClassScanner.java:147)
          at com.ibm.ws.ecs.internal.scan.impl.ClassScanner.scanInputStream(ClassScanner.java:124)
          at com.ibm.ws.ecs.internal.scan.impl.ClassScanner.scanInputStream(ClassScanner.java:120)
          at com.ibm.ws.webcontainer.webapp.WebAppImpl.scanForHandlesTypesClasses(WebAppImpl.java:765)
          at com.ibm.ws.webcontainer.webapp.WebAppImpl.initializeServletContainerInitializers(WebAppImpl.java:606)
          at com.ibm.ws.webcontainer.webapp.WebAppImpl.initialize(WebAppImpl.java:410)
          at com.ibm.ws.runtime.component.CompositionUnitImpl.start(CompositionUnitImpl.java:123)
          at com.ibm.ws.runtime.component.CompositionUnitMgrImpl.start(CompositionUnitMgrImpl.java:379)
          at com.ibm.ws.runtime.component.CompositionUnitMgrImpl.access$500(CompositionUnitMgrImpl.java:127)
          at com.ibm.ws.runtime.component.CompositionUnitMgrImpl$1.run(CompositionUnitMgrImpl.java:654)
          at com.ibm.ws.security.auth.ContextManagerImpl.runAs(ContextManagerImpl.java:5554)
          at com.ibm.ws.security.auth.ContextManagerImpl.runAsSystem(ContextManagerImpl.java:5680)
          at com.ibm.ws.security.core.SecurityContext.runAsSystem(SecurityContext.java:255)
          at com.ibm.ws.runtime.component.CompositionUnitMgrImpl.startCompositionUnit(CompositionUnitMgrImpl.java:668)
          at com.ibm.ws.runtime.component.CompositionUnitMgrImpl.startCompositionUnit(CompositionUnitMgrImpl.java:612)
          at com.ibm.ws.runtime.component.ApplicationMgrImpl.startApplication(ApplicationMgrImpl.java:1303)
          at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
          at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:90)
          at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:55)
          at java.lang.reflect.Method.invoke(Method.java:508)
          at org.apache.struts.action.RequestProcessor.process(Unknown Source)
          at org.apache.struts.action.ActionServlet.process(Unknown Source)
          at org.apache.struts.action.ActionServlet.doPost(Unknown Source)
          at javax.servlet.http.HttpServlet.service(HttpServlet.java:595)
          at javax.servlet.http.HttpServlet.service(HttpServlet.java:668)
          at com.ibm.ws.http.channel.inbound.impl.HttpICLReadCallback.complete(HttpICLReadCallback.java:88)
          at com.ibm.ws.ssl.channel.impl.SSLReadServiceContext$SSLReadCompletedCallback.complete(SSLReadServiceContext.java:1833)
          at com.ibm.ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:175)
          at com.ibm.io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:217)
          at com.ibm.io.async.AsyncChannelFuture.fireCompletionActions(AsyncChannelFuture.java:161)
          at com.ibm.io.async.AsyncFuture.completed(AsyncFuture.java:138)
          at com.ibm.io.async.ResultHandler.complete(ResultHandler.java:204)
          at com.ibm.io.async.ResultHandler.runEventProcessingLoop(ResultHandler.java:775)
          at com.ibm.io.async.ResultHandler$2.run(ResultHandler.java:905)
          at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1892)
[9/20/18 18:35:17:911 MSK] 00000089 ecs           W
  com.ibm.ws.ecs.internal.scan.context.impl.ScannerContextImpl scanJAR
  unable to open input stream for resource module-info.class in archive
  WEB-INF/lib/log4j-api-2.10.0.jar
                                   java.lang.IllegalArgumentException
          at org.objectweb.asm.ClassReader.(Unknown Source)
          at org.objectweb.asm.ClassReader.(Unknown Source)
          at org.objectweb.asm.ClassReader.(Unknown Source)
          at com.ibm.ws.ecs.internal.scan.impl.ClassScanner.scanInputStream(ClassScanner.java:147)
          at com.ibm.ws.ecs.internal.scan.impl.ClassScanner.scanInputStream(ClassScanner.java:124)
          at com.ibm.ws.ecs.internal.scan.impl.ClassScanner.scanInputStream(ClassScanner.java:120)
          at com.ibm.ws.ecs.internal.scan.context.impl.ScannerContextImpl.scanJAR(ScannerContextImpl.java:275)
          at com.ibm.ws.ecs.internal.scan.context.impl.ScannerContextImpl.scanJARs(ScannerContextImpl.java:315)
          at com.ibm.ws.security.core.SecurityContext.runAsSystem(SecurityContext.java:255)
          at com.ibm.ws.runtime.component.CompositionUnitMgrImpl.startCompositionUnit(CompositionUnitMgrImpl.java:668)
          at com.ibm.ws.runtime.component.CompositionUnitMgrImpl.startCompositionUnit(CompositionUnitMgrImpl.java:612)
          at com.ibm.ws.runtime.component.ApplicationMgrImpl.startApplication(ApplicationMgrImpl.java:1303)
          at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
          at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:90)
          at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:55)
          at java.lang.reflect.Method.invoke(Method.java:508)
          at sun.reflect.misc.Trampoline.invoke(MethodUtil.java:83)
          at sun.reflect.GeneratedMethodAccessor89.invoke(Unknown Source)
          at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:55)
          at java.lang.reflect.Method.invoke(Method.java:508)
          at sun.reflect.misc.MethodUtil.invoke(MethodUtil.java:287)
          at javax.management.modelmbean.RequiredModelMBean$4.run(RequiredModelMBean.java:1263)
          at java.security.AccessController.doPrivileged(AccessController.java:664)
          at java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:91)
          at javax.management.modelmbean.RequiredModelMBean.invokeMethod(RequiredModelMBean.java:1257)
          at javax.management.modelmbean.RequiredModelMBean.invoke(RequiredModelMBean.java:1096)
          at com.sun.jmx.interceptor.DefaultMBeanServerInterceptor.invoke(DefaultMBeanServerInterceptor.java:831)
          at org.apache.struts.action.ActionServlet.doPost(Unknown Source)
          at javax.servlet.http.HttpServlet.service(HttpServlet.java:595)
          at javax.servlet.http.HttpServlet.service(HttpServlet.java:668)
          at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1233)
          at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:782)
          at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:481)
          at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.handleRequest(ServletWrapperImpl.java:178)
          at com.ibm.ws.webcontainer.filter.WebAppFilterChain.invokeTarget(WebAppFilterChain.java:136)
          at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:79)
          at org.apache.struts.action.ActionServlet.process(Unknown Source)
          at org.apache.struts.action.ActionServlet.doPost(Unknown Source)
          at javax.servlet.http.HttpServlet.service(HttpServlet.java:595)
          at javax.servlet.http.HttpServlet.service(HttpServlet.java:668)
          at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1233)
          at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:782)
          at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:481)
          at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.handleRequest(ServletWrapperImpl.java:178)
          at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:463)
          at com.ibm.ws.http.channel.inbound.impl.HttpICLReadCallback.complete(HttpICLReadCallback.java:88)
          at com.ibm.ws.ssl.channel.impl.SSLReadServiceContext$SSLReadCompletedCallback.complete(SSLReadServiceContext.java:1833)
          at com.ibm.ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:175)
          at com.ibm.io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:217)
          at com.ibm.io.async.AsyncChannelFuture.fireCompletionActions(AsyncChannelFuture.java:161)
          at com.ibm.io.async.AsyncFuture.completed(AsyncFuture.java:138)
          at com.ibm.io.async.ResultHandler.complete(ResultHandler.java:204)
          at com.ibm.io.async.ResultHandler.runEventProcessingLoop(ResultHandler.java:775)
          at com.ibm.io.async.ResultHandler$2.run(ResultHandler.java:905)
          at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1892)
[9/20/18 18:35:36:037 MSK] 00000089 webapp        I
  com.ibm.ws.webcontainer.webapp.WebApp log SRVE0292I: Servlet Message -
  [myApp#SBRiskDataSvcs.war]:.2 Spring WebApplicationInitializers
  detected on classpath [9/20/18 18:35:36:906 MSK] 00000089
  SpringApplica E org.springframework.boot.SpringApplication
  reportFailure Application run failed
                                   java.lang.BootstrapMethodError: java.lang.LinkageError: loading constraint violation when overriding
  method
  "org/springframework/boot/context/config/ConfigFileApplicationListener$DocumentFilterFactory.getDocumentFilter(Lorg/springframework/boot/context/config/ConfigFileApplicationListener$Profile;)Lorg/springframework/boot/context/config/ConfigFileApplicationListener$DocumentFilter;"
  during creation of class
  "org/springframework/boot/context/config/ConfigFileApplicationListener$Loader$$Lambda$330/0000000039C78270":
  loader "java/lang/InternalAnonymousClassLoader@d1c57825" of class
  "org/springframework/boot/context/config/ConfigFileApplicationListener$Loader$$Lambda$330/0000000039C78270"
  and loader "com/ibm/ws/classloader/CompoundClassLoader@9d596fe4" of
  class
  "org/springframework/boot/context/config/ConfigFileApplicationListener$DocumentFilterFactory"
  have different types for the method signature
          at org.springframework.boot.context.config.ConfigFileApplicationListener$Loader.load(ConfigFileApplicationListener.java:336)
          at org.springframework.boot.context.config.ConfigFileApplicationListener.addPropertySources(ConfigFileApplicationListener.java:215)
          at org.springframework.boot.context.config.ConfigFileApplicationListener.postProcessEnvironment(ConfigFileApplicationListener.java:198)
          at org.springframework.boot.context.config.ConfigFileApplicationListener.onApplicationEnvironmentPreparedEvent(ConfigFileApplicationListener.java:185)
          at org.springframework.boot.context.config.ConfigFileApplicationListener.onApplicationEvent(ConfigFileApplicationListener.java:171)
          at org.springframework.context.event.SimpleApplicationEventMulticaster.doInvokeListener(SimpleApplicationEventMulticaster.java:172)
          at org.springframework.context.event.SimpleApplicationEventMulticaster.invokeListener(SimpleApplicationEventMulticaster.java:165)
          at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:139)
          at org.springframework.context.event.SimpleApplicationEventMulticaster.multicastEvent(SimpleApplicationEventMulticaster.java:127)
          at org.springframework.boot.context.event.EventPublishingRunListener.environmentPrepared(EventPublishingRunListener.java:74)
          at org.springframework.boot.SpringApplicationRunListeners.environmentPrepared(SpringApplicationRunListeners.java:54)
          at org.springframework.boot.SpringApplication.prepareEnvironment(SpringApplication.java:361)
          at org.springframework.boot.SpringApplication.run(SpringApplication.java:320)
          at org.springframework.boot.web.servlet.support.SpringBootServletInitializer.run(SpringBootServletInitializer.java:157)
          at org.springframework.boot.web.servlet.support.SpringBootServletInitializer.createRootApplicationContext(SpringBootServletInitializer.java:137)
          at org.springframework.boot.web.servlet.support.SpringBootServletInitializer.onStartup(SpringBootServletInitializer.java:91)
          at org.springframework.web.SpringServletContainerInitializer.onStartup(SpringServletContainerInitializer.java:172)
          at com.ibm.ws.webcontainer.webapp.WebAppImpl.initializeServletContainerInitializers(WebAppImpl.java:620)
          at com.ibm.ws.webcontainer.webapp.WebAppImpl.initialize(WebAppImpl.java:410)
          at com.ibm.ws.webcontainer.webapp.WebGroupImpl.addWebApplication(WebGroupImpl.java:88)
          at com.ibm.ws.webcontainer.VirtualHostImpl.addWebApplication(VirtualHostImpl.java:171)
          at com.ibm.ws.runtime.component.ApplicationMgrImpl.start(ApplicationMgrImpl.java:1211)
          at com.ibm.ws.runtime.component.DeployedApplicationImpl.fireDeployedObjectStart(DeployedApplicationImpl.java:1390)
          at com.ibm.ws.runtime.component.DeployedModuleImpl.start(DeployedModuleImpl.java:639)
          at com.ibm.ws.runtime.component.DeployedApplicationImpl.start(DeployedApplicationImpl.java:979)
          at com.ibm.ws.runtime.component.ApplicationMgrImpl.startApplication(ApplicationMgrImpl.java:795)
          at com.ibm.ws.runtime.component.ApplicationMgrImpl.startApplicationDynamically(ApplicationMgrImpl.java:1413)
          at com.ibm.ws.runtime.component.ApplicationMgrImpl.start(ApplicationMgrImpl.java:2273)
          at com.ibm.ws.runtime.component.CompositionUnitMgrImpl.start(CompositionUnitMgrImpl.java:436)
          at com.ibm.ws.runtime.component.CompositionUnitImpl.start(CompositionUnitImpl.java:123)
          at com.ibm.ws.runtime.component.CompositionUnitMgrImpl.start(CompositionUnitMgrImpl.java:379)
          at com.ibm.ws.runtime.component.CompositionUnitMgrImpl.access$500(CompositionUnitMgrImpl.java:127)
          at com.ibm.ws.runtime.component.CompositionUnitMgrImpl$1.run(CompositionUnitMgrImpl.java:654)
          at com.ibm.ws.security.auth.ContextManagerImpl.runAs(ContextManagerImpl.java:5554)
          at com.ibm.ws.security.auth.ContextManagerImpl.runAsSystem(ContextManagerImpl.java:5680)
          at com.ibm.ws.security.core.SecurityContext.runAsSystem(SecurityContext.java:255)
          at com.ibm.ws.runtime.component.CompositionUnitMgrImpl.startCompositionUnit(CompositionUnitMgrImpl.java:668)
          at com.ibm.ws.runtime.component.CompositionUnitMgrImpl.startCompositionUnit(CompositionUnitMgrImpl.java:612)
          at com.ibm.ws.runtime.component.ApplicationMgrImpl.startApplication(ApplicationMgrImpl.java:1303)
          at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
          at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:90)
          at org.apache.struts.action.RequestProcessor.processActionPerform(Unknown
  Source)
          at org.apache.struts.action.RequestProcessor.process(Unknown Source)
          at org.apache.struts.action.RequestProcessor.doForward(Unknown Source)
          at org.apache.struts.tiles.TilesRequestProcessor.doForward(Unknown
  Source)
          at org.apache.struts.action.RequestProcessor.processForwardConfig(Unknown
  Source)
          at org.apache.struts.tiles.TilesRequestProcessor.processForwardConfig(Unknown
  Source)
          at org.apache.struts.action.RequestProcessor.process(Unknown Source)
          at org.apache.struts.action.ActionServlet.process(Unknown Source)
          at org.apache.struts.action.ActionServlet.doPost(Unknown Source)
          at javax.servlet.http.HttpServlet.service(HttpServlet.java:595)
          at javax.servlet.http.HttpServlet.service(HttpServlet.java:668)
          at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1233)
          at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:782)
          at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:481)
          at com.ibm.ws.webcontainer.servlet.CacheServletWrapper.handleRequest(CacheServletWrapper.java:87)
          at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:949)
          at com.ibm.ws.webcontainer.WSWebContainer.handleRequest(WSWebContainer.java:1817)
          at com.ibm.ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:200)
          at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:463)
          at com.ibm.io.async.AsyncChannelFuture.fireCompletionActions(AsyncChannelFuture.java:161)
          at com.ibm.io.async.AsyncFuture.completed(AsyncFuture.java:138)
          at com.ibm.io.async.ResultHandler.complete(ResultHandler.java:204)
          at com.ibm.io.async.ResultHandler.runEventProcessingLoop(ResultHandler.java:775)
          at com.ibm.io.async.ResultHandler$2.run(ResultHandler.java:905)
          at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1892) Caused by: java.lang.LinkageError: loading constraint violation when
  overriding method
  "org/springframework/boot/context/config/ConfigFileApplicationListener$DocumentFilterFactory.getDocumentFilter(Lorg/springframework/boot/context/config/ConfigFileApplicationListener$Profile;)Lorg/springframework/boot/context/config/ConfigFileApplicationListener$DocumentFilter;"
  during creation of class
  "org/springframework/boot/context/config/ConfigFileApplicationListener$Loader$$Lambda$330/0000000039C78270":
  loader "java/lang/InternalAnonymousClassLoader@d1c57825" of class
  "org/springframework/boot/context/config/ConfigFileApplicationListener$Loader$$Lambda$330/0000000039C78270"
  and loader "com/ibm/ws/classloader/CompoundClassLoader@9d596fe4" of
  class
  "org/springframework/boot/context/config/ConfigFileApplicationListener$DocumentFilterFactory"
  have different types for the method signature
          at sun.misc.Unsafe.defineAnonymousClass(Native Method)
          at java.lang.invoke.InnerClassLambdaMetafactory.spinInnerClass(InnerClassLambdaMetafactory.java:339)
          at java.lang.invoke.InnerClassLambdaMetafactory.buildCallSite(InnerClassLambdaMetafactory.java:206)
          at java.lang.invoke.LambdaMetafactory.metafactory(LambdaMetafactory.java:315)
          at java.lang.invoke.DirectHandle.invokeExact_thunkArchetype_L(DirectHandle.java:302)
          at java.lang.invoke.AsTypeHandle.invokeExact_thunkArchetype_X(AsTypeHandle.java:49)
          at java.lang.invoke.MethodHandle.resolveInvokeDynamic(MethodHandle.java:841)
          ... 120 more
[9/20/18 18:35:36:921 MSK] 00000089 FfdcProvider  W
  com.ibm.ws.ffdc.impl.FfdcProvider logIncident FFDC1003I: FFDC Incident
  emitted on
  /opt/IBM/WebSphere/AppServer/profiles/AppSrv01/logs/ffdc/server1_49377909_18.09.20_18.35.36.9168814475377962815599.txt
  com.ibm.ws.webcontainer.webapp.WebGroup 131 [9/20/18 18:35:36:924 MSK]
  00000089 webapp        E com.ibm.ws.webcontainer.webapp.WebGroupImpl
  WebGroup SRVE0015E: Failure to initialize Web application Tomcat Host
  Manager springboot.Application [9/20/18 18:35:36:929 MSK] 00000089
  DeployedAppli W   WSVR0206E: Module, SBRiskDataSvcs.war, of
  application, myApp.ear/deployments/myApp, failed to start [9/20/18
  18:35:36:932 MSK] 00000089 ApplicationMg W   WSVR0101W: An error
  occurred starting, myApp [9/20/18 18:35:36:932 MSK] 00000089
  ApplicationMg A   WSVR0217I: Stopping application: myApp [9/20/18
  18:35:36:942 MSK] 00000089 ApplicationMg A   WSVR0220I: Application
  stopped: myApp [9/20/18 18:35:36:945 MSK] 00000089 CompositionUn E
  WSVR0194E: Composition unit WebSphere:cuname=myApp in BLA
  WebSphere:blaname=myApp failed to start. [9/20/18 18:35:36:955 MSK]
  00000089 FfdcProvider  W com.ibm.ws.ffdc.impl.FfdcProvider logIncident
  FFDC1003I: FFDC Incident emitted on
  /opt/IBM/WebSphere/AppServer/profiles/AppSrv01/logs/ffdc/server1_49377909_18.09.20_18.35.36.9468746152542961403991.txt
  com.ibm.ws.runtime.component.CompositionUnitMgrImpl 679 [9/20/18
  18:35:36:970 MSK] 00000089 FfdcProvider  W
  com.ibm.ws.ffdc.impl.FfdcProvider logIncident FFDC1003I: FFDC Incident
  emitted on
  /opt/IBM/WebSphere/AppServer/profiles/AppSrv01/logs/ffdc/server1_49377909_18.09.20_18.35.36.9567976105862242199088.txt
  com.ibm.ws.management.AdminServiceImpl.invoke 679 [9/20/18
  18:35:36:971 MSK] 00000089 MBeanHelper   E   Could not invoke an
  operation on object:
  WebSphere:name=ApplicationManager,process=server1,platform=proxy,node=wasNode01,version=8.5.5.13,type=ApplicationManager,mbeanIdentifier=ApplicationManager,cell=wasNode01Cell,spec=1.0
  because of an mbean exception: com.ibm.ws.exception.RuntimeWarning:
  com.ibm.ws.webcontainer.exception.WebAppNotLoadedException: Failed to
  load webapp: Failed to load webapp: java.lang.LinkageError: loading
  constraint violation when overriding method
  "org/springframework/boot/context/config/ConfigFileApplicationListener$DocumentFilterFactory.getDocumentFilter(Lorg/springframework/boot/context/config/ConfigFileApplicationListener$Profile;)Lorg/springframework/boot/context/config/ConfigFileApplicationListener$DocumentFilter;"
  during creation of class
  "org/springframework/boot/context/config/ConfigFileApplicationListener$Loader$$Lambda$330/0000000039C78270":
  loader
  "java/lang/InternalAnonymousClassLoader@d1c57825"
  of class
  "org/springframework/boot/context/config/ConfigFileApplicationListener$Loader$$Lambda$330/0000000039C78270"
  and loader
  "com/ibm/ws/classloader/CompoundClassLoader@9d596fe4"
  of class
  "org/springframework/boot/context/config/ConfigFileApplicationListener$DocumentFilterFactory"
  have different types for the method signature

A: Рабочее решение для IBM WAS ND 8.5.0 напрямую реализовать WebApplicationInitializer даже оставим методы пустыми.
https://stackoverflow.com/questions/21714642/cannot-deploy-spring-app-to-websphere


text:
Q: Javascript file causing Ionic app to crash I'm trying to create a new angular service for my Ionic app, however the new javascript file is 'mysteriously' causing the app to behave inappropriately, for e.g. when I call the $cordova.getDevice() method it returns me the results that would usually get from call CacheFactory.get("cache_key").
I tried removing all the code from the file, even with the code there were error reported in the console, I tried changing the name of the service.Although there is barely any code in the .js file, it still causes the app to crash.
The only thing that works is removing the completely removing the file reference from the index.html file, thereafter the app behaves normally.
Here's the angular service:
function() {
'use strict';
angular.module('starter').factory('TokenService', ['$http', '$q', '$ionicLoading', 'StringService', TokenService]);

function TokenService($http, $q, $ionicLoading, StringService){

}
})();

As mentioned previously, even with the little code it has, it still causes issues.


text:
Q: Determine P(D|C,F) from P(D), P(F) and P(C|D,F) How do I determine $P(A|B,C)$ when the following is known: $P(A)$, $P(C)$, $P(B|A,C)$
I do understand the Bayes theorem that states:
$P(A|B,C) = P(A,B|C)/P(B|C)$
However, I am failing to see how I can rearrange my given probabilities to work out the answer using Bayes or probability addition/multiplication rules.