text:
Q: How to rename a tag in Azure DevOps We have a large instance of Visual Studio Online or VSTS or Azure DevOps.
We have a Tag on work items that is called "A B" for example. Someone also
created another tag "AB". I want to just rename the tag "A B" to "Don't use A B" or
just delete the tag if possible. Is there an API I could use to do this?
I checked out the TAGHelper add-in but because we have many tags, the tag helper add-in is just unusable. I can write a simple tool if needed, but wondering if there is a quick way to do this.

A: Sadly, you can't delete it directly, only create a new one and unassign all the old usages.
From the documentation

You can't delete a tag itself. However, if you delete a tag from all
work items to which it's currently assigned, the system will delete
the tag. The system automatically deletes unassigned tags after 3 days
of disuse.
If you misspell a tag, don't assign the misspelled tag to any work
item and the system will automatically delete it within 3 days.

A: You might find helpful Tags Manager extension, it is available freely in VS marketplace

A: I tried different options and no luck. So the workaround was

*

*Filter the tasks in the backlog by the tag

*Selected all of them (do this in backlog view, not board view)

*Right Click -> Edit

*Tag(remove) the tag I don't want

*Tag(add) the tag I want

A: I found a way to do this using the CSV import feature.

*

*In DevOps, under Boards > Work Items, filter by the Tag you want to change

*Click "Open filtered view in Queries"

*Click "Export to CSV" (you may have to click the three dots to see this option)

*Open the file in Excel

*Find and replace every instance of the tag with the correct spelling and save

*In DevOps, Go to the Boards > Queries page click "Import Work Items"

*Choose the file and click "Import"

*Click "Save Items"

Since the downloaded file contains the ID column, the tags will be updated on the existsing work items.

A: I did below and worked:

*

*Click on Create Tag.

*Give the new Name of tag. (in above case it is "A B")

*In field "Tag From" select wrong tag. (in above case it is "AB")

*Provide Description and click Create.

*Now delete the wrong named Tag. (in above case "AB")
Thats it, done.


text:
Q: Item$.take is not a function TypeError: item$.take is not a function I face a problem regarding take(1) is not a function of angular firebase object.
I can try with valuechages or snapshotchanges but this could not help for me as I have to use but there are other problem.I am using angular 6.
Here is my version details:-

Angular CLI: 6.2.5
Node: 8.12.0
OS: win32 x64
Angular: 6.1.10
... animations, common, compiler, compiler-cli, core, forms
... http, language-service, platform-browser
... platform-browser-dynamic, router

Package                           Version
-----------------------------------------------------------
@angular-devkit/architect         0.8.5
@angular-devkit/build-angular     0.8.5
@angular-devkit/build-optimizer   0.8.5
@angular-devkit/build-webpack     0.8.5
@angular-devkit/core              0.8.5
@angular-devkit/schematics        0.8.5
@angular/cli                      6.2.5
@angular/fire                     5.1.0
@ngtools/webpack                  6.2.5
@schematics/angular               0.8.5
@schematics/update                0.8.5
rxjs                              6.3.3
typescript                        2.9.2
webpack                           4.20.2

In case of subscribe method I face with same problem.
Here is my code:-

import { Injectable, OnDestroy } from '@angular/core';
import { AngularFireDatabase, AngularFireObject } from '@angular/fire/database';
import 'rxjs/add/operator/take';
import { Product } from './models/product';
import { Subscription } from 'rxjs/Subscription';
import { take, map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class ShoppingCartService  {

  suscription: Subscription ;

  constructor(private db: AngularFireDatabase) { }

  async addToCart(product: Product) {
    this.updateItemQty(product, 1);
  }

  async removeFromCart(product) {
    this.updateItemQty(product, -1);
  }

  async getCart() {
    const cartId = await this.getOrCreateCartId();
    return this.db.object('/shopping-cart/' + cartId)

  }

  async clearAllCart() {
    const cartId = await this.getOrCreateCartId();
    return this.db.object('/shopping-cart/' + cartId).remove();
  }

  private async updateItemQty(product: Product, change: number) {
    const cartId = await this.getOrCreateCartId();
    const item$ = this.getItem(cartId, product.$key);
    item$.take(1).subscribe(item => {
      const quantity = (item.quantity || 0) + change;
      if (quantity === 0) { item$.remove(); } else { item$.update({
        title: product.title,
        imageUrl: product.imageUrl,
        price: product.price,
        quantity: quantity
      });
      }
    });
  }

  private createCartId() {
    return this.db.list('shopping-cart').push({
      dateTime: new Date().getTime()
    });
  }

  private async getOrCreateCartId(): Promise<string> {
    let cartId = localStorage.getItem('cardId');
    if (cartId) { return cartId; }

    const cart = await this.createCartId();

    cartId = localStorage.getItem('cardId');
    if (cartId) { return cartId; }

    localStorage.setItem('cardId', cart.key);
    return cart.key;
  }

  private getItem(cartId, key) {
    return this.db.object('/shopping-cart/' + cartId + '/items/' + key);
  }

}

So , I can't use snapshotchanges() and valuechanges() because then I am unable to use or I got error like-item.quantity,item$.remove and item$.update.
Why take(1) or  subscribe is not function for  @angular/fire                     5.1.0?
Please suggestion or any alternative way to implement.

A: Since you are using Angular 6, it uses rxjs version 6.
In this rxjs version the way you use "take" (and other operators) has changed.
you'll need to convert your code like this
item$.pipe(take(1))
            .subscribe(item => {
            const quantity = (item.quantity || 0) + change;
            if (quantity === 0) { item$.remove(); } else { item$.update({
                title: product.title,
                imageUrl: product.imageUrl,
                price: product.price,
                quantity: quantity
            });
            }
        });

Also you'll need to change import statement to
import { take } from 'rxjs/operators';

redpajama_set_name: RedPajamaStackExchange


text:
Q: Troubleshooting ggplot2 stacked bar plot I'm trying to create a stacked identity barplot but ggplot2 keeps lumping my data together.
Instead of providing the stacked plot with each respective categories for each sector, it's aggregating the direct, indirect.down and indirect.up categories together.
test.df = data.frame(scenario=(c("s1", "s1", "s1", "s2", "s2", "s2", "s3", "s3", "s3",
                             "s1", "s1", "s1", "s2", "s2", "s2", "s3", "s3", "s3",
                             "s1", "s1", "s1", "s2", "s2", "s2", "s3", "s3", "s3")),
              sector=(c("Agriculture", "Manufacturing", "Services", "Agriculture", "Manufacturing", "Services", "Agriculture", "Manufacturing", "Services",
                        "Agriculture", "Manufacturing", "Services", "Agriculture", "Manufacturing", "Services", "Agriculture", "Manufacturing", "Services",
                        "Agriculture", "Manufacturing", "Services", "Agriculture", "Manufacturing", "Services", "Agriculture", "Manufacturing", "Services" )),
              loss=(runif(27,0,1000)), shock=(c("direct", "indirect.up", "indirect.down","direct", "indirect.up", "indirect.down","direct", "indirect.up", "indirect.down",
                        "direct", "indirect.up", "indirect.down","direct", "indirect.up", "indirect.down","direct", "indirect.up", "indirect.down",
                        "direct", "indirect.up", "indirect.down","direct", "indirect.up", "indirect.down","direct", "indirect.up", "indirect.down")))

library(ggplot2)

ggplot(test.df, aes(x=sector, y=loss)) + geom_bar(stat = "identity", aes(fill=shock))  + facet_wrap(~ scenario) + coord_flip()

I want it to look like this in terms of how the shocks to each sector are stacked:

A: That's because in your sample data, each sector has only one kind of shock associated to it.
table(test.df$sector, test.df$shock)

#              direct indirect.down indirect.up
# Agriculture        9             0           0
# Manufacturing      0             0           9
# Services           0             9           0

Adding some data to create some more associations between sector and shock:
df2 <- test.df

df2$shock[df2$shock == "indirect.down"] <- "indirect.up"
df2$shock[df2$shock == "direct"] <- "indirect.down"

test.df <- rbind(test.df, df2)

table(test.df$sector, test.df$shock)

#               direct indirect.down indirect.up
# Agriculture        9             9           0
# Manufacturing      0             0          18
# Services           0             9           9

Test your code now:
library(ggplot2)

ggplot(test.df, aes(x=sector, y=loss)) +
 geom_bar(stat = "identity", aes(fill=shock))  +
 facet_wrap(~ scenario) + coord_flip()


text:
Q: If $9\cdot M \cdot N = \overline{abcde}$, then find all pairs (M, N) The question goes follow

M is a two-digit natural number $\overline{ab}$ while N is a three-digit natural number $\overline{cde}$. If $9\cdot M \cdot N = \overline{abcde}$, then find all pairs (M, N) that satisfy.

All can i conclude is that $9MN=1000M+N$. It means that $M+N\equiv0 $ $(\mod 9)$ I am stuck on there. Please share me your idea.

A: Rearrange your equation to get
$$
(9M-1)N=1000M.
$$
$9M-1$ is coprime with $M$ so for integer solutions you have to have $(9M-1)|1000$. A numerical search from 10 to 99 yields only $M=14$, since $9\times14-1=125|1000$ and $N=1000M/125=112$. (There might be a way to skip the numerical search, but I couldn't think of one.)


text:
Q: Custom xml with drawable and depended location Image with the desired layout:
I have the following situation:
I have group which contains buttons that are populated from database(for example, 10 items in the specific table will populate 10 buttons in this group) - that works fine.
The parts that I don't know how to do is:

*

*I wold like that this buttons will shows as a circle (Drawable) and within that circle there is an image (the path will be taken from the database) and a label from the above explanation(from a table).

*If there is a one item, it will be in the center of the screen and as the amount of the buttons growth, the circles will set within a Grid of 3 columns.
Can someone help me with this issues?
the older version where I try deferent method (with RadioButtons), in this example there is no Image or drawable and the items are a radioButtons within RadioGroup:
DatBas dbc = new DatBas(Tamar_appActivity.this);
    dbc.open();
    SQLiteDatabase tdb = dbc.getDatabase();
    String[] columns = new String[] { DatBas.KEY_ROW_B_ID,
            DatBas.KEY_B_NAME };
    Cursor c = tdb.query(DatBas.DATABASE_TABLE_SETTINGS, columns, null,
            null, null, null, null);

    int iRawBId = c.getColumnIndex(DatBas.KEY_ROW_ID);
    int iBName = c.getColumnIndex(DatBas.KEY_B_NAME);

    for (c.moveToFirst(); !c.isAfterLast(); c.moveToNext()) {

        RadioGroup radiogroup = (RadioGroup)
                    findViewById(R.id.bNameSelectGroup);
        final Button rdbtn = new Button(this);

        rdbtn.setId(iRawBId);
        rdbtn.setText(c.getString(iBName));
        radiogroup.addView(rdbtn);
    }
    dbc.close();

}

This is the SpacialButton.java code:
public class SpecialButton extends RelativeLayout {

public TextView text;
//public ImageView image;

public SpecialButton(Context context) {
    super(context);
    this.setBackgroundResource(R.drawable.cb_shape);
    LayoutInflater.from(context).inflate(R.layout.cb_inner,
            this, true);
    text = (TextView) findViewById(R.id.textView1);
//    image = (ImageView) findViewById(R.id.imageBB);
}

public SpecialButton(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
}

public SpecialButton(Context context, AttributeSet attrs) {
    super(context, attrs);
}

}

This is the cb_inner.xml code:
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android" >

    <!-- This will hold the image from the database -->
    <ImageView
        android:id="@+id/imageBB"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true" />

    <View
        android:id="@+id/anchor"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_centerInParent="true" />

    <!-- This will be the label. It will be placed below the center -->
    <TextView
        android:id="@+id/cbTextView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/anchor"
        android:layout_centerHorizontal="true"
        android:text="TextView"
        android:textColor="#000000" />

</merge>

This is the Main.java code:
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        TableLayout tl = (TableLayout) findViewById(R.id.grid);
            Display display2 = getWindowManager().getDefaultDisplay();
            int width = display2.getWidth();
            int height = display2.getHeight();
            int realSize = width / 3;

        DatBas dbc = new DatBas(Tamar_appActivity.this);
        dbc.open();
        SQLiteDatabase tdb = dbc.getDatabase();
        String[] columns = new String[] { DatBas.KEY_ROW_B_ID,
                DatBas.KEY_B_NAME };
        Cursor c = tdb.query(DatBas.DATABASE_TABLE_SETTINGS, columns, null,
                null, null, null, null);
        c.moveToFirst();
        int iRawBId = c.getColumnIndex(DatBas.KEY_ROW_B_ID);
        int iBName = c.getColumnIndex(DatBas.KEY_B_NAME);
        int iBimage = c.getColumnIndex(DatBas.KEY_B_IMAGE_PATH);
//      ic_launcher.png
        int cursorSize = c.getCount();
        int rows = (cursorSize / 3) + 1; // +1 so you have at least one row if the number of button is below 3
        int current = 1; // starting position
        for (int i = 0; i < rows; i++) {
            TableRow tr1 = new TableRow(this);
            tr1.setLayoutParams(new TableLayout.LayoutParams(
                    TableLayout.LayoutParams.FILL_PARENT,
                    TableLayout.LayoutParams.WRAP_CONTENT));
            for (int j = 0; j < 3; j++) {
                if (current <= cursorSize) {
                    SpecialButton sb = new SpecialButton(this);
                    sb.text.setText(c.getString(iBName));
                    sb.setLayoutParams(new TableRow.LayoutParams(realSize,
                            realSize));
                    // other stuff you would do
//                  sb.image.getDrawable();
                    tr1.addView(sb);
                    c.moveToNext();
                }
                current++;
            }
            tl.addView(tr1);
        }
        dbc.close();

    }

