text:
Q: soap address location contains docker service name instead of domain name I have a spring boot soap web service which runs in a docker container. The spring boot application is exposed on port 8081 and this is the Spring configuration
    @Bean
    public ServletRegistrationBean messageDispatcherServlet(ApplicationContext context) {
        MessageDispatcherServlet servlet = new MessageDispatcherServlet();
        servlet.setApplicationContext(context);
        servlet.setTransformWsdlLocations(true);
        return new ServletRegistrationBean(servlet, "/ws/*");
    }

    @Bean
    public XsdSchema userSchema() {
        return new SimpleXsdSchema(new ClassPathResource("users.xsd"));
    }

    @Bean(name = "user")
    public DefaultWsdl11Definition defaultWsdl11Definition(XsdSchema userSchema) {

        DefaultWsdl11Definition definition = new DefaultWsdl11Definition();
        definition.setSchema(userSchema);
        definition.setLocationUri("/ws");
        definition.setPortTypeName("UserServicePort");
        definition.setTargetNamespace("http://demo.example.com/user");
        return definition;
    }

And following is the docker compose file for this application and I have exposed this application through a traefik load balancer
version: '3.0'

services:
   hello-app:
     image: hello
     labels:
      - traefik.enable=true
      - traefik.port=8081
     networks:
      - web
     deploy:
      replicas: 1

networks:
  web:
    external: true

And this is the configuration for traefik. It will redirect requests which comes for http://localhost/mydomain to http://hello-app:8081
[entryPoints]
 [entryPoints.http]
  address = ":80"

[api]
dashboard = true

[file]
  [backends]

    [backends.mydomain]
      [backends.mydomain.servers.server]
      url = "http://hello-app:8081"

    [frontends.mydomain]
    entryPoints = ["http"]
    backend = "mydomain"
      [frontends.mydomain.routes.traefik]
      rule = "PathPrefixStrip:/mydomain"

[docker]

My problem is that when I get the WSDL for this URL it contains http://hello-app:8081/ws as the soap address location.

When I create a soap project in SOAP UI using the wsdl http://localhost/mydomain/ws/user.wsdl
I get http://hello-app:8081/ws as the request address which is incorrect. It should be http://localhost/mydomain/ws/

So how do I configure the soap:address location to be <soap:address location="http://localhost/mydomain/ws"/>
in the wsdl.


text:
Q: For each date, print event three time How to print for each elements from the list date  three elements from the event list
    @Test
    public void Container() throws InterruptedException {

        List<WebElement> date = driver.findElements(
            By.cssSelector("td.first.member-area"));
        List<WebElement> event = driver.findElements(
            By.cssSelector("span.selection-link.normal"));

        System.out.println(date.size());
        System.out.println(" =============== Offer ================= ");

        for (int j = 0; j < date.size(); j++) {
            System.out.println(date.get(j).getText() + "\t - " + event.get(j).getText() ) ;
        }
}

A: It sounds like you want to use nested loops.
for (int j = 0; j < date.size(); j++) {
    System.out.println(date.get(j).getText());
    for(int i = 0; i < 3; i++){
        System.out.println(event.get(i).getText());
    }
}

Hope this helps!

redpajama_set_name: RedPajamaStackExchange


text:
Q: Giving a two dates (or two months) detect in what season we are in PHP I would like to know if there is some easy way to identify seasons: spring, summer, autumn or winter. I'm have to generate a 'resume' and I'd like that if a period of working roughly fits a season (not exactly but with a +/-10 days error for example) it returns spring, summer, autumn or winter.
Like:

*

*input: 25/06/2010, 30/09/2010

*output: Summer 2010

(In Spain summer is between 21 July and 20 September)

*

*input: 02/02/2009, 30/04/2010

*output: 2009-2010

Any idea  how to do this?

A: Looks like this guy got that function written already : http://biostall.com/get-the-current-season-using-php
Even has hemisphere support !
But this should do the trick :
<?php
    function getSeason($date) {
        $season_names = array('Winter', 'Spring', 'Summer', 'Fall');
        if (strtotime($date) < strtotime($date_year.'-03-21') || strtotime($date) >= strtotime($date_year.'-12-21')) {
            return $season_names[0]; // Must be in Winter
        } elseif (strtotime($date) >= strtotime($date_year.'-09-23')) {
            return $season_names[3]; // Must be in Fall
        } elseif (strtotime($date) >= strtotime($date_year.'-06-21')) {
            return $season_names[2]; // Must be in Summer
        } elseif (strtotime($date) >= strtotime($date_year.'-03-21')) {
            return $season_names[1]; // Must be in Spring
        }
    }

A: As you are looking for a season for a period I quickly wrote this function, it can be improve and may have some bugs but you have somewhere to start.
function season($period)
{
    $seasons    = array(
        'spring'    => array('March 21'     , 'June 20'),
        'summer'    => array('June 21'      , 'September 22'),
        'fall'      => array('September 23' , 'December 20'),
        'winter'    => array('December 21'  , 'March 20')
    );

    $seasonsYear = array();

    $start      = strtotime($period[0]);
    $end        = strtotime($period[1]);

    $seasonsYear[date('Y', $start)] = array();

    if (key(current($seasonsYear)) != date('Y', $end))
        $seasonsYear[date('Y', $end)] = array();

    foreach ($seasonsYear as $year => &$seasonYear)
        foreach ($seasons as $season => $period)
            $seasonYear[$season] = array(strtotime($period[0].' '.$year), strtotime($period[1].' '.($season != 'winter' ? $year : ($year+1))));

    foreach ($seasonsYear as $year => &$seasons) {
        foreach ($seasons as $season => &$period) {
            if ($start >= $period[0] && $end <= $period[1])
                return ucFirst($season).' '.$year;

            if ($start >= $period[0] && $start <= $period[1]) {
                if (date('Y', $end) != $year)
                    $seasons = $seasonsYear[date('Y', $end)];
                    $year = date('Y', $end);

                $nextSeason = key($seasons);
                $nextPeriod = current($seasons);
                do {
                    $findNext   = ($end >= $nextPeriod[0] && $end <= $nextPeriod[1]);

                    $nextSeason = key($seasons);
                    $nextPeriod = current($seasons);
                } while ($findNext = False);

                $diffCurr   = $period[1]-$start;
                $diffNext   = $end-$nextPeriod[0];

                if ($diffCurr > $diffNext)
                    return ucFirst($season).' '.$year;
                else {
                    return ucFirst($nextSeason).' '.$year;
                }
            }
        }
    }
}

echo season(array('07/20/2010', '08/20/2010'));
echo "\n";
echo season(array('06/25/2010', '09/30/2010'));
echo "\n";
echo season(array('08/25/2010', '11/30/2010'));
echo "\n";
echo season(array('12/21/2010', '01/01/2011'));
echo "\n";
echo season(array('12/21/2010', '03/25/2011'));

Result:
/*
Summer 2010
Summer 2010
Fall 2010
Winter 2010
Winter 2011
*/

And the except you want for "season year overflow":
if (date('Y', $end) != $year)
    return $year.'-'.date('Y', $end);

Instead of:
if (date('Y', $end) != $year)
    $seasons = $seasonsYear[date('Y', $end)];
    $year = date('Y', $end);

Note: Winter is coming.

A: Here's a rough overview of what you need to do:

*

*Work out when your season boundarys are going to be. This is a big, big job if you're going to do this for an international scope!

*When presented with a date range, first work out exactly how many days of that range are in each season.
You want output like:
 Range | Days | complete?
  Su10 |  12  |     0
   A10 |  90  |     1
   W10 |  02  |     0

*

*Once this is done you'll need to identify if a single season is 'complete', which should be 1 if the whole season is worked, within 10 days. If it is, choose that season. If more are complete, or none, return false.


text:
Q: Android M request permission non activity My widget makes calls to secure permissions outside of an Activity scope. Is it possible to request permissions for Android M outside of an Activity?

A: I found a workaround which seems to work fine. The trick is to create a transparent activity which is only there to request the permissions and is finished immediately afterwards. You'll still need a context of course but it doesn't have to be an activity.
The activity can return the result (granted or denied) via a broadcast (since startActivtyForResult is not possible outside of an activity).
You can use this activity:
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.support.v4.app.ActivityCompat
import android.support.v7.app.AppCompatActivity

internal const val PERMISSIONS_KEY = "permissions"
internal const val ACTION_PERMISSIONS_GRANTED = "GetPermissionsActivity.permissions_granted"
internal const val ACTION_PERMISSIONS_DENIED = "GetPermissionsActivity.permissions_denied"

class GetPermissionsActivity: AppCompatActivity() {

    private val permissionRequestCode = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        ActivityCompat.requestPermissions(
            this,
            intent.getStringArrayExtra(PERMISSIONS_KEY),
            permissionRequestCode
        )
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        if (requestCode == permissionRequestCode) {
            if ((grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)) {
                sendBroadcast(Intent(ACTION_PERMISSIONS_GRANTED))
            } else {
                sendBroadcast(Intent(ACTION_PERMISSIONS_DENIED))
            }
            finish()
        } else {
            super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        }
    }
}

And this style for the activity
<style name="Theme.Transparent" parent="Theme.AppCompat">
    <item name="android:windowIsTranslucent">true</item>
    <item name="android:windowBackground">@android:color/transparent</item>
    <item name="android:windowContentOverlay">@null</item>
    <item name="android:windowNoTitle">true</item>
    <item name="android:windowIsFloating">true</item>
    <item name="android:backgroundDimEnabled">false</item>
    <item name="android:windowAnimationStyle">@null</item>
</style>

In the manifest:
<activity android:name="GetPermissionsActivity" android:theme="@style/Theme.Transparent" />

And then use it like this (context required)
class SomeClass : BroadcastReceiver() {

    private fun someFunction(context: Context) {
        val intentFilter = IntentFilter()
        intentFilter.addAction(ACTION_PERMISSIONS_GRANTED)
        intentFilter.addAction(ACTION_PERMISSIONS_DENIED)
        context.registerReceiver(this, intentFilter)
        val intent = Intent(context, GetPermissionsActivity::class.java)
        intent.putExtra(PERMISSIONS_KEY, arrayOf(<your permissions>))
        context.startActivity(intent)
    }

    override fun onReceive(context: Context, intent: Intent) {
        when {
            intent.action == ACTION_PERMISSIONS_GRANTED -> {
                context.unregisterReceiver(this)
                onPermissionsGranted()
            }
            intent.action == ACTION_PERMISSIONS_DENIED -> {
                context.unregisterReceiver(this)
                onPermissionsDenied()
            }
            else -> super.onReceive(context, intent)
        }
    }

    private fun onPermissionsGranted() {
        // ...
    }

    private fun onPermissionsDenied() {
        // ...
    }
}

A: No, it's not possible. What you can do is to send a notification where the user can tap and then use an activity to request/manage the permission (maybe with dialog theme).

A: You could use the Easy Permissions library.
Android requires that these request come from an Activity. With Easy Permissions this is no longer an issue, you may request permission from anywhere as long as you provide Context. In addition, if you request a permission that is already granted the user will not be prompted.

Full disclosure, our company manages and develops this free to use library. That being said, we are confident that it is a useful tool and we would not share it otherwise.

A: You can only request permission either from Activity or from fragment.
Figure out a point in your Activity or Fragment where you feel App will require a permission, then call requestPermission method. sending notification will not work because you wanna your code processing un-till you get that requested permissions, and then resume your functionality from onRequestPermissionResult() method.

