text:
Q: Android auto backup not working: Transport rejected package because it wasn't able to process it at the time I have developed an application with Flutter and Sqlite and I can't get the android auto backup working.
I have explicitly put android:allowBackup="true" in the AndroidManifest.xml.
The very first time I executed the command:
adb shell bmgr backupnow
I got:

Running incremental backup for 1 requested packages. Package @pm@ with
  result: Success Package  with result: Size quota
  exceeded Backup finished with result: Success

After that time I got:

Running incremental backup for 1 requested packages. Package @pm@ with
  result: Success Package  with result: Transport rejected
  package because it wasn't able to process it at the time Backup
  finished with result: Success

I can't understand why I have the error "Size quota exceeded": the sqlite database size is far below 25 mb! I have tried on different devices, with no success.

A: Regarding being over 25MB, are there any flutter temporary files used to speed up debugging installed in the app's private folders?
If you have a debuggable app installed, you should be able to query the internal storage of the app to see what's stored there by calling:
adb shell run-as <APP_PACKAGENAME> ls -al

That way you can see what is in the files and databases folders it's trying to backup.  If there are files you want to exclude, or only a few you want to include in the backup you can specify custom rules by adding:
android:fullBackupContent="@xml/backup_rules"

along side the android:allowBackup="true" setting (see https://developer.android.com/guide/topics/data/autobackup for more details on the contents of that xml file).
It might also be worth logging into Google Backups to see the backups associated with the Google account you're logged in with.  From there you can see how many apps, and how much setting data is stored, and delete stale backups.
You may also delete a device's backup by toggling off and on again the Backup To Google Drive setting.  That way you'd know you're starting a test from "fresh".
After trying various combinations of backup commands from other "solutions" I found MH's answer here: How Do You Test the Android 6.0 Full-Backup Behavior?
By deleting the test device's backup, then following the steps in that link that got me past the Quota and "Transport rejected package because it wasn't able to process it at the time" errors I was seeing, and get an actual backup response like:
Running incremental backup for 1 requested packages.
  Package @pm@ with result: Success
  Package com.example.myapp with progress: 512/66048
  Package com.example.myapp with progress: 2560/66048
  Package com.example.myapp with progress: 10752/66048
  Package com.example.myapp with progress: 18944/66048
  Package com.example.myapp with progress: 27136/66048
  Package com.example.myapp with progress: 35328/66048
  Package com.example.myapp with progress: 43520/66048
  Package com.example.myapp with progress: 51712/66048
  Package com.example.myapp with progress: 59904/66048
  Package com.example.myapp with progress: 68096/66048
  Package com.example.myapp with progress: 68608/66048
  Package com.example.myapp with result: Success
  Backup finished with result: Success

After that, uninstalling and re-installing the app on that test device showed the backed up content correctly restored.


text:
Q: Angular2, inputmask ngModel binding I have some problem with ng2 and inputmask. For example I have had this code
component.html

  Phone *
  <input type="text" [(ngModel)]="sender.phone" class="form-control" id="sender-phone" placeholder="Phone">

component.ts
ngAfterViewInit() {
  let phoneNumberInput = document.getElementById('sender-phone');
  let inputmask = new Inputmask('+7(999)999-99-99');
  inputmask.mask(element);
}

Inputmask is working good. But my [(ngModel)] didn't work. Anyone know how I can resolve my issue ?
My code for example http://plnkr.co/edit/F3pob7hH2ZrJv0MDNa9x?p=preview

A: I have resolve problem of this issue.
http://plnkr.co/edit/tN6y5d2fsl0b7cRq6Prv?p=preview
You need create directive with InputMask
@Directive({ selector: '[tdInputmask]' })
export class InputmaskDirective {
@Output('tdInputmaskUnmaskedValue') unmaskedValueEmitter = new EventEmitter();

@Input() set defaultValue (value: string) {
    //this._defaultColor = colorName || this._defaultColor;
}

@Input('tdInputmask') mask: string;

private el: HTMLElement;
constructor(el: ElementRef) {
    this.el = el.nativeElement;
}

ngAfterViewInit() {
   let inputmask = new Inputmask(this.mask);
    let elementCallback = () =>  {
        if (this.el.inputmask) {
            this.unmaskedValueEmitter.emit('7' + this.el.inputmask.unmaskedvalue());
            //if (!this.el.inputmask.isComplete()) {
            //    this.el.parentElement.classList.add('has-error');
            //} else {
            //    this.el.parentElement.classList.remove('has-error');
            //}
        }
    };

    inputmask.opts.oncomplete = elementCallback;
    inputmask.opts.onincomplete = elementCallback;
    inputmask.opts.onBeforePaste = (pastedValue: string) => {
        if (pastedValue[0] == '7' || pastedValue[0] == '8') {
            return pastedValue.slice(1);
        }
        return pastedValue;
    };
    inputmask.mask(this.el);
}
}

And in HTML code I use
<input [tdInputmask]="'+7(999)999-99-99'" (tdInputmaskUnmaskedValue)="val3 = $event">

redpajama_set_name: RedPajamaStackExchange


text:
Q: XSLT - XML data extraction I want to use data from XML:
<SOURCES>
<LINK type="1">https://example.com</LINK>
<LINK type="2">http://example-two.com</LINK>
</SOURCES>

and use it in my XSLT:
<xsl:value-of select="type@1"/>
text

so I can get:
text

or
text

A: If you are in the context of LINK, then
text

will produce:
text

and:
 text

I don't see where the type attribute figures in this; in any case, you need to use @type to get it.

but how to CHOOSE witch link to use (type=1 or type=2) ?

It depends again on where exactly you are (XSLT is very context-dependent). For example, from the context of SOURCES, you can select all LINKs of type 1 as:
LINK[@type='1']


text:
Q: Issue with SQL Server UNION Statement I have been reading about the difference between UNIONS and JOINS and believe UNION is what I need for my solution, however I am unable to get this working as I think it's intended.
I've been looking on some other SO articles, including this one.
What is the difference between JOIN and UNION?
According to some of the detailed answers in that link, UNION would combine two queries together to form one dataset.
My scenario is that I have a sales database showing number of sales, and at what sales level. I have two such tables with similar information that need to come together to form a complete set.
Table 1: North Side
Item    | Type      | SalesLevel
--------------------------------
John    | Apple     | 1
John    | Pear      | 2
Craig   | Apple     | 1
Dylan   | Apple     | 1

Table 2: South Side
Item    | Type      | SalesLevel
--------------------------------
John    | Apple     | 1
John    | Pear      | 1
Craig   | Apple     | 1
Dylan   | Apple     | 2

As you can see the tables contain the same columns, and my expected results needs to show only the item for each individual where the Type has the highest SalesLevel.
The results that I am after would then look like the following.
Item    |  Type   |  SalesLevel
--------------------------------
John    |  Apple  | 1
John    |  Pear   | 2
Craig   |  Apple  | 1
Dylan   |  Apple  | 2

When I run my query, I am only getting the Max value per Select statement. I can see 'why' this might happen with the construct of the query, but would have thought that the UNION would have joined these two select statements into one query first? I'm looking for some assistance on how to better construct this query to obtain the expected results.
My query so far
Select Name, Item, MAX(SalesLevel)
FROM NorthSide
Group By Name, Item
UNION
Select Name,
Item, MAX(SalesLevel)
FROM SouthSide
Group By Name, Item

A: UNION will simply a SET operation which combines two resultsets into one, after removing duplicates. Read more about UNION
In your case, you need to get the maximum Saleslevel, in the two sets. You can achieve the same in the below way
SELECT Item, Type, MAX(SalesLevel)
FROM
(
SELECT Item, Type, SalesLevel
FROM North_rs
UNION
SELECT Item, Type, SalesLevel
FROM South_rs
)
GROUP BY Item, Type

A: You may achieve this by using JOIN or UNION, it just depend on your approach.
By Using UNION
  Select Name, Item, Max(SalesLevel) from (
  Select Name, Item, SalesLevel
  FROM NorthSide
  UNION ALL
  Select Name, Item, SalesLevel
  FROM SouthSide ) as tab
  group by name , item

By using JOIN
 Select S.Name, S.Item,
 case when N.SalesLevel > S.SalesLevel
 then N.SalesLevel
 else S.SalesLevel end as SalesLevel
 from NorthSide as N inner join SouthSide as S
 on N.Name=S.Name and N.Item=S.Item

A: You can use this query
use Full Join so you get items that exist in one table but not the other
also use Isnull(X,Y) to get results from both tables
I haven't test the code, so it may need some fixes
Select ISNULL(N.Name, S.Name) AS Name, ISNULL(N.Item, S.Item) AS Item, MAX(SalesLevel)
FROM NorthSide N
FULL JOIN SouthSide S ON N.Name = S.Name AND N.Item = S.Item
Group By ISNULL(N.Name, S.Name), ISNULL(N.Item, S.Item)

A: if you need some combined from 2 tables with the same structure I think "UNION" is the most appropriate way I already test on my local computer
with this query
    SELECT pp.Item, pp.Type, MAX(pp.SalesLevel)
FROM
(
SELECT Item, Type, SalesLevel
FROM North_side
UNION ALL
SELECT Item, Type, SalesLevel
FROM South_side
) pp
GROUP BY pp.Item, pp.type

if you need some condition after grouping you can add "HAVING" and add some "aggregate" condition
enter image description here


text:
Q: Passing data from android to Backend via SOAP I have to create an expense to a dynamics backend using soap. I'm currently on the same network so no authentification is needed yet. The service takes (date, amount, currency, user) as paramters, but I can't seem to even get connection to the webservice. Can anyone help me?
MyActivity
import com.example.KsoapExample.R;
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MyActivity extends Activity {
private TextView txt;
private String celsius;

/**
 * Called when the activity is first created.
 */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    final EditText edt = (EditText) findViewById(R.id.value_to_convert);
    final EditText edt2 = (EditText) findViewById(R.id.amount);
    final EditText edt3 = (EditText) findViewById(R.id.user);
    Button btn = (Button) findViewById(R.id.submit);
    txt = (TextView) findViewById(R.id.answer);

    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (edt.length() > 0) {
                createRecord(edt.getText().toString(), Integer
                        .parseInt(edt2.getText().toString()), edt3
                        .getText().toString());
            } else {
                txt.setText("values can not be empty.");
            }
        }
    });
}

public Handler handler = new Handler(new Handler.Callback() {

    @Override
    public boolean handleMessage(Message msg) {
        switch (msg.what) {

        case 0:
            txt.setText(celsius);
            break;
        }
        return false;
    }
});

private final void createRecord(final String date, final int i,
        final String user) {
    new Thread(new Runnable() {

        @Override
        public void run() {
            SoapRequests ex = new SoapRequests();
            celsius = ex.getResponse(date, i, user);
            handler.sendEmptyMessage(0);
        }
    }).start();
}
}

SoapRequests Activity
    package com.example.KsoapExample;

import android.util.Log;
import org.ksoap2.HeaderProperty;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import java.io.IOException;
import java.net.Proxy;
import java.net.SocketTimeoutException;
import java.util.ArrayList;
import java.util.List;

public class SoapRequests {

    private static final boolean DEBUG_SOAP_REQUEST_RESPONSE = true;
    private static final String MAIN_REQUEST_URL = "LOCAL HOST";
    private static final String NAMESPACE = "http://tempuri.org/";
    private static final String SOAP_ACTION = "http://tempuri.org/";
    private static String SESSION_ID;

    private final void testHttpResponse(HttpTransportSE ht) {
        ht.debug = DEBUG_SOAP_REQUEST_RESPONSE;
        if (DEBUG_SOAP_REQUEST_RESPONSE) {
            Log.v("SOAP RETURN", "Request XML:\n" + ht.requestDump);
            Log.v("SOAP RETURN", "\n\n\nResponse XML:\n" + ht.responseDump);
        }
    }