A:
I wold like that this buttons will shows as a Circle (Drawable),
  within that Circle there is an image (the path will be taken from the
  database), and a label from the above explanation (from a table).

I would recommend you to make a layout file to simulate all the items:
<?xml version="1.0" encoding="utf-8"?>
<merge xmlns:android="http://schemas.android.com/apk/res/android" >

    <!-- This will hold the image from the database -->
    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true" />

    <View
        android:id="@+id/anchor"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_centerInParent="true" />

    <!-- This will be the label. It will be placed below the center -->
    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/anchor"
        android:layout_centerHorizontal="true"
        android:text="TextView"
        android:textColor="#000000" />

</merge>

The item_background drawable used above:
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="oval" >

    <solid android:color="#92c47d" />

    <stroke
        android:width="2dp"
        android:color="#000000" />

</shape>

Then you'll probably want to put this in a custom View class for easy handling:
    public class SpecialButton extends RelativeLayout {

    public TextView text;
    public ImageView image;

    public SpecialButton(Context context) {
        super(context);
        this.setBackgroundResource(R.drawable.item_background1);
        LayoutInflater.from(context).inflate(R.layout.views_special_btn_layout,
                this, true);
        text = (TextView) findViewById(R.id.textView1);
        image = (ImageView) findViewById(R.id.image);
    }

    public SpecialButton(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
    }

    public SpecialButton(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

}

To simulate a Button add a OnCLickListener to the above custom view. There is no way to make a circle in a xml drawable(as far as I know) so if you don't have an exact size for the custom View above(like a value of 100dp) you'll have calculate it in code. Also if you want to place the TextView label at some specific position you'll have to do it in code again. I don't know exactly how do you want the buttons to be placed on the screen, but normally  you would find out the width and height of the screen and work the real dimension from that:
// in the onCreate method
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
// here I assumed you have only 3 buttons and you want them to be placed taking all
// the width of the screen(of course this isn't ideal because if the user turns the
// phone, in landscape, you'll end up with 3 really big buttons so you may want to
// set a default size for the buttons )
int realSize = width / 3;
Cursor c = tdb.query(DatBas.DATABASE_TABLE_SETTINGS, columns, null,
            null, null, null, null);
    int iRawBId = c.getColumnIndex(DatBas.KEY_ROW_ID);
    int iBName = c.getColumnIndex(DatBas.KEY_B_NAME);
    int cursorSize = c.getCount();
    int rows = (cursorSize / 3) + 1; // +1 so you have at least one row if the number of button is below 3
    int current = 1; // starting position
    for (int i = 0; i < rows; i++) {
        TableRow tr = new TableRow(this);
        tr.setLayoutParams(new TableLayout.LayoutParams(
                TableLayout.LayoutParams.FILL_PARENT,
                TableLayout.LayoutParams.WRAP_CONTENT));
        for (int j = 0; j < 3; j++) {
            if (current <= cursorSize) {
                SpecialButton sb = new SpecialButton(this);
                sb.text.setText(c.getString(iBName));
                sb.setLayoutParams(new TableRow.LayoutParams(realSize,
                        realSize));
                // other stuff you would do
                tr.addView(sb);
                c.moveToNext();
            }
            current++;
        }
        tl.addView(tr);
    }

If there is a one item, it will be in the center of the screen, and as
  the amount of the buttons growth, the Circles will set within a Grid
  of 3 columns.

I don't know your current layout but this could be done very easy in a layout like this(I assumed that you want to place the items in a TableLayout):
<?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:gravity="center"
    android:orientation="vertical" >

    <TableLayout
        android:id="@+id/grid"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >
    </TableLayout>

</LinearLayout>

Then you would place your elements in code(each 3 items in a TableRow) and the gravity  of the parent LinearLayout attribute should place them in the center. You could use a GridView instead of a TableLayout but you'll have to work hard to center the items. The example for the 3 Buttons above:
       // in the onCreate method
       tl = (TableLayout) findViewById(R.id.grid);
        Display display = getWindowManager().getDefaultDisplay();
        int width = display.getWidth();
        int height = display.getHeight();
        int realSize = width / 3;
        TableRow tr = new TableRow(this);
        tr.setLayoutParams(new TableLayout.LayoutParams(
                TableLayout.LayoutParams.FILL_PARENT,
                TableLayout.LayoutParams.WRAP_CONTENT));
        SpecialButton sb1 = new SpecialButton(this);
        sb1.setLayoutParams(new TableRow.LayoutParams(realSize, realSize));
        SpecialButton sb2 = new SpecialButton(this);
        sb2.setLayoutParams(new TableRow.LayoutParams(realSize, realSize));
        SpecialButton sb3 = new SpecialButton(this);
        sb3.setLayoutParams(new TableRow.LayoutParams(realSize, realSize));
        tr.addView(sb1);
        tr.addView(sb2);
        tr.addView(sb3);
        tl.addView(tr);


text:
Q: What is the minimal polynomial of $\sqrt 3+\sqrt 5$ over $\mathbb Q(\sqrt 5)$? What is the minimal polynomial of $\sqrt 3+\sqrt 5$ over $\mathbb Q(\sqrt 5)$ ?
I proved that $\mathbb Q(\sqrt 3+\sqrt 5)=\mathbb Q(\sqrt 3,\sqrt 5)\supset \mathbb Q(\sqrt 5)$, and thus that $\mathbb Q(\sqrt 3+\sqrt5 )/\mathbb Q(\sqrt 5)$ has degree $2$. Since the minimal polynomial of $\sqrt 3+\sqrt 5$ is $X^4-16X^2+4$, the minimal polynomial of $\sqrt 3+\sqrt 5$ over $\mathbb Q(\sqrt 5)$ must be a polynomial of order 2 that divide $X^4-16X^2+4$. It's roots are $\pm\sqrt{8\pm 2\sqrt{15}}$. But I tried to make all combinaisons $(X\pm\sqrt{8\pm2\sqrt{15}})(X\mp\sqrt{8\mp2\sqrt{15}})$, but I didn't get any polynomial of order $2$ in $\mathbb Q(\sqrt 5)$ that canceled $\sqrt 3+\sqrt 5$. Where is my mistakes ?

A: Since $\sqrt3\notin k=\Bbb Q(\sqrt5\,)$, the minimal polynomial for $\sqrt3$ over $k$ is $x^2-3=f(x)$. Clearly, then, the minimal polynomial for $\sqrt3+\sqrt5$ is $f(x-\sqrt5\,)=(x-\sqrt5\,)^2-3=x^2-2\sqrt5x+2$.
I know this wasn't your strategy, but it is the quickest way to get the minimal polynomial.

A: Its conjugate is $\sqrt5-\sqrt3$.
Therefore, the minimal polynomial is:
$$\begin{array}{rcl}
(x-(\sqrt3+\sqrt5))(x-(\sqrt5-\sqrt3))
&=& (x-\sqrt5)^2 - (\sqrt3)^2 \\
&=& x^2-2\sqrt5x+5-3 \\
&=& x^2-2\sqrt5x+2
\end{array}$$


text:
Q: Local Storage with phonegap? I  want to incorporate local storage in my phonegap code, where I want to save an array of data.
A part of my code reads :

LOGIN

            <form id="login-form" data-ajax="false" method="post">
                USERNAME:<input name="text-1"  id="text-1" type="text" value="subin">
                PASSWORD:<input name="password"  id="password" type="password" value="passwordx">

                <input type="button" data-theme="b" name="submit" id="submit" value="enter" data-iccon="plus">
            </form>

now I want to capture the username and password, and use JSON.Stringify and use that to store the data. However I am so sure about the syntax.

A: You can refer this snippet:

var userObj = {
  user: 'User',
  password: 'password'
};
var setLS = document.getElementById('setLS');
var getLS = document.getElementById('getLS');
var setter = function() {
  localStorage.setItem('userObj', JSON.stringify(userObj));
  console.log('userObj set in localStorage');
};
var getter = function() {
  var storage = localStorage.getItem('userObj');
  console.log(JSON.parse(storage));
};
setLS.addEventListener('click', setter);
getLS.addEventListener('click', getter);
<button id="setLS">Set LocalStorage</button>
<button id="getLS">Get LocalStorage</button>

You can refer this JSFIDDLE as well..


text:
Q: Linux CRC Error I'm getting an error when trying to boot from live Ubuntu cd. "Uncompressing Linux... crc error -- System halted". I've also tried this using a Linux mint live cd, same error. Is this something related to the MB?

A: According to this the kernel doesn't like itself. Based on what you've said, I feel like your hard drive might be to blame. Is it old? Do you have a spare to test on?

A: If you can, try the live cd on another computer, or a different cd rom in the same computer.
If you can't do either of those, I'd try installing from a flash drive.
I think that a flakey cd drive is more likely than the motherboard. You can also try a memory test, live cd here or some Ubuntu live cds have it on there.
Motherboard problems could in theory be an issue too, but I've never seen it, so I'd try the above first.


text:
Q: Export emails but keep them searchable I've got a couple of mailboxes for old businesses on my MacMail. I keep them there because there are loads of emails, and I may need them in the future. The reason I haven't just exported them and archived them is that I still want them to show up in search results when I search through my emails.
The problems I have are:

*

*I keep getting notifications that I have to put the passwords in for these mailboxes. That's very frustrating.

*For some reason, something keeps blocking my IP address from one of the business' domain name. Any time I log onto a different wifi, it blocks that IP address too. I suspect it's something to do with invalid details on one of these mailboxes (but if it could be anything else, please let me know).

My ideal solution would be to have these mailboxes sat there, but completely inactive, not connected to the internet in anyway, just a repository for a bunch of emails. But I may have to face facts that I may need to delete them altogether, exporting the emails first. But then they won't be included in the search. Is there any way I can have my cake and eat it?

A: You can move the emails to a 'mailbox' which is only on your Mac.   The instructions here assume you have the latest version of macOS and Apple Mail, but older versions are much the same.

*

*In Mail's sidebar on the left you should see "On My Mac". With the
mouse, hover, click on the disclosure triangle to show the mailboxes
(folders) inside "On My Mac".

*Create a new mailbox (folder) by clicking on the + symbol.  You may
want to create multiple mailboxes to keep your emails organised. You
can even create a tree structure if you want.

*Then just drag and drop (with the Command key pressed) your old
business emails from the external mailboxes into your new mailboxes
within "On My Mac". The command key ensures that you do a copy (not a
move) as you probably don't yet want to delete them from the external
service.

*Alternatively use 'Copy to' from the Message menu.

*You can now disconnect from the old mail services.
The emails will be indexed (it will take a little) and be available to Mail's search.
Because the emails are now stored just on your Mac, you become responsible for ensuring your backups are sound.


text:
Q: Number of monotically increasing functions where $f(k) = l$ How many monotically functions $f: \{1,2, ..., m\} \rightarrow \{1,2, ..., n\}$ are there if $f(k) = l$, where $1 \le k \le m$ and $1 \le l \le n$?
I tried to compute as answer in counting monotonically increasing functions and I has this result: ${{(k-1)+(l-1)} \choose {l-1}} \cdot { {(m-k)+(n-l)} \choose {n-l}}$. Is this correct?


text:
Q: Rescrict Ip's per Pc/Server I am faily new to networking and want to lern more about it.
Lets say i have 2 Servers and give each one a specific ip
server 1 has 192.168.178.10
server 2 has 192.168.178.11
and here is my problem:
I want server 1 and server 2 to only have use their assigned ip's and prevent them from using any other ip.
so Server 1 can't use 192.168.178.11
and Server 2 can't use 192.168.178.10
what type of equipment is needed to prevent the unwanted access of other ips?
How do i need to setup my network to allow specific ip ranges for different machines and prevent them from using any other ip?
and how is the method called to do this so i can learn more about it
i've read about pfsense and that they can route different ips to different macs but you can also spoof and change those macs and access get their ips
best regards
Justin


text:
Q: disconnected sql server when run stored procedure When I try to create or alter stored procedures, it automatically disconnects dbserver.
It only does so for stored procedure create,alter.
This is the error I get:

A transport-level error has occurred when receiving results from the
  server. (provider: TCP Provider, error: 0 - The semaphore timeout
  period has expired.)

How can I solve this issue?

A: I am not sure if it's the problem but check the query execution option from Tools -> Options menu and go to Query Execution - > Sql Server -> Advanced section. As shown below Disconnect after the query executes option should be unchecked.


text:
Q: My ruby calculator won't output to my console So I'm using atom to code up a calculator and I can't seem to get the console to output the first instance of puts. It just says [Finished in 2.88s]. Is there anything missing that's causing my code to not be printed to the console or am I just stupid to think that it should be outputting anything to the console? Here is my code:

def add
  puts "What is the first number to be added?"
  n1 = gets.chomp
  puts "What is the second number to be added?"
  n2 = gets.chomp
  answer = n1 + n2
  puts "Congrats, your number is #{answer}"
end
def sub
  puts "What is the first number to be subtracted?"
  n1 = gets.chomp
  puts "What is the second number to be subtracted?"
  n2 = gets.chomp
  answer = n1 - n2
  puts "Congrats, your number is #{answer}"
end
def multiply
  puts "What is the first number to be multiplied?"
  n1 = gets.chomp
  puts "What is the second number to be multiplied?"
  n2 = gets.chomp
  answer = n1 * n2
  puts "Congrats, your number is #{answer}"
end
def divide
  puts "What is the first number to be divided?"
  n1 = gets.chomp
  puts "What is the second number to be divided?"
  n2 = gets.chomp
  answer = n1 / n2
  puts "Congrats, your number is #{answer}"
end

print "Would you like to add, subtract, multiply, or divide a number? "
response = gets.chomp
if response == "add" then
  add
elsif response == "subtract" then
  sub
elsif response == "multiply" then
  multiply
else response == "divide"
  divide
end


text:
Q: In Junit testing, how to comparing two ArrayList using assertEquals(), and is there an better alternative? I'm currently writing a Junit test where I use assertEquals() to compare the value of two ArrayList<Double>.
@Test
public void test(){

        QuadraticFormula one = new QuadraticFormula(3, 4, -4);
        List<Double> results = new ArrayList<>();
        results.add(0.66666);
        results.add(-2.0);

        assertEquals(results, one.getRoots());
    }

However, Junit prints out the following failure message:
expected:<[0.66666, -2.0]> but was:<[0.6666666666666666, -2.0]>
junit.framework.AssertionFailedError

Is there anyway I can specify how many decimal places I want the test to compare? I know how to test equality of two double values to certain accuracy, but is there anyway that this can be achieved when comparing two ArrayList of doubles?

A: I guess you can use BigDecimal instead of Double.
check this SO for more details

A: You can use NumberFormat or BigDecimal
Below will round-of
    double d = 0.66666666;
    NumberFormat format = new DecimalFormat("#.##");
    System.out.println(format.format(d)); // 0.67
    BigDecimal bigDecimal = new BigDecimal(d);
    bigDecimal = bigDecimal.setScale(2, BigDecimal.ROUND_HALF_UP);
    System.out.println(bigDecimal); // 0.67

If you don't want to round-of
    double d = 0.66666666;
    DecimalFormat format = new DecimalFormat("#.##");
    format.setRoundingMode(RoundingMode.DOWN);
    System.out.println(format.format(d)); // 0.66
    BigDecimal bigDecimal = new BigDecimal(d);
    bigDecimal = bigDecimal.setScale(2, RoundingMode.DOWN);
    System.out.println(bigDecimal); //0.66


text:
Q: Mojolicious connection to DB occasionally crashes I run a productive app to manage publications of our research group. The app is written in mojolicious framework in perl. I use sqlite3 as a DB and Hypnotoad as an app server.
My problem is that the connection to the DB occasionally crashes (2 times per week) without giving a reasonable error message. The only thing that helps is restart of the Hypnotoad. Any ideas why this may happen?
Example of an error message:
[Fri Jan 16 08:43:09 2015] [error] Can't call method "execute" on an undefined value at /home/piotr/perl/publiste2/script/../lib/AdminApi/Core.pm line 525.

The code there looks as follows:
my $qry = "SELECT DISTINCT our_type FROM OurType_to_Type WHERE landing=1 ORDER BY our_type ASC";
my $sth = $dbh->prepare( $qry );
$sth->execute(); # this is the line 525

The dbh variable is returned by helper:
DBI->connect('dbi:SQLite:dbname='.$config->{normal_db}, '', '') or die $DBI::errstr .". File is: ".$config->{normal_db};

Full code is available here:  https://bitbucket.org/vikin9/hex64publicationlistmanager/src

A: $dbh->prepare returns an undefined value. This can have several reasons. Try something similar to this:
$sth = $dbh->prepare($qry) or die $dbh->errstr;

A: I know it's been some time and maybe you have already figured out, but I thought I'll give it a try.
If you run it using hypnotoad, there's a known problem if you create the handlers before preforking: Database connection problem in preforking
Hope it helps

A: This error kept appearing twice a month. It was so annoying that I have rewritten the app to use MySQL and the proper DBI MySQL connector. Since then, no more crashes.


text:
Q: Need help updating time element with output from jq? Current object with proposed format
[
  {
    "time": "2022-01-28T17:50:31.620Z"
  }
]

Command executed to convert from iso8601 to unix
jq '.[].time | sub("\.[0-9]+Z$"; "Z") | fromdate' time_test.json
Output
1643392231
I've tried varying combinations but how to do I update the time value in the object. I can get the conversion to work but can't seem to update the value with the output.
Expected Result -
[
  {
    "time": "1643392231"
  }
]

A: You mapped all the values in the array but you're not actually modifying or recreating the array.
To modify, use an assignment: (you were almost there)
.[].time |= (sub("\\.\\d+Z$"; "Z") | fromdate)

To recreate, map it.
map(.time |= (sub("\\.\\d+Z$"; "Z") | fromdate))

A: Cancel the fractional seconds and you're good to go with fromdate. To escape within the regex, use double backslashes.
jq 'map(.time |= (sub("\\.\\d+"; "") | fromdate))'

[
  {
    "time": 1643392231
  }
]

Demo


text:
Q: If I want to auto-charge users when they use the service Right now I am making a website that will charge service buyers' money after the service with paypal, Will I be able to do it?
I know that most of the time website that use paypal to process money will need the buyer to perform the paying action. I am in question if there is way that my website can use paypal as a money processor to charge buyers money without they have to perform any action, kind of like those recurring payment that buyer do not need to bother to do the paying procedure again and again. We would like the website to charge them whenever they use the service, and they will be notified that money is charged after they have the service.
Can paypal money processor do that? or there is some other better way?
Thanks


text:
Q: I want to get user-input in a same line, but print() function sends focus on next line insted of focussing on same line Here is my simple dart code. That takes user-name.
import 'dart:io';
void main() {
    print("Enter Your name: ");
    String userName = stdin.readLineSync();
    print("Welcome $userName");
}

here is output:
Enter Your name:  // I want to enter it here.
jay    //but it forces me to enter here.
Welcome jay

A: stdout.write should do what you want:
stdout.write("Enter Your name: ");


text:
Q: Order By in Postgres I want to get the result set in the descending range order. Below is my Query
select quantity_range as quantity_range, count(*) as number_of_items,
sum(amount) as total_amount,
from (
  select *,case
    when quantity between 0 and 500 then '<=500'
    when quantity between 501 and 525 then '501-525'
    when quantity between 526 and 550 then '526-550'
    when quantity between 551 and 575 then '551-575'
    when quantity between 576 and 600 then '576-600'
    when quantity between 601 and 625 then '601-625'
    when quantity between 626 and 650 then '626-650'
    when quantity between 651 and 675 then '651-675'
    when quantity between 676 and 700 then '676-700'
    when quantity between 701 and 725 then '701-725'
    when quantity between 726 and 750 then '726-750'
    else '>750' end as quantity_range
  from Sales )
group by quantity_range order by quantity_range;

I want my Result set like:
<=500   100 100000.00
600-625 10  5000.00
>700    25  25000.00

How to get this ordering? If i give Order By clause then >700 coming at 2nd position.

A: Use RIGHT to get last number from string:
select quantity_range as quantity_range, count(*) as number_of_items,
sum(amount) as total_amount
from (
  select *,case
    when quantity between 0 and 500 then '<=500'
    when quantity between 501 and 525 then '501-525'
    when quantity between 526 and 550 then '526-550'
    when quantity between 551 and 575 then '551-575'
    when quantity between 576 and 600 then '576-600'
    when quantity between 601 and 625 then '601-625'
    when quantity between 626 and 650 then '626-650'
    when quantity between 651 and 675 then '651-675'
    when quantity between 676 and 700 then '676-700'
    when quantity between 701 and 725 then '701-725'
    when quantity between 726 and 750 then '726-750'
    else '>750' end as quantity_range
  from Sales ) as sub
group by quantity_range
order by RIGHT(quantity_range,3);

SqlFiddleDemo


text:
Q: En javascript; ¿Cómo selecciono una propiedad específica, compartida por los elementos de un array para poder compararla con el valor de una variable? Copio el código para ser mas claro.
Quiero comparar el dato guardado en la variable "user", con el valor de la propiedad "usuario" de cada uno de los elementos del Array,( y no se como seleccionar la propiedad de cada elemento del array )
El resultado lo quiero utilizar para  que al confirmar el usuario y el password recibido por prompt, y si el socio está activo, permita ingresar a la web.
let user = prompt("Introduzca su usuario: ");
let pass = prompt("ahora su password: ");

let socios = [
  {
    nombre: "Gustavo",
    apellido: "Castro",
    email: "castrogustavo@gmail.com",
    usuario: "Gustavito",
    password: "soyGus",
    activo: true,
  },
  {
    nombre: "Luis",
    apellido: "Gonzalez",
    email: "luisg@gmail.com",
    usuario: "Luisito",
    password: "soyLuis",
    activo: false,
  }];

A: Para seleccionar los elementos tienes que recorrer el array socios, y para seleccionar cualquier propiedad del JSON lo haces así: arreglo[x].propiedad (socios[0].nombre, por ejemplo).
Con el código que indicas te paso este otro, recorre el array y compara las credenciales y si esta inactivo o no
for(let r in socios){
   if(user == socios[r].usuario && pass == socios[r].password){
      if(socios[r].activo){
         alert('Eres: ' + socios[r].nombre + ' ' + socios[r].apellido);
      }else{
         alert('Usuario inactivo');
      }
   }
}

Espero te sirva, saludos


text:
Q: What is the exact solution to $x^{x^{-1/x}} = 2$?
What is the exact solution of this equation?
  $$x^{x^{-1/x}} = 2$$

I for the life of me have not been able to figure it out nor have I been able to find anything online that would be able to even get me started.

A: Do not expect an explicit solution for the equation
$$x^{x^{-1/x}}=2$$ which can only be solved using numerical methods.
If you plot the lhs, you will notice that the solution is close to $x=3$ and that, around this value, the lhs is almost linear (this is good news). So, let us use Newton method with $x_0=3$ and get the following iterates
$$\left(
\begin{array}{cc}
 n & x_n \\
 0 & 3.0000000000000000000 \\
 1 & 2.7231817852467105312 \\
 2 & 2.7220005777936185465 \\
 3 & 2.7220005621935536562 \\
 4 & 2.7220005621935536535
\end{array}
\right)$$
This number is not identified by inverse symbolic calculators.
Just for the fun of it, this number can be approximated by
$$x=\frac{746 e^2+367 e-77}{379 e^2+171 e-902}=2.7220005621935536538$$
Injecting this value, the lhs is $2.0000000000000000002$.
Edit
Taking logarithms, you could consider that you look for the zero of function
$$f(x)=x \log (\log (x))-kx -\log (x)\qquad \text{with} \qquad k=\log (\log (2))$$ Expanding as a Taylor series around $x=e$ would give
$$f(x)=-(e k+1)+\left(-k-\frac{1}{e}+1\right) (x-e)+O\left((x-e)^2\right)$$ Ignoring the higher order terms the gives
$$x \sim e-\frac{e (e k+1)}{e (k-1)+1}\approx 2.722001500$$ which is not bad as an approximation.
In fact, expanding to first order corresponds to the first iterate of Newton method.
Let us do it with Halley method and get for the first iterate
$$x\sim e-\frac{2 e (e (k-1)+1) (e k+1)}{e \left(2 e (k-1)^2+5 k-4\right)+3}\approx 2.722000562$$
For the fun, let us continue with Householder method and get for the first iterate
$$x\sim e-\frac{3 e (e k+1) \left(e \left(2 e (k-1)^2+5 k-4\right)+3\right)}{e \left(34   k+2 e (k-1) (13 k-9)+e^2 (k (k (6 k-19)+18)-6)-25\right)+14}$$ which is
$2.72200056219156$
You almost have an analytical solution.
Now, using one iteration of high order iterative methods
$$\left(
\begin{array}{ccc}
n & x_{(n)} & \text{method}\\
 1 & 2.7220014995535917953 & \text{Newton} \\
 2 & 2.7220005620261286697 & \text{Halley} \\
 3 & 2.7220005621915662442 & \text{Householder} \\
 4 & 2.7220005621935614452 & \text{no name} \\
 5 & 2.7220005621935536322 & \text{no name} \\
\cdots & \cdots & \cdots\\
\infty & 2.7220005621935536535
\end{array}
\right)$$

A: Note that the equation $x^{x^{-1/x}} = 2$ can be re-expressed as
$$x=\frac{\ln x}{\ln(\ln x) - \ln(\ln 2)}$$
Also note that the actual value of $x$ is very close to $e$. Thus, a good analytic approximation can be obtained by replacing $x= e$ on the RHS, i.e.
$$x = -\frac1{\ln(\ln 2)} = 2.7284 $$


text:
Q: FileNotFound Exception when saving an image to sub directory in external storage private fun takeScreenshot() {
    val now = Date()
    val formattedTimestamp = DateFormat.format("yyyy-MM-dd_hh:mm:ss", now)
    try {
        //val mPath : String = Environment.getExternalStorageDirectory().toString().toString().toString() + "/" + formattedTimestamp + ".jpg"
        // image naming and path  to include sd card  appending name you choose for file
        val mPath: String = Environment.getExternalStorageDirectory().toString().toString() + "/mobile/" + GetSetContext.getApplicationName() + "/Screenshots/" + formattedTimestamp + ".jpg"
            // create bitmap screen capture

        val v = this.view!!

        v.setDrawingCacheEnabled(true)
        v.buildDrawingCache(true)
        val bitmap: Bitmap = Bitmap.createBitmap(v.getDrawingCache())
        v.setDrawingCacheEnabled(false)
        val imageFile = File(mPath)
        val outputStream = FileOutputStream(imageFile)
        val quality = 100
        bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream)
        outputStream.flush()
        outputStream.close()
        ScreenshotUploadWorkManager().setupUploadingRequest(context, applicationConfiguration,mPath)

I am using the file path mPath here. when I using commented out mPath, there is no issue occuring. But when I use the mPath which is not commented out in the code, I am getting a FileNotFound Exception.
java.io.FileNotFoundException: /storage/emulated/0/mobile/App/Screenshots/2022-06-20_09:00:18.jpg: open failed: EISDIR (Is a directory)

Created these sub directories using Device File Explorer in Android Studio but issue is still occurring. What am I missing here?

A: First create a directory using mkdirs() like this
val dir = File(Environment.getExternalStorageDirectory().toString().toString() + "/mobile/" + GetSetContext.getApplicationName() + "/Screenshots/")
if(!dir.exists()){
    dir.mkdirs()
}

Then create a new file for your image
val imageFile = File(dir, formattedTimestamp + ".jpg")

Then copy the stream to image File


text:
Q: How to place controls depending on there data in ios? I am facing an issue with statically placing controls on view in viewcontroller, i am using storyboard for designing all the UI flow in an app using autolayout, among few viewcontrollers, one of them will be getting data from the server, i had statically placed all the controls, and it looks good if i am getting data for all the controls in that viewcontroller.There are  also chances that few controls may not have data, if few controls doesn't have data, then the space for that perticular control is left empty and looks bad. i need to remove that control if there is no data for that and had to move other controls so that there is no empty space left. is placing controls dynamically is only the option for this? or can i achieve this applying constraints for each control using autolayout? any sample or link would help me a lot. thanks..

A: No, sorry there are no such options for this using storyboard (or xib). You have to approach your problem using code only.


text:
Q: Can I call a custom class in the cakephp framework I am new to cakePHP,
I have write a class in MODEL with name of myClass() and I have one function like func().
CODE:
class myClass(){
    function func(){
        echo "test";
    }

}

But I don't know how to call the "myClass class" and run the function func() in the controller file in the cakePHP framework.

A: Of-course you can http://book.cakephp.org/view/943/Loading-Vendor-Files
App::import('Vendor', 'myClass');
$class = new myClass();


text:
Q: How to merge multiple API calls into one call in REST API For instance, if I have an API call http://localhost:3006/send-message?email=abc@mysite.com&password=xxxxxx&count=4&location=US and another API call http://localhost:3006/cancel-request?email=abc@mysite.com&password=xxxxxx&count=2&usernames=abc,xyz.
So, can I merge these two calls into one by doing something like http://localhost:3006/send-message?email=abc@mysite.com&password=xxxxxx&count=4&location=US/cancel-request?count=2&usernames=abc,xyz. If Yes then how I can handle this in Node.js with express.

A: I'd suggest making these operations a POST instead of a GET.  Then, you can have one URL for a multi-operation and you can have a JSON payload in the body that contains an array of operations and their parameters:
http://localhost:3006/multi-operation

With a JSON payload that parses to this:
[
   {
       operation: "send-message",
       email: "abc@mysite.com",
       password: "xxxxx",
       count: 4,
       location: "US"
   },
   {
       operation: "cancel-request",
       email: "abc@mysite.com",
       password: "xxxxx",
       count: 2,
       usernames: ["abc","xyz"]
   }
]

This would also only be sending sensitive information such as passwords in the body of the request which is generally considered safer than putting them in the URL (where they might get logged by various infrastructure).
Note: In a REST API design, a GET request is not supposed to have "side-effects".  It's supposed to retrieve some resource.  Calling it 0 times, 1 time or 10 times should have the same effect on the server/world.  So, independent of the desire to specify multiple operations in one API call, neither of these operations should have been a GET operation anyway because they both have side effects (they cause some change to occur).  So, these should likely be POST operations.  There are lots of good articles on when to use GET, POST, PUT, PATCH, etc... in a REST API.  If you're confused by this, you can start with these articles or find many others with a search:
https://restfulapi.net/http-methods/
https://www.restapitutorial.com/lessons/httpmethods.html


text:
Q: Does $exists:false use an index? We have the following use case: Due to protocolling reasons we do not remove deleted or updated records from the database. We $set their deleted field to the date/time when they were updated/deleted and create a new record( if updated). So all "current" records do not have the deleted field". All indexes on current records look like this:
{
    field_a: 1,
    field_b: 1,
    ...,
    deleted: 1
}

A query concerning current records looks like this:
find( {
    field_a: "...",
    field_b: "...",
    deleted: { $exists: false}
} )

Because I am not sure if the {$exists: false} uses the index, I have added a field current set to true to all current fields (those without deleted) and I changed the indexes to:
{
    field_a: 1,
    field_b: 1,
    ...,
    current: 1
}

and my query to:
find( {
    field_a: "...",
    field_b: "...",
    current: true
} )

Can anyone tell me if the latter case is really the better one? Or do they perform indetically and I can spare the additional current field?
Thanks for any hint.


text:
Q: gcloud: how to download the app via cli I depolyed an app with gcloud preview app deploy.
Is there a way to download it to an other local machine?
How can I get the files? I tried it via ssh with no success (can't access the docker dir)
UPDATE:
I found this:
gcloud preview app modules download default --version 1 --output-dir=my_dir

but it's not loading files
Log
Downloading module [default] to [my_dir/default]
Fetching file list from server...
|- Downloading [0] files...                                 -|

A: Currently, the best way to do this is to pull the files out of Docker.
Put instance into self-managed mode, so that you can ssh into it:
$ gcloud preview app modules set-managed-by default --version 1 --self

Find the name of the instance:
$ gcloud compute instances list | grep gae-default-1

Copy it out of the Docker container, change the permissions, and copy it back to your local machine:
$ gcloud compute ssh --zone=us-central1-f gae-default-1-1234 'sudo docker cp gaeapp:/app /tmp'
$ gcloud compute ssh --zone=us-central1-f gae-default-1-1234 "chown -R $USER /tmp/app"
$ gcloud compute copy-files --zone=us-central1-f gae-default-1-1234:/tmp/app /tmp/
$ ls /tmp/app
Dockerfile
[...]

A: IMHO, the best option today (Aug 2018) is:
Under the main menu, under Products, go to Tools -> Cloud Build -> Build history.
There, click the ID of the build you want.
Then, in the opened window (Build details), click the source link, the download of your compressed code begins.
As simple as that.
HTH.

A: I am coming to Google App Engine after two years, I see that they have made lots of improvements and added tons of features. But sadly, their documentation sometimes leaves much to be desired.
I used to download my code of the uploaded version with the appcfg.pyusing the following command.
appcfg.py download_app -A <app_id> -V <version> <output-dir>
But of course now that they have culminated everything in the gcloud shell where appcfg.py is not accessible.
However, the following method helped me to download the deployed code:

*

*Go the console and in to the Google App Engine.

*Select the project you want to work with.

*Once the project's dashboard opens, Click on the top right to
open the built in console window.

*Which should load the cloud shell at the bottom, now if you check appcfg.py is available to you to use in this VM.

*Hence, use appcfg.py download_app -A <app_id> -V <version> <output-dir> to download the code.

*Now once you have the code in the desired folder, in order to download it on your local machine - You can open the docker code editor

*Now here I assumed if I rightclicked and exported the desired
folder it would work,

but instead it gave me the following error message.
{"Error":"'concurrency' must be a number but it is [object Undefined]","Message":"'concurrency' must be a number but it is [object Undefined]"}

*So, I thought maybe it would play along nicely if the the folder
was an archive. Go back to the cloud shell and using whatever
utility you fancy make an archive of the folder
zip -r mycode.zip mycode

*Go to the docker code editor, export and download.

Now. Of course there might many more ways do it (hopefully) but this is what made sense to me after returning to Google App Engine after 2 years.

A: As of Feb 2021, you can install appengine-sdk using pip
pip install appengine-sdk
Once installed, appcfg can be used to download the app code.
python -m appcfg download_app -A app_id [ -V version ] out-dir

A: Nothing works. Finally I found the source code this way. Simply go to google cloud storage. choose buckets starting with us.artifacts...., select containers > images > download the latest one (look by created date). unzip after downloaded file. it will have all the deployed source code of app engine.


text:
Q: Proving that if left coset multiplication is well-defined then $H$ is a normal subgroup I am given the left coset multiplication rule which is :
$$aHbH=abH$$
Taking representatives $x \in aH $ and $a^{-1} \in a^{-1}H$
$$xHa^{-1}H=xa^{-1}H$$
Take representatives $a\in aH$ and $a^{-1}\in a^{-1}H$ Then
$$aHa^{-1}H=H$$
If, multiplication is well defined then, $xa^{-1}H=H \implies xa^{-1}=h \ \ for \ some \ h\in H \implies x=ha \implies aH \subseteq Ha$
Now in order to prove the containment in other direction what should I do? I can easily do the exact same thing, but I'm not given a definition for right coset multiplication - I don't know how to multiply right cosets? Should I act as if I was given the such property? If I should, why? If shouldn't how ?

A: I prefer the definition of a normal subgroup as the kernel of a homomorphism. Then you're told that $\phi: a \mapsto aH$ is a homomorphism (because coset multiplication is well-defined); its kernel is just $H$, so you're done.


text:
Q: Argument flag that is null when not used and default value when used without argument I'm using argparse to parse arguments. I'd like to have a flag that is NULL when not used, foo when used without an argument, and the argument value when used with an argument.
ap = argparse.ArgumentParser(description='test')
ap.add_argument('--bar', action='store_true')
args = ap.parse_args()

The above code is what i have currently.
I would like python test.py to have ap.bar=None, python test.py --bar to have ap.bar=foo, and python test.py --bar ctest to have ap.bar=ctest. What would I modify to have this happen?

A: I am assuming that you mean None rather than NULL.
You can do:
import argparse

ap = argparse.ArgumentParser(description='test')
ap.add_argument('--bar', nargs='?', const='foo')
args = ap.parse_args()

print(args.bar)

This gives:
$ python3 test.py
None

$ python3 test.py --bar
foo

$ python3 test.py --bar ctest
ctest

As a possible mnemonic, the nargs='?' syntax (meaning zero or one) is similar to the usage of ? in regular expressions.


text:
Q: Every prime ideal is max. if anysequence $I_1 \supseteq I_2 \supseteq I_3 \supseteq \cdots $ stabilises? Let $R$ be a comutative ring with $1 \neq 0 $. Assume that for every sequence of ideals $I_1 \supseteq I_2 \supseteq I_3 \supseteq \cdots $ there is a $N$ such that
$$
n,m \geq N \quad \Longrightarrow \quad I_n=I_m
$$
Show that every prime ideal in this ring is maximal.

I don't know what I can do to prove it. A small hint please?

A: Your ring is called Artinian.
Let $\mathfrak{p}$ be a prime ideal of $R$, then $R/\mathfrak{p}$ is an Artinian integral domain. For any $x$, consider the sequence of principal ideals of $R/\mathfrak{p}$
$$(x)\supseteq (x^2)\supseteq\cdots\supseteq (x^n)\supseteq\cdots$$
The fact that sequence stops implies ...


text:
Q: how to use constant from class as an argument definition in php function? I have a class:
class FetchMode
{
 const FetchAll = 0;
 const FetchOne = 1;
 const FetchRow = 2;}

and a function:
function getRecordSet(FetchMode $FetchMode){ some switch cases }

I would like to use $FetchMode as switch case criteria but receiving an error:
Catchable fatal error: Argument  passed to getRecordSet() must be an instance of FetchMode, integer given
this is how I call a function:
getRecordSet(FetchMode::FetchOne);

I would like to offer a list of possible choices in calling a function.
Is it possible in php?

A: You've hinted PHP to expect an instance of FetchMode (just like it says in the error message), but FetchMode::FETCH* passes the constant value. You'd have to use some sort of Enum instance (which we dont have natively in PHP. (Oh well, there is SplEnum but who uses that?)) or change the method signature to exclude the typehint.
However, instead of a Switch/Case you could solve this more easily via Polymorphism and a Strategy pattern, e.g. instead of doing something like
public function getRecordSet($mode)
{
    switch ($mode) {
        case FetchMode::ALL:
            // code to do a fetchAll
            break;
        case FetchMode::ONE:
            // code to do a fetchOne
            break;
        default:
    }
}

which will increase the Cylcomatic Complexity of your class and forces changes to that class and FetchMode whenever you need to add additional FetchModes, you can do:
public function getRecordSet(FetchMode $fetchModeStrategy)
{
    return $fetchModeStrategy->fetch();
}

and then have an interface to protect the variation
interface FetchMode
{
    public function fetch();
}

and add concrete FetchMode classes for each supported FetchMode
class FetchOne implements FetchMode
{
    public function fetch()
    {
        // code to fetchOne
    }
}
class FetchAll …
class FetchRow …

This way, you'll never have to touch the class with that getRecordSet method again because it will work for any class implementing that FetchMode inteface. So whenever you have new FetchModes, you simply add a new class, which is much more maintainable in the long run.

A: I don't know what you mean by

would like to offer a list of possible choices in calling a function. Is it possible in php?

but for the error part: Imagine you have a var, e.g. $foo. When you do echo $foo you don't get the name of the var but its value. This is because a var has a name and points to a value.  Every access to the var basically returns the value it points to. Its the same with constants; You put the constant name in there, but basically you are pointing to your stored value. Which means getRecordSet(FetchMode::FetchOne); and getRecordSet(1); is the same.
So, getRecordSet(FetchMode $FetchMode) raises must be an instance of FetchMode because FetchMode::FetchOne points to an integer.
To fix this, you need to use getRecordSet(int $FetchMode).


text:
Q: Firebase signInWithCustomToken in React Native I use email and password for login at first login and I have a token with getToken() function, after I add localStoreage with AsyncStoreage.setItem("ACCESS_TOKEN",token). I want to refresh to app signup with token and I use signInWithCustomToken(token) but I have an error. its 'auth/invalid-custom-token' (The token you provided is not valid.). I can't login.
DataStore.js
onLogin: function (Data) {
    ApiRequest.login(Data)
        .then((authData) => {
            authData.getToken().then((token)=>{

                AccessToken.set(token)
                    .then(() => Actions.login.completed(authData));
            })
                    .catch((err) => Actions.login.failed(err))
        })
        .catch((err) => Actions.login.failed(err))
}

ApiRequest.Js
    login(data) {
    // first.login data = (email.password) && after.login data=(token)
    return new Promise((next, error) => {
        if (data && data.email && data.password) {
            this.firebase.auth().signInWithEmailAndPassword(data.email,data.password)
                .then((uData) => {;
                    next(uData)
                })
                .catch((err)=> error(err));
        } else {

            console.log("TOKEN:");
            console.log(data);
            this.firebase.auth().signInWithCustomToken(data)
                .then((authData)=>next(authData))
                .catch((err)=>{console.log("Error #232",err)})

       }
    });
}

AccessToken.Js
get(){
    return new Promise((next,error) => {
       if(this._accessToken) {
           console.log("LastToken");
           return next(this._accessToken);

       }
        AsyncStorage.getItem("ACCESS_TOKEN")
            .then((token)=>{
                if(token){
                    next(JSON.parse(token));
                }else{
                    error()
                }
            })
            .catch((err)=>error(err));
    });

}
set(token){
    this._accessToken=token;
    return AsyncStorage.setItem("ACCESS_TOKEN",JSON.stringify(token));
}

Authenticate Listener
actions.auth.listen(function () {
AccessToken.get()
    .then((token) => actions.login(token))
    .catch((err) => actions.logout());
 })

Token

eyJhb...Ckz95w


text:
Q: How do I know to where my object is going when I drag and drop between the columns dragula and I am facing with an issue that is, how to know which column the object is going by the ID or something like that.
I do have 3 columns, but when I move an object between them I got the JSON information that doesn't tell me source column and target column, I need this information to send to the backend and save into the database.
This code below is an example that I am trying to do on my real code.
https://stackblitz.com/edit/angular-7k1bcq
This first JSON is an example that what I am receiving in console
{name: "listagem", el: {…}, target: {…}, source: {…}…}
el: HTMLLIElement
item: Object
name: "listagem"
sibling: HTMLLIElement
source: HTMLUListElement
sourceIndex: 0
sourceModel: Array[1]
target: HTMLUListElement
targetIndex: 1
targetModel: Array[3]
__proto__: Object

This second JSON is what I am expecting to receive to treat the data before to send to backend.
{name: "listagem", el: {…}, target: {…}, source: {…}…}
el: HTMLLIElement
item: Object
name: "listagem"
sibling: HTMLLIElement
source: HTMLUListElement
sourceIndex: 0
sourceModel: Array[1]
target: HTMLUListElement
targetIndex: 1
targetModel: Array[3]
sourceColumn: 0
targetColumn: 1
__proto__: Object

sourceColumn and targetColumn are the fields that I am trying to track

A: The easiest way to get this is to use one JSON and rearrange everything in this. Finally you can get all information from them.
But of course you can use dragula services to get this data.
You can subscribe .drag event and get information about source from this.
        this.dragula$.add(this.dragulaService.drag('ITEMS')
            .subscribe(({name, el, source}) => {
                console.log(source); // information about source group
            })
        );

And to get information about target column you can use event .drop:
        this.dragula$.add(this.dragulaService.drop('ITEMS')
            .subscribe(({name, target}) => {
                console.log('target', target);
            })
        );

To use events you need only create new Subscription like this: this.dragula$ = new Subscription(); and .add new subscription.
If you need more information, feel free to ask.
EDIT---
ready part of code:
import { Component } from '@angular/core';
import { DragulaService } from 'ng2-dragula';
import {Subscription} from 'rxjs/internal/Subscription';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent {
  dragula$: Subscription;
  listas = [
    {
      nome: "Lista 1",
      id_lista: 1,
      itens: [
        { item: 'Lapis' },
        { item: 'Borracha' },
      ]
    },
    {
      nome: "Lista 2",
      id_lista: 2,
      itens: [
        { item: 'Maca' },
        { item: 'Banana' },
      ]
    },
    {
      nome: "Lista 3",
      id_lista: 3,
      itens: [
        { item: 'Doce' },
        { item: 'Chocolate' },
      ]
    }
  ];

  constructor(private dragulaService: DragulaService) {
    this.dragula$ = new Subscription();

    this.dragula$.add(this.dragulaService.drag('listagem')
      .subscribe(({name, el, source}) => {
        console.log('source', source.childNodes, source.parentElement.className);
       })
    );

    this.dragula$.add(this.dragulaService.drop('listagem')
      .subscribe(({name, target}) => {
          console.log('target', target);
      })
    );
  }

}


text:
Q: Completely delete EF database in c# I've been messing around with changing my object properties, and that requires me to keep updating my table, but I keep getting errors, so does anyone know how I can just delete the whole DB and start over?
I have this code
using (var ctx = new Context())
            {
                foreach (Item2 block in new_Items)
                {
                    ctx.items_db2.Add(block);
                }
                ctx.SaveChanges();

                test = (from b in ctx.items_db2
                        orderby b.Index
                        select b).ToList();
            }

I've tried truncating the table but I can't do that since I've changed the object properties, and even when I run the commands from the package manager console to update the table, I get other errors so I'd just like to start from a clean slate.

A: If the migrations are not important, I:

*

*Delete migrations.

*Delete all the tables in the database.

*Run the Enable-migration command.

*Run the Add-migration command, to add an initial migration.

*Run the Upgrade-database command. This will rebuild all the tables in the db, and you back to square one :)

I use code first.

A: You can do it from from your code just by running:
using (var ctx = new Context())
{
   ctx.Database.Delete();
}

Alternatively connect to your database using VS - View --> SqlServer Object Explorer connect to your database server, right click on the database you want to delete and select Delete. You want to check the checkbox to close existing connection otherwise deletion may fail.


text:
Q: How do I get values (multiple rows and columns) to be set in another sheet with the getLastRow? I have a button in my sheet that should copy the ranges (found below, called 'values') into another sheet. The data should be placed in two columns and continue down the sheet with time when new data is sent. Therefore I try to use the getLastRow, however, I am not able to copy the ranges due to an error:
"Cannot copy C30:C51 to int"
Thanks for the help
function sendBudgetData() {

var ss = SpreadsheetApp.getActiveSpreadsheet();
var budget = ss.getSheetByName("BUDGET");
var budgettransaktion = ss.getSheetByName("BUDGETTRANSAKTIONER");

var values = [

[budget.getRange("C30:C51","H30:H51").getValues()],
[budget.getRange("C58:C64","H58:H64").getValues()],
[budget.getRange("C69:C72","H69:H72").getValues()]

];

//I want to set the values above in two columns.
budgettransaktion.getRange(budgettransaktion.getLastRow()+1,4,3,2).setValues(values);

}

A: Your method of trying to attach the two columns together won't work in its current structure. You can accomplish this a couple ways (and there are probably more efficient ways than my solution), but this will work. I would suggest that you should consider using named ranges instead of hard coded cell addresses. Also make sure when you set values in your sheet, you have the proper number of rows which can be identified using values.length.
function sendBudgetData() {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var budget = ss.getSheetByName("BUDGET");
  var budgettransaktion = ss.getSheetByName("BUDGETTRANSAKTIONER");

  var firstColumn = budget.getRange("C30:C51").getValues().concat(
    budget.getRange("C58:C64").getValues(),
    budget.getRange("C69:C72").getValues());

  var secondColumn = budget.getRange("H30:H51").getValues().concat(
    budget.getRange("H58:H64").getValues(),
    budget.getRange("H69:H72").getValues());

  //you now have two arrays with value. Te below loop will run through all elements and push them
  // into the values array with the propery structure of two values per row.
  var values = [];
  for (var i = 0; i < firstColumn.length; i++) {
    for (var c = 0; c < firstColumn[0].length; c++) {
      values.push([firstColumn[i][c], secondColumn[i][c]]);
    }
  }

  //set the values in your spreadsheet. Not to make sure to use the length of values.
  //Your prior code only allowed for three rows.
  budgettransaktion.getRange(budgettransaktion.getLastRow() + 1, 4, values.length, 2).setValues(values);
}


text:
Q: How to create JaCoCo xml report and xml summary for Microsoft Visual Studio Team? I need to switch on JaCoCo coverage reports in Microsoft Visual Studio Team.
I can see the form:

So, I need the summary file. How can I create it?
Is it true that I need to create a report in xml format locally?
I am trying to create this reports, but I have a problem.
My project use Gradle, so I add this in gradle.build:
apply plugin: "jacoco"

And:
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
    }
    debug {
        testCoverageEnabled true
    }
}