A: I think it's possible to request a permission outside of an Activity, as long as you use the method
ActivityCompat.requestPermissions (Activity activity, String[] permissions, int requestCode)
from the support library and pass the Activity as a parameter of the method.
For example:
ActivityCompat.requestPermissions(targetActivity, new String[] {Manifest.permission.CAMERA}, PERMISSION_REQUEST_CODE);

where targetActivity is the Activity that should implement the method:
onRequestPermissionsResult (int requestCode, String[] permissions, int[] grantResults)
That's the method that will handle de permission request result.

A: I was creating an app that required to check for permissions in many activities, so I created a static class that I could use globally in the app.
And it worked.
This worked for me.
I created a method to check request for permissions in a different class like this.
public class CheckForPermissions implements ActivityCompat.OnRequestPermissionsResultCallback {
private static final int MY_PERMISSIONS_REQUEST_READ_LOCATION = 1;

    public static void checkForLocationPermissions(Activity context){
        if(ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION)  != PackageManager.PERMISSION_GRANTED
        || ContextCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION)  != PackageManager.PERMISSION_GRANTED){
            ActivityCompat.requestPermissions(context,
                    new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                    MY_PERMISSIONS_REQUEST_READ_LOCATION);

    }
}}

In my Activity, I called the method like this
        CheckForPermissions.checkForLocationPermissions(this);


text:
Q: Request factory is sending back the entire List even if only one element is altered When I load an entity proxy which has a nested collection of entity proxies (eg: AddressBook entity proxy containing a list of Contact proxies) and if I make changes to the inner list ( the List of Contacts) like removal of an item, and call a persist on it, Request Factory is sending the entire list of contacts. Is this the expected behaviour, or is it supposed to send only a command to delete the item on the server also?
The question is, does request factory send deltas just for field level changes, or does it calculate deltas for collections also?
ContactProxy
interface ContactProxy extends EntityProxy {

    ...

    //Getters and setters for firstName, lastName, phoneNumber etc...

    ...
}

AddressBookProxy
interface AddressBookProxy extends EntityProxy {

      ...

      List<ContactProxy> getContacts();
      void setContacts(List<ContactProxy> contacts);

      ...

}

Focus code:
//Assume I received an abProxy from a previous context.

AddressBookRequestContext context = requestFactory.requestContext();

abProxy = context.edit(abProxy);

abProxy.getContacts().remove(0);

context.persist().using(abProxy).fire();

The above piece of code is sending the entire list of contacts received in the previous context, but I expected to send only a delete command to the server. Am I doing something wrong?
Now when I make a change to a single contact in the AddressBook entity proxy and make a call to persist, it is still sending the entire list of contacts. What is the workaround to get deltas working for these kind of collection level changes.

A: You're modifying the list from a list of 10 elements to a list of 9 elements, so RF sends the new list of 9 elements (and will call the setter with the new list on the server side).
However, it only sends the IDs of the contacts, not their properties, because those haven't changed (and yes, it means all contacts will have to be retrieved on the server-side, in order to populate the new list of 9 elements, before setting it into the address book).
There's probably room for improvement in RF though: when you edit() a proxy, it automatically edits all the proxies it references (recursively), so all 10 contacts are edit()ed, and thus all 10 contacts IDs are sent to the server, an all 10 contacts are retrieved from the database and validated, even though only 9 of them are used afterwards. As a result (and that could be seen as a feature) in the event the removed contact has been updated since originally retrieved on the client, the server will send an EntityProxyChange for the contact to the client in the response.
In a few words: there's no magic, everything comes to a cost, so be careful when designing your "APIs"; you might want to add a removeContact method to your RequestContext instead of modifying the list (and retrieve the address book again –batched in the same RequestContext– to get the update on the client-side)


text:
Q: Improve a query from Explain results I have a complex query that is dynamically assembled based upon search criteria. However, in its simplest form, it is still very slow. The main table it runs against has ~10M records. I ran an explain against a 'base' query and the first row of the explain looks bad (at least to a novice dba like me). I have read a couple tutorials about EXPLAIN, but I still am unsure how to fix the query. So, the first row of the results seems to indicate the problem, but I don't know what to do with it. I couldn't make a composite key that long even if I wanted to and some of the field names in that possible_keys column are not even in the patients table. Any help will be greatly appreciated.
   id,select_type,table,type,possible_keys,key,key_len,ref,rows,Extra
1,SIMPLE,patients,range,"PRIMARY,location,appt_date,status,radiologist,contract,lastname,paperwork,images_archived,hash,created,document_attached,all_images_archived,last_image_archived,modality,study_uid,company,second_access,firstname,report_delivered,ssn,order_entry_status,dob,tech,doctor,mobile_facility,accession,location_appt_date,location_created,location_lastname,ref,person_seq",location_appt_date,55,NULL,573534,"Using index condition; Using where; Using temporary; Using filesort"
1,SIMPLE,receivable_transactions,ref,patient_seq,patient_seq,4,ris-dev.patients.seq,1,NULL
1,SIMPLE,patients_dispatch,ref,patient_seq,patient_seq,4,ris-dev.patients.seq,1,NULL
1,SIMPLE,mobile_facility,ref,"unique_index,name,location",unique_index,115,"ris-dev.patients.mobile_facility,const",1,"Using where"
1,SIMPLE,mobile_facility_service_areas,eq_ref,PRIMARY,PRIMARY,4,ris-dev.mobile_facility.service_area,1,NULL

Edit: same EXPLAIN, but reformatted to be easier to read:
id select_type table                         type   possible_keys        key                key_len ref                                    rows   Extra

1  SIMPLE      patients                      range  PRIMARY              location_appt_date 55      NULL                                   573534 Using index condition; Using where; Using temporary; Using filesort
                                                    location
                                                    appt_date
                                                    status
                                                    radiologist
                                                    contract
                                                    lastname
                                                    paperwork
                                                    images_archived
                                                    hash
                                                    created
                                                    document_attached
                                                    all_images_archived
                                                    last_image_archived
                                                    modality
                                                    study_uid
                                                    company
                                                    second_access
                                                    firstname
                                                    report_delivered
                                                    ssn
                                                    order_entry_status
                                                    dob
                                                    tech
                                                    doctor
                                                    mobile_facility
                                                    accession
                                                    location_appt_date
                                                    location_created
                                                    location_lastname
                                                    ref
                                                    person_seq

1  SIMPLE      receivable_transactions       ref    patient_seq          patient_seq        4       ris-dev.patients.seq                   1      NULL
1  SIMPLE      patients_dispatch             ref    patient_seq          patient_seq        4       ris-dev.patients.seq                   1      NULL
1  SIMPLE      mobile_facility               ref    unique_index         unique_index       115     ris-dev.patients.mobile_facility,const 1      Using where
                                                    name
                                                    location
1  SIMPLE      mobile_facility_service_areas eq_ref PRIMARY              PRIMARY            4       ris-dev.mobile_facility.service_area   1      NULL

The explain is setup against the following query and table structures.
    SELECT patients.fax_in_queue, patients.modality, patients.stat, patients.created, patients.seq, patients.lastname,
patients.firstname, patients.appt_date, patients.status, patients.contract, patients.location, patients.unique_hash,
patients.images_archived, patients.report_delivered, patients.doctor, patients.mobile_facility, patients.history,
patients.dob, patients.all_images_archived, patients.order_entry_status, patients.tech, patients.radiologist,
patients.last_image_archived, patients.state, patients.ss_comments, patients.completed, patients.report_status,
patients.have_paperwork, patients.facility_room_number, patients.facility_station_name, patients.facility_bed,
patients.findings_level, patients.document_attached, patients.study_start, patients.company, patients.accession,
patients.number_images, patients.client_number_images, patients.sex, patients.threshhold , GROUP_CONCAT(CONCAT(CONCAT(receivable_transactions.modifier, " "),
receivable_transactions.description) SEPARATOR ", ") AS rt_desc , patients_dispatch.seq AS doc_seq, patients_dispatch.requisition_last_sent,
patients_dispatch.requisition_signed_by_file_seq, patients_dispatch.requisition_signed, patients_dispatch.order_reason, patients_dispatch.order_comments,
patients_dispatch.order_taken, patients_dispatch.order_tech_last_notified, patients_dispatch.order_tech_in_transit, patients_dispatch.order_tech_in,
patients_dispatch.order_tech_out, patients_dispatch.order_tech_ack, patients_dispatch.addr1 AS d_addr1, patients_dispatch.addr2 AS d_addr2,
patients_dispatch.city AS d_city, patients_dispatch.state AS d_state, patients_dispatch.zip AS d_zip, CONCAT(patients.status, order_tech_out,
order_tech_in, order_tech_in_transit) as pseudo_status , mobile_facility.requisition_fax, mobile_facility.station_list, mobile_facility.address1 as mf_addr1,
mobile_facility.address2 as mf_addr2, mobile_facility.city as mf_city, mobile_facility.state as mf_state, mobile_facility.zip as mf_zip,
mobile_facility.phone as mf_phone, mobile_facility.phone2 as mf_phone2, mobile_facility_service_areas.name as mf_service_area
FROM patients LEFT JOIN receivable_transactions ON patients.seq = receivable_transactions.patient_seq
LEFT JOIN patients_dispatch ON patients.seq = patients_dispatch.patient_seq
LEFT JOIN mobile_facility ON patients.location = mobile_facility.location AND patients.mobile_facility = mobile_facility.name
LEFT JOIN mobile_facility_service_areas ON mobile_facility.service_area = mobile_facility_service_areas.seq
WHERE patients.location = "XYZCompany"  AND  ((patients.appt_date >= '2020-03-19' AND patients.appt_date <= '2020-03-19 23:59:59')
OR (patients.appt_date <= '2020-03-19' AND patients.status < 'X'))
GROUP BY patients.seq DESC
ORDER BY patients.status, patients.order_entry_status,  pseudo_status, patients.order_entry_status,patients.lastname);