    public String getResponse(String date, int expense, String user) {
        String data = null;
        String methodname = "createRecord";

        SoapObject request = new SoapObject(NAMESPACE, methodname);
        request.addProperty("Date", date);
        request.addProperty("Expense", expense);
        request.addProperty("User", user);

        SoapSerializationEnvelope envelope = getSoapSerializationEnvelope(request);

        HttpTransportSE ht = getHttpTransportSE();
        try {
            ht.call(SOAP_ACTION + methodname, envelope);
            testHttpResponse(ht);
            SoapPrimitive resultsString = (SoapPrimitive) envelope
                    .getResponse();

            @SuppressWarnings("unchecked")
            List<HeaderProperty> COOKIE_HEADER = (List<HeaderProperty>) ht
                    .getServiceConnection().getResponseProperties();

            for (int i = 0; i < COOKIE_HEADER.size(); i++) {
                String key = COOKIE_HEADER.get(i).getKey();
                String value = COOKIE_HEADER.get(i).getValue();

                if (key != null && key.equalsIgnoreCase("set-cookie")) {
                    SoapRequests.SESSION_ID = value.trim();
                    Log.v("SOAP RETURN", "Cookie :" + SoapRequests.SESSION_ID);
                    break;
                }
            }
            data = resultsString.toString();

        } catch (SocketTimeoutException t) {
            t.printStackTrace();
        } catch (IOException i) {
            i.printStackTrace();
        } catch (Exception q) {
            q.printStackTrace();
        }
        return data;
    }

    private final SoapSerializationEnvelope getSoapSerializationEnvelope(
            SoapObject request) {
        SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(
                SoapEnvelope.VER11);
        envelope.dotNet = true;
        envelope.implicitTypes = true;
        envelope.setAddAdornments(false);
        envelope.setOutputSoapObject(request);
        return envelope;
    }

    private final HttpTransportSE getHttpTransportSE() {
        HttpTransportSE ht = new HttpTransportSE(Proxy.NO_PROXY,
                MAIN_REQUEST_URL, 60000);
        ht.debug = true;
        ht.setXmlVersionTag("<?xml version=\"1.0\" encoding= \"UTF-8\" ?>");
        return ht;
    }

    @SuppressWarnings("unused")
    private final List<HeaderProperty> getHeader() {
        List<HeaderProperty> header = new ArrayList<HeaderProperty>();
        HeaderProperty headerPropertyObj = new HeaderProperty("cookie",
                SoapRequests.SESSION_ID);
        header.add(headerPropertyObj);
        return header;
    }
}

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

    <EditText
        android:id="@+id/value_to_convert"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:hint="@string/date"
        android:gravity="center"
        android:inputType="number|text" />

    <EditText
        android:id="@+id/amount"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:gravity="center"
        android:hint="@string/amount"
        android:inputType="number" >

        <requestFocus />
    </EditText>

    <EditText
        android:id="@+id/user"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:ems="10"
        android:gravity="center"
        android:hint="@string/user"
        android:inputType="textPersonName" />

    <Button
        android:layout_width="200dp"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal"
        android:text="@string/submit"
        android:id="@+id/submit"/>

    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:gravity="center_horizontal"
        android:textSize="30sp"
        android:id="@+id/answer"
        android:hint="@string/response"
        />
</LinearLayout>


text:
Q: IIS: requesting PNG returns 401 I am attempting to create a web application, and I am testing it on my desktop using IIS.
My problem comes whenever I attempt to request a PNG image. The server responds with a 401 specifically for PNG images, but it responds just fine with JPEG images in the same folder.
I even ensured specifically that PNG files are allowed in the IIS Manager, as you can see in the image below:

Here is the log file:
2015-10-04 18:32:55 127.0.0.1 GET /asteroids/resources/millenium_falcon.png - 80 - 127.0.0.1 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/46.0.2490.52+Safari/537.36 http://localhost/asteroids/index.html 401 3 5 0
2015-10-04 18:32:55 127.0.0.1 GET /asteroids/resources/background.jpg - 80 - 127.0.0.1 Mozilla/5.0+(Windows+NT+10.0;+Win64;+x64)+AppleWebKit/537.36+(KHTML,+like+Gecko)+Chrome/46.0.2490.52+Safari/537.36 - 304 0 0 22

Is there anything else I am not checking here? I would appreciate any help!

A: Your IIS_IUSRS account in Windows might not be authorized to access the png files.
Check the Security applied to the JPG files and to the PNG files as below:

This is default settings, note that Read permissions are allowed and so are Read & Execute.
This is by default on my files. I haven't changed these permissions.
HTH


text:
Q: Is there any difference in ENEQuery object between Endeca 5 and Endeca 6? I am trying to integrate some code written for Endeca 6 to a codebase that queries a Endeca 5 server. I got exceptions:
Navigation Engine not able to process request
I am using the code like this:
 l_oQueryResults = getSearchConnection().getConnection(pRequest.get(SearchRequestBean.Locale)).query(pEneQuery);

I think theoretically if I pass the right pEneQuery, I can query the Endeca 5 indexes, right? So I am wondering if I passed a correct pEneQuery that can be identified by Endeca 5 navigation lib.Do you have any ideas?

A: The issue is probably with the endeca_navigation.jar being the wrong version.  You need to make sure that you use the endeca_navigation.jar that comes with Platform Services 5.X.

A: absolutely - there is a difference even among minor versions of their API (.jar or .dll). The version of your application API must match the mdex server's API version.


text:
Q: How do I rename a USB drive? How exactly would I rename a USB drive?
I've read that you can go into the Disk Utility, click on Edit Partition, and there is an option to rename the label but I can't click in the area to rename.
Is there any other way?

A: *

*Open "Disks" application

*Select the flash drive in the panel on the left

*Press the Unmount button (should look like a "stop button")

*Click on the gears icon ("More actions") and choose "Edit filesystem"

A: First, obtain the location of your USB drive:
sudo fdisk -l

Assuming that your device location is /dev/sdb1/:
You can safely check the current label without any side effects by issuing the following command:
sudo file /dev/sdb1 -s

Most USB sticks are formatted using  FAT16/FAT32. To change the label via the prompt, use the mlabel command. The label of a FAT filesystem requires to be exactely 11 characters. No more, no less. When characters are omitted, spaces are added at the beginning, and seemingly random characters are appended at the end.
Install the mtools package (GNU Tools for MSDOS filesystems):
sudo apt-get install mtools

Then you might need to configure the mtools drives settings, hence add the following two lines to /etc/mtools.conf (you will need sudo to edit)
# second and third drives, first partition
drive u: file="/dev/sdb1"
drive v: file="/dev/sdc1"

Having saved, you should then be able to look at your USB drive in (say) /dev/sdb1 as drive u:
sudo mtools -v u:

(See comments ....)
Then relabel:
sudo mlabel -i /dev/sdb1 -s ::"LABEL HERE "

For other filesystems (rarely used for USB sticks), see this page.

A: None of the given answers worked for me on my 14.10 system.
I used gparted as described in https://help.ubuntu.com/community/RenameUSBDrive.

*

*sudo apt-get install gparted

*open gparted

*choose the thumbdrive from the dropdown in the top-right corner

*unmount the volume (right-click on drive)

*right click and choose "label"

*click on green tick to apply changes

A: Right click on the drive you want to edit to bring up the properties window. Then the name will be highlighted by default. Just type your name and click enter.

A: Simpler:
Insert USB into a Mac or Windows PC
Right click on the device in Finder or Explorer > Rename
or
In macOS Finder > command click on USB name > it is selected > type new name
or
In macOS Finder > select USB > hit Enter > name is selected > type new name


text:
Q: How to display a screen for a few seconds when the app launches? I'm trying to display a screen for a few seconds when my app launches but I can't find how to do it in kotlin. I wanted that screen to be the first the user sees, then, after a few seconds, it would go directly to the login screen, can you help me?

A: please use handler to add some time delay to launch next functionality (in your case is launch next activity )
 new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
        @Override
        public void run() {
          displayData();
        }
    }, 5000);  //5000 is delay time you can change according to you need

A: You can create a new Activity then set it as your starting activity like this:
<activity
    android:name=".SplashScreenActivity">
    <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
    </intent-filter>
</activity>

Then, in your SplashScreenActivity, handle the delay like this:
Handler().postDelayed({
    val intent = Intent(this, LoginActivity::class.java)
    startActivity(intent)
    finish()
}, 3000)  // 3 seconds


text:
Q: TexStudio 2.12.4 (hg 6475:fe21cf14c0b4) Compile not defined Selecting 'Compile' from the quickstart menu, the following error occurs:
"Command txs:///compile not defined".
However, choosing 'Tools | Command| LuaLatex from the menus, starts the compile process which runs normally.
Similarly when 'View' is selected the following error occurs: "Command txs:///view not defined".
I have reinstalled TexStudio 12.12.4 with no success.
I installed TexStudio 12.12.2 which runs with no problems, compiling and displaying the same files files in an external pdf reader.
I have tried copying the contents of the build section of preferences in texstudio.ini 12.12.2 to 12.12.4 with no success.
I would appreciate any advice - thanks.

A: I was able to fix the problem by removing the following:
% !TEX TS-program = xelatex
I do not know why this is causing it, other than TeXStudio is not interpreting the code correctly.
I did not experience the problem with View command.
Hope this helps.


text:
Q: Win7 freeze/crash at random after all updates finish Already a couple of months I have that my computer starts freezing (screen stays on but nothing moves anymore, wont come out of this condition) after windows update. I reverted with system restore to the previous state and then all is ok. But I want my updates of course...
How can I find out what is causing this? It's a Win 7 pro n x64.
Note that the problem appears when restarting after windows update around 5th.June. What do I do when there are not enough versions to restore to ?

A: For that sort of problem i would do a full backup and wipe, i have spent days on similar issues .. clean machine and image before you run updates and afterwards using one of these
http://www.techsupportalert.com/best-free-drive-imaging-program.htm


text:
Q: Why function zip creates empty .zip archive from big sized files? I wrote a function that makes a .zip archive from a directory (and subdir-s, files in it)
func ZipDirectory(backupName string) error {
    file, err := os.Create(backupName)
    if err != nil {
        return err
    }
    defer file.Close()

    w := zip.NewWriter(file)
    defer w.Close()

    walker := func(path string, info os.FileInfo, err error) error {
        if err != nil {
            return err
        }
        if info.IsDir() {
            return nil
        }

        file, err := os.Open(path)
        if err != nil {
            return fmt.Errorf("error opening file %q: %w", path, err)
        }
        defer file.Close()

        f, err := w.Create(path)
        if err != nil {
            return fmt.Errorf("error creating file %q: %w", path, err)
        }

        _, err = io.Copy(f, file)
        if err != nil {
            return fmt.Errorf("error copying file %q: %w", path, err)
        }

        return nil
    }
    err = filepath.Walk(config.FilePath, walker)
    if err != nil {
        return err
    }
    return nil
}

but if directory weights more then 3GB it creates empty archive which weights exactly as it should be.
it looks like this:

help, don't understand this mystic result....

A: Big zip archives shows empty after archivation because you don't have installed software for unzipiing it (like 7Zip)
After installation and openning with 7Zip everything works