But I can't see any reports from jacoco.
I can create a full jacoco report with Android studio, but it's the only html.
How can I create the summary for Microsoft Visual Studio Team?

A: For the Jacoco configuration, you can refer to the code sample here: Gradle Example. I have tested it, it can generated XML report correctly.
And then you can run the build and publish the code coverage result from VSTS:

Published result in VSTS:


text:
Q: Cython: power inferior to 1 crash Jupyter kernel I'm computing the Total Variation inside a Cython function in Jupyter Notebook/Python 3.6 :
%%cython --compile-args=-O3 --compile-args=-fopenmp --link-args=-fopenmp

# cython: boundscheck=False
# cython: cdivision=True
# cython: wraparound=False
# cython: profile=False

import numpy as np
cimport numpy as np
cimport cython
from cython.parallel cimport parallel, prange

cdef extern from "stdlib.h":
    float abs(float x) nogil

cdef void p_norm(float[:, :, ::1] img, float[:, ::1] output, long p) nogil:
    cdef int M = img.shape[0]
    cdef int N = img.shape[1]
    cdef int i, j

    with parallel(num_threads=8):
        for i in prange(M, schedule="static"):
            for j in range(N):
                output[i, j] = (abs(img[i, j, 0]) ** p + abs(img[i, j, 1]) ** p) **(1/p)