CREATE TABLE `patients` (
  `seq` int(11) NOT NULL AUTO_INCREMENT,
  `person_seq` int(11) NOT NULL,
  `firstname` varchar(20) NOT NULL DEFAULT '',
  `lastname` varchar(30) NOT NULL DEFAULT '',
  `middlename` varchar(20) NOT NULL DEFAULT '',
  `ref` varchar(50) NOT NULL DEFAULT '',
  `location` varchar(50) NOT NULL DEFAULT '',
  `doctor` varchar(50) NOT NULL,
  `radiologist` varchar(20) NOT NULL DEFAULT '',
  `contract` varchar(50) NOT NULL,
  `history` mediumtext NOT NULL,
  `dob` varchar(15) NOT NULL DEFAULT '0000-00-00',
  `appt_date` date NOT NULL DEFAULT '0000-00-00',
  `status` tinyint(4) NOT NULL DEFAULT '0',
  `tech` varchar(50) NOT NULL DEFAULT '',
  `created` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  `ss_comments` mediumtext NOT NULL,
  `mobile_facility` varchar(60) NOT NULL DEFAULT '',
  `facility_room_number` varchar(50) NOT NULL,
  `facility_bed` varchar(20) NOT NULL,
  `facility_station_name` varchar(50) NOT NULL,
  `stat` tinyint(4) NOT NULL DEFAULT '0',
  `have_paperwork` tinyint(4) NOT NULL DEFAULT '0',
  `completed` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  `sex` char(1) NOT NULL DEFAULT '',
  `unique_hash` varchar(100) NOT NULL DEFAULT '',
  `number_images` int(11) NOT NULL DEFAULT '0',
  `client_number_images` int(11) NOT NULL,
  `images_archived` tinyint(4) NOT NULL DEFAULT '0',
  `completed_fax` varchar(10) NOT NULL DEFAULT '0' COMMENT 'This is the number the completed report is faxed to.',
  `report_delivered` tinyint(4) NOT NULL DEFAULT '0',
  `report_delivered_time` datetime NOT NULL,
  `document_attached` tinyint(4) NOT NULL DEFAULT '0',
  `modality` varchar(3) NOT NULL,
  `last_image_archived` datetime NOT NULL,
  `all_images_archived` tinyint(4) NOT NULL DEFAULT '0',
  `fax_in_queue` varchar(12) NOT NULL,
  `accession` varchar(100) NOT NULL,
  `study_uid` varchar(100) NOT NULL,
  `order_entry_status` tinyint(4) NOT NULL,
  `compare_to` varchar(15) NOT NULL,
  `state` varchar(3) NOT NULL,
  `company` int(11) NOT NULL,
  `second_access` varchar(50) NOT NULL,
  `threshhold` datetime NOT NULL,
  `report_status` tinyint(4) NOT NULL,
  `second_id` varchar(50) NOT NULL,
  `rad_alerted` tinyint(4) NOT NULL,
  `assigned` datetime NOT NULL,
  `findings_level` tinyint(4) NOT NULL,
  `report_viewed` tinyint(4) NOT NULL,
  `study_received` datetime NOT NULL,
  `study_start` datetime NOT NULL,
  `study_end` datetime NOT NULL,
  `completed_email` varchar(50) NOT NULL,
  `completed_send` varchar(255) NOT NULL,
  `ssn` varchar(12) NOT NULL,
  `exorder_number` varchar(30) NOT NULL,
  `exvisit_number` varchar(30) NOT NULL,
  `row_updated` timestamp NOT NULL ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`seq`),
  KEY `location` (`location`),
  KEY `appt_date` (`appt_date`),
  KEY `status` (`status`),
  KEY `radiologist` (`radiologist`),
  KEY `contract` (`contract`),
  KEY `lastname` (`lastname`),
  KEY `paperwork` (`have_paperwork`),
  KEY `images_archived` (`images_archived`),
  KEY `hash` (`unique_hash`),
  KEY `created` (`created`),
  KEY `document_attached` (`document_attached`),
  KEY `all_images_archived` (`all_images_archived`),
  KEY `last_image_archived` (`last_image_archived`),
  KEY `modality` (`modality`),
  KEY `study_uid` (`study_uid`),
  KEY `company` (`company`),
  KEY `second_access` (`second_access`),
  KEY `firstname` (`firstname`),
  KEY `report_delivered` (`report_delivered`),
  KEY `ssn` (`ssn`),
  KEY `order_entry_status` (`order_entry_status`),
  KEY `dob` (`dob`),
  KEY `tech` (`tech`),
  KEY `doctor` (`doctor`),
  KEY `mobile_facility` (`mobile_facility`),
  KEY `accession` (`accession`),
  KEY `location_appt_date` (`location`,`appt_date`),
  KEY `location_created` (`location`,`created`),
  KEY `location_lastname` (`location`,`lastname`),
  KEY `ref` (`ref`),
  KEY `person_seq` (`person_seq`)
) ENGINE=InnoDB AUTO_INCREMENT=10242952 DEFAULT CHARSET=latin1;

CREATE TABLE `receivable_transactions` (
  `seq` int(11) NOT NULL AUTO_INCREMENT,
  `patient_seq` int(11) NOT NULL DEFAULT '0',
  `cptcode` varchar(15) NOT NULL DEFAULT '',
  `modifier` char(2) NOT NULL DEFAULT '',
  `description` varchar(100) NOT NULL DEFAULT '',
  `amount` decimal(6,2) NOT NULL DEFAULT '0.00',
  `type` char(2) NOT NULL DEFAULT '',
  `transaction` varchar(10) NOT NULL DEFAULT '',
  `radiologist` varchar(20) NOT NULL DEFAULT '',
  `status` tinyint(4) NOT NULL DEFAULT '0',
  `completed` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  `created` datetime NOT NULL DEFAULT '0000-00-00 00:00:00',
  `report_meta_seq` int(11) NOT NULL DEFAULT '0',
  `report_header` varchar(255) NOT NULL,
  `report_body` blob NOT NULL,
  `report_impression` mediumtext NOT NULL,
  `report_hide` tinyint(4) NOT NULL,
  `radiologist_group` varchar(50) NOT NULL,
  `addendum` int(4) NOT NULL DEFAULT '0',
  `addendum_type` varchar(20) NOT NULL,
  `peer_review` int(4) NOT NULL DEFAULT '0',
  `qa_reason` varchar(255) NOT NULL DEFAULT '',
  `qa_agree` decimal(2,1) NOT NULL DEFAULT '0.0',
  `findings` tinyint(4) NOT NULL,
  `comments` mediumtext NOT NULL,
  `company` int(11) NOT NULL,
  `row_updated` timestamp NOT NULL ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY (`seq`),
  KEY `patient_seq` (`patient_seq`),
  KEY `cptcode` (`cptcode`),
  KEY `transaction` (`transaction`),
  KEY `type` (`type`),
  KEY `created` (`created`),
  KEY `radiologist` (`radiologist`),
  KEY `status` (`status`),
  KEY `report_meta_seq` (`report_meta_seq`),
  KEY `Billing Check Dropdown` (`status`,`completed`),
  KEY `qa_agree` (`qa_agree`),
  KEY `peer_review` (`peer_review`),
  KEY `addendum` (`addendum`),
  KEY `company` (`company`),
  KEY `completed` (`completed`)
) ENGINE=InnoDB AUTO_INCREMENT=9380351 DEFAULT CHARSET=latin1;

CREATE TABLE `patients_dispatch` (
  `seq` int(11) NOT NULL AUTO_INCREMENT,
  `patient_seq` int(11) NOT NULL,
  `order_taken` datetime NOT NULL,
  `order_taken_by` varchar(50) NOT NULL,
  `order_person_calling` varchar(50) NOT NULL,
  `order_supervising_physician` varchar(50) NOT NULL,
  `order_trip_count` tinyint(4) NOT NULL,
  `order_trip_count_max` tinyint(4) NOT NULL,
  `order_trip_visit` tinyint(4) NOT NULL,
  `order_tech_in` datetime NOT NULL,
  `order_tech_out` datetime NOT NULL,
  `order_ssn` varchar(12) NOT NULL,
  `order_service_request_time` datetime NOT NULL,
  `order_reason` varchar(255) NOT NULL,
  `order_tech_ack` datetime NOT NULL,
  `order_tech_assigned` datetime NOT NULL,
  `order_tech_last_notified` datetime NOT NULL,
  `requisition_last_sent` datetime NOT NULL,
  `requisition_signed` datetime NOT NULL,
  `requisition_signed_by` varchar(50) NOT NULL,
  `requisition_signed_by_text` varchar(75) NOT NULL,
  `requisition_signed_by_file_seq` int(11) NOT NULL,
  `order_comments` mediumtext NOT NULL,
  `order_tech_in_transit` datetime NOT NULL,
  `fasting` tinyint(1) NOT NULL,
  `collection_time` time DEFAULT NULL,
  `addr1` varchar(100) NOT NULL,
  `addr2` varchar(100) NOT NULL,
  `city` varchar(30) NOT NULL,
  `state` varchar(3) NOT NULL,
  `zip` varchar(12) NOT NULL,
  `phone` varchar(15) NOT NULL,
  `mileage_start` int(11) NOT NULL,
  `mileage_end` int(11) NOT NULL,
  PRIMARY KEY (`seq`),
  KEY `patient_seq` (`patient_seq`)
) ENGINE=InnoDB AUTO_INCREMENT=2261091 DEFAULT CHARSET=latin1;

CREATE TABLE `mobile_facility` (
  `seq` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(60) NOT NULL,
  `location` varchar(50) DEFAULT NULL,
  `address1` varchar(50) NOT NULL,
  `address2` varchar(50) NOT NULL,
  `city` varchar(50) NOT NULL,
  `state` varchar(2) NOT NULL,
  `zip` varchar(10) NOT NULL,
  `phone` varchar(15) NOT NULL,
  `phone2` varchar(15) NOT NULL,
  `fax` varchar(110) NOT NULL,
  `rads_can_read` text NOT NULL,
  `rads_cant_read` text NOT NULL,
  `only_techs` text NOT NULL,
  `never_modalities` varchar(255) NOT NULL COMMENT 'A serialized list of modalities a facility may not use.',
  `station_list` mediumtext NOT NULL,
  `email` varchar(255) NOT NULL,
  `misc1` varchar(255) NOT NULL,
  `latitude` float NOT NULL DEFAULT '0',
  `longitude` float NOT NULL DEFAULT '0',
  `affiliation` int(11) NOT NULL COMMENT 'mobile_facility_affiliations seq',
  `branch` int(11) NOT NULL COMMENT 'mobile_facility_branches seq',
  `service_area` int(11) NOT NULL COMMENT 'mobile_facility_service_areas seq',
  `other_id` varchar(50) NOT NULL COMMENT 'Usually used for HL7',
  `facility_type` varchar(2) DEFAULT NULL,
  `no_stat` tinyint(1) NOT NULL DEFAULT '0' COMMENT 'Should the facility allow stat priority on patients?',
  `facility_notes` varchar(512) DEFAULT NULL,
  `requisition_fax` varchar(110) NOT NULL,
  `report_template` text NOT NULL,
  `all_orders_stat` tinyint(1) NOT NULL,
  `sms_notification` varchar(15) NOT NULL,
  `tat` varchar(10) NOT NULL,
  `npi` varchar(15) NOT NULL,
  `NMXR` tinyint(4) NOT NULL DEFAULT '0',
  `billing_type` varchar(10) NOT NULL,
  `salesman` varchar(75) NOT NULL,
  `created_at` datetime NOT NULL,
  `updated_at` datetime NOT NULL,
  `default_bill_to` tinyint(4) NOT NULL DEFAULT '0',
  PRIMARY KEY (`seq`),
  UNIQUE KEY `unique_index` (`name`,`location`),
  KEY `name` (`name`),
  KEY `location` (`location`)
) ENGINE=InnoDB AUTO_INCREMENT=155104 DEFAULT CHARSET=latin1;

CREATE TABLE `mobile_facility_service_areas` (
  `seq` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(50) NOT NULL,
  `location` varchar(50) NOT NULL,
  PRIMARY KEY (`seq`)
) ENGINE=InnoDB AUTO_INCREMENT=841 DEFAULT CHARSET=latin1;

A: It's only using the index on location, but that only narrows down the search to about a half a million rows. You'd like it to use an index to further narrow down by the appt_date.
However, the use of OR in your WHERE clause is causing a problem. It can't decide how to use the index.
Here's what I suggest:

*

*Drop the index on location because it's redundant with the other indexes that have location as their first column.

*Replace the index on location_appt_date with an index on location_appt_date_status.
ALTER TABLE patients
  DROP KEY location,
  DROP KEY location_appt_date,
  ADD KEY location_appt_date_status (location, appt_date, status);