text:
Q: Trouble setting bool value of destination view controller in segue As I segue from SearchViewController to MatchCenterViewController, I want to set the bool value of _didAddNewItem in MatchCenterViewController to YES. I'm attempting to accomplish this like so:
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    if ([segue.identifier isEqualToString:@"ShowMatchCenterSegue"]) {
        MatchCenterViewController *controller = (MatchCenterViewController *) segue.destinationViewController;
        _didAddNewItem = YES;

        NSLog(@"we're about to set controller values before segueing to MC");
        // Send over the matching item criteria
        controller.itemPriority = self.itemPriority;

        if (_didAddNewItem == YES) {
           NSLog(@"Did add new item is YES");
        }
        [self.tabBarController setSelectedIndex:1];
    }
}

The destination view controller is tab 1, so I want to set the bool before it switches to that tab. It is logging out "Did add new item is YES", which tells me that the value of the bool is indeed YES just before segueing.
However, upon switching to the destination, when the viewDidAppear of the destination controller runs, it logs out "don't refresh".
- (void)viewDidAppear:(BOOL)animated
{
   if (_didAddNewItem == YES) {
        NSLog(@"well then lets refresh the MC");
   }
   else if (_didAddNewItem == NO) {
        NSLog(@"dont refresh");
   }
}

I set the bool property in the headers of both originating and destination VC like so:
@property (assign) BOOL didAddNewItem;

Very confused as to what I'm missing here.

A: You are confusing access to a property with access to the automatically synthesised iVar.
When you say
@property BOOL something;

and don't use an @synthesize statement the compiler will automatically create an iVar  BOOL _something to store the property.  You can then access this property using self.something or _something.  You should get into the habit of always using self.something (or object.something in the case of another object reference) except in initialiser methods.
In your code you are setting the local iVar _didAddNewItem when what you want is to set the property on the destination controller -
 controller.didAddNewItem = YES;


text:
Q: purrr: element-wise length comparison of multiple lists? I have three lists with 2 elements each. How do I check whether every element has the same length in every list? Preferably using purrr. Thank you!
list.a = list(a = 1, b = c(1, 2))
list.b = list(a = 2, b = c(1, 2))
list.c = list(a = 3, b = c(1, 2, 3))

Should return T, T, F.

A: For any two lists:
all(lengths(list.a)==lengths(list.b))

To check if all lists are equal:
same_length <- function (x, y) all(lengths(x) == lengths(y))
Reduce(f, list(list.a, list.b, list.c))

If you want to use purrr:
same_length <- function (x, y) all(lengths(x) == lengths(y))
purrr::reduce(list(list.a, list.b, list.c), f)

A: each element has the same length in every list? - This would be a single TRUE or FALSE. Based on your expected output and task I think you want to compare for specific length of list elements.
master_list <- list(list.a, list.b, list.c)
map_lgl(master_list, ~ all(lengths(.x) == 1:2))
[1]  TRUE  TRUE FALSE

A: Not entirely sure on the requirement but here's 2 potentially usefully snippets.
map_lgl(transpose(list(list.a, list.b, list.c)), ~ var(lengths(.x))==0)

  a     b
 TRUE FALSE

or for a more general output you can manipulate easier
map_dfr(list(list.a, list.b, list.c), ~map(.x, length))

      a     b
1     1     2
2     1     2
3     1     3


text:
Q: expects catch() or return even after returning the result sorry for asking a silly question but I have returned everything in the the given code but still it says
52:5   error    Expected catch() or return      promise/catch-or-return

I don't know what its expecting.this is my code.
52:5    rp(options).then(function (response,body) {
            a = response.data;
            return a;
        }).catch(function (error) {
            // POST failed...
            return console.log('error');

        }).then(result =>{
           console.log('key: ' + a);
           return db.collection('Users').doc(user_id).set({name:name1,notification_key:a,image:image1,token_id:token_id1,email:token_email});
});

A: It's a linter error (eslint rule promise/catch-or-return). It's meant to avoid unhandled rejections and promises.
The problem with line 52 is most likely that the full code is:
function myFunction() {
   /* ... */
   rp().then(/*.*/).catch(/*.*/).then(/*.*/);
}

You are not handling the promise, so either you add a catch() after the final then or return the whole promise with return rp().


text:
Q: PCA in R: different results for caret and prcomp Can some tell my why the preProcess function from the caret packages gives a different result than the prcomp function?
library(caret)

X <- as.matrix(iris[,1:4])
X <- apply(X, 2, function(x) x - mean(x))

car <- preProcess(X,
                  method = c('pca'),
                  thres = 1)

car$rotation
#                   PC1         PC2        PC3        PC4
# Sepal.Length  0.5210659 -0.37741762  0.7195664  0.2612863
# Sepal.Width  -0.2693474 -0.92329566 -0.2443818 -0.1235096
# Petal.Length  0.5804131 -0.02449161 -0.1421264 -0.8014492
# Petal.Width   0.5648565 -0.06694199 -0.6342727  0.5235971

p <- prcomp(X)
p$rotation
#                   PC1         PC2         PC3        PC4
# Sepal.Length  0.36138659 -0.65658877  0.58202985  0.3154872
# Sepal.Width  -0.08452251 -0.73016143 -0.59791083 -0.3197231
# Petal.Length  0.85667061  0.17337266 -0.07623608 -0.4798390
# Petal.Width   0.35828920  0.07548102 -0.54583143  0.7536574

n <- nrow(X)
cov_matrix <-  t(X)%*% X /n
e <- eigen(cov_matrix)
e$vectors
#             [,1]        [,2]        [,3]       [,4]
# [1,]  0.36138659  0.65658877 -0.58202985  0.3154872
# [2,] -0.08452251  0.73016143  0.59791083 -0.3197231
# [3,]  0.85667061 -0.17337266  0.07623608 -0.4798390
# [4,]  0.35828920 -0.07548102  0.54583143  0.7536574

Thanks for your help!

A: From the caret:preProcess documentation:

If PCA is requested but centering and scaling are not, the values will still be centered and scaled.

dev <- apply(X, 2, FUN="sd")
X.scaled <- t(t(X) / dev)
p <- prcomp(X.scaled)
print(p$rotation)
#                     PC1         PC2        PC3        PC4
# Sepal.Length  0.5210659 -0.37741762  0.7195664  0.2612863
# Sepal.Width  -0.2693474 -0.92329566 -0.2443818 -0.1235096
# Petal.Length  0.5804131 -0.02449161 -0.1421264 -0.8014492
# Petal.Width   0.5648565 -0.06694199 -0.6342727  0.5235971


text:
Q: In React useEffect does not update after the value has changed from other component I am trying to do some kind of online shop for myself and I got a problem.
I want to render my shopping cart size in the NavBar component (which is on every page).
I created a Cart Items service where I put all my added items, and it also has functions to addItem, removeItem, getCart, getCartSize.
When I click on Add/Remove on specific product, I would like to do that the value on NavBar with cart size would be changing depending on the cart size (from getCartSize method). I already tried to use useEffect hook, but it does not recognize when the value of cartSize is changed, how can I do that?
This is what I have done already.
navbar.jsx:
//...
//...
import {getTotalCount} from '../../services/myCart';

export default function Navbar() {
  // ...
  const [count, setCount] = useState();

  useEffect(() => {
    setCount(getTotalCount());
    console.log('counto useeffect');
  },[getTotalCount()]);

  return (
    <>

                <Link className="navbar__list-item__home-icon" to="/"><FaHome/></Link>
                <Link className="navbar__list-item" to="/products">Products</Link>

cart size--> {count}

                <Link className="navbar__list-item__cart-img" to="shopping-cart"><FaShoppingCart/></Link>

    </>
  );
}

myCart.js all functions work fine and I call them when I click add/remove button in on my component in the products page.
var InTheCart = [

];
var totalCount = 0;

export function AddToCart(item) {
    // ... logic
    totalCount++;
}

export function ContainsInTheCart(id) {
    return InTheCart.findIndex(x=> x.item.id == id) != -1 ? true: false;
}

export function RemoveFromCart(id) {
   // ... logic
        totalCount--;
}

export function getCart() {
    return InTheCart;
}

export function getTotalCount() {
    return totalCount;
}

A: In the dependency array you need to pass only the name of the function, just like below:
useEffect(() => {
   setCount(getTotalCount());
   console.log('count useEffect');
}, [getTotalCount]); // not like => getTotalCount()

The code was calling also the function like getTotalCount() but only the name is needed, you don't need to call that.
I hope that helps!


text:
Q: heroku mongo typeerror Cannot read property 'split' of null Any luck with this error anyone.
TypeError: Cannot read property 'split' of null
This is the error message on Heroku logs. The code runs perfectly locally with a mongo db atlas link but am getting a few issues on the deploying.


text:
Q: Como tomar valor de una grilla y adjuntarla a otra grilla? les paso a comentar mi necesidad.
tengo dos formularios "A" con punto de venta, y "B" con busqueda de articulo, cada uno con una grilla.
como hago para que cuando selecciono el articulo de la grilla del formulario "B", se cargue en la grilla del formulario "A"?

A: Lo que plantas se resuelve comunicando los formularios, aqui
Comunicar Formularios
explica como puede lograrlo, no lo explico con dos grids, pero si envio los datos seleccionados del grid del form hijo B al form padre A

Hay varias formas de resolverlo

*

*usando interfaces

*usando eventos

ambas permiten desacoplar la interaccion y pasar los datos
Para la primera defines la interfaz como ser
interface IForm{
   void ArticuloSeleccionado(Articulo item);
}

entonces en el form padre implementas la interfaz
public class FormPrincipal : Form, IForm {

    //codigo del form

    //implementas el metodo de la interfaz que recibe el articulo
    public void ArticuloSeleccionado(Articulo item)
    {
       //aqui agregas la row al grid
    }

    private void button1_Click(...){
      frmArticulo frm = new frmArticulo(this);
      frm.Show()
    }
}

Es importante ese this en el constructor del form hijo al instanciarlo
Despues el form hijo envias la seleccion teniendo la instancia
public class frmArticulo : Form{

     private IForm _form;

     public frmBuscar(IForm form){ //este es el constructor
          _form = form;
     }

     private void gridview1_DoubleClick(...)
     {
         //aqui conviertes los datos a la entidad articulo
         _form.ArticuloSeleccionado(...);
     }
 }


text:
Q: Can I get ST3 to kill the previous instance of my program before starting another when building? In my project settings, I have a build system that looks like this:
"build_systems":
[
    {
        "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)",
        "name": "My Python Builder",
        "selector": "source.python",
        "shell_cmd": "/.../env/bin/python -u \"/.../main.py\""
    }
],

This way I can run my program from anywhere in the project with cmd-B. The problem is, unless I explicitly exit the program, when I run cmd-B again it just launches another instance. Is there a way to get Sublime to kill the previous instance launched via Build when I build again?

A: I've bodged this to work by making my program write out its own pid, then doing the following:
"shell_cmd": "kill -9 `cat /tmp/myapp.pid`; env/bin/python -u main.py",


text:
Q: Removing consecutive duplicate words in a string I am trying to write a function that removes consecutive duplicate words within a string.   It's vital that one any matches found by the regular expression remains.   In other words...

A very very very dirty dog

should become...

A very dirty dog

I have a regular expression that seems to work well (based on this post)
(\b\S+\b)(($|\s+)\1)+

However I'm not sure how to use preg_replace (or if there's a better function) to implement this.   Right now I have it deleting all matching repeated words without leaving one copy of the word intact.    Can I parse a variable or special instruction to it to keep a match ?
I have this currently...
$string=preg_replace('/(\b\S+\b)(($|\s+)\1)+/', '', $string);

A: You may use a regex like \b(\S+)(?:\s+\1\b)+ and replace with $1:
$string=preg_replace('/\b(\S+)(?:\s+\1\b)+/i', '$1', $string);

See the regex demo
Details:

*