def run_norm(a, output, p):
    return p_norm(a, output, p)

And computing the TV norm for p < 1
a = np.ascontiguousarray(np.arange(2*2048**2).reshape((2048, 2048, 2)), dtype=np.float32)
out = np.empty((a.shape[0], a.shape[1]), dtype=np.float32)
run_norm(a, out, 0.5)

makes the Jupyter kernel crash with no error. Changing
# cython: cdivision=False

makes it run indefinitely.
What did I do wrong ?

A: Ok found it… It was the 1/p division in the power… Replacing by 1./p did the trick (float division) and p should have been a float type.


text:
Q: Choice of technology to develop multi-platform application What I have is business WinForms application written in C#.
What I would like to do is to redesign it to meet multi-platform approach.
I was thinking about architecture involving application server (executing all the logic and performing database operations) and thin client side running on Windows and Mac OS as well as Android, iPhone or just in web browser. Windows version should also have to be able to use methods from some DLLs.
Solution that comes to my mind is desktop client developed to target Silverlight (for Windows and Mac OS users). Web part, based on ASP.NET, would be adjusted for mobile devices. All would use WebServices provided by WCF server running on Mono.
What do you think about this approach? Why is it good and why if it's not? I know that all of those platforms are in range of Adobe AIR but choosing it will result in abandonment of all existing code and development team's knowledge about .NET.
Thank you for any hint.