*Refactor the query to use UNION instead of OR:
SELECT ... (all the columns you have) ...
FROM (
        SELECT * FROM patients USE INDEX (location_appt_date_status)
        WHERE location = 'XYZCompany' AND appt_date >= '2020-03-19' AND appt_date < '2020-03-20'
        UNION
        SELECT * FROM patients USE INDEX (location_appt_date_status)
        WHERE location = 'XYZCompany' AND appt_date <= '2020-03-19' AND status < 'X'
) AS p
LEFT JOIN receivable_transactions FORCE INDEX (patient_seq)
  ON p.seq = receivable_transactions.patient_seq
LEFT JOIN patients_dispatch FORCE INDEX (patient_seq)
  ON p.seq = patients_dispatch.patient_seq
INNER JOIN mobile_facility FORCE INDEX (unique_index)
  ON p.location = mobile_facility.location AND p.mobile_facility = mobile_facility.name
INNER JOIN mobile_facility_service_areas FORCE INDEX (PRIMARY)
  ON mobile_facility.service_area = mobile_facility_service_areas.seq
GROUP BY p.seq
ORDER BY p.status, p.order_entry_status, pseudo_status, p.order_entry_status, p.lastname

You might not need all the USE INDEX() / FORCE INDEX() optimizer hints I used. I did those because I was testing with empty tables, and that can confuse the optimizer.

A: Let me focus on the part that affects optimization the most:
    FROM  patients AS p
    LEFT JOIN  receivable_transactions AS rt  ON p.seq = rt.patient_seq
    LEFT JOIN  patients_dispatch AS pd  ON p.seq = pd.patient_seq
    LEFT JOIN  mobile_facility AS mf  ON p.location = mf.location
      AND  p.mobile_facility AS mf = mf.name
    LEFT JOIN  mobile_facility_service_areas AS sa  ON mf.service_area = sa.seq
    WHERE  p.location = "XYZCompany"
      AND  ((p.appt_date >= '2020-03-19'
                      AND  p.appt_date <= '2020-03-19 23:59:59')
              OR  (p.appt_date <= '2020-03-19'
                      AND  p.status < 'X')
           )
    GROUP BY  p.seq DESC
    ORDER BY  p.status, p.order_entry_status, pseudo_status, p.order_entry_status,
        p.lastname);

The biggest issue is the OR.  It often prevents most optimizations.  The usual fix is to turn it into a UNION:
( SELECT ...
    FROM .. JOIN ..
    WHERE p.location = "XYZCompany"
      AND  p.appt_date >= '2020-03-19'
      AND  p.appt_date  < '2020-03-19' + INTERVAL 1 DAY
   ...
)
UNION ALL
( SELECT ...
    FROM .. JOIN ..
    WHERE p.location = "XYZCompany"
      AND  p.appt_date <= '2020-03-19'
      AND  p.status < 'X'
   ...
)

Each select can benefit from this composite index on patients:
(location, appt_date, status)

The < 'X' is problematic because two ranges (appt_date and status) cannot both be used effectively.  What are the possible values of status?  If there is only one value before 'X', say 'M', then this would be much better:  p.status = 'M' together with another index: (location, status, appt_date)
SELECT lots of stuff, then GROUP BY p.seq -- This is probably create strange results.  (Search for ONLY_FULL_GROUP_BY for more discussion).  It may be better to first get the patients.seq values (since that is all you are filtering on), then join to the other tables.  This would eliminate the GROUP BY, or at least force you to deal with which row to fetch from each of the other tables.
range location_appt_date 55 573534 Using index condition; Using where; Using temporary; Using filesort -- says

*

*55 = 2+50 (for varchar(50)) + 3 (for date) -- neither is NULL.

*Based on the 55, I wonder if it is so well optimized that the OR->UNION is not needed.

*"Using index condition" is internally called ICP (Index Condition Pushdown) if you want further understanding.

*"Using filesort" may be an understatement -- There are probably two sorts, one for GROUP BY, one for ORDER BY.  EXPLAIN FORMAT=JSON SELECT ... would make it clear.  (And hence my hint that the GROUP BY should be avoided.

You have some redundant indexes (not relevant to much other than disk space):  INDEX(a,b), INDEX(a) --> toss INDEX(a).
patients has an awful number of indexes.
The other tables seem to have adequate indexes for your query.


text:
Q: how to make only one side to be observed in android studio/kotlin/observer/ Now, regardless of pageNum, definitely observing both sides(userRecent/userSaved)
this is Fragment
        overViewModel.userResent.observe(viewLifecycleOwner, Observer { userlist ->
            userlist?.apply {
                val pageNum = arguments?.getInt(ARG_SECTION_NUMBER)
                if (pageNum == 1) {
                    viewModelAdapter?.data = userlist
                }
            }
        })

        overViewModel.userSaved.observe(viewLifecycleOwner, Observer { userlist ->
            userlist?.apply {
                val pageNum = arguments?.getInt(ARG_SECTION_NUMBER)
                if (pageNum == 2) {
                    viewModelAdapter?.data = userlist
                }
            }
        })

How do I code so that only one side is observed?
<Currently, both userRecent and userSaved are using observe, and I am thinking about how to combine them into one.>


text:
Q: Counting operations without null values in matrix multiplication in r I have a vector a and matrix A
a = c(2,5,6)
b=cbind(c(2,7,0),c(3,0,11),c(99,0,0))
A = as.matrix(b)

I want to multiply a on matrix A and to get as the result vector which counts numbers of operations without nulls.For this example the answer should be :
2*2+5*7+6*0  (there are two operations without 0.So the answer is 2)
2*3+5*0+6*11 (there are two operations without 0.So the answer is 2)
2*99+5*0+6*0 (there is  one operation  without 0.So the answer is 1)
THe answer should be (2,2,1)

How should I solve this problem?

A: You can do something like this
>  rowSums((t(A) * a)  !=0)
[1] 2 2 1

A: We multiple 'A' with 'a', convert it to a logical matrix by comparing whether the values are not equal to 0 and get the column sums of the logical columns
colSums((A * a) != 0)
#[1] 2 2 1

Note that
A * a
#    [,1] [,2] [,3]
#[1,]    4    6  198
#[2,]   35    0    0
#[3,]    0   66    0

and
t(A) * a
#    [,1] [,2] [,3]
#[1,]    4   14    0
#[2,]   15    0   55
#[3,]  594    0    0

The values in OP's post
2*2+5*7+6*0

matches with A * a
Based on the example, as there are no zero elements in 'a'
colSums(A != 0)
#[1] 2 2 1

or using apply
apply(A, 2, FUN = function(x) sum((x * a) != 0))
#[1] 2 2 1

A: Thank you very much for your answers.
I tried to work with vector also with nulls:
d= c(0,2,4,6)
b=cbind(c(2,7,0,7),c(3,0,11,9),c(99,0,0,2),c(9,0,0,2))
B= as.matrix(b)

Then I multyply vector d to matrix B
d*B
        [,1] [,2] [,3] [,4]
  [1,]    0    0    0    0
  [2,]   14    0    0    0
  [3,]    0   44    0    0
  [4,]   42   54   12   12

the last one is to summ numbers of columns without 0:
colSums((d*B)  !=0)

PROFIT!
final code is:
d= c(0,2,4,6)
b=cbind(c(2,7,0,7),c(3,0,11,9),c(99,0,0,2),c(9,0,0,2))
B= as.matrix(b)
colSums((d*B)  !=0)


text:
Q: Mule ClassNotFoundException for class existing in a library in the class path I have a class in a Mule application which resides in a jar of a third party library. The library gets included in the lib folder after the project builds so it is definitely in the classpath. The class is then used in a Mule component. The applications deploys successfully in AnyPoint Studio'sembedded server. However, when the Mule component is processing data, Mule complains that it can't find the class.
As soon as the line with the following code snippet is encountered it throws the NoClassDefFoundError.
populator.put(ScanType.MRI,container);

Here is a portion of the stacktrace:
Root Exception stack trace:
java.lang.ClassNotFoundException: com.tcfg.utils.defn.Populator
    at java.net.URLClassLoader.findClass(URLClassLoader.java:381)
    at org.mule.module.launcher.FineGrainedControlClassLoader.findClass(FineGrainedControlClassLoader.java:175)
    at org.mule.module.launcher.MuleApplicationClassLoader.findClass(MuleApplicationClassLoader.java:134)
    at org.mule.module.launcher.FineGrainedControlClassLoader.loadClass(FineGrainedControlClassLoader.java:119)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)

I also know that this is the only instance of the class in the whole project when I use a tool to search the entire lib folder for instances of the class. This is definitely not a situation of multiple versions of the class or of other classes existing in one of the jars with a similar name. What could be the cause of this and how can I resolve it?

A: Even though if you add the jar in lib folder you need to manually add that jar to your class path.So, that it will be available.

A: They are 2 possibilities here one is there might be a need of OS specific library to be downloaded and configured in Anypoint Stduio in Run configurations like for SAP we need to point it to the DLL which windows will refer to. Giving below an example.
-Djava.library.path=C:\Users\adm-snandu\AnypointStudio\workspace\

For most of the Class Notfound errors you need to make sure the maven dependency is given in the pom.xml which takes care of downloading all the relevant libraries and referring to them during run time.


text:
Q: Python CDP client using Scapy and Pyinstaller I am trying to write a Python-based CDP client, similar to WinCDP for those familiar.  For the purposes of troubleshooting compilation I have a significantly shortened version:
# Suppress Scapy IPv6 warning
import logging
logging.getLogger("scapy.runtime").setLevel(logging.ERROR)

import re from scapy.all import *

load_contrib("cdp") class main:
    def __init__(self):
        self.filter = "ether host 01:00:0c:cc:cc:cc"
        self.interfaces = str(ifaces)
        print(self.interfaces)
        try:
            self.p = sniff(count=1,iface='Intel(R) 82578DM Gigabit Network Connection',filter=self.filter,timeout=60)
        except:
            print('OUCH!  Something went wrong.')
        else:
            print('Finished processing...')
            print("DeviceID: {}".format(self.p[0].payload["CDPMsgDeviceID"].val.decode('utf-8')))
            print("PortID: {}".format(self.p[0].payload["CDPMsgPortID"].iface.decode('utf-8')))
            print("NativeVLAN: {}".format(self.p[0].payload["CDPMsgNativeVLAN"].vlan))
            print("IPv4addr: {}".format(self.p[0].payload["CDPAddrRecordIPv4"].addr))
            print("Model: {}".format(self.p[0].payload["CDPMsgPlatform"].val.decode('utf-8')))
            print("Duplex: {}".format(self.p[0].payload["CDPMsgDuplex"].duplex))
            print("VTP Domain: {}".format(self.p[0].payload["CDPMsgVTPMgmtDomain"].val.decode('utf-8')))

if __name__ == "__main__": main()

On all versions of Python I've tried this produces results similar to the following:
INDEX  IFACE                                            IP              MAC
10     Hyper-V Virtual Ethernet Adapter                 172.31.253.241  78:15:27:01:22:F1
11     Intel(R) 82578DM Gigabit Network Connection      10.X.Y.Z     78:2B:CB:00:11:22
21     Hyper-V Virtual Ethernet Adapter #2              10.0.75.1       00:15:5D:CD:BE:03
26     Npcap Loopback Adapter                           127.0.0.1       00:00:00:00:00:00
4      VirtualBox Host-Only Ethernet Adapter #2         192.168.56.1    0A:00:27:00:00:04
9      NETGEAR WNA3100M N300 Wireless Mini USB Adapter                  2C:B0:5D:00:11:22
Finished processing...
DeviceID: switch01
PortID: GigabitEthernet5/0/29
NativeVLAN: 120
IPv4addr: 10.X.Y.Z
Model: cisco WS-C2960X-48FPD-L
Duplex: 1
VTP Domain: XYZ