*\b(\S+)  - Group 1 capturing one or more non-whitespace symbols that are preceded with a word boundary (maybe \b(\w+) would suit better here)

*(?:\s+\1\b)+ - 1 or more sequences of:

*

*\s+ - 1 or more whitespaces

*\1\b - a backreference to the value stored in Group 1 buffer (the value must be a whole word)

The replacement pattern is $1, the replacement backreference that refers to the value stored in Group 1 buffer.
Note that /i case insensitive modifier will make \1 case insensitive, and I have a dog Dog DOG will result in I have a dog.

A: <?php
$text ='one one, two three, two';
$result_text = preg_replace("/\b(\w+)\s+\\1\b/i", "$1", $text);
echo "Result Text: ".$result_text; //one, two three, two
?>

Try this. It should return one copy intact.


text:
Q: Minimum amount of material to make a cuboid with fixed volume I'm trying to assist a student with the following optimization problem. The instructions say to use the partial derivative test which I'm having trouble with. I can solve the problem with Lagrange multipliers just fine, but the student doesn't know that method yet.

A rectangular metal tank with an open top is to hold $256$ cubic feet of liquid. What are the dimensions of the tank that require the least material to build?

Let $A(x,y,z)=xy+2xz+2yz$. Then we want to find $\min \left\{A(x,y,z) \mid xyz=256\right\}$. First I find the critical points,
$$\begin{cases}\frac{\partial A}{\partial x} = y + 2z = 0 \\ \frac{\partial A}{\partial y} = x + 2z = 0 \\ \frac{\partial A}{\partial z} = 2x + 2y = 0\end{cases} \implies x=y=-2z \implies 4z^3 = 256$$
so that $z=4$, but $x$ and $y$ both turn out to be negative. Is there something I am missing, or is this problem flawed in some fundamental way?

A: $A(x,y,z)=xy+2xz+2yz ~$ itself has no minimum.
So you should apply the constraint and then take the partial derivatives.
$ \displaystyle A = xy + 2x \cdot \frac{256}{xy} + 2y \cdot \frac{256}{xy} = xy + \frac{512}{y} +  \frac{512}{x}$
$ \displaystyle \frac{\partial A}{\partial x} = y - \frac{512}{x^2} = 0$
$ \displaystyle \frac{\partial A}{\partial y} = x - \frac{512}{y^2} = 0$
So, $x^2y = xy^2 = 512 \implies x = y = 8$ and that leads to $z = 4$.


text:
Q: Matrix that are not upper triangular I saw in the book "Linear algebra done right" (by S. Axler) that all complex operator has a Jordan form. The proof is based on the fact that all complex operator is upper triangular (i.e. there is a basis s.t. the matrix is upper triangular). My questions are the following :

*

*1) Could you give me an example of operator that is not upper triangular (I guess such an operator has no eigenvalue... may be an operator with $x^2+1$ as polynomial characteristic ?)

*2) If an operator has at least one eigenvalue, does it has a Jordan form ? (in the proof of Axler it's indeed based on the fact that it has an eigenvalue, but also on the fact that the characteristic polynomial is of the form $(x-\lambda _1)^{m_1}...(x-\lambda _n)^{m_n}$ (btw how do you call such a form ? in french we say "scindé" but I didn't find an english equivalent on wikipedia). So I guess that a characteristic polynomial of the form $x^2+x+1$ will not have a Jordan form even not a upper triangular form... but these are just supposition, and if anyone can confirm or not, I would be very happe :)

A: Consider the map $T\colon\mathbb{R}^2\longrightarrow\mathbb{R}^2$ defined by $T(x,y)=(-y,x)$. There is no basis of $\mathbb{R}^2$ such that the matrix of $T$ with respect to that basis is upper triangular. Note that, as you suspected, $T$ has no (real) eigenvalues.
And the map $U\colon\mathbb{R}^3\longrightarrow\mathbb{R}^3$ defined by $U(x,y,z)=(-y,x,0)$ has one eigenvalue ($0$), but no Jordan form.


text:
Q: Crossfading between 2 audio signals / single supply opamp circuit Will this circuit work? Any comments? Thanks!
Edit :
by "work" I mean I can blend the 2 audio signals in any ratio with the pot;
it would be an OPA2132 opamp;
input would be audio signals in the range of 0-3.3v

it seems even this circuit would work?

A: There are simpler circuits like this one: -

And I've posted it for two reasons, 1) to show the decoupling capacitors that must be fitted and 2) to explain that your circuit has certain benefits that may not be that obvious.
You circuit does not rely on the signal sources being low impedance - if the pot is totally at one end of its travel it will 100% attenuate one signal whereas the simplified circuit won't do that if the output impedances of the signal sources are not zero.
If you are expecting unity gain, then you ought to figure out the proper value of feedback resistor - with your circuit's pot at one end, the other channel will suffer a fair amount of attenuation but this can be easily remedied however you need to state what value your pot has. I'd go for your circuit over my example.

A: The basic idea is OK, but the DC biasing is messed up.  The DC level of R3 should be decoupled from the opamp input.

A: I suggest you using such a circuit as below. first section is a inverting unity gain op-amp. then a voltage divider. and finally a voltage subtract circuit.
Vou = Input2 + (Input1/K)
which K is the constant of pot R3.
Advantages of this circuit :

*

*No Loading effect on the both input voltages.

*Control Gain of each Input voltage independently.

simulate this circuit – Schematic created using CircuitLab


text:
Q: Does Hibernate Session release the db connection if it is not used for a long time I know that Hibernate Session obtains a database connection only when it is required. And I know that the connection is released when session.close() is called. But what I am not clear is, what happens to the connection if the session was not closed? Does hibernate automatically release the database connection after some time?

A: AFAIK, it doesn't. Depending on your environment (client or server, connection pool usage, ...) the connection behavior regarding timeout might be defined in a different layer, usually the connection pool.


text:
Q: What is a name for co-Sobczyk Banach spaces?
Definition. Let us define a Banach space $X$ to be co-Sobczyk if every linear bounded operator $T:Z\to c_0$ defined on a separable subspace $Z$ of $X$ extends to a bounded operator $\bar T:X\to c_0$.

By the classical Sobczyk Theorem, each separable Banach space is co-Sobczyk.
But the class of co-Sobczyk spaces includes many non-separable Banach spaces.
In particular, a Banach space $X$ is co-Sobczyk if each separable subspace of $X$ is contained in a complemented separable subspace. So, all classical Banach spaces $c_0(\Gamma)$ and $\ell_p(\Gamma)$ for $1\le p<\infty$, are co-Sobczyk for any set $\Gamma$.
I have a strong feeling that co-Sobczyk spaces have been studied in the theory of non-separable Banach spaces, so asking the MO commubnity for a proper reference and an existing terminology (I suspect that co-Sobczyk spaces are called differently).

A: Nigel Kalton studied a similar but stronger notion: for $\lambda \geqslant 1$, he termed a Banach space $X$ to have the $(\lambda, \mathcal{C})$-extension property, when for any compact space $K$ you may find extensions of operators $T$ from subspaces of $X$ into $C(K)$ to operators from $X$ to $C(K)$ with norm at most $\lambda \|T\|$.
It is thus natural to term your spaces as having the $(\lambda, c_0)$-separable extension property if you care about the extension constant.
Update: Correa and Tausk call this separable $c_0$-extension property.


text:
Q: Can't display putExtra in share at navigation bar I have code for share in navigation bar and i fetch package and text but my one putExtra line is not displayed.
else if (id == R.id.nav_share) {
            try {
                Intent i = new Intent(Intent.ACTION_SEND);
                i.setType("text/plain");
                i.putExtra(Intent.EXTRA_SUBJECT, " Hey Download this App Called\n App name");
                String sAux = " to Improve your Life's....... \nAt least One Time Try This\n";
                sAux = sAux + "https://play.google.com/store/apps/details?id=com.example.kishorsinh.app \n\n";
                i.putExtra(Intent.EXTRA_TEXT, sAux);
                startActivity(Intent.createChooser(i, "Choose one"));
            } catch(Exception e) {
                //e.toString();
            }
        }

i have use this code in app and share then it display only....
to Improve your Life's.......
At least One Time Try This
https://play.google.com/store/apps/details?id=com.example.kishorsinh.app
can anyone suggest me what is the problem? It's not reflecting putExtra field.

A: I have changed whole program it may solve others problem it's worked perfect for me
   try {
                    Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
                    final String appPackageName = getApplicationContext().getPackageName();
                    String strAppLink = "https://play.google.com/store/apps/details?id=" + appPackageName;
                    shareIntent.setType("text/plain");
                    String shareBody = strAppLink;
                    String shareSub = "Hey Download this App Called\n Appname ........\nAt least One Time Try This\n";
                    shareIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, shareSub);
                    shareIntent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
                    startActivity(Intent.createChooser(shareIntent, "Share using"));
                }
                catch (ActivityNotFoundException e)
                {

                }


text:
Q: White space below the footer In the home page of my site there is a big white space after the footer.
You can check here

A: The problem is cause by the submenu for Merceria. It's waaaaay too big.
Removing that submenu makes the empty space go away.
You may consider displaying your submenus on multiple columns.


text:
Q: Is there a more stringent version of std::stoi? I just discovered (much to my surprise) that the following inputs do not cause std::stoi to throw an exception:
3.14
3.14helloworld

Violating the principle of least surprise - since none of these are valid format integer values.
Note, perhaps even more surprisingly 3.8 is converted to the value 3.
Is there a more stringent version of std::stoi which will throw when an input really is not a valid integer? Or do I have to roll my own?
As an asside, why does the C++ standard library implement std::stoi this way? The only practical use this function has is to desperately try and obtain some integer value from random garbage input - which doesn't seem like a very useful function.
This was my workaround.
static int convertToInt(const std::string& value)
{
    std::size_t index;
    int converted_value{std::stoi(value, &index)};

    if(index != value.size())
    {
        throw std::runtime_error("Bad format input");
    }

    return converted_value;
}

A: The answer to your question:

Is there a more stringent version of std::stoi?

is: No, not in the standard library.
std::stoi, as described here behaves like explained in CPP reference:

Discards any whitespace characters (as identified by calling std::isspace) until the first non-whitespace character is found, then takes as many characters as possible to form a valid base-n (where n=base) integer number representation and converts them to an integer value. The valid integer value consists of the following parts:  . . . . .

And if you want a maybe more robust version of std::stoi which fits your special needs, you do really need to write your own function.
There are that many potential implementations that there is not the ONE "correct" solution. It depends on your needs and programming style.
I just show you (one of many possible) example solution:
#include <iostream>
#include <string>
#include <utility>
#include <regex>

// Some example. Many many other different soultions possible
std::pair<int, bool> stoiSpecial(const std::string s) {

    int result{};
    bool validArgument{};

    if (std::regex_match(s, std::regex("[+-]?[0-9]+"))) {
        try {
            result = stoi(s);
            validArgument = true;
        }
        catch (...) {};
    }
    return {result, validArgument };
}

// Some test code
int main() {

    std::string valueAsString{};
    std::getline(std::cin,valueAsString);

    if (const auto& [result, validArgument] = stoiSpecial(valueAsString); validArgument)
        std::cout << result << '\n';
    else
        std::cerr << "\n\n*** Error: Invalid Argument\n\n";
}

A:
Is there a more stringent version of std::stoi which will throw when an input really is not a valid integer? Or do I have to roll my own?

You will have to roll your own, because your demands clash with the one, consistent, unsurprising way in which all "string to integer" functionality in both C and C++ is defined.
First off, you'd have to come up with your definition of "a valid integer". Do you accept leading 0 (octal), leading 0x (hexadecimal), and / or leading 0b (binary)? Do you accept leading whitespace?
If you're OK with both, your workaround is good enough. Otherwise, you'd have to check the first character of your string to be isdigit as well as being non-null.