A:
I was thinking about architecture involving application server (executing all the logic and performing database operations) and thin client side running on Windows and Mac OS as well as Android, iPhone or just in web browser. Windows version should also have to be able to use methods from some DLLs.

I would recommend you just make it a website. Pick any .NET server stack you want (preferably ASP.NET MVC) and just serve content as HTML5/CSS3/JavaScript.
That's the easiest way to go cross-platform. You can even use a tool like PhoneGap to compile your website to native android / iOS applications.

Silverlight

is an option but then you drop Linux support and force your users to install silverlight (I personally won't out of principle), You also have a completely separate code-base for mobile and desktop. I would personally only choose silverlight if you can port more then 50% of your UI directly into silverlight verbatim.

A: Since the existing application uses WinForms, have you considered Mono?  It's a cross platform implementation of the CLR (core of .NET).  You would still have some work to do, but you wouldn't have to throw out your existing code.

A: As Raynos said, making the app a regular web application may be your best bet. In making a client application, do you need to support some sort of specialised / improved UX or disconnected data functionality? These are the main reasons I consider a thin client UI.


text:
Q: Laravel switching from MySQL to MSSQL I'm currently developing a web apps for my client, and my development server (a shared hosting server) only support MySql. But I just came to know that my client on whose server I'm going to deploy the laravel web apps on only support Mssql.
So my question is, later when I deploy the laravel web app on my client's server, what should I do to make the web apps works perfectly well? Is it enough if I just change the default driver from mysql to sqlsrv?


text:
Q: Resizing svg in a panel in java I have a svg file in a panel and it is displayed. The problem occurs when i try to change the size of it (svg). I tried setSize, setPreferredSize  and resize but none work. I noticed that when i try to resize it resizes but then goes back to it's previous size. Can someone help me, please?
svg.setPreferredSize(new Dimension(700,700));
svg.setSize(new Dimension(700,700));
this.add(svg, BorderLayout.NORTH);
this.setSize(1000, 1000);

My class extends JPanel. I'm using batik.

A: I added svg to JSVGScrollPane. Now it works fine, resizes well and i have scrollbars when svg is bigger. It took me day and a half of experimenting with JPanels, JScrollPanes, but this is the best solution. [:


text:
Q: Tooltip for D3.js graphs I want to make a tooltip for a realtime D3.js and javascript graph that moves smoothly on the data. Does any one know any example. All I have found is related to static graphs.

A: If your data is bound to <g> elements, you can add the tooltips to the <g> as a <text> element. Or, you could use a <foreignObject> with some nested HTML if you'd prefer CSS styling.


text:
Q: Multiple aggregate functions in HAVING clause Due to the nature of my query i have records with counts of 3 that would also fit the criteria of having count of 2 and so on. I was wondering is it possible to query 'having count more than x and less than 7' ? How could I write this. Here is my current code.
GROUP BY meetingID
HAVING COUNT( caseID )<4

I'd like something like
GROUP BY meetingID
HAVING COUNT( caseID )<4 AND >2

That way it would only count for exactly 3

A: For your example query, the only possible value greater than 2 and less than 4 is 3, so we simplify:
GROUP BY meetingID
HAVING COUNT(caseID) = 3

In your general case:
GROUP BY meetingID
HAVING COUNT(caseID) > x AND COUNT(caseID) < 7

Or (possibly easier to read?),
GROUP BY meetingID
HAVING COUNT(caseID) BETWEEN x+1 AND 6

A: Here I am writing full query which will clear your all doubts
SELECT BillingDate,
       COUNT(*) AS BillingQty,
       SUM(BillingTotal) AS BillingSum
FROM Billings
WHERE BillingDate BETWEEN '2002-05-01' AND '2002-05-31'
GROUP BY BillingDate
HAVING COUNT(*) > 1
AND SUM(BillingTotal) > 100
ORDER BY BillingDate DESC

A: Something like this?
HAVING COUNT(caseID) > 2
AND COUNT(caseID) < 4

A: There is no need to do two checks, why not just check for count = 3:
GROUP BY meetingID
HAVING COUNT(caseID) = 3

If you want to use the multiple checks, then you can use:
GROUP BY meetingID
HAVING COUNT(caseID) > 2
 AND COUNT(caseID) < 4

A: GROUP BY meetingID
HAVING COUNT(caseID) < 4 AND COUNT(caseID) > 2

A: select CUSTOMER_CODE,nvl(sum(decode(TRANSACTION_TYPE,'D',AMOUNT)),0)) DEBIT,nvl(sum(DECODE(TRANSACTION_TYPE,'C',AMOUNT)),0)) CREDIT,
nvl(sum(decode(TRANSACTION_TYPE,'D',AMOUNT)),0)) - nvl(sum(DECODE(TRANSACTION_TYPE,'C',AMOUNT)),0)) BALANCE from TRANSACTION
GROUP BY CUSTOMER_CODE
having nvl(sum(decode(TRANSACTION_TYPE,'D',AMOUNT)),0)) > 0
AND (nvl(sum(decode(TRANSACTION_TYPE,'D',AMOUNT)),0)) - nvl(sum(DECODE(TRANSACTION_TYPE,'C',AMOUNT)),0))) > 0