I have managed to get the script to compile and it will run with the following:
pyinstaller -F cdpscript.py --hidden-import=queue

But, when the executable is run the output is:
INDEX  IFACE  IP  MAC
OUCH!  Something went wrong.

Which leads me to believe that enough of Scapy is running to print the headers of the ifaces command, but nothing else works.  This was done on Python 3.6.6 as the Pyinstaller documentation indicates this is the most recent version supported, with Scapy 2.4.0 and PyInstaller 3.3.1.
I'm hoping to be able to give my techs an executable on a USB drive they can run and get CDP information without having to install anything locally, similarly to how we had been using WinCDP.  Except, WinCDP has not been playing well with Windows 10 lately.  I am hoping to create our own version so we can do fancier stuff like stick information in a database to track our machines.  At any rate, none of this fun can happen if I can't get the script to compile into a working exe.  Also, does anyone familiar with Scapy know if NPcap is going to have to be installed on the target machines?  Any help would be greatly appreciated.


text:
Q: Android Loopj's Async JsonObject reponse is cast to Objectid failed I'm relatively new in Android & Restful API programming, so I might be making some stupid mistakes. However I am facing this from my response JsonObject:

Cast to ObjectId failed for value \"login\" at path \"_id\" for model \"User\"","name":"CastError","stringValue":"\"login\"","kind":"ObjectId","value":"login","path":"_id"}

I have tested my Rest API on Postman and everything returns just fine. The Restful API is written in Node.js and Express.
The Rest API is suppose to return a status, userid, and message to let the app know if the user logged in using the right username and password. The login works fine and it returns me a 200 which allows the app to login and keep it logged in using a session. However, I can't get anything from the response JsonObject to get the userid for my next step in displaying user information.
(Target Android API 23)
Code:
Restful.Java
public class RestClient {

    private static final String BASE_URL = "http://10.0.2.2:8000/api/";
    private static AsyncHttpClient client = new AsyncHttpClient();

    public static void get(String url, RequestParams params, AsyncHttpResponseHandler responseHandler){
        client.get(getAbsoluteUrl(url), params, responseHandler);
    }

    public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler){
        client.post(getAbsoluteUrl(url), params, responseHandler);
    }

    private static String getAbsoluteUrl(String relativeUrl){
        Log.d("URL: ", BASE_URL+relativeUrl);
        return BASE_URL + relativeUrl;
    }
}