I just discovered (much to my surprise) that the following inputs do not cause std::stoi to throw an exception:

Reading a good reference on any function you are not very familiar with before using it is a rather basic requirement.
That reference states very clearly that, after skipping any leading whitespace, it will take "as many characters as possible" to form "a valid [...] integer number representation", and that the second argument "will receive the address of the first unconverted character".

Violating the principle of least surprise - since none of these are valid format integer values.

Note, perhaps even more surprisingly 3.8 is converted to the value 3.

Is there a more stringent version of std::stoi which will throw when an input really is not a valid integer? Or do I have to roll my own?

There is one significant problem here: You have made assumptions, haven't bothered to check them with a reference, and are now digging in your heels that you know better. Not only is the behavior you observed internally consistent with all of C++'s istream operator>>, std::sto* family, and C's *scanf, strto*, and ato* family. It is also how Java's Scanner.nextInt(), C#'s int.TryParse, Perl's int, and similar functions from a dozen other languages work.
(By the way, this is also true for the various floating-point parsing functions as well.)

Why is std::stoi implemented this way?

Because this is the most efficient implementation for the general use-case.

The only practical use this function has is to desperately try and obtain some integer value from random garbage input - which doesn't seem like a very useful function.

Consider:
4;3.14;16

That is clearly not "random garbage input", but semicolon-separated data -- something encountered quite often, you will agree.
If "reading an int" would throw an exception at a non-digit input, like you suggest, we would be looking at a minimum of two exceptions being thrown for parsing this very non-exceptional line of input. Alternatively, we would have to pass over that input twice, first for finding the semicolons / line ends (and either having to write into the input string or setting up several temporary variables), then a second time for parsing. That would be very inefficient.


text:
Q: Match tuple values within the list Compare tuples within a list, I have list which contains details of the address, and i need to compare if two address's are same or not,
address1= [('1546-1711', 'AddressNumber'),
  ('South', 'StreetNamePreDirectional'),
  ('4650', 'AddressNumber'),
  ('West,', 'StreetNamePostDirectional'),
  ('Green', 'PlaceName'),
  ('Lake', 'PlaceName'),
  ('town,', 'PlaceName'),
  ('MI', 'StateName'),
  ('84107', 'ZipCode')]

 address2 = [('800', 'AddressNumber'),
  ('Green', 'StreetName'),
  ('Lake', 'PlaceName'),
  ('town,', 'PlaceName'),
  ('MI', 'StateName'),
  ('84110', 'ZipCode')]

There are some attibutes which are missing in second address like 'StreetNamePreDirectional' and 'StreetNamePostDirectional', so i have to compare on the remaining attributes whichever is present, so first i need to check what attributes are common between both and then compare if they have matching values, what's the pythonic way to do it
My code so far:
for item1 in add2:
    for item2 in add1:
        if(item2[1]=='AddressNumber' and item1[1]=='AddressNumber'):
            addressnumbermatch = True
        if(item2[1]=='StreetNamePreDirectional' == item1[1]=='StreetNamePreDirectional'):
            StreeNameDirectionMatch = True
        if(item2[1]=='StreetNamePreDirectional' == item1[1]=='StreetNamePreDirectional'):
            StreetNamePreDirectionalMatch = True

if(addressnumbermatch and StreeNameDirectionMatch and StreetNamePreDirectionalMatch ):
    # Do somthing

Note: There are multiple attibutes like AddressNumber and Place Name so it should match any one value out of multiple values. so first address contains two Address number so need to check if any of these two values matches with the Address number of Address2

A: (Apart from the issue @glibdud pointed out) The way to go, I think, is to use set.
s1 = set(address1)
s2 = set(address2)
common = s1.intersection(s2)

Of course you can use more set operations to determine whether the overlap is enough evidence of being similar, but we do not have that information on your data.
In this case, it will output:
s1.intersection(s2)
Out[31]: {('Lake', 'PlaceName'), ('MI', 'StateName'), ('town,', 'PlaceName')}

In the end, I get the feeling from the definition of the question where one of the two can contain multiple addresses that you want to know whether an address is listed in your address register. In that case instead of intersection you'll want to use s1.issuperset(s2) or s2.issubset(s1), which returns you a nice bool to work with.
s1.issuperset(s2)
>> False

A: a good way to do this is to have a function that will extract the information you need from the tuple list i.e.
def get_address_info(address_data):
    address_number = None
    street_name_pre_directional = None
    street_name_post_directional = None

    for value, property_name in address_data:
        if property_name == "AddressNumber":
            address_number = value
        elif property_name == "StreetNamePreDirectional":
            street_name_pre_directional = value
        elif property_name == "StreetNamePostDirectional":
            street_name_post_directional = value

    return address_number, street_name_pre_directional, street_name_post_directional

that way you dont have to compare the items with each another, and the maintenance is easier
now you can get the necessary data and compare them directly and determine whether some information is missing by checking whether None is present in the info
add1_info = get_address_info(add1)
add2_info = get_address_info(add2)
if add1_info  == add2_info and None not in add1_info and None not in add2_info :
    #do something...


text:
Q: Clarification on using stripe I'm essentially following this guide:
https://rails.devcamp.com/ruby-gem-walkthroughs/payment/how-to-use-a-custom-form-for-stripe
However, I'm confused about two things:

*

*What if I want to add additional data to be filled out by the user, such as billing address, zip code, full name, and use that for stripe to verify the credit card with? What do I need to add and where?

*How do I tell that the payment has gone through? I'm going to be selling an online product -- I need some way to verify that the user has paid successfully in order to unlock access to the product.

Thanks!

A: 1) You can specify with the Stripe.js options whether you would like to add billing and/or shipping address to your checkout form.
2) You can check your payment results by:

*

*The return value of your API call to create a charge. Look for the status parameter

*Log in to your dashboard and check it there

*Use Stripe's webhooks, and listen for the charge.succeeded event type.


text:
Q: Show that $m^{*}([a, b]\backslash G)=b − a- m^{*}{(G)}$ In the proof of Theorem 1.23 in Real Analysis by Bruckner it is used the following without a proof

Let $G$ be an open subset of an interval $[a, b]$ and write $K =[a, b]\backslash G$. Then $m^{*}{(K)}=b − a- m^{*}{(G)}$.

If it were measure, yes $G$ and $K$ are disjoint thus $m(K)=b − a- m(G)$ holds but how to prove the equality for outer measure that is defined by $m^{*}{(E)}=\inf{\{ \sum_{i=1}^{\infty} |I_i| \ :\ E\subset\cup_{i=1}^{\infty}I_i }\}$. I even know $G$ can be written as a countable union of open intervals and $K$ is a compact set but those don't help too. A detailed explanation would be much appreciated.
Added: Actually $m^{*}([a, b]\backslash G)=b − a- m_{*}{(G)}$ holds for every set $G$ and the claim to be proved is $m^{*}{(G)}=m_{*}{(G)}$. The book hasn't introduced much things yet!

A: It suffices to prove that, if $G$ is an open subset of $[a, b]$, then we have $m_*(G) = m^*(G)$, where $m_*(G)$ is defined as $\sup\{m^*(K): K \subseteq G \text{ compact}\}$.
We write $G$ as a countable disjoint union of open intervals $G = \bigcup_{i = 1}^\infty I_i$. I assume that you know that $m^*(G) = \sum_{i = 1}^\infty |I_i|$.
Since $m_*(G) \leq m^*(G)$ always holds, it suffices to show the other direction.
In the following, we assume that $m^*(G) < \infty$. The case $m^*(G) = \infty$ can be treated similarly.
For a given $\epsilon > 0$, we choose a finite subset $S \subseteq \{1, 2, \dots\}$ such that $m^*(G) - \sum_{i \in S} |I_i| < \frac \epsilon 2$.
Without loss of generality, we may assume that $S$ is the set $\{1, \dots, n\}$. We write $I_i = (a_i, b_i)$.
We then construct a compact set $K = \bigcup_{i = 1}^n [a_i + \frac \epsilon{4n}, b_i - \frac \epsilon{4n}]$. Since $K$ contains the disjoint union $\bigcup_{i = 1}^n (a_i + \frac \epsilon{4n}, b_i - \frac \epsilon{4n})$, we have $$m^*(K) \geq m^*(\bigcup_{i = 1}^n (a_i + \frac \epsilon{4n}, b_i - \frac \epsilon{4n})) = \sum_{i = 1}^n (|I_i| - \frac \epsilon {2n}) = (\sum_{i = 1}^n |I_i|) - \frac \epsilon 2 > m^*(G) - \epsilon. $$
Therefore we have shown that $m_*(G) > m^*(G) - \epsilon$ for any $\epsilon > 0$.


text:
Q: Selberg Integral - Change of Variables I am trying to evaluate a Selberg-Like integral and I need to make the integral separable (unbinding the variables), but I can't come up with an appropriate change of variables. The integral is:$$\underset{[0,1]^m}{\int\dots\int} d^2z_1\dots d^2z_m \prod_{i<j} |z_i-z_j|^{-\gamma^2} f(z_1,\dots, z_m).$$
I am thinking about this as a function of $\gamma$, so the function $f(z_1,\dots, z_m)$ doesn't really matter yet. I need to introduce a change of variables such that $\prod_{i<j} |z_i-z_)|^{-\gamma^2}$ can be split into terms that include only one variable each. The case with $m=2$ is easy (polar coordinates). For $m=3$, I tried the following: $x_1-x_2=y_1$ and $x_1-x_3=y_1y_2$. This works fine when $m=3$, but I am not sure it can be extended to any $m\in\mathbb{N}$.