text:
Q: Django custom manager with RelatedManager There must be a problem with super(InviteManager, self).get_query_set() here but I don't know what to use.  When I look through the RelatedManager of a user instance,
len(Invite.objects.by_email()) == len(user.invite_set.by_email())

Even if the user does not have any invites.  However, user.invite_set.all() correctly returns all of the Invite objects that are keyed to the User object.
class InviteManager(models.Manager):
    """with this we can get the honed querysets like user.invite_set.rejected"""

    use_for_related_fields = True

    def by_email(self):
        return super(InviteManager, self).get_query_set().exclude(email='')

class Invite(models.Model):
    """an invitation from a user to an email address"""

    user = models.ForeignKey('auth.User', related_name='invite_set')
    email = models.TextField(blank=True)
    objects = InviteManager()

'''
u.invite_set.by_email() returns everything that Invite.objects.by_email() does
u.invite_set.all() properly filters Invites and returns only those where user=u
'''

A: You may want a custom QuerySet that implements a by_email filter.  See examples on Subclassing Django QuerySets.
class InviteQuerySet(models.query.QuerySet):
    def by_email(self):
       return self.exclude(email='')

class InviteManager(models.Manager):
    def get_query_set(self):
        model = models.get_model('invite', 'Invite')
        return InviteQuerySet(model)