LoginActivity.Java (Only the login part)
public void checkLoginDB(final RequestParams params, final String username){
        prgDialog.show();

        RestClient.post("user/login", params, new JsonHttpResponseHandler(){
            @Override
            public void onSuccess(int statusCode, Header[] headers, JSONArray response) {
                Log.d("StatusCode: ", "Code "+ statusCode);
                try {
                    if (statusCode == 200) {
                        Toast.makeText(getApplicationContext(), "Logged In!", Toast.LENGTH_LONG).show();
                        session.createLoginSession(username);
                        Log.d("Log: ", "what " + response);
                        navigatetoHomeActivity();
                    }
                } catch (Exception e){
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
                Log.d("StatusCode: ", "Code "+ statusCode);
                prgDialog.hide();
                Toast.makeText(getApplicationContext(), "Failed!", Toast.LENGTH_LONG).show();
            }
        });
    }

Restful API's Server.js
  router.post('/user/login', function(req, res){
    var username = req.body.username;
    var password = req.body.password;
    if(username.length > 0 && password.length > 3){
      User.findOne({username: username, password: password}, function(err, user){
        if(err)
          res.json({statusCode: 0, message: "login error: " + err});
        if(!user)
          res.json({statusCode: 0, message: "Not Found"});

        res.json({statusCode: 200, userid: user._id, message: "Login Sucessful"});
      })
    } else {
      res.json({statusCode: 0, message: "Invalid Fields"});
    }
  });

  app.use('/api', router)

User.js (Defined schema)
var mongoose = require('mongoose');
var Schema = mongoose.Schema;

var UserSchema = new Schema({
  username: String,
  password: String,
  firstname: String,
  lastname: String,
  agentID: Number,
  email: String,
  phone: Number
});

module.exports = mongoose.model('User', UserSchema);

A: Whenever you want to Login the user and want user details in return use post() method.
in your code the second method is not post, so change client.get() to client.post()
like this public static void post(String url, RequestParams params, AsyncHttpResponseHandler responseHandler){
        client.post(getAbsoluteUrl(url), params, responseHandler);
    }


text:
Q: can't get "clipboard.js" to work I can't get the clipboard.js to work; I think it's a simple "misunderstanding" about how the whole thing works, since I'm not even able to get the most simple example to work properly like in this Fiddle...
My specific problem is getting this to work:
HTML:
<button class="copyButton"
        id="copyButtonId"
        data-id="@item.Type"
        data-clipboard-action="copy"
        data-clipboard-target="#copy_@item.Type">
</button>

The div that should be copied is this:

       @item.Type
       Name...: @item.Name
       Address: @item.Address

`

The JS is:
$(function() {
$(document).on("click", ".copyButton", function() {
    var clipboard = new Clipboard(".copyButton");
    clipboard.destroy();
  });
});

I'm getting into the function, but nothing is happening. I tried:
clipboard.copy();

but that just throws me an exception...
I can get the text, that I want to copy
var id= "copy_" + $(this).attr("data-id");
   var source = ($("#" + agent).html());
But I should be able only to work it out by using clipboard.js.
I can't get any examples to work, so I would be happy if someone shows me a complete example. I've really tried to understand and I may be overthinking the whole thing and making this more complicated than it is.
I don't want any workarounds, as I used that before and think this is a great js-solution... If I could just understand it :)
Every hint into the right direction is appreciated!

A: Make sure you add the right library first ;)

Or your local min.js
I've altered your code to this:

    @item.Type
    Name...: @item.Name
    Address: @item.Address

<button class="copyButton" id="copyButtonId" data-id="@item.Type"
 data-clipboard-action="copy" data-clipboard-target="div#copy">Copy!</button>

and the js:
var clipboard = new Clipboard('.copyButton');
clipboard.on('success', function(e) {
    console.log(e);
});
clipboard.on('error', function(e) {
    console.log(e);
});

With me it copies the div now. Let me know if it doesn't for you.

A: Incase of API data use
import Clipboard from 'clipboard';
''''''
''''''
''''''
 var clipboard = new Clipboard('.class_name_of_the_div');
  clipboard.on('success', function (event) {});
  clipboard.on('error', function (evwnt) {});

data-clipboard-text={data.text}

A: Sorry, I haven't got time to read all but for the library https://www.npmjs.com/package/clipboard you can use
import ClipboardJS from 'clipboard'
and then new ClipboardJS('.btn')
or check if this import Clipboard from 'clipboard' works specially for your solution


text:
Q: how to avoid for loop using apply function in this question mat<-matrix(1:9,nrow=3,ncol=3)
for(i in 1:3){
  print(colSums(mat[1:i,]))
}

I'm trying to calculate mean of colSums of part of a matrix.

How do I avoid for loop in this case? The answer may be similar to the code below but I don't know how to proceed.
apply(mat,2,function(x) colSums(mat[]))

Thanks in advance!

A: The simplest way is to use cumsum() to get the sums and rowMeans() to get the means:
apply(mat, 2, cumsum)[2:4, ]
#      [,1] [,2] [,3] [,4]
# [1,]    3   11   19   27
# [2,]    6   18   30   42
# [3,]   10   26   42   58
rowMeans(apply(mat, 2, cumsum)[2:4, ])
# [1] 15 24 34


text:
Q: Why is my gremlin.net gremlin client not working with azure cosmos graph db I've set up a serverless azure cosmos graph db account and now I'm trying to connect to it using the following code:
.AddSingleton(s =>
    {
        var connectionPool = new ConnectionPoolSettings
        {
            MaxInProcessPerConnection = 32,
            PoolSize = 4,
            ReconnectionAttempts = 4,
            ReconnectionBaseDelay = TimeSpan.FromSeconds(1)
        };
        var server = new GremlinServer("<project-name>.documents.azure.com", 443, true, "/dbs/<DatabaseName>/colls/<GraphName>", "<primary key>");
        return new GremlinClient(server, connectionPoolSettings: connectionPool);
    })

The GremlinClient throws an Exception with the message

The server returned status code '200' when status code '101' was expected.

I'm using Gremlin.Net 3.6.0 with NET 6
Any ideas?

A: If you were connecting well with earlier versions of Gremlin.Net you might want to revert. According to their website their supported version is 3.4.6. While later versions along 3.4.x might work, it might require more configuration (like, I think you might have to switch the serializer as I dont think CosmosDB supports the GraphBinary serializer) and you'd have to take care to not  use certain features that newer versions of TinkerPop have that 3.4.6 did not.

A: The issue was resolved by changing the uri from
<project-name>.documents.azure.com

to
<project-name>.gremlin.cosmosdb.azure.com

https://learn.microsoft.com/en-us/azure/cosmos-db/graph/gremlin-api-faq#why-am-i-getting-the--websocketexception--the-server-returned-status-code--200--when-status-code--101--was-expected--error-


text:
Q: MongoDB driver 4.4.0 throws UnsupportedAddressTypeException with Java 17 I have problems with the latest mongodb driver 4.4.0 on my Linux machine with Java 17. It throws following exception:
  Exception java.io.UncheckedIOException: java.net.SocketException: Unsupported address type
        at DatagramSocketAdaptor.connect (DatagramSocketAdaptor.java:120)
        at DatagramSocket.connect (DatagramSocket.java:474)
        at DnsClient.doUdpQuery (DnsClient.java:408)
        at DnsClient.query (DnsClient.java:214)
        at Resolver.query (Resolver.java:81)
        at DnsContext.c_getAttributes (DnsContext.java:434)
        at ComponentDirContext.p_getAttributes (ComponentDirContext.java:235)
        at PartialCompositeDirContext.getAttributes (PartialCompositeDirContext.java:141)
        at PartialCompositeDirContext.getAttributes (PartialCompositeDirContext.java:129)
        at InitialDirContext.getAttributes (InitialDirContext.java:171)
        at DefaultDnsResolver.resolveAdditionalQueryParametersFromTxtRecords (DefaultDnsResolver.java:114)
        at ConnectionString.<init> (ConnectionString.java:388)
        at (#5:1)
  Caused by: java.net.SocketException: Unsupported address type
        at Net.translateToSocketException (Net.java:187)
        at DatagramSocketAdaptor.connectInternal (DatagramSocketAdaptor.java:95)
        at DatagramSocketAdaptor.connect (DatagramSocketAdaptor.java:118)
        ...
  Caused by: java.nio.channels.UnsupportedAddressTypeException
        at Net.checkAddress (Net.java:161)
        at DatagramChannelImpl.connect (DatagramChannelImpl.java:1217)
        at DatagramSocketAdaptor.connectInternal (DatagramSocketAdaptor.java:91)
        ...

It works as expected on my Windows with Java 17 and also on that Linux with Java 11.
How do I test it:
$ jshell --class-path mongodb-driver-core-4.4.0.jar

jshell> import com.mongodb.ConnectionString;

jshell> ConnectionString cs = new ConnectionString("mongodb+srv://xyz.mongodb.net/");

Expected result is javax.naming.NameNotFoundException: DNS name not found, however actual result is the java.nio.channels.UnsupportedAddressTypeException.
Any idea how to make it work?

A: After a lot of "jdbing" I found out, that I can make it work with older implementation of DatagramSocketImpl as is stated here https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/net/DatagramSocketImpl.html
I.e. if I set jdk.net.usePlainDatagramSocketImpl system property to "true" then it works.
Although I don't know proper solution or the real cause of the problem, I can live with the workaround and it works for me.


text:
Q: single border for UITextField within a UIcollectionViewCell (swift 3 xcode) I'm trying to apply a single bottom border to a textField that sits within one of my collectionViewCells. Here is the code:
class AddressCell: UICollectionViewCell {

override init(frame: CGRect) {
    super.init(frame: frame)
    setupViews()
}

func basicTextField(placeHolderString: String) -> UITextField {
    let textField = UITextField()
    textField.font = UIFont.boldSystemFont(ofSize: 12)
    textField.attributedPlaceholder = NSAttributedString(string: placeHolderString, attributes:[NSForegroundColorAttributeName: UIColor.lightGray, NSFontAttributeName: UIFont.boldSystemFont(ofSize: 12)])
    textField.backgroundColor = UIColor.white
    textField.translatesAutoresizingMaskIntoConstraints = false
    return textField
}

required init?(coder aDecoder: NSCoder) {
    fatalError("init(coder:) has not been implemented")
}

func setupViews() {
    backgroundColor = UIColor.white
    layer.addBorder(edge: UIRectEdge.bottom, color: .black, thickness: 0.5)

    let streetTextfield = basicTextField(placeHolderString: "street")

    addSubview(streetTextfield)
}

}
I am using an extension that enables me to apply a single border, which has worked great so far:
extension CALayer {

func addBorder(edge: UIRectEdge, color: UIColor, thickness: CGFloat) {

    let border = CALayer()

    switch edge {
    case UIRectEdge.top:
        border.frame = CGRect.init(x: 0, y: 0, width: frame.width, height: thickness)
        break
    case UIRectEdge.bottom:
        border.frame = CGRect.init(x: 0, y: frame.height - thickness, width: frame.width, height: thickness)
        break
    case UIRectEdge.left:
        border.frame = CGRect.init(x: 0, y: 0, width: thickness, height: frame.height)
        break
    case UIRectEdge.right:
        border.frame = CGRect.init(x: frame.width - thickness, y: 0, width: thickness, height: frame.height)
        break
    default:
        break
    }

    border.backgroundColor = color.cgColor;

    self.addSublayer(border)
}

}
When i simply add a borderWidth to the textfield like this:
textField.layer.borderWidth = 0.5

I get a border and it renders fine. However, when i apply the extension to add a bottom border, like this:
textField.layer.addBorder(edge: UIRectEdge.bottom, color: .black, thickness: 0.5)

the border doesn't apply for some reason.

A: I'm not sure about the extension, but I have a working solution for a TextField with a bottom border.
basically create a class BottomBorderedTextField subclassing UITextField and insert the following code:
class BottomBorderedTextField: UITextField {

    override func draw(_ rect: CGRect) {

        super.draw(rect)

        //this is the color of the bottom border. Change to whatever you what
        let color: UIColor = UIColor.rgb(red: 230, green: 230, blue: 230)

        let bottomBorder = CALayer()

        bottomBorder.frame = CGRect(x: 0, y: bounds.size.height - 1, width: bounds.size.width, height: 2)

        bottomBorder.backgroundColor = color.cgColor

        self.layer.addSublayer(bottomBorder)

    }
}

Then on your basicTextField function set the return type to the BottomBorderedTextField class you just made. so your new code will look like:
func basicTextField(placeHolderString: String) -> BottomBorderedTextField {
    let textField = BottomBorderedTextField()
    textField.font = UIFont.boldSystemFont(ofSize: 12)
    textField.attributedPlaceholder = NSAttributedString(string: placeHolderString, attributes:[NSForegroundColorAttributeName: UIColor.lightGray, NSFontAttributeName: UIFont.boldSystemFont(ofSize: 12)])
    textField.backgroundColor = UIColor.white
    textField.translatesAutoresizingMaskIntoConstraints = false
    return textField
}

A: I wrote a UIView extension that accomplishes the same thing:
extension UIView {

    func addBottomBorder(width: CGFloat, color: UIColor, alpha: CGFloat) {
        let border = CALayer()
        let width = width
        border.borderColor = color.withAlphaComponent(alpha).cgColor
        border.frame = CGRect(x: 0, y: self.frame.size.height - width, width:  self.frame.size.width, height: self.frame.size.height)
        border.borderWidth = width
        self.layer.addSublayer(border)
        self.layer.masksToBounds = true
    }
}

Usage:
    usernameField.addBottomBorder(width: 2.0, color: UIColor.white, alpha: 0.5)

Also, seems within setupViews() you're calling:
layer.addBorder... //this is being called on the collection view cells layer

As opposed to:
streetTextfield.layer.addBorder...


text:
Q: The structure of the  module of Kähler differentials of R[[x]] over R It seems that $\Omega_{R[[x]]/R}^1$ is rather big. For example, take $R$ to be the rational numbers.
We can see that $\Omega_{R((x))/R}^1$ is a $R((x))$-vector space of infinite rank. As by results from Matsumura's book, a basis of $\Omega_{R((x))/R}^1$ coincides with a transcedence basis of $R((x))$ over $R$----remember that we take $R$ to be the rationals which is of char $0$. Yet this has nothing to do with the torsion in $\Omega_{R[[x]]/R}^1$. And what can we say for structures of $\Omega_{R[[x]]/R}^1$ for general $R$'s?

A: *

*If $R$ is a field of characteristic $0$, then the differentials of a transcendence basis of $R((x))$ over $R$ constitute a basis of $\Omega^1_{R((x))/R}$ over $R((x))$.

In this sense this module is big: If $d$ denotes the transcendence degree, then we have $|R|^{\aleph_0} = max(|R|,\aleph_0,d)$. Thus if $R$ is countable, we have $d = |R|^{\aleph_0}$. But I don't know $d$ if $|R| = |R|^{\aleph_0}$. Since $\Omega^1$ commutes with localization, this also shows that $\Omega^1_{R[[x]]/R}$ is very big.

*

*There is an exact sequence of $R[[x]]$-modules $0 \to \cap_ {n \geq 1} x^n \Omega^1_{R[[x]]/R} \to \Omega^1_{R[[x]]/R} \to R[[x]] \to 0$. Here the map on the right is induced by the formal derivative $R[[x]] \to R[[x]]$.

For a proof (thanks owk!), we use the exact sequence of $A/I$-modules
$I/I^2 \to \Omega^1_{A/R} \otimes A/I \to \Omega^1_{(A/I)/R} \to 0$, where $A$ is a $R$-algebra and $I \subseteq A$ an ideal.
If we put $A=R[[x]]$ and $I=(x^n)$, it follows that $0 \to x^n \Omega^1_{R[[x]]/R} \to \Omega^1_{R[[x]]/R} \to \Omega^1_{R[[x]]/x^n / R} \to 0 (*)$ is exact. If we put $A = R[x], I = (x^n)$, we get a exact sequence $0 \to x^n R[x] \to R[x] \to \Omega^1_{R[[x]]/x^n / R} \to 0$. Using this, take the inverse limit of $(*)$ and get the desired sequence.

*

*If $M$ is a $R[[x]]$-module which is complete and separated with respect to the $x$-adic topology, then the map $Hom(\Omega^1_{R[[x]]/R},M)=Der_R(R[[x]],M) \to M, \delta \mapsto \delta(x)$ is bijective. For a proof, remark that the leibniz equality ensures that $\delta$ is continuous.

I think that $\Omega^1_{R[[x]]/R}$ is a rather pathological object. But the last remark shows that it is simple free of rank $1$ (as in the polynomial case) if we restrict to complete and separated modules, which also fits to $R[[x]]$ as $R$-module.

A: In the adic case, when things are rarely finitely generated, what people are usually working with is the - universally finite module of differentials. A derivation $d:R\rightarrow M$ is called finite if $RdR$ is a finitely generated $R$-module. Universally finite derivation is a derivation $d$ for which any other finite derivation could be obtained by composing $d$ with a linear map. Then one defines $\Omega^1_{R/k}$ to be $RdR$ where $d$ is a Universally finite derivation. For example, if $char k = 0$, and $R = k[[x_1,\dots,x_n]]$, then
$\Omega^1_{R/k} = \oplus_{i=1}^n Rd x_i$.
More details on universally finite derivations can be found at the book "Kahler Differentials" by Ernst Kunz.


text:
Q: flutter : RangeError (index): Invalid value: Valid value range is empty: class PictureBox extends StatefulWidget {
  int num;
  PictureBox({Key key, this.num}): super(key:key);

  @override
  _PictureBoxState createState() => _PictureBoxState();
}

var _writeprofile = writeprofileState();

class _PictureBoxState extends State<PictureBox> {
  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      child: InkWell(
        onTap: () async {
          print('asddd1');
          var getimage =
              await ImagePicker.pickImage(source: ImageSource.gallery);
          setState(() {
            tmpimage = getimage;
            imageBytes = getimage.readAsBytesSync();
            image64 = base64Encode(imageBytes);
            print(tmp64list.length);
            print('Image Path $tmpimage');
          });
          tmp64list[widget.num] = image64;
        },

'tmp64list[widget.num] = image64;' That has been error since.
I wanted put through the index of the list
Like this :
PictureBox pictureBox1 = PictureBox(num:1);
PictureBox pictureBox2 = PictureBox(num:2);
PictureBox pictureBox3 = PictureBox(num:3);
PictureBox pictureBox4 = PictureBox(num:4);
PictureBox pictureBox5 = PictureBox(num:5);
PictureBox pictureBox6 = PictureBox(num:6);

But my intention is not running, but appear error.
error :
Unhandled Exception: RangeError (index): Invalid value: Valid value range is empty: 3
#0      List._setIndexed (dart:core-patch/growable_array.dart:153:72)
#1      List.[]= (dart:core-patch/growable_array.dart:150:5)

i think so, because initState in stateful
right ?
but i can't solve because i don't understand enough about flutter
can you help me ?

A: tmp64list did not init correctly
when use tmp64list[widget.num], the element did not exist yet
In your case, List start from 0 not 1
If you init with 3 elements
List<String> tmp64list = ['','',''];

and you can use 0,1,2 not 1,2,3
if want to start from 1, you can do num -1 in widget's logic to match List index
PictureBox(num:0);
PictureBox(num:1);
PictureBox(num:2);

full example code
import 'package:flutter/material.dart';
import 'package:image_picker/image_picker.dart';
import 'dart:convert';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Flutter Demo Home Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      // This call to setState tells the Flutter framework that something has
      // changed in this State, which causes it to rerun the build method below
      // so that the display can reflect the updated values. If we changed
      // _counter without calling setState(), then the build method would not be
      // called again, and so nothing would appear to happen.
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    // This method is rerun every time setState is called, for instance as done
    // by the _incrementCounter method above.
    //
    // The Flutter framework has been optimized to make rerunning build methods
    // fast, so that you can just rebuild anything that needs updating rather
    // than having to individually change instances of widgets.
    return Scaffold(
      appBar: AppBar(
        // Here we take the value from the MyHomePage object that was created by
        // the App.build method, and use it to set our appbar title.
        title: Text(widget.title),
      ),
      body: Center(
        // Center is a layout widget. It takes a single child and positions it
        // in the middle of the parent.
        child: Column(
          // Column is also a layout widget. It takes a list of children and
          // arranges them vertically. By default, it sizes itself to fit its
          // children horizontally, and tries to be as tall as its parent.
          //
          // Invoke "debug painting" (press "p" in the console, choose the
          // "Toggle Debug Paint" action from the Flutter Inspector in Android
          // Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
          // to see the wireframe for each widget.
          //
          // Column has various properties to control how it sizes itself and
          // how it positions its children. Here we use mainAxisAlignment to
          // center the children vertically; the main axis here is the vertical
          // axis because Columns are vertical (the cross axis would be
          // horizontal).
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            PictureBox(num:1),
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.display1,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

class PictureBox extends StatefulWidget {
  int num;
  PictureBox({Key key, this.num}): super(key:key);

  @override
  _PictureBoxState createState() => _PictureBoxState();
}

List<String> tmp64list = ['','',''];
String image64;

class _PictureBoxState extends State<PictureBox> {
  @override
  Widget build(BuildContext context) {
    return Container(
        height: 100,
        width: 100,
        color: Colors.blue,
        child: InkWell(
        onTap: () async {
      print('asddd1');
      var getimage =
          await ImagePicker.pickImage(source: ImageSource.gallery);
      setState(() {
        var tmpimage = getimage;
        var imageBytes = getimage.readAsBytesSync();
        image64 = base64Encode(imageBytes);
        print(tmp64list.length);
        print('Image Path $tmpimage');
      });
      tmp64list[widget.num] = image64;
      print('${tmp64list[widget.num]}');
    }));
  }
}

demo picture print base64 string if tmp64list init correctly.


text: Q: Connections on bundles over algebraic variety I am asking for a reference for the theory of connections on vector bundles over algebraic varieties. I am particularly interested in the notion of Gauss-Manin connection, the notions of torsion, p-curvature and monodromy.


text:
Q: Mysql query in with the answer true, false I was not too long ago studying java, so maybe I have a stupid question.
I have a table, where i store some info.
And i want to check in this table on availability of some information (it will be only one line), and if yes - take from this line, the information in a particular column, if no - do another thing.
I really don`t know how to do this.
My idea was something like this: at first - check the table:
SELECT * FROM tablename WHERE nickname = "kvant";

then if true, do another query with searching info.
and do this with condition if\else. but all my attempts not turn.
I hope for your help, sorry for my awry English.

A: Check if the data exists like this:
IF EXISTS(SELECT * FROM tablename WHERE nickname = "kvant")
BEGIN
    --value is found so go ahead
END
ELSE
    --value not found
BEGIN
END

A: One simple way is to query the database and get the result. If result!=Null {//do something} else {//Do something}
(Can use try - catch as well)

A: Pure java possible solution:
Try to get that value in the query. Get the ResultSet rs of that query and:
if(rs.next()) {
    String value = rs.getString("value"); //Assuming the column is value and that it is a String.
    //Do whatever you want with the value
} else {
    //The other thing
}

If you can not take the value from the first ResultSet, do another query in the if.

A: write in sql like select case exists (select * from yourtable where condition) then 'dothis thing' else 'dootherthing' from 'yourtable' where 'yourcondition'
since you wanted to run some other query after you know you have some conditon exists.


text:
Q: Minecraft XBOX Updates? Does Mojang plan to update the XBOX version of Minecraft?  Can we expect to see all the features in the PC/Mac version to appear on the XBOX version someday?

A: See Xbox 360 Edition.
The company responsible for the port is 4JStudios, and so I imagine its entirely up to them how much of the functionality that they choose to port and how frequently they choose to update it, however the Wiki does state that "Updates will be free of charge" (which implies that it will at some point be updated free of charge with new Minecraft features).
The "Gameplay" section fairly concisely lists the current gameplay differences, most notably I imagine that some of the intended differences (such as the difference in the crafting system and in the UI) will mean that some features of the PC version of Minecraft obviously won't make much sense in the XBox version.

Gameplay
The Xbox 360 edition is currently based on an earlier version of the
  PC edition (Beta 1.6.6), and therefore lacks some items and features,
  such as sprinting.
For the most part the Xbox 360 edition of the game is identical to the
  PC edition, but has several notable differences and features:

*

*The player can optionally make use of Xbox Kinect functionality to assist in their gameplay, although Kinect
  functionality was not available at launch.

*The Xbox 360 edition doesn't make use of the standard crafting interface as in the original version, but still has similarities to
  the PC's 2x2 and 3x3 crafting grids. The interface doesn't require the
  Player to place items in the correct place in a crafting menu, but
  simply shows the blocks required to craft the selected item, and
  crafts it if the Player has enough blocks.

*There are 8 default skin types, all of which appear to have Steve's face, but wearing different outfits.

*The game features split-screen functionality, however an HDTV with a Component or HDMI cable required for Split-Screen play. Up to 4
  players can play in split screen*, as well as the possibility to play
  8-person online multiplayer game modes in split-screen.

*Mods, Texture Packs and extra player skins will be available much later.

*The Xbox 360 edition includes a tutorial mode not included in the PC version of the game. This tutorial leads the player through the
  basics of mining and placing blocks, crafting, as well as building
  their first house to survive the night (video).

*You cannot change a world's difficulty mid-game. You can change it when you select the world for play.

*You always begin a new world with a map.

*Unlike the PC version, each world in the Xbox 360 Edition is currently limited to 1024 by 1024 blocks. This is approximately the
  size of an in-game map. It is expected, but not known if the world
  size will be increased along with the updates that will bring the Xbox
  360 version of Minecraft up to date with the PC version.

*You can not walk through Sugar Cane.


text:
Q: Get data from bottom navigation activity I have two activity first is MainActity(FirstActivity) that just show data,
second is BottomNavigationView Activity(SecondActivitys).
When I go to Some activity of SecondActivitys I want to send data back to FirstActity.
I have use Intent but on MainActivity have only one button that starts some of SecondActivitys. That means I have to call startActivity without requestCode the I cant use onActivityResult on MainActivity
how can I solve it? pls, help thx!!

A: I don't understand, Why you can't use onActivityResult?
But here is the alternative:
You can try BroadcastReceiver or EventBus.
Actually EventBus is a library which is using BroadcastReceivers.
You can look there: Android-Broadcast Receiver
Note: Don't use Broadcast Receivers everywhere please. Because they are reducing the readability of the Code.


text:
Q: Basic Velocity Algorithm? Given the following dataset for a single article on my site:
Article 1
2/1/2010 100
2/2/2010 80
2/3/2010 60

Article 2
2/1/2010 20000
2/2/2010 25000
2/3/2010 23000

where column 1 is the date and column 2 is the number of pageviews for an article. What is a basic velocity calculation that can be done to determine if this article is trending upwards or downwards for the most recent 3 days?
Caveats, the articles will not know the total number of pageviews only their own totals. Ideally with a number between 0 and 1. Any pointers to what this class of algorithms is called?
thanks!

A: update: Your data actually already is a list of velocities (pageviews/day). The following answer simply shows how to find the average velocity over the past three days. See my other answer for how to calculate pageview acceleration, which is the real statistic you are probably looking for.
Velocity is simply the change in a value (delta pageviews) over time:
For article 1 on 2/3/2010:
delta pageviews = 100 + 80 + 60
                = 240 pageviews
delta time = 3 days

pageview velocity (over last three days) = [delta pageviews] / [delta time]
                                         = 240               / 3
                                         = 80 pageviews/day

For article 2 on 2/3/2010:
delta pageviews = 20000 + 25000 + 23000
                = 68000 pageviews
delta time = 3 days

pageview velocity (over last three days) = [delta pageviews] / [delta time]
                                         = 68,000             / 3
                                         = 22,666 + 2/3 pageviews/day

Now that we know the maximum velocity, we can scale all the velocities to get relative velocities between 0 and 1 (or between 0% and 100%):
relative pageview velocity of article 1 = velocity / MAX_VELOCITY
                                        = 240      / (22,666 + 2/3)
                                        ~ 0.0105882353
                                        ~ 1.05882353%

relative pageview velocity of article 2 = velocity      / MAX_VELOCITY
                                        = (22,666 + 2/3)/(22,666 + 2/3)
                                        = 1
                                        = 100%

A: "Pageview trend" likely refers to pageview acceleration, not velocity. Your dataset actually already is a list of velocities (pageviews/day). Pageviews are non-decreasing values, so pageview velocity can never be negative. The following describes how to calculate pageview acceleration, which may be negative.
PV_acceleration(t1,t2) = (PV_velocity{t2} - PV_velocity{t1}) / (t2 - t1)
("PV" == "Pageview")

Explanation:
Acceleration is simply change in velocity divided by change in time. Since your dataset is a list of page view velocities, you can plug them directly into the formula:
PV_acceleration("2/1/2010", "2/3/2010") = (60 - 100) / ("2/3/2010" - "2/1/2010")
                                        = -40        / 2
                                        = -20 pageviews per day per day

Note the data for "2/2/2010" was not used. An alternate method is to calculate three PV_accelerations (using a date range that goes back only a single day) and averaging them. There is not enough data in your example to do this for three days, but here is how to do it for the last two days:
PV_acceleration("2/3/2010", "2/2/2010") = (60 - 80) / ("2/3/2010" - "2/2/2010")
                                        = -20        / 1
                                        = -20 pageviews per day per day

PV_acceleration("2/2/2010", "2/1/2010") = (80 - 100) / ("2/2/2010" - "2/1/2010")
                                        = -20        / 1
                                        = -20 pageviews per day per day

PV_acceleration_average("2/3/2010", "2/2/2010") = -20 + -20 / 2
                                                = -20 pageviews per day per day

This alternate method did not make a difference for the article 1 data because the page view acceleration did not change between the two days, but it will make a difference for article 2.

A: Just a link to an article about the 'trending' algorithm reddit, SUs and HN use among others.

*

*http://www.seomoz.org/blog/reddit-stumbleupon-delicious-and-hacker-news-algorithms-exposed


text:
Q: CakePHP updating multiple rows with record ids, same model I want to update a model. I have a query like this
UPDATE mymodels SET `myfield` = 100 WHERE `id`=12 OR `id`=13 OR `id`=14
// also the same:
UPDATE mymodels SET `myfield` = 100 WHERE `id` IN (12,13,14)

And I tried this:
$this->MyModel->updateAll(
    // fields
    array('MyModel.myfield' => 100),
    // conditions
    array('MyModel.id' => 12)
);

But I need to update 20 different records.
Record ids are like this 12, 13, 14 ....

A: If the records you want to update are sequential, then try adding two conditions like this
$this->MyModel->updateAll(
    array('MyModel.myfield' => 100),
    // conditions
    array('MyModel.id >=' => 12, 'MyModel.id <=' => 20)
);

If there's no relation between indexes of ids, try using an array
$this->MyModel->updateAll(
    array('MyModel.myfield' => 100),
    // conditions
    array('MyModel.id' => array(12,13,14...))
);


text: Q: Power Apps SharePoint document library browser reusable Kindly help me if its possible to develop reusable experience for Power Apps SharePoint document library as for now I am able to develop for predefined document library as below but I'm not sure how to make things work for different document library, reusable experience.


text:
Q: Update values in model-database using scritps outside Django I have a model with the fields name, email, login, have_purchased.
To avoid mixing the website code and some backend/analysis code, the have_purchased (boolean) value is updated 6 times a day using some scripts on another server, since it takes a lot of time and lot of computation power, that the website should not suffer from.
I'm wondering, if updating values in a model database, such as myapp_model here, outside Django e.g using pandas.df.to_sql("myapp_model") can cause some damage?
If that is bad idea, what is the best idea when having other scripts running that does not do anything but update the values of the model?


text:
Q: MongoDB - find() calls getting stuck sometimes - Timeout We are using MongoDb for saving and fetching data.
All calls that are putting data into collections are working fine and are through common method.
All calls that are fetching data from collections are working fine sometimes and are through common method.
But Sometimes, only for one of the collection, i get my calls being stuck for forever, consuming CPU usage. I have to manually kill the threads otherwise it consumes my whole CPU.
Mongo Connection
MongoClient mongo = new MongoClient(hostName , Integer.valueOf(port));
DB mongoDb = mongo.getDB(dbName);

Code To fetch
DBCollection collection = mongoDb.getCollection(collectionName);
DBObject dbObject = new BasicDBObject("_id" , key);
DBCursor cursor = collection.find(dbObject);

Though i have figured out the collection for which it is causing issues, but how can i improve upon this, since it is occurring for this particular collection and sometimes.
EDIT
Code to save
DBCollection collection = mongoDb.getCollection(collectionName);
DBObject query = new BasicDBObject("_id" , key);
DBObject update = new BasicDBObject();
update.put("$set" , JSON.parse(value));
collection.update(query , update , true , false);

Bulk Write / collection
DB mongoDb = controllerFactory.getMongoDB();
        DBCollection collection = mongoDb.getCollection(collectionName);

        BulkWriteOperation bulkWriteOperation = collection.initializeUnorderedBulkOperation();

        Map<String, Object> dataMap = (Map<String, Object>) JSON.parse(value);

        for (Entry<String, Object> entrySet : dataMap.entrySet()) {
            BulkWriteRequestBuilder bulkWriteRequestBuilder = bulkWriteOperation.find(new BasicDBObject("_id" ,
                    entrySet.getKey()));

            DBObject update = new BasicDBObject();
            update.put("$set" , entrySet.getValue());

            bulkWriteRequestBuilder.upsert().update(update);
        }

How can i set timeout for fetch calls..??

A: Just some possible explanations/thoughts.
In general "query by id" has to be fast since _id is supposed to be indexed, always. The code snippet looks correct, so probably the reason is in mongo itself. This leads me to a couple of suggestions:
Try to connect to mongo directly from the command line and run the "find" from there. The chances are that you'll still be able to observe occasional slowness.
In this case:

*

*Maybe its about the disks (maybe this particular server is deployed on the slow disk or at least there is a correlation with some slowness of accessing the disk).

*Maybe your have a sharded configuration and one shard is slower than others

*Maybe its a network issue that occurs sporadically. If you run mongo locally/on staging env. with the same collection does this reproduce?

*Maybe (Although I hardly believe that) the query runs in sub un-optimal way. In this case you can use "explain()" as someone has already suggested here.

*If you happen to have replica set, please figure out what is the [Read Preference]. Who knows, maybe you prefer to get this id from the sub-optimal server

A: A different approach is to use the proposed method for MongoDB 3.2 Driver. Keep in mind that you have to update your .jar libraries (if you haven't) to the latest version.
public final MongoClient connectToClient(String hostName, String port) {
    try {
        MongoClient client = new MongoClient(hostName, Integer.valueOf(port));
        return client;
    } catch(MongoClientException e) {
        System.err.println("Cannot connect to Client.");
        return null;
    }
}

public final MongoDatabase connectToDB(String databaseName) {
    try {
        MongoDatabase db = client.getDatabase(databaseName);
        return db;
    } catch(Exception e) {
        System.err.println("Error in connecting to database " + databaseName);
        return null;
    }

public final void closeConnection(MongoClient client) {
    client.close();
}

public final void findDoc(MongoDatabase db, String collectionName) {
    MongoCollection<Document> collection = db.getCollection(collectionName);
    try {
        FindIterable<Document> iterable = collection
                .find(new Document("_id", key));
        Document doc = iterable.first();
        //For an Int64 field named 'special_id'
        long specialId = doc.getLong("special_id");
    } catch(MongoException e) {
        System.err.println("Error in retrieving document.");
    } catch(NullPointerException e) {
        System.err.println("Document with _id " + key + " does not exist.");
    }
}

public final void insertToDB(MongoDatabase db, String collectioName) {
    try {
        db.getCollection(collectionName).insertOne(new Document()
            .append("special_id", 5)
            //Append anything
        );
    catch(MongoException e) {
        System.err.println("Error in inserting new document.");
    }
}

public final void updateDoc(MongoDatabase db, String collectionName, long id) {
    MongoCollection<Document> collection = db.getCollection(collectionName);
    try {
        collection.updateOne(new Document("_id", id),
                             new Document("$set",
                                     new Document("special_id",
                                             7)));
    catch(MongoException e) {
        System.err.println("Error in updating new document.");
    }
}

public static void main(String[] args) {
    String hostName = "myHost";
    String port = "myPort";
    String databaseName = "myDB";
    String collectionName = "myCollection";
    MongoClient client = connectToClient(hostName, port);
    if(client != null) {
        MongoDatabase db = connectToDB(databaseName);
        if(db != null) {
            findDoc(db, collectionName);
        }
        client.closeConnection();
    }
}

EDIT: As the others suggested, check from the command line if the procedure of finding the document by its ID is slow too. Then maybe this is a problem with your hard drive. The _id is supposed to be indexed but for better or for worse, re-create the index on the _id field.

A: The answers posted by others are great, but did not solve my purpose.
Actually issue was in my existing code itself , my cursor was waiting in while loop infinite time.
I was missing few checks which has been resolved now.


text:
Q: How to accept more than one connection with ztcp How do I make ZSH's ZTCP module accept more than one connection? Here is my code so far:
zmodload zsh/net/tcp
ztcp -ld3 7000
lfd=3

while true;
do
ztcp -ad4 $lfd
done &
pid=$!
talkfd=4
while true; do read -r line <&$talkfd; echo $line >&$talkfd;

kill $pid

but that doesn't seem to work. Any ideas?


text:
Q: How to calculate total price using keyup function in jquery or javascript? Hello guys I just want to ask how can I perform an automatically computation using jquery?
Like for example if I have 3 textbox. The textbox 1 is for quantity and textbox 2 is for price and textbox 3 is for result. When the user entered a value in textbox 1 and textbox 2 the textbox 3 will automatically solve the computation (price * quantity). If the user That's all guys I hope you can help me. Thanks.
Here's my html code.

   <input type='text' name='qty' id='qty' value='' />
   <input type='text' name='price' id='price' value='' />
   <input type='text' name='total' id='total' value='' />

In javascript how can I perform a calculation?

A: The best way to handle input update events is with jQuery.on('input',...). You can use parseFloat and parseInt to get the values from the other inputs, toFixed to ensure the final value looks like currency (remove that if it's not needed), and provide a fallback of 0 in case something can't be parsed.
$('#qty, #price').on('input',function() {
    var qty = parseInt($('#qty').val());
    var price = parseFloat($('#price').val());
    $('#total').val((qty * price ? qty * price : 0).toFixed(2));
});

JSFiddle Demo

A: You have to give your textboxes a class name then loop through that class and add their value.
Let's say this is your text field
<input type="text" class="row-total">

And this is how you add them up
var total = 0;
$.each(".row-total", function(){
 total += $(this).val()
});

A: In this thing you need to give your textbox1 and textbox2 a ("Comp") Class name
Ex:
<input type="text" name="textbox1" class="Comp">
<input type="text" name="textbox2" class="Comp">

Then this will be the script:
$(document).ready(function(){
    $(".Comp").change(function(){
        var total = 0.00;
        var textbox3= 0.00;    // this gonna be your third textbox
        $(".Comp").each(function(){
            total += parseFloat(this.value);
        });
        textbox3= $("#textbox3").val((total).toFixed(2));

    });
});

NOTE: Just edit the computation that suits to your need. This one only add the two textboxes (textbox1 and textbox2)


text:
Q: error Command failed: gradlew.bat app:installDebug When I run "react-native run-android" or "npx react-native run-android" or "cd andriod  ./gradlew clean" those commands then the errors show
PS D:\work\Myproject-app> npx react-native run-android

    info Starting JS server...
    Starting a Gradle Daemon, 2 incompatible and 2 stopped Daemons could not be reused, use --status                                 for details

    > Configure project :app
    Reading env from: .env

    FAILURE: Build completed with 2 failures.

    1: Task failed with an exception.
    -----------
    * What went wrong:
    A problem occurred evaluating project ':app'.
    > A problem occurred starting process 'command 'security''

    * Try:
    Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get         more log output. Run with --scan to get full insights.
    ==============================================================================

    2: Task failed with an exception.
    -----------
    * What went wrong:
    A problem occurred configuring project ':app'.
    > compileSdkVersion is not specified.

    * Try:
    Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get         more log output. Run with --scan to get full insights.
    ==============================================================================

    * Get more help at https://help.gradle.org

    BUILD FAILED in 19s
    error Could not install the app on the device, read the error above for details.
    Make sure you have an Android emulator running or a device connected and have
    set up your Android development environment:
    https://facebook.github.io/react-native/docs/getting-started.html
    error Command failed: gradlew.bat app:installDebug. Run CLI with --verbose flag for more details.

I tried also to use the latest version of Gradle!
OS Windows 10
Node: 14.2.0
Java: java version "1.8.0_251"
      Java(TM) SE Runtime Environment (build 1.8.0_251-b08)
      Java HotSpot(TM) 64-Bit Server VM (build 25.251-b08, mixed mode)
Gradle version: 5.1.1
JAVA_HOME, ANDROID_HOME, and path added to the environment

A: I don't have enough rep to comment, but....
I ran into this problem today. My situation was that the project worked fine on a mac. However, I needed to get it running on a windows system. Within my android\app\build.gradle file, I setup a getPassword method that would make it easy for me to sign my apk's. Within the getPassword method I had this call:
commandLine 'security', '-q', 'find-generic-password', '-a', currentUser, '-s', keyChain, '-w'

I commented out all of the references to the getPassword method and it started working without a problem.
The root of the problem is that the "security" commandline tool that mac uses isn't available on windows. Since I'm now needing to use a windows box as well, I've configured the passwords within an external credentials file.

A: I met the same question, but the first answer is too simple. I don't know how to add a getPassword method and where to add.
However, the first answer inspired me. 'My situation was that the project worked fine on a mac. However, I needed to get it running on a windows system. '
we should shift right of CLI commands on Windows 10. type 'cmd' to use the command line tool on by right click, choose administrator mode.
and try 'yarn react-native run-android' or 'npx react-native run-android' again.
yarn will automatically downloads proper vision of gradle which needs. if you see these changes, let's rock.