A: If you just want to split the $z_{i}-z_{j}$ and don't care if you complicate the $f(z_{1},\cdots ,z_{n})$, then the Fourier representation is the way to go. To simplify, I will sketch the method using real variables x, the extension to complex variables is tedious, but I think the principle holds.
Start from $\prod_{i<j}g^{2}(|x_{i}-x_{j}|)=\prod_{i\neq j}g(|x_{i}-x_{j}|)$,
Define $g(x)$such that $g(x)=|x|^{-\frac{1}{2}\gamma^{2}}\text{for }x\in[0,1]$ and $0$ elsewhere.
Define $g=\int dke^{ikx}\tilde{g}(k)$ (the Fourier representation) and suppose you can evaluate it in closed form (exercise for the reader).
The Integral $$ I=\int dx_{1}\cdots dx_{n}\prod_{i\neq j}g(x_{i}-x_{j})f(x_{1},\cdots,x_{n})$$ becomes $$I =\int dx_{1}\cdots dx_{n}\int \prod_{i\neq j} dk_{ij}\tilde{g}(k_{ij})e^{i\sum_{i\neq j}k_{ij}(-x_{i}+x_{j})}f(x_{1},\cdots,x_{n})$$
let us examine the exponent: $\sum_{i\neq j}k_{ij}(-x_{i}+x_{j})=\sum_{i}x_{i}\sum_{j}(k_{ji}-k_{ij})$
So,
$$I=\int dx_{1}\cdots dx_{n}\int \prod_{i\neq j} dk_{ij}\tilde{g}(k_{ij})e^{i\sum x_{i}\sum_{j}(k_{ji}-k_{ij})}f(x_{1}\cdots x_{n}).$$ Notice that the x integration is actually a Fourier transform of $f$ (at least if we extend the function $f$ to be zero outside the $x$ integration range.
$$I=\int\prod_{ij} dk_{ij}\tilde{g}(k_{ij})\tilde{f}(\sum_{p}(k_{p1}-k_{1p}),\cdots,\sum_{p}(k_{pn}-k_{np}))$$ which is as far as I can get without making more assumptions.
Whether this helps, or just moves the difficulty elsewhere is up to you.


text:
Q: Unable to exit this illegal statement exception loop I am new to android.And i got this task at work.you can see in the logs i am getting illegal statement multiple times.what i want is it should give this exception only one time .below is the method that i think causing the exception.
   @Override
    public boolean executeInsertQuery(String query) {
        boolean isInsertSuccess;
        SQLiteStatement sqlStmt = null;
        try {
            if (dbWriteInstance == null) {
                dbWriteInstance = getWriteableDatabase();
            }
            sqlStmt = dbWriteInstance.compileStatement(query);
            sqlStmt.executeInsert();
            dbWriteInstance.yieldIfContendedSafely();
            isInsertSuccess = true;
        } catch (Exception e) {
            bllLog.logInfo(LogWarningEvent.UNEXPECTED_EXCEPTION, e,
                    "Exception in SQLiteAccess.executeInsertQuery()");
            isInsertSuccess = false;
        } finally {
            if (sqlStmt != null) {
                sqlStmt.close();
            }
        }

        return isInsertSuccess;
    }

    /**
     * Compiles an SQL statement into a reusable pre-compiled statement object.
     * The parameters are identical to {@link #execSQL(String)}. You may put ?s in the
     * statement and fill in those values with {@link SQLiteProgram#bindString}
     * and {@link SQLiteProgram#bindLong} each time you want to run the
     * statement. Statements may not return result sets larger than 1x1.
     *
     * @param sql The raw SQL statement, may contain ? for unknown values to be
     *            bound later.
     *
     * @return A pre-compiled {@link SQLiteStatement} object. Note that
     * {@link SQLiteStatement}s are not synchronized, see the documentation for more details.
     *
     * @throws SQLException If the SQL string is invalid for some reason
     * @throws IllegalStateException if the database is not open
     */
    public SQLiteStatement compileStatement(String sql) throws SQLException {
        lock();
        try {
            if (!isOpen()) {
                throw new IllegalStateException("database not open");
            }
            return new SQLiteStatement(this, sql);
        } finally {
            unlock();
        }
    }

See the image from 10689 to 10715 i am getting this multiple times i just want this whole block one time

Any suggestion on this will be helpful thanks..

A: yes @Bentaye the name of this class is also sqlitedbaccess.sry stack overflow is not allowing me to comment more.


text:
Q: Decoding seems to have no effect in Python socket script I am attempting to communicate between two AWS EC2 instances using Python sockets.
The code is as follows:
sQuery.connect((hostIP, port))
inpString = str(inpString)
inpString = inpString.encode('utf-8')
sQuery.sendall(inpString)

which was, before
sQuery.connect((hostIP, port))

sQuery.sendall(inpString).encode('utf-8')

and it worked fine, till one test run when the machine decided it needed a bytes object not string. So I changed it to the explicit version above. The code iterates through this for every IP address in a list (connecting to one, doing some stuff, then disconnecting then connecting to next). If I do not keep the
inpString = str(inpString) then the first iteration goes fine but the second one it says bytes has no attribute 'encode'.
The problem is on the other end of the socket, which runs this code:
searchTerm = (conn.recv(2048))
print(type(searchTerm))
searchTerm = searchTerm.decode('utf-8')
print(type(searchTerm))
print('Data received: ', searchTerm)

to get the following output:
Listening on  <Listening PORT>
Connected by  ('IP ADDRESS', PORT)
<class 'bytes'> #received data
<class 'str'> #after performing the explicit decode above
Data received:  b'yard' #AND YET IT SHOWS A BYTE OBJECT

As you can see, even after the type of object is str (string), the Data received: print statement shows a byte object!
Then when I use the 'data received' term, in this case "b'yard'" while searching through a text file it says nothing found, since it is a byte object not a string. But I do not know what I am doing wrong with the data type changes? I explicitly change it to string, and Python agrees, but when using the decoded string, it shows up as a byte object!
EDIT: Steffen Ullrich's answer below made sense and it worked!
TO answer his question, I changed this code:
sQuery.connect((hostIP, port))
inpString = str(inpString)
inpString = inpString.encode('utf-8')
sQuery.sendall(inpString)

to this:
sQuery.connect((hostIP, port))

try:
    inpString = inpString.encode('utf-8')
except AttributeError:
    pass

My reasoning was: if on the second iteration the code encounter inpString to be bytes, and would like to throw "Bytes object has no attribute encode", this should take care of it.

A: Your problem has nothing to do with sockets. You simply sent the wrong string from start and you don't recover from this mistake in the recipient.

inpString = str(inpString)

You have the wrong assumption that str(...) converts bytes to a string. But it does not, at least not in the way you want. It does not treat the bytes as characters but it converts it only into a readable representation which still shows that this was bytes:
$ python3
...
>>> b=b'1234'
>>> len(b)
4
>>> s=str(b)
>>> s
"b'1234'"
>>> len(s)
7

As you can see it converts the bytes sequence b'1234' (length 4) into the string "b'1234'" (length 7). Instead of using str you should treat the bytes  as sequence of characters and decode it into a string:
>>> s=b.decode('utf-8')
>>> s
'1234'
>>> len(s)
4


text:
Q: Why does LinearLayout not correctly display nested FrameLayout? I have an XML layout where I nested a FrameLayout within a LinearLayout and attempted to stack a sibling viewing group on top of the FrameLayout. It does not show the sibling viewing group at all, but just the FrameLayout. I wanted to please get some help in understanding why replacing the root ViewGroup to a RelativeLayout produces an expected output.
Here is the Layout:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
     android:layout_height="match_parent"
     android:orientation="vertical">
     <FrameLayout
         android:layout_width="match_parent"
         android:layout_height="match_parent"
         android:id="@+id/mainFrameLayout"
         android:background="#787878"/>
    <LinearLayout
         android:layout_width="match_parent"
         android:layout_height="match_parent"
         android:orientation="vertical">
         <ImageView
             android:id="@+id/ImageView01"
             android:layout_height="wrap_content"
             android:layout_width="match_parent"
             android:src="@drawable/download"
             android:adjustViewBounds="true"/>
         <TextView
             android:layout_width="match_parent"
             android:layout_height="wrap_content"
             android:textColor="#000"
             android:textSize="40sp"
             android:text="Top text" />
         <TextView
             android:layout_width="match_parent"
             android:layout_height="wrap_content"
             android:layout_gravity="bottom"
             android:gravity="right"
             android:text="bottom_text"
             android:textColor="#fff"
             android:textSize="50sp" />
</LinearLayout>

</LinearLayout>
I only see the FrameLayout by itself filling the screen. When I change the root ViewGroup to a RelativeLayout defined with a layout_height and layout_width to "match_parent", I get my expected output where the ImageView and both TextViews show on top of the FrameLayout. I am confused on how that made it work because I didn't specify any RelativeLayout parameters to the child ViewGroups/View like "bottomof" or "topof".
Is there a resizing propery or weight distribution that RelativeLayout has that LinearLayout does not? I have been looking online, but unfortunately have not found an answer.
Thank you!

A: In the code you showed, the first FrameLayout matches the parent's height, so the LinearLayout that follows is pushed offscreen below (y-axis, not z-axis) the FrameLayout. This is because their parent is a LinearLayout, which arranges it's children one below the other vertically (y-axis), non-overlaping (as in a roll of toiler paper where each view is a paper square).
If you wanted the child FrameLayout and LinearLayout to be on top of the other (z-axis) their parent would have to be a FrameLayout, which arranges it's children one on top of the other overlaping in the z-axis (as in a stack of paper sheets).
As to why a RelativeLayout without specifying layout parameters gave you your expected behavior, it's because the default is to place child views at the top left corner of the container (from RelativeLayout documentation):

By default, all child views are drawn at the top-left of the layout, so you must define the position of each view using the various layout properties available from RelativeLayout.LayoutParams.

A: You should remove match_parent from FrameLayout as Linearlayout in vertical orientation placed the view one after another.
In your case, FrameLayout is responsible for taking the entire device screen hence remaining views are getting pushed offscreen.


text:
Q: Ecommerce web (.net platform) hosted on a domain, Is it possible to host wordpress on domain subfolder? My .net e-commerce web application is hosted in IIS on a domain www.domain.com
Now I want to host WordPress blog on a domain subfolder or subdirectory i.e. www.domain.com/blog
Is there any way that I can achieve it?
Actually dont have resources and time to implement a custom blog with in my eccomerce .net web application as it is itself a very big project.


text:
Q: In C Use 64 bit ints or 16 bit ints for performance on a 64 bit CPU? On a 64 bit CPU with decent sized cache, which will lead to better performance in a C application which uses  many fairly large arrays of structures of int: using 64 bit ints so that everything is always aligned on 8 byte boundaries, which the CPU likes, or 16 bit ints so that there are more array elements in the cache ?
Has anyone ever benchmarked this sort of issue ?

A: On mainstream 64-bit processors (ie. x86-64 and arm64), the size of integers has significant impact on the performance of scalar instructions.
However, it is generally better to work on the smallest possible type if the code is vectorized since SIMD instructions work on fixed-size internal SIMD vectors (128 bits for SSE, 256 for AVX/AVX2, 512 for AVX-512, 128 for Neon). Note that using types of different sizes can introduces quite-expensive conversions or reduce the capacity of some compiler to vectorize efficiently the loops (recent mainstream optimizing compilers are relatively good to vectorize code in this case although the generated code is often not optimal).
Regarding caches, arrays with smaller integer items can be loaded faster from the memory hierarchy. Indeed, the L1/L2 cache are generally quite small, so if an array can fit in such caches, the accesses to this array will be faster (lower latency and higher throughput). The impact is particularly visible for random accesses.
Regarding the alignment, its does not generally have a significant impact on x86-64 platforms as compilers and runtimes do a good job to align arrays efficiently and processors are optimized to access unaligned data (even using SIMD instruction). For example, malloc/realloc returns memory addresses aligned on 16-bytes by default on most x86-64/arm64 platforms.


text:
Q: When do a holomorphic function's zeroes occur in conjugate pairs? I have the following proof that a holomorphic function's zeroes occur in conjugate pairs when its derivatives evaluated at $0$ lie on a line through $0$:
Let $f:\mathbb{C}\mapsto\mathbb{C}$ be holomorphic, then
$$f(z)=\sum\limits_{r=0}^{\infty}\frac{f^{(r)}(0)}{r!}z^r.$$
Writing $z\equiv\cos(\arg(z))+i\sin(\arg(z))$, and invoking De Moivre's theorem, we get
$$\Re(f(z))=\sum\limits_{r=0}^{\infty}\frac{|z|^r}{r!}(\Re(f^{(r)}(0))\cos(r\cdot\arg(z))-\Im(f^{(r)}(0))\sin(r\cdot\arg(z))),$$
$$\Im(f(z))=\sum\limits_{r=0}^{\infty}\frac{|z|^r}{r!}(\Im(f^{(r)}(0))\cos(r\cdot\arg(z))+\Re(f^{(r)}(0))\sin(r\cdot\arg(z))).$$
Suppose $f^{(r)}(0)\in\mathbb{R}$ for all $r\in\mathbb{N}_0$, then $\Im(f^{(r)}(0))=0$ for all $r$, so
$$\Re(f(z))=\sum\limits_{r=0}^{\infty}\frac{|z|^r}{r!}f^{(r)}(0)\cos(r\cdot\arg(z)),$$
$$\Im(f(z))=\sum\limits_{r=0}^{\infty}\frac{|z|^r}{r!}f^{(r)}(0)\sin(r\cdot\arg(z)).$$
Therefore, $\Re(f(z))$ is even with respect to $\arg(z)$, and $\Im(f(z))$ is odd with respect to $\arg(z)$, so $f(\overline{z})=\overline{f(z)}$ for all $z\in\mathbb{C}$. Therefore, if $f(z)=0$, $f(\overline{z})=0$.
Now let $f$ be such that its derivatives evaluated at $0$ lie on a line through $0$ such that $\arg(z)=\theta$ for all non-zero $f^{(r)}(0)$, then $g(z)=e^{-i\theta}f(z)$ is such that $g^{(r)}(0)\in\mathbb{R}$ for all $r$ since $g^{(r)}(0)=e^{-i\theta}f^{(r)}(0)$. Therefore, the zeroes of $g$ occur in conjugate pairs, and $f$ is simply a rotation of $g$ about $0$, so the zeroes of $f$ occur in conjugate pairs.
My question is, are there known results about curves $\gamma$ in $\mathbb{C}$ other than lines through $0$ such that any holomorphic $f$ such that $f^{(r)}(0)\in\gamma$ for all $r\in\mathbb{N}_0$ is such that, if $f(z)=0$, $f(\overline{z})=0$. I've looked around online and all I can find is the conjugate pair theorem, which is a special case of what I have already proven.
A method I have tried of extending the class of curves that have this property is to note that, given some curve $\gamma$ and any sequence of points $(a_n)_{n\in\mathbb{N}}$ such that $a_n\in\gamma$ for all $n\in\mathbb{N}$, if there exists some holomorphic $g$ such that $g^{(r)}(0)\in\mathbb{R}$ for all $r$ and some holomorphic $T$ such that $T(0)=0$ and $T(z)\neq 0$ for all non-zero $z\in\mathbb{C}$, such that $(T\circ g)^{(r)}(0)=a_r$ for all $r$, then any function whose derivatives evaluated at $0$ lie on $\gamma$ is such that it zeroes occur in conjugate pairs. I won't write out the whole proof, but I then used the combinatorial form of Faa De Bruno's formula to show that one has sufficient freedom in the choosing of the derivatives of $T$ and $g$ to conclude that there exists some $T$ and $g$ such that $(T\circ g)^{(r)}(0)=a_r$ for all $r\in\mathbb{N}$, and, moreover, that there is even more freedom in the choosing than that; I have come close to proving that you can get $T(0)=0$, but not that $T(z)\neq 0$ for all non-zero $z$ (in fact, this is definitely not true for all $\gamma$, and I don't see how I will be able to distinguish between those curves for which it is true and those for which it isn't, even if I do make progress on determining what curves one has "more freedom" for), and was wondering if there are known results related to this.

A: It's not true for curves through $0$ other than straight lines.  Suppose $\gamma$ contains $0$, $\alpha$ and $\beta$ where $\alpha/\beta$ is not real.  Then $f(z) = \alpha + \beta z$ has $f(0) = \alpha$, $f'(0) = \beta$, $f^{(k)}(0)=0$ otherwise, and its unique zero $-\alpha/\beta$ is not equal to its complex conjugate.
EDIT: In fact we can remove the "through $0$".  Suppose $\gamma$ is any curve not contained in a straight line through $0$.  Thus there are $\alpha, \beta \in \gamma$ such that $\alpha \ne 0$ and $\beta/\alpha$ is not real.  Consider
$$ f(z) = \alpha \cosh(z) + \beta \sinh(z)$$
which has $f^{(k)}(0) = \alpha$ if $k$ is even, $\beta$ if $k$ is odd.  The zeros
are $\text{arctanh}(-\beta/\alpha) + \pi i n$ for integers $n$.  If this is symmetric under complex conjugation, $\text{Im}(\text{arctanh}(-\beta/\alpha))$ is a multiple of $\pi i/2$.  But then $-\beta/\alpha = \tanh(x + k \pi i/2) = \tanh(x)$ or $\coth(x)$ for some real $x$, which is real.


text:
Q: Is there an easy way to print a Matplotlib figure (Saros Dial) to an exact size on a DIN A4 jpeg? As part of a COVID/Lockdown/Geek project making a 3D Antikythera model I need to print a Saros Dial to be exactly 8.9 cm in width. I have muddled my way through playing around with the print scale. This works for the office printer. However I want to have it etched on plexiglas and I need to upload a DIN A4 jpeg or pdf with the (0,0) coordinate right in the centre
Code for the dial below:
import numpy as np
import matplotlib.pyplot as plt
%matplotlib inline

# define parameters
a = 2 # determines the width of the turns - set to 1 means width is 2 Pi
thetaMin, thetaMax = 26*np.pi, 34*np.pi # Dial starts at the 13th turn and finishes at the 17th turn
steps = 223+1 # Number of Saros periods (+1 for end marker)

# Generate plotting values
# Main spiral

theta = np.linspace(thetaMin, thetaMax, steps)

r = theta * a

x = r*np.cos(theta)
y = r*np.sin(-theta)

# Main spiral outer rim completion
thetaMinComp, thetaMaxComp = thetaMax, thetaMax+(2*np.pi)

thetaComp= np.linspace(thetaMinComp, thetaMaxComp,steps)

rComp = thetaComp * a

xComp = rComp*np.cos(thetaComp)
yComp = rComp*np.sin(-thetaComp)

# Seperator lines
# Need to plot between the period startpoint accros the turn(out from the center (0,0))
l=np.sqrt(np.square(x)+np.square(y)+1.2) # calculate length from center, just shortening it makes it not overshoot
xnew= x*1/l*(l+2*np.pi*a) # get the x  for the line extendeaccros the turn
ynew= y*1/l*(l+2*np.pi*a) # get the y  for the line extendeaccros the turn

#start plotting
fig, ax = plt.subplots(figsize=(20,20))

plt.axis('off')

for i in range(len(x)):
    plt.plot([x[i],xnew[i]],[y[i],ynew[i]], c='r', lw=2)
#     plt.scatter(x[i], y[i], c = 'g') # Plots dial points for reference

steps = 223+1 # Number of Saros periods (+1 for end marker)
a = 2 # determines the width of the turns - set to 1 means width is 2 Pi
thetaMin, thetaMax = (26*np.pi+(2*np.pi)/(.5*steps)), (34*np.pi+(2*np.pi)/(.5*steps)) # Dial starts at the 13th turn and finishes at the 17th turn

theta = np.linspace(thetaMin, thetaMax, steps)

r = theta * a

xx = r*np.cos(theta)
yy = r*np.sin(-theta)
xxnew= xx*1/l*(l+2*np.pi*(a*.5)) # get the x  for the line extendeaccros the turn
yynew= yy*1/l*(l+2*np.pi*(a*.5)) # get the y  for the line extendeaccros the turn
plt.plot(x, y, c='r', lw=2)
plt.plot(xComp, yComp,c='r', lw=2)

plt.scatter(0,0)

plt.text(0,75,'Saros Dial', {'fontname': 'Herculanum',
                         'fontsize': '100',
        'fontweight' : 'bold',
        'verticalalignment': 'baseline',
        'horizontalalignment': 'center'})

plt.show()

I have found Using matplotlib, how can I print something "actual size"? but is still fiddling. Is there an easier way?

A: This proved to be frustrating. It is printer dependent...and online printer specifications for the margins may not match the actual margins when printing. I have a hunch it may even be OS or driver specific.
import matplotlib.pyplot as plt
import matplotlib as mpl

# This example fits DIN A4 paper on a HP Laserjet Pro 200 MFP

# figure settings

left_margin = 0.2
right_margin = 0.9
top_margin = 0.6
bottom_margin = 0.6

left_right_margin = left_margin+right_margin
top_bottom_margin = top_margin+bottom_margin
figure_width = 21-left_right_margin # cm
figure_height = 29.7-top_bottom_margin

# Don't change
left   = left_right_margin / figure_width # Percentage from height
bottom = top_bottom_margin / figure_height # Percentage from height
width  = 1 - left*2
height = 1 - bottom*2
cm2inch = 1/2.54 # inch per cm
h_corr = 1.017
v_corr = 1.011

# specifying the width and the height of the box in inches
fig = plt.figure(figsize=(figure_width*cm2inch*h_corr,figure_height*cm2inch*v_corr))

ax = fig.add_axes((left, bottom, width, height))

# limits settings (important)
# plt.xlim(0, figure_width * width)#(0,0) at left bottom
# plt.ylim(0, figure_height * height)#(0,0) at left bottom
plt.xlim(-figure_width * width/2, figure_width * width/2) #centers (0,0)
plt.ylim(-figure_height * height/2, figure_height * height/2)#centers (0,0)

# your Plot (consider above limits)
# # define parameters
a = .03538 # determines the width of the turns - set to 1 means width is 2 Pi
thetaMin, thetaMax = 26*np.pi, 34*np.pi # Dial starts at the 13th turn and finishes at the 17th turn
steps = 223+1 # Number of Saros periods (+1 for end marker)

# Generate plotting values
# Main spiral

theta = np.linspace(thetaMin, thetaMax, steps)

r = theta * a

x = r*np.cos(theta)
y = r*np.sin(-theta)

# Main spiral outer rim completion
thetaMinComp, thetaMaxComp = thetaMax, thetaMax+(2*np.pi)

thetaComp= np.linspace(thetaMinComp, thetaMaxComp,steps)

rComp = thetaComp * a

xComp = rComp*np.cos(thetaComp)
yComp = rComp*np.sin(-thetaComp)

# Seperator lines
# Need to plot between the period startpoint accros the turn(out from the center (0,0))
l=np.sqrt(np.square(x)+np.square(y)+1.2) # calculate length from center, just shortening it makes it not overshoot
xnew= x*1/l*(l+2*np.pi*a) # get the x  for the line extendeaccros the turn
ynew= y*1/l*(l+2*np.pi*a) # get the y  for the line extendeaccros the turn

for i in range(len(x)):
    plt.plot([x[i],xnew[i]],[y[i],ynew[i]], c='r', lw=1)

xx = r*np.cos(theta)
yy = r*np.sin(-theta)
xxnew= xx*1/l*(l+2*np.pi*(a*.5)) # get the x  for the line extendeaccros the turn
yynew= yy*1/l*(l+2*np.pi*(a*.5)) # get the y  for the line extendeaccros the turn
plt.plot(x, y, c='b', lw=1)
plt.plot(xComp, yComp,c='g', lw=1)
plt.scatter(0,0)

plt.text(0,4.75,'Saros Dial',
         {'fontname': 'Herculanum',
        'fontsize': '30',
        'fontweight' : 'bold',
        'verticalalignment': 'baseline',
        'horizontalalignment': 'center'})

plt.plot([-8,-8],[-10,10])
plt.text(-7,0, ' 20 centimeters' , rotation=90, ha='center', va='center', fontsize=30, color='magenta')
plt.show()

plt.show()

# save figure ( printing png file had better resolution, pdf was lighter and better on screen)
fig.savefig('A4_grid_cm.png', dpi=1000)
fig.savefig('tA4_grid_cm.pdf')


text:
Q: what would my command arguments be for my timer So, I've been trying to figure out how this timer works, and now that I finally got it to compile with no errors, I can't seem to get it to run properly, I'm assuming because I'm not giving it the proper cmd ln args but I don't know what args to provide. the code is as follows:
import java.time.*;

public class Clock {
    private LocalTime startTime;
    private LocalTime stopTime;
    private Duration duration;
    private int hours, minutes, seconds;

    // no argument constructor that initializes the startTime to the current time
    public Clock() {
        startTime = LocalTime.now();
    }
    public Clock(LocalTime start, LocalTime stop) {
        startTime = start;
        stopTime = stop;
    }

    //public Clock(start, stop) {

    //}

    // resets the startTime to the given time
    public void start(int h, int m, int s) {
        hours = ((h >= 0 && h < 24) ? h : 0);
        minutes = ((m >= 0 && m < 60) ? m : 0);
        seconds = ((s >= 0 && s < 60) ? s : 0);
        startTime = LocalTime.of(hours, minutes, seconds);
    }

    //a stop() method that sets the endTime to the given time
    public void stop(int h, int m, int s) {
        hours = ((h >= 0 && h < 24) ? h : 0);
        minutes = ((m >= 0 && m < 60) ? m : 0);
        seconds = ((s >= 0 && s < 60) ? s : 0);
        stopTime = LocalTime.of(hours, minutes, seconds);
    }

    //a getElapsedTime() method that returns the elapsed time in seconds
    public Duration getElapsedTime() {
        System.out.println("Difference is " + Duration.between(stopTime, startTime).toNanos()/1_000_000_000.0 + " Seconds.");
        duration = Duration.between(stopTime, startTime);
        return duration;
    }
    public static void main(String[] args) {

       LocalTime argOne;
       LocalTime argTwo;
       argOne = LocalTime.parse(args[0]);
       argTwo = LocalTime.parse(args[1]);
       Clock clockOne = new Clock(argOne, argTwo);
       clockOne.getElapsedTime();
    }
}

A: after successful compile, command line args should be in this format, (to include calling the java class) so mine would look like:
java Clock 03:14:43 03:17:00 || java Clock 03:14 03:17
expected output:Elapsed time in seconds: 180


text:
Q: compressed CGImage with CGImageDestination truncated after getting bytes I want to get the compressed data from a CGImageRef to send it over a network connection.
To do so, i use a CGImageDestinationRef (CGImageDestinationCreateWithData).
After pulling the Data out of the CFDataRef Object the image misses a couple of rows at the bottom.
Here is what i do (cleaned for reading purpose...):
CFImageRef image = getTheImageRefIWant();

CFMutableDataRef pngData = CFDataCreateMutable (kCFAllocatorDefault, 0);

CGImageDestinationRef dataDest = CGImageDestinationCreateWithData (pngData, kUTTypePNG, 1, NULL);

CGImageDestinationAddImage (dataDest, image, NULL); //also tried this with options...

CGImageDestinationFinalize (dataDest);

CFIndex len = CFDataGetLength(pngData);

//copy data
unsigned char* m_image = malloc(len);
CFDataGetBytes (pngData, CFRangeMake(0,len), m_image);

//save data - for testing purpose
FILE *file = fopen("/path/test.png", "wb");
fwrite(m_image, 1, len, file);

//adding header and stuff - skipped here...

//send data
send(sockfd, m_image, len, 0);

If i use the CFData Object as NSData Object and save it to disk it does work:
NSData *data = [(NSData *)pngData autorelease];
[data writeToFile:@"/path/test.png" atomically:YES];

but if is use NSDatas byte method, it is the same (truncated image):
NSUInteger len = [data length];
m_image = malloc(len);
memcpy(m_image, (unsigned char*)[data bytes], len);

seems the data in CFData Object seems to be ok.
But how to get the bytes properly?
Thanks for any advice.

A: Have you either fflush()ed or fclose()d the file after writing it?  Your data may just be buffered in memory.


text:
Q: Has uniform ellipticity implications on the spectrum? Let $X$ be a complete Riemann surface with a smooth metric, and $L$ a line bundle on it also equipped with a smooth metric; associated to this data there is a Laplace-Beltrami operator $D_L$ acting on sections of $L$.
We know that if $X$ is compact the operator $D_L$ has only discrete spectrum.
In the specific situation I'm considering $X$ is not compact but the metrics are such that $D_L$ is uniformly elliptic, and not just elliptic as in the general non-compact case. I would like to conclude from this that $D_L$ is discrete, viewing the uniform ellipticity as a "replacement" for the compactness of the surface.
Does it work? If it does not, is it possible to add some more hypothesis to deduce such a result or the facts

*

*$D_L$ is uniformly elliptic on a complete surface

*$D_L$ is discrete

are completely unrelated?

A: I tend to consider such things from the perspective of Dirac operators.
Let $D$ be a Dirac operator on a
complete Riemann manifold, acting on a vector bundle $E$.
There is a Weitzenboeck type formula
$D^2 = \nabla^{\ast} \nabla + R$. The Weitzenboeck remainder $R$ is of order zero and symmetric. We write $\nabla^* \nabla =: \Delta$, the Laplace
operator. The Laplace you are interested in is $D^2$, not $\Delta$.
It is a standard result that $D^2$, $D$ and $\Delta$ are essentially selfadjoint.
If you take the operator $D=d+d^{*}$ on exterior
forms, suitably twisted with a line bundle, you get the situation you were takling about in
the question.
You want to know a criterion for $D$ or equivalently $D^2$ to have a discrete spectrum.
I believe that the following results are true, and indicate a proof (potentially flawed). The basic result is the following extension of the Fredholm property on noncompact manifolds.
THEOREM 1: ''Let $\Delta =\nabla^{\ast} \nabla$. Let $P$ be an essentially selfadjoint elliptic operator
of order $2$.
Assume that there exists $c>0$ and a compact set $K \subset M$ such that for all compactly supported
sections $u$ with support disjoint from $K$, one has
$$\langle Pu,u \rangle \geq \langle \Delta u , u \rangle + c^2 \langle u, u\rangle. $$
Then $P$ is Fredholm.''
I defer the proof to the end of this post, as it is technical, and discuss some applications.
COROLLARY 1: ''Let $D$ be a Dirac operator on a complete manifold $M$. Assume that there exists a compact
$K$ and a $c>0$ such that the Weitzenboeck remainder $R$ is estimated from below by $c^2$ over $M-K$. Then
$spec (D) \cap (-c,c)$ is discrete.''
One could phrase this by saying that an estimate of the Weitzenboeck remainder from below enforces an essential
spectral gap, at least as large as $c$.
PROOF:
Let $\lambda^2 < c^2$. Let $Q := D^2-\lambda^2$. Over $M-K$, we find that $Q = \Delta + R-\lambda^2 \geq \Delta + (c^2-\lambda^2)$.
By Theorem 1, $Q$ is Fredholm. Thus $\lambda^2$ is an isolated point of the spectrum of $D^2$, and hence $\pm \lambda$
are isolated points of $spec (D)$. QED
Note that in Corollary 1, the size of $K$ was inessential and could be increased, which allows the possibility for a stronger estimate on the complement of $K$ and hence
to enlarge the essential spectral gap. This is the content of the next result.
THEOREM 2: ''Let $D$ be a Dirac operator on $M$ and $f: M \to \mathbb{R}$ be a proper function
that is bounded from below. If the remainder term $R$ in the Weitzenboeck formula $D^2 = \Delta + R$ is bounded
below by $f$, then the spectrum of $D$ (and hence that of $D^2$) is discrete.''
PROOF: For each $C>0$, we find a compact set $K \subset M$ and an estimate $R \geq C^2$ on $M-K$. By Corollary 1,
$spec (D) \cap (-C,C)$ is discrete. As $C$ was arbitrary, $spec (D) \subset \mathbb{R}$ is discrete. QED.
PROOF OF THEOREM 1:
The first step is a strengthening of Gardings inequality. Namely, we prove that there is a constant $C$ with
$$
(!!!) \; \|u \|_2 \leq C (\| u|_K \|_0 + \| Pu \|_0).
$$
Without loss of generality $c \leq 1$.
Let $u$ be a section with compact support
$supp (u)\subset M-K$. I write $\| u \|_r$, $r=0,1,2$, for the Sobolev norms.
Estimate using the condition on $P$:
$$
\| u \|_2^2 = \|u \|_0^2 + \|\Delta u \|_0^2 \leq \frac{1}{c^2} \|P u\|_0^2
$$
If $K \subset U$ is a relatively compact neighborhood, and $u$ supported in $U$, the usual Garding inequality
shows
$$
\| u \|_2^2 \leq C(\| u\|_0^2 + \| Pu\|_0^2)
$$
To patch both estimates together, choose $a$ supported in $U$, $b$ supported in $M-K$ such that $a + b =1$.
For an arbitrary compactly supported section $u$, we find that
$$
\| u \|_2 \leq \| au \|_2+\| bu \|_2 \leq C' (\| au\|_0^2 + \| P a u\|_0^2 + \| Pbu\|_0^2) $$
The first term is bounded by $\| u|_K \|_0 $.
Furthermore $\| P a u\|_0 \leq \| [P,a] u \|_0 + \| a P u \|_0 \leq  \| [P,a] u \|_0 + C\|  P u \|_0$. But $[P,a]$ has order $1$ and is supported in $U$. Therefore, there is a function $h$ with $[P,a]h=[P,a]$ and hence $\| [P,a] u \|_0 \leq C \| hu \|_1 $. By the Peter-Paul inequality, there is for $\epsilon>0$ a constand $C(\epsilon)$ such that $\| hu \|_1  \leq \epsilon \| hu \|_2 + C(\epsilon) \| hu \|_0\leq C\epsilon \| u \|_2 + \| u|_K\|_0$. Picking $\epsilon$ small enough, we can swap the first summand to the left hand side of the estimate. Similarly, the term $\|Pbu\|$ is estimated, and we have proved the strengthened inequality (!!!).
Why did I do all this stuff? Well, the operator $W^2 \to L^2 \stackrel{|_K}{\to} L^2$ is compact by Rellichs theorem. It is a general fact (e.g. Proposition 3.7.2 in my lecture notes http://wwwmath.uni-muenster.de/u/jeber_02/skripten/mainfile.pdf) that this implies that $P$ has closed range and finite-dimensional kernel. Since $P$ is essentially
selfadjoint, the cokernel is the kernel of $P$ and so finite-dimensional as well. QED (Theorem 1).


text:
Q: How to change data in custom loaded config array I'm doing pagination using Codeigniter pagination class. My current config variable is:
$config['base_url'] = base_url('admin/sub_categories');
$config['total_rows'] = $this->sub_categories_model->get_count();
$config['base_url'] = "";
$config['total_rows'] = "";
$config['per_page'] = 30;
$config['first_link'] = 'Эхнийх';
$config['last_link'] = 'Сүүлийх';
$config['full_tag_open'] = '
';
$config['full_tag_close'] = '
';
$config['first_link'] = false;
$config['last_link'] = false;
$config['first_tag_open'] = '
';
$config['first_tag_close'] = '
';
$config['prev_link'] = '&laquo';
$config['prev_tag_open'] = '
';
$config['prev_tag_close'] = '
';
$config['next_link'] = '&raquo';
$config['next_tag_open'] = '
';
$config['next_tag_close'] = '
';
$config['last_tag_open'] = '
';
$config['last_tag_close'] = '
';
$config['cur_tag_open'] = '
';
$config['cur_tag_close'] = '
';
$config['num_tag_open'] = '
';
$config['num_tag_close'] = '
';

Then using it on every controller was using too many lines. So I created pagination.php under config/ folder. Then put above codes. Then loaded it like:
$this->config->load('pagination', TRUE);
$this->pagination->initialize($this->config->item('pagination'));

Now you see, my problem is $config['base_url'] and $config['total_rows'] can be different on every controllers. How can I change their value after load?

A: If I understand you, then you may try this:
$this->config->load('pagination', TRUE);
$conf = $this->config->item('pagination');
$conf['base_url'] = base_url('admin/sub_categories');
$conf['total_rows'] = $this->sub_categories_model->get_count();
$this->pagination->initialize($conf);

You should do it at every controller you want to use paginator with diferent values for base_url and total_rows