A: Try:
def by_email(self):
    return super(InviteManager, self).exclude(email='')

If nothing else, the .get_query_set() is redundant. In this case, it may be returning a whole new queryset rather than refining the current one.

A: The documentation specifies that you should not filter the queryset using get_query_set() when you replace the default manager for related sets.

Do not filter away any results in this type of manager subclass
One reason an automatic manager is used is to access objects that are related to from some other model. In those situations, Django has to be able to see all the objects for the model it is fetching, so that anything which is referred to can be retrieved.
If you override the get_query_set() method and filter out any rows, Django will return incorrect results. Don't do that. A manager that filters results in get_query_set() is not appropriate for use as an automatic manager.

A: Try using .all() in place of .get_query_set(). That seemed to do the trick for a similar problem I was having.
def by_email(self):
    return super(InviteManager, self).all().exclude(email='')


text:
Q: Ocaml String.sub: How to get all characters until end of string So I'm using the String.sub function and I'm wondering if there's any way to get all the characters in a string until the end of the string. Since String.sub takes in a string, int (the index of where to start getting chars), and then a number of how many chars, I'm not sure what the easiest way of doing all chars since we want a possibly positive infinite amount

A: For String.sub you just have to subtract from the length of the string. There's no simpler way, i.e., there's no value for length that has a special meaning. A value larger than the remainder of the string is an error in OCaml (which tends to be strict when checking parameters).
Assume i is >= 0 and < length of the string:
String.sub s i (String.length s - i)

You can use Str.last_chars, but you still need to know how many characters you want. I.e., you still have to subtract from the length of the string.
Str.last_chars s (String.length s - i)


text: Q: Unstable acoustic mode For a stirling thermoacoustic engine that works with a simple stack inside a test tube (with temperature gradient), it is said the frequency at steady state is that of the most unstable acoustic mode - what does this mean ? I was under the impression that it's merely a simple standing wave, please help, thanks !


text:
Q: JavaFX changing font size results in tiny text appearing for a fraction of a second I am making a cross number puzzle game (cross word with numbers). For the actual puzzle itself, I have a grid pane containing stack panes (the squares of puzzle grid). Some of the stack panes have labels in their corners to denote the start of a question and some of them have text fields for the user to write their answers. I have added a listener to each stack pane so that when its height changes, it will also change the font size of the text field attached to that stack pane. Here is the code:
      ChangeListener<Number> squareSizeListener = (observable, oldValue, newValue) -> {
            textField.setStyle("-fx-font-size: " + (newValue.intValue() / 4));
      };
      square.heightProperty().addListener(squareSizeListener);

I use an identical listener to change the size of the label denoting the question number.
While this does the job of changing the font size of the text field and question numbers as I resize the window (and hence the stack panes), I have come across a strange problem where, while resizing the window, a smaller version of the text will very briefly appear instead of the text and then quickly dissapear. This smaller text is always the same size and colour. It's as if it reseting the style of the text to a default before applying the new one.
Here is a video of what I am talking about.
I have no clue why this is happening and I have been unable to find anything regarding this online. I've tried changing the stack pane to a different container but encountered the same issue. Could someone please help me figure out whats going on?
Many thanks!
PS. If someone also knows that the outline of the text field is also dissappearing and reappearing, I would be very grateful!

EDIT: So somehow I stumbled upon a solution. I don't know why or how it works, but it does. Calling the applyCss method on the textfield/label after changing their fonts using setStyle seems to fix the problem.

A: So somehow I stumbled upon a solution. I don't know why or how it works, but it does. Calling the applyCss method on the textfield/label after changing their fonts using setStyle seems to fix the problem.


text: Q: Language conversion I have a English store which I have brought over from shopify. Is there an easy way I can bring over my 9 other stores and convert the same products to different languages for them? Rather than manually going into each product to translate and save it


text:
Q: How to find potential difference at A As shown below the schematic diagram is given.Point B is grounded.

I did take the potential at A is 2V since it is on the same node where the  2V batteries are located , am I correct? . I want to verify the accuracy of my  answer !. What is your opinion?

A: Another approach is to take each one of the branches with batteries and substitute them with their Norton equivalent, i.e. a \$5\Omega\$ resistor in parallel with a \$ \dfrac{2V}{5\Omega}=0.4A\$ current source.

simulate this circuit – Schematic created using CircuitLab
Then you get three paralleled \$5\Omega\$ resistors driven by two paralleled \$0.4A\$ current sources. This means a total \$0.8A\$ flowing into an equivalent \$\dfrac{5\Omega}{3}\$ resistor.

simulate this circuit
By Ohms'law you get:
\$ V_{AB} = \dfrac{5\Omega}{3} \times 0.8A = \dfrac{4}{3}V \approx 1.33V \$
EDIT
(Since it seems you have not grasped the concept of circuit ground).
A voltage is an electrical quantity always measured between two points in a circuit. Since it is cumbersome to draw schematics full of arrows (or +- symbols) specifying where are all the voltages you need, it is customary to take a common reference point (node, to be precise) for all voltages: that point (that node) is called circuit ground. Then you specify only node voltages, i.e. voltages between a node and the ground node. That is, for each node k, \$V_k = V_{kG} \$ where G indicates ground. This is a definition!
So, by marking a node (B in your case) with the ground symbol you are saying that any other node voltage is measured/specified with respect to that node (B). This allows specifying node voltages with only one subscript. Moreover this doesn't lead to a loss of generality, because it can be easily shown that a voltage \$V_{XY}\$ between any two points X and Y in the circuit can be written as a difference between two node voltages, i.e. \$V_{XY} = V_X - V_Y\$ (if either X or Y is ground, the corresponding node voltage is of course 0).

A: You can solve this by stepwise reduction.
1) The left side of the two batteries is connected, hence the right sidse of the batteries have the same potentional. Connect those two point with a wire.
2) Now you have two same-voltage batteries in parallel. Remove one.
3) Now you have two 5 Ohm resistors in parallel. Replace them by a single suitable resistor.
4) Now you have a simple circuit with one battery and two resistors in series. Calculate the current and use it to determine the voltage at the junction of the two resistors. Or alternatively, regard the two resistors as a voltage divider and use that to calculate the voltage at the junction.
Optional step: The fact that the batteries do not have one side grounded might make you a little nervous. But two elements in series can always be swapped without influencing the rest of the circuit, so you could swap both battteries with their series resistors. (But do note that this will influence the voltage at the junction of the battery and its series resistor!)

A: Your outright guess that node A is 2V with respect to node B is not correct.
There are resistors in series with the two batteries that must be taken into account.

A: Ground is just a reference point.  Just move the ground to point A and calculate the voltage at B.  The relationship between A and B will always be the same, regardless of where you put ground.


text:
Q: What does .I do when used within .SD, and how do you stipulate which one to use? This stems from some code I created for this other question I asked. With sample data:
tmp_dt <- data.table(grp = c(1, 1, 1, 2), x = runif(4))

One can obtain the first and last rows in each group, without duplicates, by:
tmp_dt[, .SD[unique(c(1, .N))], by = grp]
#     grp         x
# 1:   1 0.0628539
# 2:   1 0.1552129
# 3:   2 0.5827001

I don't understand why using .I does not work to do the same thing:
tmp_dt[, .SD[.I %in% c(1, .N)], by = grp]
#     grp         x
# 1:   1 0.6244266
# 2:   1 0.2340571

It looks like .I refers to the row index within .SD, whereas .N refers to the number of rows in each group outside of .SD. How does one refer to .I so that it is while grouping, it holds for each item in the group, it's row location in x?
(I suppose one could do tmp_dt[, .SD[seq_len(.N) %in% c(1, .N)], by = grp] to achieve the desired result.)

A: One way to get the output with .I will be
tmp_dt[tmp_dt[, .I[unique(c(1, .N))], grp]$V1]


text:
Q: django: assertRedirect clears session data django I'm a beginner in Django and I'm writing a simple accounting app. Now I've started to write some test cases for this app.
There is a profile form in my app that allows user to edit his or her profile. If the data has been successfully changed, I call HttpResponseRedirect to index page
I use an assertRedirect method to ensure that when the form data is correct the page is redirected to the index page
But when I call this method in my TestCase class, I see that it clears session data and the user is no more logged in
Here is some parts of my code:
class TestEditProfile(TestCase):

    def test_change_password(self):
        response = self.client.get(reverse('account:profile'))
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, 'First name')
        data = self.get_user_data()
        response = self.client.post(reverse('account:profile'), data=data)
        self.assertRedirects(response, reverse('account:index'))

When I debug my program, I see that after calling self.assertRedirects the User session data will be cleared and the user is no more logged in so if I want to post some request to profile page it ignores it because the profile view is login_required
Is there a problem in my code or something else?
Thanks a lot
UPDATE: I took a deeper look in code using pydev debugger and realized that this method clears user session data:
if fetch_redirect_response:
    redirect_response = response.client.get(path, QueryDict(query),
                                                secure=(scheme == 'https'))

The source code is line 320 of file: testcase.py
before running this line self.client.session._session had size 3 and had keys:'_auth_user_backend' (4413833840), '_auth_user_hash' (4411636976) and '_auth_user_id' (4408855216) But after running this line self.client.session._session is completely cleared!


text:
Q: Allow Anonymous Access to Reports I am trying to Direct url access to reports with no auth.
After doing all kind of setting available online i am getting the

"java.lang.RuntimeException: java.lang.NullPointerException"

Please help me out,Any kind of help would be very appreciable.
I am working on the jasperserver 6.0.1 version.

A: I have implemented that by using the direct URL access for reports via Jasperserver.
You can implement that by using an Iframe.:-)


text:
Q: ReferenceError: Cannot access module before initialization I already created my model 'order'
I try to add new order into my mongodb, but keep showing this error,please help me! Thanks
I rely on the add_order.ejs to submit the form.
"ReferenceError: Cannot access 'order' before initialization"
I have the other two model 'recipe' and 'customer',but they worked! I don't understand why only
order has error?
order.js
const userSchema = new mongoose.Schema({
    order_id :{
        type: String,required : true
    },
    sum :{
        type:Number,
        required : true,
    },
    account :{
        type :String,
        required : true,
    }
});
module.exports = mongoose.model('order',userSchema);

routes.js
const express = require('express');
const mongoose = require('mongoose');
const router = express.Router();
const customer = require('../models/customer');
const recipe = require('../models/recipe');
const multer = require('multer');
const { GridFSBucketReadStream } = require('mongodb');
const fs = require('fs');
const order = require('../models/order');

//insert an order into database route
router.post('/add_order', upload, (req,res) => {
    const order = new order({
        order_id : req.body.order_id,
        sum : req.body.sum,
        account : req.body.account,
    });
    order.save((err) => {
        if(err){
            res.json({message : err.message, type :'danger'});
        }
        else{
            req.session.message={
                type:'success',
                message :'Customer added successfully!'
            };
            res.redirect("/");
        }
    })
})

add_order.ejs
      <form action="/add_order" method="POST" id="add-form" enctype="multipart/form-data">

          order_id *
          <input type="text" name="order_id" placeholder="Enter order_id" size="22" required />

          sum *
          <input type="number" name="sum" placeholder="Enter sum"  size="22" required>

          account *
          <input type="text" name="account" placeholder="Enter account" size="22" required />

          <input type="submit" name="submit" value="Add order" />
          <input type="reset" name="reset" value="Reset Form">
       </form>

A: You have a problem on this:
const order = require('../models/order');

//insert an order into database route
router.post('/add_order', upload, (req,res) => {
    const order = new order**({ // <- you trying to change an immutable class definition

Class variable and instance variable needs to have different names.
Recommend you to change your class name to Order (with capital O):
const Order = require('../models/order');
then call your instance like this:
const order = new Order({ ... });
See more


text:
Q: How can I remove a keychain that won't delete? I have a rogue keychain called Sophos.keychain. I uninstalled Sophos, but this pesky keychain won't go away. The reason I need it removed is Adobe's apps are trying to use it and it is causing errors.
When I log in as root, I see the keychain in the Keychain Access app, but I cannot delete it. There is a small icon on the keychain file icon that looks like a user icon (maybe).
When I am logged in as my normal admin account, I cannot see this Sophos keychain file.
As root, I have also tried deleting it via command line using security list-keychains and then security delete-keychain with the path to the Sophos.keychain file. Nothing seems work.
Sophos will not assist as I was using the free version. Googling how to remove it leads to dead ends. Apple has also been useless.
When I login as root, I get these errors:
Clicking on Reset to Defaults, and putting in the password doesn't seem to do anything.
I am on Big Sur 11.5.2
Any ideas how I can remove this keychain file?

A: This question seemed to contain the key to the answer:

To fix this you have to manually edit the file /Library/Preferences/com.apple.security-common.plist as root, and delete the corresponding hardcoded <dict>...Sophos...</dict> entry in there.
Great care must be taken because you can totally screw up  your system(-keychain) if you leave any errors inside this .plist file. The section that needs to be deleted looks as follows:
 ...
 <dict>
     <key>DbName</key>
     <string>/Library/Sophos Anti-Virus/Sophos.keychain</string>
     <key>GUID</key>
     <string>{some UUID string here}</string>
     <key>SubserviceType</key>
     <integer>6</integer>
 </dict>
 ...

However, there your setup, as indicate in the comments, was somewhat different, and required finding the right file.
The relevant file path was found to be /private/var/root/Library/Preferences/com.apple.security.plist

A: [I would just comment, but I don't have enough reputation points.]
You didn't say which version of macOS you're using, or if you actually got an error message when trying to delete the keychain from within the Keychain Access utility.  Years ago, I created a private keychain file to keep all my secure notes separate from my login.keychain (and a different password is required to open it).  That resulted in a file called <private keychain name>.keychain being created in the ~/Library/Keychains folder.  That file is still there to this day, and gets updated every time I modify the private keychain.  Nowadays, there is also a <private keychain name>.keychain-db file in the same directory.  Try to find your Sophos.keychain file(s) in a similar location on your system, and delete it/them using Finder or Terminal (perhaps make compressed copies in case you need to recover).  Please note, I have not tried this myself...  [On reading @juandesant's answer, I defer to his suggestion.]


text:
Q: Need to display a notification in my iOS application when there is new update (latest version) available in app store I need to display a notification in my iOS Application when there is a new update available in app store, when I click the notification I need to redirect user to the my app page in itunes.apple.com.

A: Take a look at Urban Airship. Its a 3rd party server that helps you send push notifications to the devices. The tutorial is available here

A: You can also use third party with servers integration like Xtify or the french solution Mainline