text:
Q: How I can work on sections of a json in python? Hi I'm working with a json and now it occurred to me divide it by parts, ie the personal structure should be a section, another section or part address table. someone comes up and I can iterate? I tried the following but not working.
with open("prueba.json") as json_file:
  document = json.load(json_file)
  for item in document:
    print item['structure']["name"]
    if item['structure']["name"] == personales
        for data_item in item['data']:
             attributesName.append(data_item['name'])
             attributesValue.append(data_item['value'])
        tableH = (attributesName,attributesValue)
        tableV=map(None,*tableH)
        doc.addTable(tableV,col_widths = [180,300],typeTable = PDF.HEADER,
        extra_style = [
            ('ALIGN',(0,0),(0,0),'LEFT'),
            ('GRID', (0,0), (-1,-1), 1, colors.gray),
        ])
        attributesName,attributesValue = [],[]

  for item in document:
    print item['structure']["name"]
    if item['structure']["name"] == personales
        for data_item in item['data']:
             attributesAddress.append(data_item['name'])
             attributesValueAddress.append(data_item['value'])
        tableH2 = (attributesName,attributesValue)
        tableV2=map(None,*tableH2)
        doc.addTable(tableV2,col_widths = [180,300],typeTable = PDF.HEADER,
        extra_style = [
            ('ALIGN',(0,0),(0,0),'LEFT'),

            ('GRID', (0,0), (-1,-1), 1, colors.gray),
        ])
        attributesAddress,attributesValueAddress = [],[]

but print all the values in all tables.
This is the json document
[
 {
    "files": 0,
    "data": [
        {"name": "RFC", "value": "XXXXXXX", "attId": 01},
        {"name": "NOMBRE", "value": "JOSE", "attId": 02},
        {"name": "APELLIDO PATERNO", "value": "MONTIEL", "attId": 03},
        {"name": "APELLIDO MATERNO", "value": "MENDOZA", "attId": 04},
        {"name": "FECHA NACIMIENTO", "value": "1989-02-04", "attId": 05}
    ],
    "dirId": 1,
    "docId": 4,
    "structure": {
        "name": "personales",
        "folioId": 22
    }
},
{
    "files": 0,
    "data": [
        {"name": "CALLE", "value": "AMOR", "attId": 06},
        {"name": "No. EXTERIOR", "value": "4", "attId": 07},
        {"name": "No. INTERIOR", "value": "2", "attId": 08},
        {"name": "C.P.", "value": "55060", "attId": 09},
        {"name": "ENTIDAD", "value": "ESTADO DE MEXICO", "attId": 10},
        {"name": "MUNICIPIO", "value": "ECATEPEC", "attId": 11},
        {"name": "COLONIA", "value": "INDUSTRIAL", "attId": 12}
        ],
    "dirId": 1,
    "docId": 4,
    "structure": {
        "name": "direccion",
        "folioId": 22
    }
 }
]

A:     TABLE_WIDTH = 540
    json_data = []
    attributesValue = []
    attributesName = []
    tableH = []
    tableV = []
    doc = SimpleDocTemplate(path, pagesize=letter)
    width, height = letter
    styleSheet = getSampleStyleSheet()
    doc = PDF()
    for item in documents:

        nameTemplate = item['structure']['name']
        nameTemplate = nameTemplate.upper()
        template=doc.Paragraph('''<para align=center fontName="Helvetica" fontsize=9>{0}</para>'''.format(nameTemplate));

        for data_item in item['data']:
            attributesName.append(data_item['name'])
            attributesValue.append(data_item['value'])
        tableH = (attributesName,attributesValue)
        tableV=map(None,*tableH)

        tableNameTemplate = [[template]]

        doc.addTable(tableNameTemplate,col_widths = [480],typeTable = PDF.HEADER,
            extra_style = [
                ('GRID', (0,0), (-1,-1), 0.5, colors.green),
                ('SPAN', (0,0), (-1,-1)),
                ('ALIGN', (0,0), (-1,-1),'CENTER'),
                ('VALIGN',(0,0),(-1,-1),'MIDDLE'),
                ('BACKGROUND', (0, 0), (-1,-1),colors.HexColor('#C59AF5'))
            ])
        doc.addTable(tableV,col_widths = [180,300],typeTable = PDF.HEADER,
            extra_style = [
                ('GRID', (0,0), (-1,-1), 0.5, colors.green),
                ('ALIGN',(0,0),(-1,-1),'LEFT')
            ])
        doc.addSpacer(20)

        attributesName,attributesValue = [],[]
doc.save(path)


text:
Q: Create a pdf file out of a html file I have a html script
script.html
How can I use wkhtmltopdf to create a pdf file out of it?
Should I generate a webpage out of the html file before using wkhtmltopdf ??

A: You should read documentation.
In Command Line Interface you should you the command :
wkhtmltopdf script.html my.pdf

Link to documentation

A: Should I generate a webpage out of the html file before using wkhtmltopdf ??

First you have to download web page in html format.For that you can use wget command.
For example
wget -p http://your/site/yourpage.html

Now  wkhtmltopdf syntax is
 wkhtmltopdf [html file] [pdf file]

Using above syntax you can convert above html file to pdf by
wkhtmltopdf yourpage.html yourpage.pdf

redpajama_set_name: RedPajamaStackExchange


text:
Q: Does it makes sense to partition on a foreign key? I have a MySQL table which looks a bit like this:
ID (BIGINT, PK), OtherID (INT, FK, indexed), NegativeTimestamp (BIGINT, indexed)

Selects should go very fast, updates almost never happens, inserts are not so frequent.
Queries will always query data within the same OtherID. The other filter will always be a range of NegativeTimestamp (which is a negative timestamp, so I can use ASC index while I always need the timestamps to be DESC), or the top (for example top 1000 rows with lowest timestamps). Recent data (lowest NegativeTimestamps) are requested most frequently, but there is no clear line which timestamps are more frequently requested than others.
I'm not sure if I should partition on OtherID (as queries will then never involve two partitions), or on Timestamp, or on none of them.
Any other optimizations are always welcome of course. If possible, also explain why so I can use this information in the future.
Extra info:
Table:
CREATE TABLE `myTable` (
  `ID` bigint(20) NOT NULL AUTO_INCREMENT,
  `MarketID` int(11) NOT NULL,
  `Close_Datetime` datetime NOT NULL,
  `Data` decimal(30,15) DEFAULT NULL,
  `Close_NegativeTimestamp` bigint(20) NOT NULL DEFAULT '0',
  PRIMARY KEY (`ID`),
  UNIQUE KEY `ID` (`ID`),
  KEY `IX_FK_MarketPriceCandle` (`MarketID`),
  KEY `OpenTimestamp` (`Open_Datetime`),
  KEY `CloseTimestamp` (`Close_Datetime`),
  KEY `CloseNegativeTimestamp` (`Close_NegativeTimestamp`),
  KEY `MarketIDIndex` (`MarketID`),
  KEY `CloseNegativeTimestampMarketID` (`MarketID`,`Close_NegativeTimestamp`),
  CONSTRAINT `FK_MarketMyTable` FOREIGN KEY (`MarketID`) REFERENCES `markets` (`ID`) ON DELETE NO ACTION ON UPDATE NO ACTION
) ENGINE=InnoDB AUTO_INCREMENT=110011638 DEFAULT CHARSET=utf8;

This table has currently more than 100 million rows and will continue to grow.
Most executed query:
SELECT * FROM myTable p
 WHERE p.MarketID = @marketID AND p.Close_NegativeTimestamp <= @start AND p.Close_NegativeTimestamp >= @end
 ORDER BY p.Close_NegativeTimestamp ASC;

A: FOREIGN KEYS are not supported in PARTITIONed tables.  (With luck this might change in 5.8.)
If you don't have over a million rows, don't bother to PARTITION.
If you are not depending on FOREIGN KEY CONSTRAINTS, don't use them.  INDEXes will suffice.
If you would like to discuss these further, please provide SHOW CREATE TABLE (even if not finalized) and the main SELECTs.
Based on what you said, I would guess that you need a compound index:
INDEX(OtherID, NegativeTimestamp)

Edit
I see a redundant index on MarketID.  Also UNIQUE(ID) is redundant since the PRIMARY KEY is a UNIQUE key.
If the two Close columns have the same information, but one is negated, then the negative on can probably be removed.  Then use DESC in the ORDER BY.
The use of @variables in the WHERE may be poorly optimized; let's see EXPLAIN SELECT ....
I would replace all of the indexes with just 2:
PRIMARY KEY (`MarketID`, Close_Datetime, ID),
INDEX(ID),  -- This is sufficient for AUTO_INCREMENT (except for protecting from deliberate dup)
-- nonexistent field?  KEY `OpenTimestamp` (`Open_Datetime`),
-- unneeded?   KEY `CloseTimestamp` (`Close_Datetime`),
-- unneeded?   KEY `CloseNegativeTimestamp` (`Close_NegativeTimestamp`),
-- covered     KEY `MarketIDIndex` (`MarketID`),
-- replaced    KEY (`MarketID`,`Close_NegativeTimestamp`),

Also, I would shrink most of the fields to save space and improve cacheability.  BIGINT is not really needed?  MEDIUMINT would suffice for MarketID?  decimal(30,15) takes 14 bytes, mostly zeros.  DOUBLE (8 bytes) might work?
(I am assuming this is Stock Market data?)
If you choose to get rid of the FK and go with PARTITION, then I would need to see the other important SELECTs.
But, for that matter, do you need ID?  Can't (MarketID, CloseDate) be the unique PRIMARY KEY?  Note: It would be a 3-byte DATE, not a 5 or 8-byte DATETIME.


text:
Q: How to set mm with multiple fields in Solr In the schema.xml, I have 3 fields - id, text and type. I set default operator to "AND"
My query is "q = (text:fire at Thai square) (type:fire)"
I tried to use edismax and set mm to 75% but It doesn't work with multiple fields.


text:
Q: why isnt my thread starting? I'm making a threaded app, and the main class is also the runnable class. for some reason, my thread WILL NOT START. any idea why? updateThread is the culprit...
here is the code:
package avtech.software.bitprice.display;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JTextField;

import avtech.software.bitprice.dialogs.*;
import avtech.software.bitprice.listeners.*;

@SuppressWarnings("serial")
public class Display extends JFrame implements Runnable {

    /**
     * variables
     */
    private static final int WIDTH = 200, HEIGHT = 200;
    private static double currentPrice = 0.0;
    private static double pauseLength;
    private static boolean running = false;
    private static String greaterLess = "";
    /**
     * objects
     */
    private static Display d;
    private static Thread updateThread;
    private static JLabel currentPriceLabel = new JLabel("Current Price: $" + currentPrice);
    private static JTextField pullDelayArea = new JTextField("Price Pull Delay In Minutes...");
    private static JTextField priceValueArea = new JTextField("Price You Are Waiting For...");
    private static JButton update = new JButton("UPDATE DATA");

    public Display() {
        running = true; // program is now running
        updateThread = new Thread(d); // create the local thread

        /**
         * create the frame
         */
        setLayout(null);
        setSize(WIDTH, HEIGHT);
        setResizable(false);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setTitle("BitPrice");

        /**
         * set bounds of the components
         */
        currentPriceLabel.setBounds(((WIDTH / 2) - (currentPriceLabel.toString().length() / 5)), 5, WIDTH, 50);
        pullDelayArea.setBounds(10, 40, WIDTH - 25, 25);
        priceValueArea.setBounds(10, 70, WIDTH - 25, 25);
        update.setBounds(10, 100, WIDTH - 25, 25);

        /**
         * set up the listeners to the components
         */
        pullDelayArea.addMouseListener(new PullDelayAreaListener(pullDelayArea));
        pullDelayArea.addActionListener(new PullDelayAreaListener(pullDelayArea));
        priceValueArea.addMouseListener(new PriceValueAreaListener(priceValueArea));
        priceValueArea.addActionListener(new PriceValueAreaListener(priceValueArea));
        update.addActionListener(new UpdateButtonListener());

        /**
         * add everything
         */
        add(currentPriceLabel);
        add(pullDelayArea);
        add(priceValueArea);
        add(update);

        setLocationRelativeTo(null);
        setVisible(true);
        requestFocus();

        /**
         * start the update process
         */
        System.out.println("hi");
        updateThread.start();
    }

    /**
     * everything that happens when the thread is updated, including updating
     * the price label, and all that good stuff :)
     */
    public static void update() {
        /**
         * make sure that there is data in the boxes taht is valid
         */
        if (pullDelayArea.getText().equals("Price Pull Delay In Minutes...") || pullDelayArea.getText().equals("")) {
            new MessageDialog(d, "Please enter a valid number into Price Pull Delay.");
        }
        if (priceValueArea.getText().equals("Price You Are Waiting For...") || priceValueArea.getText().equals("")) {
            new MessageDialog(d, "Please enter a valid number into Price Value.");
        }

        // set the new price double from the website

        // update the label
        currentPriceLabel.setText("Current Price: $" + currentPrice);
        currentPriceLabel.setBounds(((WIDTH / 2) - (currentPriceLabel.toString().length() / 5)), 5, WIDTH, 50);
        currentPriceLabel.repaint();

        /**
         * check to see if the current value is what the client is waiting for
         */
        String priceValueString = priceValueArea.getText();
        double priceValue = Double.parseDouble(priceValueString);

    }

    /**
     * this thread is checking the price of the Bitcoin, and will send out the
     * notification if it reaches a certain price
     */
    public void run() {
        System.out.println("started");
        /**
         * initial pause, letting the client get all set up
         */
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            new ErrorDialog(this, "Error delaying the pull request. Please restart client.");
        }
        System.out.println("started");
        while (running) {
            update();

            /**
             * add a pause to not just destroy internet speeds, pause settable
             * through the GUI
             */
            try {
                Thread.sleep((long) (pauseLength * 1000000)); // 1 million cause
                                                                // its in
                // milliseconds
            } catch (InterruptedException e) {
                new ErrorDialog(this, "Error delaying the pull request. Please restart client.");
            }
        }
    }

    public static void main(String[] args) {
        d = new Display();
    }
}

Any help would be greatly appreciated.
PS: my internet is about to turn off, so responses may be delayed until tomorrow.

A: The short version is that the reference to d is not set until the constructor exits, so in your Display, you're creating a new thread object and passing the static reference to d, which is still presently null at that point. I would remove the new Thread(d) line, and the .start() line from the constructor, and simply invoke d.start() from the main method.


text:
Q: "Unable to connect: Adaptive Server is unavailable or does not exist" in SQL Server Docker Image I am trying to connect to a Docker container running SQL Server using pymssql and I am getting the following error,
Can't connect to db: (20009, b'DB-Lib error message 20009, severity 9:
Unable to connect: Adaptive Server is unavailable or does not exist (localhost)
Net-Lib error during Connection refused (111)
DB-Lib error message 20009, severity 9:
Unable to connect: Adaptive Server is unavailable or does not exist (localhost)
Net-Lib error during Connection refused (111)\n')

Now, I know similar questions have been asked before, such as the one given below,

Database connection failed for local MSSQL server with pymssql
However, most of the solutions given revolve around opening up the Sql Server Configuration Manager and making changes through the UI or allowing network traffic to pass through. However, I am not entirely certain how to do this with a Docker container.
How can I resolve this? Is there a different SQL Server I should run? Or a different Python package I should use to establish the connection?
I have spin up my container based on the instructions given here,

https://learn.microsoft.com/en-us/sql/linux/quickstart-install-connect-docker?view=sql-server-ver16&pivots=cs1-bash
Given below are the parameters I am using to establish the connection,
{
    "host": "localhost",
    "port": "1433",
    "user": "SA",
    "password": "<my-password>",
    "database": "TestDB"
}

Update: I am actually trying to connect to the SQL Server Docker instance from within another container. It is the MindsDB container. This MindsDB container is, however, using pymysql to establish the connection.
Update: Given below are the two commands I am using to run my containers.

SQL Server:
sudo docker run -e "ACCEPT_EULA=Y" -e "MSSQL_SA_PASSWORD=<my-password>" \
   -p 1433:1433 --name sql1 --hostname sql1 \
   -d \
   mcr.microsoft.com/mssql/server:2022-latest

MindsDB:
docker run -p 47334:47334 -p 47335:47335 mindsdb/mindsdb


text:
Q: Check the Subject Field in Outlook I see this code all over the internet and everyone says how wonderful it works but it doesn't for me, I'm clueless, any ideas why?
I have Windows 7 and Outlook 2010.
Private Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean)
 Dim strSubject As String
  strSubject = Item.Subject
     If Len(Trim(strSubject)) = 0 Then
         Prompt$ = "Subject is Empty. Are you sure you want to send the Mail?"
       If MsgBox(Prompt$, vbYesNo + vbQuestion + vbMsgBoxSetForeground, "Check for Subject") = vbNo Then
        Cancel = True
      End If
    End If
End Sub

A: Please ensure you have set the correct references in your project for Outlook 2010 Library. Also ensure that Outlook 2010 should already be in running state. Thanks

A: you posted a link to a screen capture on May 20 at 16:04
go to that same place in the code and delete all the code in the sub, including sub and endsub (the code that you posted)
now click on "application" dropdown at top-left
you should see the following fill in
Private Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean)

End Sub

if something else pops up, then click on ItemSend in dropdown on top right
put in one command to get this very minimal sub (if it does not work, then nothing else will)
Private Sub Application_ItemSend(ByVal Item As Object, Cancel As Boolean)

    msgbox "this works"

End Sub

now send any email, if it works then you should see a dialog box pop up
note: i have found that "just pasting in code" does not always work and you have to click on the dropdown menus, after you paste in the code, to get the sub to be registered


text:
Q: Division result is 0 It might look stupid but as I divide 11950 by 47086514 the result is 0.
This is what I tried:
Dim total, share As Long
Dim split1 As Variant
split1 = Array(size1)

For i = 1 To size1 - 6
    split1 = Split(vetA(i), ":") 'vetA(1) = 11950 and total = 47086514
    share = CLng(split1(1)) / total
    ws.Cells(i + 4, 16).Value = share
Next i

A: Explanation about Scott Craner comment above:
Double (and Float) has a decimal point. Long doesn't. Long is simply a bigger Integer.
So if I take A/B and A = 1 and B = 2 and define both A, B as Long then the result would be 0.
If I define A, B as Decimal then the answer would be 0.5 (as you'd think).
This behaviour exists across programming languages which are typed, once you define a type (as you've done above) and it's by design. Some things (humans, cars) don't convey a real meaning beyond the decimal point (what does it mean to have 2.4 kids per family?).
When in doubt, always check the data types available in the programming language you're using. You'd be surprised where this discussion might take you.


text:
Q: Not sure how to echo out the Selected data from mysql $stmt = $mysqli->prepare("SELECT `nameData` FROM `accountsDone` WHERE `nameToSearch` = ?");
$stmt->bind_param("s", $query);
$stmt->execute();
$stmt->store_result();
if ($stmt->affected_rows > 0) {
    echo "Exists";
}

Instead of echoing out Exists, I want it to echo out nameData. How can I go about doing that?

A: First of all, if you want only one row then append LIMIT 1 to your SELECT query, like this:
$stmt = $mysqli->prepare("SELECT `nameData` FROM `accountsDone` WHERE `nameToSearch` = ? LIMIT 1");

So there are two approaches to display nameData:
Method(1):
First bind the variable $nameData to the prepared statement, and then fetch the result into this bound variable.
$stmt = $mysqli->prepare("SELECT `nameData` FROM `accountsDone` WHERE `nameToSearch` = ? LIMIT 1");
$stmt->bind_param("s", $query);
$stmt->execute();
$stmt->store_result();
if($stmt->num_rows){
    $stmt->bind_result($nameData);
    $stmt->fetch();
    echo $nameData;
}else{
    echo "No result found";
}

Method(2):
First use get_result() method to get the result set from the prepared statement, and then use fetch_array to fetch the result row from the result set.
$stmt = $mysqli->prepare("SELECT `nameData` FROM `accountsDone` WHERE `nameToSearch` = ? LIMIT 1");
$stmt->bind_param("s", $query);
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows){
    $row = $result->fetch_array()
    echo $row['nameData'];
}else{
    echo "No result found";
}

A: I think you can  below code i hope your query is working fine it returns result properly then you can use below code.
$stmt->bind_result($nameData);
    if ($stmt->fetch()) {
                printf ("%s\n", $nameData);
            }

A: Note that affected_rows won't do anything useful here.
However, nor you don't need num_rows as well (and therefore store_result too)
$stmt = $mysqli->prepare("SELECT `nameData` FROM `accountsDone` WHERE `nameToSearch` = ?");
$stmt->bind_param("s", $query);
$stmt->execute();
$stmt->bind_result($nameData);
$stmt->fetch();
echo $nameData;

Considering all that hassle, even without useless functions, you may find PDO a way better approach:
$stmt = $pdo->prepare("SELECT `nameData` FROM `accountsDone` WHERE `nameToSearch` = ?");
$stmt->execute($query);
echo->$stmt->fetchColumn();


text:
Q: 404.15 error when submitting a form with a long text field (approx 3000 chars) using Core 3.1 Razor When submitting a Core 3.1 form with a long text field I am getting:
HTTP Error 404.15 - Not Found
The request filtering module is configured to deny a request where the query string is too long.
Most likely causes:
Request filtering is configured on the Web server to deny the request because the query string is too long.
I've searched through older answer, but did not find anything specific to core 3+.

A: Make sure you HTML form has method="post" on it. In other words, you need to make the request (submit the form) via POST, not GET, so that the values go in the request body, not the query string (i.e. URI).

A: what is the type of action that you are submitting the form to - is it HttpGet or HttpPost? if its HttpGet, then querystring has certerain limitation varies from browser to browser. Please refer this link What is the maximum possible length of a query string? for detailed information on this.
With that being said, in general, if querystring exceeds the lenght that it can handle, HttpPost is used even which does not impose any such limitations.
If you post the code both view and controller action, then we can assist further.


text:
Q: Laravel fetch array of arrays with groupBy I have a Laravel table posts with multiple categories. How can I fetch all the posts grouped by categories? I was doing something like Post::where('userID', 1)->groupBy('categoryID'). But this only returned a flat array of named arrays like this:
[1 => ['title'=>'title 1'], 2 => ['title'=>'title3']]

How can I return an array of arrays like this:
[1 => [['title'=>'title 1'], ['title' => 'title 2], 2 => [['title'=>'title 3']]]

UPDATE:
I'm currently doing a join and then use Laravel's collection to sort it in php:
   Post::join('categories', ....).where('userID', 1)->get()->groupBy('categoryID');

I am able to get what I want, but wondering if there is a better way?

A: You may want this:
$catsWithPosts = Category::with(array('posts' => function($query){
    $query->select('title')->where('userID', 1);
}))->get();

Assumed that, you have declared proper relationship between Post and Category model.


text:
Q: List Mutation on Python I tried mutating a list by swapping a common element between the list and another reference list with the first element. The implementation is as shown below:
>>> L = [1,2,3,4,5,6,7,8,9]
>>> A = [3]
>>> L[0], L[L.index(A[0])] = L[L.index(A[0])], L[0] #want to swap 3 with 1
>>> L
[1,2,3,4,5,6,7,8,9,] #List L was not mutated

The list was not mutated as I anticipated. But when I modify the implementation as shown below, it worked:
>>> L = [1,2,3,4,5,6,7,8,9]
>>> A = [3]
>>> i = L.index(A[0])
>>> L[0], L[i] = L[i], L[0]
>>> L
[3,2,1,4,5,6,7,8,9,] #Now list mutated as desired even though L[i] and L[L.index(A[0])] evaluate to same value.

My question is, why couldn't the first assignment mutate the list? I thought of it but my brain coudnt explain it.

A: The problem is that the two are not equivalent. The first example is akin to doing:
>>> L = [1,2,3,4,5,6,7,8,9]
>>> A = [3]
>>> i = L.index(A[0])
>>> L[0] = L[i]
>>> i = L.index(A[0])
>>> L[i] = L[0]

This means that you end up swapping, then finding the element you just swapped and swapping back.
The reason you are confused is that you are thinking of the tuple assignment as Python doing both things at the same time - this isn't how the execution is performed, it is performed in an order, which changes the outcome.
It's worth noting that even if it did work, it would be a sub-optimal way of doing this. list.index() isn't a particularly fast operation, so doing it twice for no reason isn't a great idea.

A: Although in Python, the right-hand side is evaluated first when doing multiple assignments, the left-hand assigment targets, if they have expressions in them, are evaluated one by one when assigning.
If instead, they'd be evaluated as assignment targets first as you appear to expect, this would of course work.
This is documented in the assignment statements section:

An assignment statement evaluates the expression list (remember that this can be a single expression or a comma-separated list, the latter yielding a tuple) and assigns the single resulting object to each of the target lists, from left to right.

and

If the target list is a comma-separated list of targets: The object must be an iterable with the same number of items as there are targets in the target list, and the items are assigned, from left to right, to the corresponding targets.

Emphasis mine. The left-to-right is crucial here. L[0] is assigned to before the L[L.index(3)] is assigned to.
The documentation then describes in detail what happens to a subscription target such as L[0] and L[L.index(3)]:

If the target is a subscription: The primary expression in the reference is evaluated. It should yield either a mutable sequence object (such as a list) or a mapping object (such as a dictionary). Next, the subscript expression is evaluated.

Again, emphasis mine; the subscript expression is evaluated separately, and since the target list is evaluated from left-to-right, that evaluation takes place after the previous assignment to L[0].
You can see this by disassembling the python code:
>>> import dis
>>> def f(L):
...     L[0], L[2] = L[2], L[0]
...
>>> def g(L):
...     L[0], L[L.index(3)] = L[L.index(3)], L[0]
...
>>> dis.dis(f)
  2           0 LOAD_FAST                0 (L)   # L[2]
              3 LOAD_CONST               1 (2)
              6 BINARY_SUBSCR
              7 LOAD_FAST                0 (L)   # L[0]
             10 LOAD_CONST               2 (0)
             13 BINARY_SUBSCR
             14 ROT_TWO
             15 LOAD_FAST                0 (L)   # Store in L[0]
             18 LOAD_CONST               2 (0)
             21 STORE_SUBSCR
             22 LOAD_FAST                0 (L)   # Store in L[2]
             25 LOAD_CONST               1 (2)
             28 STORE_SUBSCR
             29 LOAD_CONST               0 (None)
             32 RETURN_VALUE
>>> dis.dis(g)
  2           0 LOAD_FAST                0 (L)   # L[L.index(3)]
              3 LOAD_FAST                0 (L)
              6 LOAD_ATTR                0 (index)
              9 LOAD_CONST               1 (3)
             12 CALL_FUNCTION            1
             15 BINARY_SUBSCR
             16 LOAD_FAST                0 (L)  #  L[0]
             19 LOAD_CONST               2 (0)
             22 BINARY_SUBSCR
             23 ROT_TWO
             24 LOAD_FAST                0 (L)  # Store in L[0]
             27 LOAD_CONST               2 (0)
             30 STORE_SUBSCR
             31 LOAD_FAST                0 (L)  # Store in L[L.index(3)]
             34 LOAD_FAST                0 (L)
             37 LOAD_ATTR                0 (index)
             40 LOAD_CONST               1 (3)
             43 CALL_FUNCTION            1
             46 STORE_SUBSCR
             47 LOAD_CONST               0 (None)
             50 RETURN_VALUE

The storing operation first stores L[0] = 3, so the next call to L.index(3) returns 0 and the 1 is thus stored right back in position 0!
The following does work:
L[L.index(3)], L[0] = L[0], L[L.index(3)]

because now the L.index(3) lookup is done first. However, it's best to store the result of an .index() call in a temporary variable as not calling .index() twice is going to be more efficient in any case.


text:
Q: Problemas con el comando ng para crear un proyecto El problemas es que recién instalo angular, no tuve problemas, la instalación fue correcta, pero cuando quiero hacer un nuevo proyecto con "ng new" no lo reconoce.

A: ¿si haces ng --version qué te aparece?, además, puedes intentar cerrando y abriendo la consola a ver si funciona.
En todo caso, puedes usar:
npx -p @angular/cli ng new aprendiendo-angular

Y de esa manera no tienes que instalar nada.


text:
Q: PHP - two multiple select dropdowns, passing user selections into a MySQL query EDIT:
The drop down menus have the following listed in them:
Typing Course
Daily Marketing Course
When using the code below to add selected text form the dropdown into the MySQL statement, only the first word appears ie. 'Typing' and 'Daily', the code looks like this:
SELECT * FROM `acme` WHERE `course` IN('Typing', 'Daily')AND `date` IN('2010-08-27', '2010-08-31')

it should be this:
SELECT * FROM `acme` WHERE `course` IN('Typing Course', 'Daily Marketing Course')AND `date` IN('2010-08-27', '2010-08-31')

Original question below:
Hi all,
Ok, I'll do my best to explain what I would like to do.
I have two dropdown menus set to multiple, the first is Course and the second is Date, here is the code that populates each dropdown:
Course
echo "<select name='course' value='' multiple='multiple'>";
            // printing the list box select command
            echo "<option value=''>All</option>";
            while($ntc=mysqli_fetch_array($queryc)){//Array or records stored in $nt
            echo "<option value=$ntc[course]>$ntc[course]</option>";
            /* Option values are added by looping through the array */
            }
            echo "</select>";// Closing of list box

Date
echo "<select name='date' value='' multiple='multiple'>";
        // printing the list box select command
        echo "<option value=''>All</option>";
        while($nt=mysqli_fetch_array($queryr)){//Array or records stored in $nt
        echo "<option value=$nt[dates]>$nt[dates]</option>";
        /* Option values are added by looping through the array */
        }
        echo "</select>";// Closing of list box

The main problem I have is passing the results of each dropdown to a MySQL query.  For example, if a user select from the Course dropdown 'Typing' AND 'Marketing' - I need the MySQL query to be:
SELECT * FROM acme WHERE course = 'Typing' OR course = 'Marketing'

In addition, I also need to add the second dropdown into the equation, so working on the assumption the user has selected 'Typing' AND 'Marketing', they then select 21-06-2010 from the Date dropdown, so the query then needs to be:
SELECT * FROM acme WHERE course = 'Typing' OR course = 'Marketing' AND date = '21-06-2010' OR date = '18-05-2010'

Clearly, I also need to build in if they select more than one date form the dropdown.
I hope I have explained clearly enough what I'm looking to achieve..any and all help gratefully received.  Really struggling to get my head around this one.
Thanks in advance,
Homer.

A: Use WHERE value IN ('a', 'b'):
SELECT * FROM acme WHERE course IN ('Typing','Marketing') AND date IN ('21-06-2010', '17-09-2010');

In HTML (or the PHP that outputs HTML), add [] to fieldnames:
<select name='course[]' value='' multiple='multiple'>

in PHP:
$courses=$_POST['course'];
$courses=array_map('mysql_real_escape_string', $courses);

$dates=$_POST['date'];
$dates=array_map('mysql_real_escape_string', $dates);

$query = 'SELECT * FROM `acme` WHERE ';
$query.='`course` IN(\''. join("', '", $courses). '\')';
$query.='AND `date` IN(\''. join("', '", $dates). '\')';

A: OK, first of all, your SQL is a bit off. Rather than WHERE course = 'Typing' OR 'Marketing', you want WHERE course = 'Typing' OR course = 'Marketing'. Alternatively, you could use WHERE course IN ('Typing', 'Marketing'). You can then create this using the array_map function to add the quotes and the join function to link them together:
<?php

...

function escape_and_add_quotes($string) {
    return '\'' . mysql_real_escape_string($string) . '\'';
}

...

$sql = 'SELECT * FROM acme WHERE course IN (' . join(',', array_map('escape_and_add_quotes', $courses)) . ')';

?>


text:
Q: Primefaces DataTable not rendering at all I have a <h:dataTable> that renders perfectly, but when I change it to p:dataTable it vanishes completely
Unfortunately I am not able to upload images yet, but other PrimeFaces components on the same page are rendering perfectly.
Here is the XHTML file:
<!DOCTYPE html>

    <h:head>
        <title>Admin</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    </h:head>

    <ui:composition template="template.xhtml">

        <ui:define name="content">

                    <h:form>
                        <h:link outcome="userHome">
                            <h:graphicImage value="resources/img/logo.png" alt="Monash South Africa - A campus of Monash Univeristy Australia"/>
                        </h:link>
                    </h:form>

                    <h:form>

Help

<h:link value="Logout" outcome="login"></h:link>

                    </h:form>

            <h:form id="adminHome">

<h:outputText value="List"/>

                            <h:column>
                                <f:facet name="header">
                                    <h:outputText value="Applicationid"/>
                                </f:facet>
                                <h:outputText value="#{item.applicationid}"/>
                            </h:column>
                            <h:column>
                                <f:facet name="header">
                                    <h:outputText value="Studentid"/>
                                </f:facet>
                                <h:outputText value="#{item.studentid}"/>
                            </h:column>
                            <h:column>
                                <f:facet name="header">
                                    <h:outputText value="Surname"/>
                                </f:facet>
                                <h:outputText value="#{item.surname}"/>
                            </h:column>
                            <h:column>
                                <f:facet name="header">
                                    <h:outputText value="Firstname"/>
                                </f:facet>
                                <h:outputText value="#{item.firstname}"/>
                            </h:column>
                            <h:column>
                                <f:facet name="header">
                                    <h:outputText value="Secondname"/>
                                </f:facet>
                                <h:outputText value="#{item.secondname}"/>
                            </h:column>
                            <h:column>
                                <f:facet name="header">
                                    <h:outputText value="Southafricanid"/>
                                </f:facet>
                                <h:outputText value="#{item.southafricanid}"/>
                            </h:column>
                            <h:column>
                                <f:facet name="header">
                                    <h:outputText value="Studyaddress"/>
                                </f:facet>
                                <h:outputText value="#{item.studyaddress}"/>
                            </h:column>
                            <h:column>
                                <f:facet name="header">
                                    <h:outputText value="Homeaddress"/>
                                </f:facet>
                                <h:outputText value="#{item.homeaddress}"/>
                            </h:column>
                            <h:column>
                                <f:facet name="header">
                                    <h:outputText value="Telnum"/>
                                </f:facet>
                                <h:outputText value="#{item.telnum}"/>
                            </h:column>
                            <h:column>
                                <f:facet name="header">
                                    <h:outputText value="Cellnum"/>
                                </f:facet>
                                <h:outputText value="#{item.cellnum}"/>
                            </h:column>
                            <h:column>
                                <f:facet name="header">
                                    <h:outputText value="Email"/>
                                </f:facet>
                                <h:outputText value="#{item.email}"/>
                            </h:column>
                            <h:column>
                                <f:facet name="header">
                                    <h:outputText value="Coursetitle"/>
                                </f:facet>
                                <h:outputText value="#{item.coursetitle}"/>
                            </h:column>
                            <h:column>
                                <f:facet name="header">
                                    <h:outputText value="Coursecode"/>
                                </f:facet>
                                <h:outputText value="#{item.coursecode}"/>
                            </h:column>
                            <h:column>
                                <f:facet name="header">
                                    <h:outputText value="Levelofstudy"/>
                                </f:facet>
                                <h:outputText value="#{item.levelofstudy}"/>
                            </h:column>
                            <h:column>
                                <f:facet name="header">
                                    <h:outputText value="Agree"/>
                                </f:facet>
                                <h:outputText value="#{item.agree}"/>
                            </h:column>
                            <h:column>
                                <f:facet name="header">
                                    <h:outputText value="Approvalcount"/>
                                </f:facet>
                                <h:outputText value="#{item.approvalcount}"/>
                            </h:column>
                            <h:column>
                                <f:facet name="header">
                                    <h:outputText value="Accountid"/>
                                </f:facet>
                                <h:outputText value="#{item.accountid}"/>
                            </h:column>

            </h:form>

        </ui:define>

    </ui:composition>

and here is the bean:
package DataAccess;

import Entities.Application;
import java.util.List;
import javax.ejb.Stateless;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;

@Stateless
@Named
public class ApplicationFacade extends AbstractFacade<Application> {
    @PersistenceContext(unitName = "com.mycompany_WSAMS_war_1.0-SNAPSHOTPU")
    private EntityManager em;

    @Override
    protected EntityManager getEntityManager() {
        return em;
    }

    public ApplicationFacade() {
        super(Application.class);
    }

    public List<Application> getApplications() {
        return em.createNamedQuery("Application.findAll").getResultList();
    }
}

I am using primefaces lib 4.0, does anyone know how to fix this issue, if it helps the primefaces selectOneMenu and radio buttons do not allow me to interact with them.

A: Change the h:column tags to p:column (Primefaces columns). After changing that, the datatable rendered for me.
You can even shorten the column definitions to:

   <h:outputText value="#{item.applicationid}"/>

A: You need to add the <h:panelGrid id="yourID"> around your dataTable.
When </h:panelGrid> is closed then you can place your

Because, prime rendered only when you call to render. Else the content would rendered when you reload the page.
Hope this is helpfull


text:
Q: Order in which program writes to a file using `>` in terminal? When I want to store the outputs of a program to a file, I typically use the following command
./program_to_run > output.txt

Today, I run a python script that calls C++ backend code, which calls an external C++ CUDA  library from NVIDIA. The external C++ CUDA has logging that is printed out, and the python script also prints out stuff. I noticed that the order in which the two were printed doesn't appear to align with their execution.
e.g., my python script looks something like
import some stuff
print("beginning")

# run some calls to C++ backend which then calls NVIDIA library

When I examined output.txt, I noticed something like this
# some logging information is printed here

beginning        # why is this printed after the logging information?

# some more logging information is printed here

The beginning wasn't printed at the beginning of output.txt, so I'm wondering what happened here? I don't think there is any multithreaded code, but there is parallel code in CUDA, but the python script starts out in serial, so shouldn't I see the string beginning at the beginning of output.txt?


text:
Q: iOS ternary conditional operator implementation is picky only on device? I'm using iOS SDK 4.2.
I think that the ternary conditional op is(?) implemented differently on the simulators (iPhone4.1, 4.2. iPad 3.2, 4.2) than on actual devices. Because:
iPad ? xibName = @"MyViewController-iPad" : @"MyViewController";

works perfect on those simulators but fails on my iPhone 4 (4.1)
while writing this way:
xibName = (iPad) ? @"MyViewController-iPad" : @"MyViewController";

allows it to work on both the simulators and device.
Anyone can tell why? Is it a bug? Is the "2nd version" better and i should always write that way?
it's strange how compiler accepts both and simulators work with both but the device only accepts one... maybe a bug for apple to check out?

A: These statements are not equivalent.
// iPad ? xibName = @"MyViewController-iPad" : @"MyViewController";
if ( iPad ) {
    xibName = @"MyViewController-iPad";
} else {
    @"MyViewController"; // Effectively a NOP
}

// xibName = (iPad) ? @"MyViewController-iPad" : @"MyViewController";
if ( iPad ) {
    xibName = @"MyViewController-iPad";
} else {
    xibName = @"MyViewController";
}

For !iPad ( like say, on an iPhone 4 ) with the first statement xibName would not get set at all, I am guessing you only ran an iPad simulator, not an iPhone.


text:
Q: .htaccess rewrites is ignored when folder exists? I have in my .htaccess
RewriteEngine On

RewriteRule ^([a-z0-9\-\_]+)$ ?page=$1 [L]

Which rewrites mysite.com/page to mysite.com/?page=page which works fine.
When I go to mysite.com/css is will ignore the rewrite and go to the css directory (which exists).  Is there anyway to have it ignore that the directory exists and continue on going to mysite.com/?page=css ?
Edit: I should add more specifically that when going to mysite.com/css is actually goes to mysite.com/css/?page=css

A: This is due to your rule running twice. Change your rule to this to prevent this behavior:
RewriteEngine On

RewriteCond %{ENV:REDIRECT_STATUS} ^$
RewriteRule ^([\w-]+)/?$ ?page=$1 [L,QSA]


text:
Q: Set variable JSTL within JavaScript
Possible Duplicate:
How to set the JSTL variable value in javascript?

I have certain codes as following:
    <c:set var="test" scope="page" value="0"/>
    <script type="text/javascript">
    var time;

    function Check(){
       if(time <= 0)
       {
           <c:set var="test" scope="page" value="1"/>
       }
      time-=1;
    }
    </script>

when I did
      <c:out value="${test}"/>

it seems that its value's always 1 and it happened before time=0 or less than 0. And also did something below:
      <c:if test="${test=='1'}">
        <sql:transaction dataSource="${dataBase}">
          <sql:update var="tDel">
               DELETE FROM tmp_time WHERE username='${username}'
          </sql:update>
        </sql:transaction>
     </c:if>

It always comes to DELETE at the first time and not wait till time=0 or less.
Can anyone help me out?


text:
Q: Is there a theory for "transactional" sequences of failing and no-fail actions? My question is about writing transaction-like functions that execute sequences of actions, some of which may fail. It is related to the general C++ principle "destructors can't throw," no-fail property, and maybe also with multi-phase transactions or exception safety. However, I'm thinking about it in language-neutral terms. My concern is with correctly designing error handling in C++ functions that must be reliable. I would like to know what the concepts below are called so that I can learn more about them.
I'm sorry that I can't ask the question more directly. Since I don't know this area I have provided an example to explain my question. The question is at the end. Here goes:
Consider a sequence of steps or actions executed sequentially, where actions belong to one of two classes: those that always succeed, and those that may fail. In the examples below:

*

*S stands for an action that always succeeds (called "no-fail" in some settings).

*F stands for an action that may fail (for example, it might fail to allocate memory or do I/O that could fail).
Consider a sequences of actions (executed sequentially from left to right):
S->S->S->S

Since each action in the sequence above succeeds, the whole sequence succeeds.
On the other hand, the following sequence may fail because the last action may fail:
S->S->S->F

So, claim: a sequence has the no-fail (S) property if and only if all of its actions are no-fail.
Now, I'm interested in action sequences that form "atomic transactions", with "failure atomicity," i.e. where either the whole sequence completes successfully, or there is no effect. I.e. if some action fails, the earlier ones must be rolled back. This requires that any successfully executed actions prior to a failing action must always be able to be rolled back. Consider the sequence:
S->S->S->F
S<-S<-S

In the example above, the first row is the forward path of the transaction, and the second row are inverse actions (executed from right to left) that can be used to roll back if the final top row actions fails.
It seems to me that for a transaction to support failure atomicity, the following invariant must hold:
Claim: To support failure atomicity (either successful completion, or complete roll-back on failure) all actions preceding the latest failable (F) action on the forward path (marked * in the example below) must have no-fail (S) inverses. The following is an example of a sequence that supports failure atomicity:
         *
S->F->F->F
S<-S<-S

Further, if we want the transaction to be able to attempt cancellation mid-way through, but still guarantee either full completion or full rollback then we need the following property:
Claim: To support failure atomicity and cancellation mid-way through execution, in the face of errors in the inverse (cancellation) path, all actions following the earliest failable (F) inverse on the reverse path (marked *) must be no-fail (S).
F->F->F->S->S
S<-S<-F<-F
      *

I believe that these two conditions guarantee that an abortable/cancelable transaction will never get "stuck".
My questions are:
What is the study and theory of these properties called? are my claims correct? and what else is there to know?
UPDATE 1: Updated terminology: what I previously called "robustness" is called atomicity in the database literature.
UPDATE 2: Added explicit reference to failure atomicity, which seems to be a thing.


text:
Q: Prevent the PyCharm-Debugger from automatically exiting the script after it has been run Is it possible to stop the PyCharm-Debugger automatically after it has executed the last line of code?
Given the following code
# Start of module
x = 0
for i in range(3):
    x += 1
# End of module

I would like to check that x is indeed 3 after running the script, by asking for the value of x in the debugger console.
Of course this would be possible by adding a new line with arbitrary content to the code to set another breakpoint beneath the loop, but that's kind of annoying.


text:
Q: Issue with the search term in the stackexchange.com moderator page search In the stackexchange.com - moderators page, there is a strange issue with the search text.
When I try with "ask" in the search box, it is displaying the matched entries such as Ask Different, Ask Patents, Ask Ubuntu and a partial match with a user.
But when I try with "stack", I'm expecting Stack Overflow and other Stack Overflow international sites. It is not displaying the expected result, again I'm adding space and o along with "stack", like "stack o", now it is displaying the expected result.
GIF for the same:

I didn't see any error in console and network tab. What is the cause for the issue?

A: This isn't a bug, it's status-bydesign. The code to search looks for any of the following:

*

*Site name

*URL or Host Address

*Moderator Name

Since stack is a part of all of the URLs for most of the sites on the network it is filtering as expected.


text:
Q: Why is Hibernate Cascadetype defaults to empty array This is a newbie question. Apologize if it is too naive
Why is CascadeType default value empty and not SAVE. If I create an object Publisher and then add an object Book to it why wouldn't I persist it to DB. I am just trying to understand the reasoning behin the default value not set as SAVE.
Thanks for helping me on this.


text:
Q: Record not created as debug log reports In my sandbox I am debugging a Web-to-Lead issue that has to do with the custom Lead trigger code. I have a trigger handler that get's called after lead insert. The handler does a few things like creating a new Account and Case record. When I run my lead test class all the tests pass and the records are created as expected. However when I do a test web-to-lead post, no errors are reported in the browser or in the debug log, but the records are not created. Some excerpts from the debug log that indicate that the records were created are:
08:14:52.189 (189585256)|METHOD_ENTRY|[36]|01p18000000DBJy|LeadTriggerHandler.postProcessInsert(Lead)
08:14:52.189 (189684839)|SYSTEM_METHOD_ENTRY|[41]|String.valueOf(Object)
08:14:52.189 (189735694)|SYSTEM_METHOD_EXIT|[41]|String.valueOf(Object)
08:14:52.189 (189773735)|SYSTEM_METHOD_ENTRY|[41]|System.debug(ANY)
08:14:52.189 (189787753)|USER_DEBUG|[41]|DEBUG|##*** New lead: 00Q18000001RfrzEAC
08:14:52.189 (189797840)|SYSTEM_METHOD_EXIT|[41]|System.debug(ANY)
08:14:52.189 (189924877)|SYSTEM_METHOD_ENTRY|[46]|System.debug(ANY)
08:14:52.189 (189952704)|USER_DEBUG|[46]|DEBUG|##*** lead status is open and Email is: jj@example.com

The problem goes away if I uninstall the Salesforce for Social Media app. I can only assume there is some conflict between the managed app and my own custom lead trigger code, but how can I debug the conflict if the debug log report is not reliable?


text:
Q: math/algorithm Fit image to screen retain aspect ratio I need help with math / algorithm  to take an image of known size and fit to one of two screen dimensions:
720 x 480 or 1280 x 1024.
The image dimensions are coming from an XML file, however those dimensions are the web dimensions, I also get a selection of images from the XML that may be of higher and lower resolution than the web dimensions.
What I want is to use the aspect ration of the web dimensions to display the higher resolution image, if available, on an HD (1280x720) screen, or, if the user is on an SD screen (720x480) display the image on that screen.
Other things that would be useful for this, but lower priority, would be, if I know the resolution of the image is smaller in both dimensions than an SD screen (in this case, all I know is the web dimension, and the horizontal dimension of the image file), to display it as actual size on that screen.

A: Aspect ratio correction with letterboxing or fit-to-screen
I wrote up a method recently to handle this exact problem in iOS. I'm using the Eigen matrix library to do scaling, but the the principle (scaling factor) is the same without matrices.
Eigen::Matrix4x4f aspectRatioCorrection(bool fillScreen, const Eigen::Vector2f &screenSize, const Eigen::Vector2f &imageSize)
{
    Eigen::Matrix4x4f scalingMatrix(Eigen::Matrix4x4f::Identity());

    float screenWidth = screenSize.x();
    float screenHeight = screenSize.y();
    float screenAspectRatio = screenWidth / screenHeight;
    float imageWidth = imageSize.x();
    float imageHeight = imageSize.y();
    float imageAspectRatio = imageWidth / imageHeight;

    float scalingFactor;
    if (fillScreen) {
        if (screenAspectRatio > imageAspectRatio) {
            scalingFactor = screenWidth / imageWidth;
        } else {
            scalingFactor = screenHeight / imageHeight;
        }
    } else {
        if (screenAspectRatio > imageAspectRatio) {
            scalingFactor =  screenHeight / imageHeight;
        } else {
            scalingFactor = screenWidth / imageWidth;
        }
    }

    scalingMatrix(0, 0) = scalingFactor;
    scalingMatrix(1, 1) = scalingFactor;

    return scalingMatrix;
}

A: I understand the accepted answer and it works, but I've always found the following method to be simpler and succinct for "best fit":
// prep
let maxWidth = 190,
    maxHeight = 150;
let imgWidth = img.width,
    imgHeight = img.height;

// calc
let widthRatio = maxWidth / imgWidth,
    heightRatio = maxHeight / imgHeight;
let bestRatio = Math.min(widthRatio, heightRatio);

// output
let newWidth = imgWidth * bestRatio,
    newHeight = imgHeight * bestRatio;

... which of course can be distilled down to:
const maxWidth = 190, maxHeight = 150;
const bestRatio = Math.min(maxWidth / img.width, maxHeight / img.height);
img.width *= bestRatio;
img.height *= bestRatio;

A: Generic as can be:
Image data: (wi, hi) and define ri = wi / hi
Screen resolution: (ws, hs) and define rs = ws / hs
Scaled image dimensions:
rs > ri ? (wi * hs/hi, hs) : (ws, hi * ws/wi)

So for example:
         20
|------------------|
    10
|---------|

--------------------     ---   ---
|         |        |      | 7   |
|         |        |      |     | 10
|----------        |     ---    |
|                  |            |
--------------------           ---

ws = 20
hs = 10
wi = 10
hi = 7

20/10 > 10/7 ==> (wi * hs/hi, hs) = (10 * 10/7, 10) = (100/7, 10) ~ (14.3, 10)

Which as you can see clearly scales to the screen size, because the height is that of the screen but clearly keeps aspect ratio since 14.3/10 ~ 10/7
UPDATE
Center the image as follows:
call (wnew, hnew) the new dimensions.
top = (hs - hnew)/2
left = (ws - wnew)/2

A: Here it is in straightforward C.
You want to scale both coordinates by the returned scale factor.

/* For a rectangle inside a screen, get the scale factor that permits the rectangle
   to be scaled without stretching or squashing. */
float
aspect_correct_scale_for_rect(const float screen[2], const float rect[2])
{
    float screenAspect = screen[0] / screen[1];
    float rectAspect = rect[0] / rect[1];

    float scaleFactor;
    if (screenAspect > rectAspect)
        scaleFactor = screen[1] / rect[1];
    else
        scaleFactor = screen[0] / rect[0];

    return scaleFactor;
}


text:
Q: How to Add Row in datagrid wpf   Private Property DataTable As DataTable
    Public Property DataView As DataView
Public Sub New()
    InitializeComponent()
    DataTable = New DataTable()
    DataTable.Columns.Add("Test")
    DataView = DataTable.DefaultView
    DataContext = Me
    Dim dr As DataRow = DataTable.NewRow()
    dr("Test") = "Wert1"
    DataTable.Rows.Add(dr)
End Sub
   <DataGrid ItemsSource="{Binding Path=DataView}"/>

Above this code working properly. But when I am substitute into my code dr is showing error message
enter image description here
below is my code
Private Property DataTable As DataTable
Public Property DataView As New DataView
Private Sub Button_Click(sender As Object, e As RoutedEventArgs)
    InitializeComponent()
    Dim startDate As Date = CType(dtpStartDate.SelectedDate, DateTime)
    Dim endDate As Date = CType(dtpEndDate.SelectedDate, DateTime)
    While startDate <= endDate
        Dim NewColumn As New DataGridTextColumn()
        NewColumn.Header = startDate.ToShortDateString()
        dgTemplate.Columns.Add(NewColumn)
        startDate = startDate.AddDays(1)
        DataView = DataTable.DefaultView
        DataContext = Me
        Dim dr As DataRow = DataTable.NewRow()
        dr(NewColumn) = "Wert1"
        DataTable.Rows.Add(dr)
    End While
End Sub

can anyone suggest to fix this...

A: Datarow constructor cant take column object as an argument.
Use column.header property to specify column.
Private Property DataTable As DataTable
Public Property DataView As New DataView
Private Sub Button_Click(sender As Object, e As RoutedEventArgs)
    InitializeComponent()
    Dim startDate As Date = CType(dtpStartDate.SelectedDate, DateTime)
    Dim endDate As Date = CType(dtpEndDate.SelectedDate, DateTime)
    While startDate <= endDate
        Dim NewColumn As New DataGridTextColumn()
        NewColumn.Header = startDate.ToShortDateString()
        dgTemplate.Columns.Add(NewColumn)
        startDate = startDate.AddDays(1)
        DataView = DataTable.DefaultView
        DataContext = Me
        Dim dr As DataRow = DataTable.NewRow()
        dr(NewColumn.Header) = "Wert1" '<----------------------------
        DataTable.Rows.Add(dr)
    End While
End Sub

Info
https://learn.microsoft.com/en-us/dotnet/api/system.data.datarow.-ctor?view=net-6.0


text:
Q: Assessing Xml node values with xmlnamespace I am trying to access "shl:Value" node using c# but getting null or run time error. I like avoid using big loops.
Code:
XmlDocument objXmlDoc1 = new XmlDocument();
objXmlDoc1.Load("C:\\inetpub\\Jobtrain\\test.xml");

XmlReader reader = XmlReader.Create(new StringReader(objXmlDoc1.InnerXml));
XElement root = XElement.Load("C:\\inetpub\\Jobtrain\\test.xml");
XmlNameTable nameTable = reader.NameTable;
XmlNamespaceManager namespaceManager = new XmlNamespaceManager(nameTable);
namespaceManager.AddNamespace("shl", "http://www.shl.com");

sScore_Raw = root.XPathSelectElement(".//shl:Scales/shl:Scale[@Tag='SHL_VAT_GENERAL_ABILITY_SCREEN_SCORE']/shl:Values/shl:Value[@Tag='RAW SCORE']", namespaceManager).Value;

Error On following lines
sJTCandidateID = root.XPathSelectElement(".//ClientOrderId/IdValue[@name='ThirdPartyCandidateId']", namespaceManager).Value;
sTestStatus = root.XPathSelectElement(".//AssessmentStatus/Status", namespaceManager).Value;

XML:
<AssessmentResult xmlns:shl="http://www.shl.com" xmlns="http://ns.hr-xml.org/2004-08-02" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://ns.hr-xml.org/2004-08-02  AssessmentResult.xsd http://www.shl.com AssessmentResultUserArea.xsd">
<ClientOrderId>
<IdValue name="ThirdPartyCandidateId">XX-00076-000-00007</IdValue>
</ClientOrderId>
<AssessmentStatus><Status>Completed</Status><Details>Successful</Details><StatusDate>2014-04-17</StatusDate></AssessmentStatus>
<UserArea>
<shl:CandidateResult>
<shl:Report />
<shl:Score IsRescored="0">
<shl:Scales>
<shl:Scale Tag="SHL_VAT_GENERAL_ABILITY_SCREEN_SCORE" IsGeneric="1">
    <shl:Name Default="General Ability Screen Score"><shl:Translation ID="en-gb">General Ability Screen Score</shl:Translation></shl:Name>
    <shl:Values>
        <shl:Value Tag="RAW SCORE">0</shl:Value><shl:Value Tag="OTHER">0</shl:Value>
    </shl:Values>
</shl:Scale>
</shl:Scales>
</shl:Score>
<shl:StatusCode>0</shl:StatusCode>
</shl:CandidateResult>
</UserArea></AssessmentResult>

A: You can simplify your code a little bit. This code works
XDocument xDoc = XDocument.Load(filename);
XmlNamespaceManager namespaceManager = new XmlNamespaceManager(xDoc.CreateNavigator().NameTable);
namespaceManager.AddNamespace("shl", "http://www.shl.com");

var child1 = xDoc.XPathSelectElement("//shl:Scale[@Tag='SHL_VAT_GENERAL_ABILITY_SCREEN_SCORE']/shl:Values/shl:Value", namespaceManager);

A: If your only requirement is to get at the shl:Value element, then that's really easy with LINQ to XML - I wouldn't personally use XPath to do it:
XNamespace shl = "http://www.shl.com";
XDocument doc = XDocument.Load(...);
XElement element = doc.Descendants(shl + "Scale")
                      .Where(x => (string) x.Attribute("Tag") == "...")
                      .Descendants(shl + "Value")
                      .Single();

And for the Status and ClientOrderId parts:
// Default namespace in the document
XNamespace ns = "http://ns.hr-xml.org/2004-08-02";
XDocument doc = XDocument.Load(...);
XElement orderId = doc.Descendants(ns + "ClientOrderId")
                      .Single(x => (string) x.Attribute("name") == "ThirdPartyCandidateId");
XElement status = doc.Descendants(ns + "AssessmentStatus")
                     .Elements(ns + "Status")
                     .Single();


text:
Q: Geo Locate component in Leaflet React v3 - unwanted duplication on each refresh I'm currently using Leaflet in React (v3) where you need to add components in order to render them on the map. This is the unwanted result output I am getting (green circles are duplicates and don't work on click either):
Map Render Image
This keeps duplicating on each map interaction. I am not sure how to fix it and presume it is the library that is the issue as no other components replicate this behavior. If it can't be fixed, an alternative is welcome - as long it is compatible with leaflet-react v3.
In short: - prevent duplicates on each map render. Geo locate user with permision in browser (on the first load, and then if the user pans away manually, to relocate/flyto with a button click)
import { useMap } from "react-leaflet";
import Locate from "leaflet.locatecontrol";
import "leaflet.locatecontrol/dist/L.Control.Locate.min.css";
import * as L from "leaflet";

const UserLocate = () => {
  const map = useMap();

  var lc = L.control
    .locate({
      position: "topright",
      strings: {
        title: "Show me where I am, yo!",
      },
    })
    .addTo(map);
  return null;
};

export default UserLocate;

/====================================================/
import EsriLeafletGeoSearch from "react-esri-leaflet/plugins/EsriLeafletGeoSearch";
import {
  MapContainer,
  Marker,
  TileLayer,
  Popup,
  ZoomControl,
  LayersControl,
  useMapEvents,
  useMapEvent,
  useMap,
} from "react-leaflet";

    import { Container, Button, Form, Row, Nav } from "react-bootstrap";
    import "leaflet/dist/leaflet.css";
    import "esri-leaflet-geocoder/dist/esri-leaflet-geocoder.css";
    import L from "leaflet";
    import { BiMapPin } from "react-icons/bi";
    import UserLocate from "./ProfilePage/UserLocate";

function GeneralMap() {
  const defaultZoom = 14;
        <MapContainer
          center={[48.856614, 2.3522219]}
          zoom={defaultZoom}
          style={{ height: 400, width: "100%" }}
        >
          <LayersControl>
            <BaseLayer checked name="Standard">
              <TileLayer
                attribution='"© Jawg - © OpenStreetMap contributors"'
                url="https://{s}.tile.jawg.io/jawg-streets/{z}/{x}/{y}{r}.png?access-token="
              />
            </BaseLayer>
            <BaseLayer name="Black and White">
              <TileLayer
                attribution='"© Jawg - © OpenStreetMap contributors"'
                url="https://{s}.tile.jawg.io/jawg-light/{z}/{x}/{y}{r}.png?access-token="
              />
            </BaseLayer>
          </LayersControl>
             <EsriLeafletGeoSearch
            position="topleft"
            useMapBounds={false}
            eventHandlers={{
              requeststart: () => console.log("Started request..."),
              requestend: () => console.log("Ended request..."),
              results: (r) => console.log(r),
            }}
          />
          <UserLocate />
        </MapContainer>

  );
}

export default GeneralMap;

A: If you need to run code once, put it in useEffect like that:

useEffect(() => {
  //Code to run once
}, []);


text:
Q: did Microsoft App Center support Baidu Push? did Microsoft App Center support Baidu Push?
When I login to App Center, I only found that FCM and APNS supported.
if not at the moment, will it be in the roadmap?
thanks.

A: No, it does not. Don't forget too that product support is provided directly from within App Center. Just click the blue chat button in the lower-right corner of any page and you're connected to the product's dedicated support team.
You can read more about this at https://intercom.help/appcenter/getting-started/getting-help-with-app-center.


text:
Q: Selenium webdriver 3.0 + java Wait until string entered I'm trying to test my Hotmail account using selenium Webdriver 3.0. I set my account to ask for two way authentication, which means Indeed to enter the last 4 digits of my mobile number and then send a message to me. Then I have to enter that code in order to open my email Account.
It worked good with me when I used implicit, waited for 60 seconds until i receive the code then enter it manually and so the test continues to my email page >> all works fine.
BUT my question is, is there any way to make the test wait until I enter the code rather than waiting for 60s?!
Is that acceptable to enter some things manually while using Selenium webdriver?

A:
is that acceptable to enter some things manually while using selenium webdriver?

Yes, because this thing is made for stopping robot activity just like Captcha code entering the process. So, in this scenario, this is acceptable to enter text manually after reading the text from mail while using selenium.
You can do one thing more if you want to do it automatically, you should implement mail API to read the last mail from your provided account in the background and fetch necessary text from the last mail using some programming stuff and enter it into textbox using selenium.

is there any way to make the test wait until I enter the code rather than waiting for 60s?

Yes, to achieve this you need to create your own custom ExpectedConditions with WebDriverWait which will wait until located text box has value greater or equal 4 character or other suitable condition which you want as below :-
//Initialize WebDriverWait first which will wait maximum 60 seconds
WebDriverWait wait = new WebDriverWait(driver, 60);

//Create suitable locator to locate textbox element eg. with xpath locator
By byObject = By.xpath("enter here textbox xpath");

//This condition will wait until text box has value greater or equal 4 character
wait.until(new ExpectedCondition<Boolean>() {
                public Boolean apply(WebDriver d) {
                    return (d.findElement(byObject).getAttribute ("value").length() >= 4)
                }
            });


text:
Q: PayTM checksum giving exception error in Android Activity but working fine in the main method I am trying to integrate Paytm with my android application.
When i generate paytm checksum through my activity, i am getting the below exception.
I/System.out: MerchantActivity.java checkSumGenerationOnload-method Starts
I/System.out: ChecksumGeneration.java getCheckSum-method Starts
I/System.out: -----------------------------
    40c19e8b2516d6e057c8027826724fac33d3bf60ac8d697569d422571ae46321fro3
    -----------------------------
W/System.err: java.security.NoSuchProviderException: No such provider: SunJCE
W/System.err:     at javax.crypto.Cipher.getInstance(Cipher.java:466)
        at com.paytm.pg.crypto.AesEncryption.encrypt(AesEncryption.java:34)
        at com.paytm.pg.merchant.CheckSumServiceHelper.genrateCheckSum(CheckSumServiceHelper.java:53)
        at com.example.merchantapp.ChecksumGeneration.getCheckSum(ChecksumGeneration.java:40)
W/System.err:     at com.example.merchantapp.MerchantActivity.checkSumGenerationOnload(MerchantActivity.java:41)

But the same method is giving proper result when i run it in main method.
Log trace:
getCheckSumChecksumGeneration.java getCheckSum-method Starts
checkSum: 3kLAvt33DJwodOF/vAPOqrW4LDN3bPbyEBXX10sjgFdjdp6CIS36H4kFj8lwUBnDHEzpo7J0CZlcmi3RCWZQAzN82zi/pPv7vH86iFf3MKU=
ChecksumGeneration.java getCheckSum-method Ends

Code snippet:
Activity Class - Having Problem
public class ChecksumGeneration {

    //Below parameters provided by Paytm

    private static String MID = "MyLife19xxxxxxx";
    private static String MercahntKey = "WtxzWMOnZIj0ddU_";
    private static String INDUSTRY_TYPE_ID = "Retail";
    private static String CHANNLE_ID = "WAP";
    private static String WEBSITE = "APPSTAGING";
    private static String CALLBACK_URL =  "https://securegw-stage.paytm.in/theia/paytmCallback?ORDER_ID=ORDER45676";

    public static void main(String s[]){
        System.out.print("getCheckSum");
        getCheckSum();
    }

    public static String getCheckSum(){

        String checkSum = null;

        TreeMap<String,String> paramMap = new TreeMap<String,String>();
        paramMap.put("MID" , MID);
        paramMap.put("ORDER_ID" , "ORDER45676");
        paramMap.put("CUST_ID" , "CUST02513");
        paramMap.put("INDUSTRY_TYPE_ID" , INDUSTRY_TYPE_ID);
        paramMap.put("CHANNEL_ID" , CHANNLE_ID);
        paramMap.put("TXN_AMOUNT" , "1.00");
        paramMap.put("WEBSITE" , WEBSITE);
        paramMap.put("EMAIL" , "thiruppathi.me@gmail.com");
        paramMap.put("MOBILE_NO" , "99425xxxxx");
        paramMap.put("CALLBACK_URL" , CALLBACK_URL);

        try{
        System.out.println("ChecksumGeneration.java getCheckSum-method Starts");
        checkSum =  CheckSumServiceHelper.getCheckSumServiceHelper().genrateCheckSum(MercahntKey, paramMap);
        System.out.println("checkSum: "+ checkSum);

        paramMap.put("CHECKSUMHASH" , checkSum);

        System.out.println("ChecksumGeneration.java getCheckSum-method Ends");

        }catch(Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        return checkSum;
    }
}


text:
Q: Tumblr like button not working for my tumblr blog Tumblr like button is not working for my Tumblr blog, the button's color change after clicking but after refreshing the page no updates happen
URL: http://cs.jumzler.com/
HTML code: `
{block:Posts}

{/block:Posts}

CSS:

JS:

What am I missing?


text:
Q: Unity admob - Resolving Android Dependencies error Сломал всю голову. Импортирую ADMOB, потом пытаюсь установить библиотеки через - Resolving  Android Dependencie
И возникает ошибка:
C:\Users\Aleksandr\Desktop\Unity games\BubblesBumbes\Temp\PlayServicesResolverGradle\gradlew.bat --no-daemon -b "C:\Users\Aleksandr\Desktop\Unity games\BubblesBumbes\Temp\PlayServicesResolverGradle\PlayServicesResolver.scripts.download_artifacts.gradle" "-PANDROID_HOME=E:/Unity/Unity_app/2020.3.5f1/Editor/Data/PlaybackEngines/AndroidPlayer\SDK" "-PTARGET_DIR=C:\Users\Aleksandr\Desktop\Unity games\BubblesBumbes\Assets\Plugins\Android" "-PMAVEN_REPOS=https://maven.google.com/" "-PPACKAGES_TO_COPY=com.google.android.gms:play-services-ads:20.2.0" "-PUSE_JETIFIER=0" "-PDATA_BINDING_VERSION=3.6.0"
Executing command: C:\Users\Aleksandr\Desktop\Unity games\BubblesBumbes\Temp\PlayServicesResolverGradle\gradlew.bat --no-daemon -b "C:\Users\Aleksandr\Desktop\Unity games\BubblesBumbes\Temp\PlayServicesResolverGradle\PlayServicesResolver.scripts.download_artifacts.gradle" "-PANDROID_HOME=E:/Unity/Unity_app/2020.3.5f1/Editor/Data/PlaybackEngines/AndroidPlayer\SDK" "-PTARGET_DIR=C:\Users\Aleksandr\Desktop\Unity games\BubblesBumbes\Assets\Plugins\Android" "-PMAVEN_REPOS=https://maven.google.com/" "-PPACKAGES_TO_COPY=com.google.android.gms:play-services-ads:20.2.0" "-PUSE_JETIFIER=0" "-PDATA_BINDING_VERSION=3.6.0"
Reporting analytics data: /androidresolver/resolve/gradle/failed/fetch?unityVersion=2020.3.5f1&unityPlatform=WindowsEditor&installSource=unitypackage&version=1.2.167&scope= 'Android Resolver: Gradle Resolve: Tool Extraction Failed'
ERROR: Gradle failed to fetch dependencies.
Failed to run 'C:\Users\Aleksandr\Desktop\Unity games\BubblesBumbes\Temp\PlayServicesResolverGradle\gradlew.bat --no-daemon -b "C:\Users\Aleksandr\Desktop\Unity games\BubblesBumbes\Temp\PlayServicesResolverGradle\PlayServicesResolver.scripts.download_artifacts.gradle" "-PANDROID_HOME=E:/Unity/Unity_app/2020.3.5f1/Editor/Data/PlaybackEngines/AndroidPlayer\SDK" "-PTARGET_DIR=C:\Users\Aleksandr\Desktop\Unity games\BubblesBumbes\Assets\Plugins\Android" "-PMAVEN_REPOS=https://maven.google.com/" "-PPACKAGES_TO_COPY=com.google.android.gms:play-services-ads:20.2.0" "-PUSE_JETIFIER=0" "-PDATA_BINDING_VERSION=3.6.0"'
stdout:
stderr:
Exception in thread "main" java.lang.RuntimeException: Gradle distribution 'C:\Users\Aleksandr.gradle\wrapper\dists\gradle-5.1.1-bin\90y9l8txxfw1s2o6ctiqeruwn' contains too many directories. Expected to find exactly 1 directory.
Прогуглил все что можно.. Что только не делал..
НУжна помощь !!!!


text:
Q: TFS2017 - NuGet push with octopack credentials I'm having issues with pushing my packages to our internal NuGet feed that I created using TFS2017 packages tab.
I'm getting the following error:
2017-04-05T09:08:24.8336348Z      6>OctoPack:
2017-04-05T09:08:24.8336348Z          Please provide credentials for: http://servername:8080/tfs/TCol/_packaging/Product/nuget/v3/index.json
2017-04-05T09:08:24.9273850Z          Unable to load the service index for source http://servername:8080/tfs/TCol/_packaging/Product/nuget/v3/index.json.
2017-04-05T09:08:24.9273850Z            Response status code does not indicate success: 401 (Unauthorized).
2017-04-05T09:08:24.9273850Z          UserName: Password:
2017-04-05T09:08:24.9430236Z ##[error]Source\packages\OctoPack.3.4.2\tools\OctoPack.targets(108,5): Error MSB3073: The command ""C:\TFS_Agents\Product_Agent_1\_work\2\s\Source\packages\OctoPack.3.4.2\tools\NuGet.exe" push "C:\TFS_Agents\Product_Agent_1\_work\2\s\Source\Company.Product.ServiceBus\obj\octopacked\Company.Product.ServiceBus.Release.3.5.0.nupkg"  -Source http://servername:8080/tfs/TCol/_packaging/Product/nuget/v3/index.json " exited with code 1.
2017-04-05T09:08:24.9430236Z      6>C:\TFS_Agents\Product_Agent_1\_work\2\s\Source\packages\OctoPack.3.4.2\tools\OctoPack.targets(108,5): error MSB3073: The command ""C:\TFS_Agents\Product_Agent_1\_work\2\s\Source\packages\OctoPack.3.4.2\tools\NuGet.exe" push "C:\TFS_Agents\Product_Agent_1\_work\2\s\Source\Company.Product.ServiceBus\obj\octopacked\Company.Product.ServiceBus.Release.3.5.0.nupkg"  -Source http://servername:8080/tfs/TCol/_packaging/Product/nuget/v3/index.json " exited with code 1. [C:\TFS_Agents\Product_Agent_1\_work\2\s\Source\Company.Product.ServiceBus\Company.Product.ServiceBus.csproj]

I want to push packages to it with OctoPack using the following build parameters:
/p:RunOctoPack=true
/p:OctoPackPublishPackageToHttp=http://servername:8080/tfs/TCol/_packaging/Product/nuget/v3/index.json
/p:OctoPackAppendToPackageId=Release
/p:OctoPackNuGetProperties=Configuration=Release

I tried using the following:
/p:OctoPackPublishApiKey=VSTS
/p:OctoPackNuGetPushProperties=-ApiKey=VSTS

Neither parameters worked..
I also don't mind removing the apikey / credentials from the feed but there is literally NO documentation how to do this in the new Package feature in TFS 2017.
Here's a stacktrace I just printed out using -Verbosity detailed in the nuget push parameters:
  OctoPack: OctoPack successful
  Publish to repository: http://tfsserver:8080/tfs/COLL/_packaging/Product/nuget/v3/index.json
  "C:\********_Agents\Product_Agent_1\_work\7\s\Source\packages\OctoPack.3.4.2\tools\NuGet.exe" push "C:\********_Agents\Product_Agent_1\_work\7\s\Source\Company.Product.ApiProxy.v2\obj\octopacked\Company.Product.ApiProxy.v2.Release.3.5.0.nupkg"  -Source http://tfsserver:8080/tfs/COLL/_packaging/Product/nuget/v3/index.json -Verbosity detailed -ApiKey key
  NuGet Version: 3.5.0.10252 (Custom build for OctoPack)
  Please provide credentials for: http://tfsserver:8080/tfs/COLL/_packaging/Product/nuget/v3/index.json
  System.AggregateException: One or more errors occurred. ---> NuGet.Protocol.Core.Types.FatalProtocolException: Unable to load the service index for source http://tfsserver:8080/tfs/COLL/_packaging/Product/nuget/v3/index.json. ---> System.Net.Http.HttpRequestException: Response status code does not indicate success: 401 (Unauthorized).
     at System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode()
     at NuGet.Protocol.HttpSource.<>c__DisplayClass12_0.<<GetAsync>b__0>d.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---
     at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
     at NuGet.Common.ConcurrencyUtilities.<ExecuteWithFileLockedAsync>d__2`1.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---
     at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
     at NuGet.Protocol.HttpSource.<GetAsync>d__12.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---
     at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
     at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
     at NuGet.Protocol.ServiceIndexResourceV3Provider.<GetServiceIndexResourceV3>d__9.MoveNext()
     --- End of inner exception stack trace ---
     at NuGet.Protocol.ServiceIndexResourceV3Provider.<GetServiceIndexResourceV3>d__9.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---
     at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
     at NuGet.Protocol.ServiceIndexResourceV3Provider.<TryCreate>d__8.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---
     at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
     at NuGet.Protocol.Core.Types.SourceRepository.<GetResourceAsync>d__16`1.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---
     at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
     at NuGet.Protocol.PackageUpdateResourceV3Provider.<TryCreate>d__1.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---
     at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
     at NuGet.Protocol.Core.Types.SourceRepository.<GetResourceAsync>d__16`1.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---
     at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
     at NuGet.Protocol.Core.Types.SourceRepository.<GetResourceAsync>d__15`1.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---
     at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
     at NuGet.Commands.CommandRunnerUtility.<GetPackageUpdateResource>d__3.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---
     at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
     at NuGet.Commands.PushRunner.<Run>d__0.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---
     at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
     at NuGet.CommandLine.PushCommand.<ExecuteCommandAsync>d__28.MoveNext()
     --- End of inner exception stack trace ---
     at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
     at System.Threading.Tasks.Task.Wait(Int32 millisecondsTimeout, CancellationToken cancellationToken)
     at NuGet.CommandLine.Command.Execute()
     at NuGet.CommandLine.Program.MainCore(String workingDirectory, String[] args)
  ---> (Inner Exception #0) NuGet.Protocol.Core.Types.FatalProtocolException: Unable to load the service index for source http://tfsserver:8080/tfs/COLL/_packaging/Product/nuget/v3/index.json. ---> System.Net.Http.HttpRequestException: Response status code does not indicate success: 401 (Unauthorized).
     at System.Net.Http.HttpResponseMessage.EnsureSuccessStatusCode()
     at NuGet.Protocol.HttpSource.<>c__DisplayClass12_0.<<GetAsync>b__0>d.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---
     at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
     at NuGet.Common.ConcurrencyUtilities.<ExecuteWithFileLockedAsync>d__2`1.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---
     at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
     at NuGet.Protocol.HttpSource.<GetAsync>d__12.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---
     at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
     at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
     at NuGet.Protocol.ServiceIndexResourceV3Provider.<GetServiceIndexResourceV3>d__9.MoveNext()
     --- End of inner exception stack trace ---
     at NuGet.Protocol.ServiceIndexResourceV3Provider.<GetServiceIndexResourceV3>d__9.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---
     at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
     at NuGet.Protocol.ServiceIndexResourceV3Provider.<TryCreate>d__8.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---
     at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
     at NuGet.Protocol.Core.Types.SourceRepository.<GetResourceAsync>d__16`1.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---
     at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
     at NuGet.Protocol.PackageUpdateResourceV3Provider.<TryCreate>d__1.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---
     at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
     at NuGet.Protocol.Core.Types.SourceRepository.<GetResourceAsync>d__16`1.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---
     at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
     at NuGet.Protocol.Core.Types.SourceRepository.<GetResourceAsync>d__15`1.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---
     at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
     at NuGet.Commands.CommandRunnerUtility.<GetPackageUpdateResource>d__3.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---
     at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
     at NuGet.Commands.PushRunner.<Run>d__0.MoveNext()
  --- End of stack trace from previous location where exception was thrown ---
     at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
     at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
     at NuGet.CommandLine.PushCommand.<ExecuteCommandAsync>d__28.MoveNext()<---

  UserName: Password:
Source\packages\OctoPack.3.4.2\tools\OctoPack.targets(108,5): Error MSB3073: The command ""C:\********_Agents\Product_Agent_1\_work\7\s\Source\packages\OctoPack.3.4.2\tools\NuGet.exe" push "C:\********_Agents\Product_Agent_1\_work\7\s\Source\Company.Product.ApiProxy.v2\obj\octopacked\Company.Product.ApiProxy.v2.Release.3.5.0.nupkg" -Source http://tfsserver:8080/tfs/COLL/_packaging/Product/nuget/v3/index.json -Verbosity detailed -ApiKey key" exited with code 1.
C:\********_Agents\Product_Agent_1\_work\7\s\Source\packages\OctoPack.3.4.2\tools\OctoPack.targets(108,5): error MSB3073: The command ""C:\********_Agents\Product_Agent_1\_work\7\s\Source\packages\OctoPack.3.4.2\tools\NuGet.exe" push "C:\********_Agents\Product_Agent_1\_work\7\s\Source\Company.Product.ApiProxy.v2\obj\octopacked\Company.Product.ApiProxy.v2.Release.3.5.0.nupkg"  -Source http://tfsserver:8080/tfs/COLL/_packaging/Product/nuget/v3/index.json -Verbosity detailed -ApiKey key" exited with code 1. [C:\********_Agents\Product_Agent_1\_work\7\s\Source\Company.Product.ApiProxy.v2\Company.Product.ApiProxy.v2.csproj]
Done Building Project "C:\********_Agents\Product_Agent_1\_work\7\s\Source\Company.Product.ApiProxy.v2\Company.Product.ApiProxy.v2.csproj" (default targets) -- FAILED.
Project "C:\********_Agents\Product_Agent_1\_work\7\s\Source\Company.Product.Solution.sln" (1) is building "C:\********_Agents\Product_Agent_1\_work\7\s\Source\Company.Product.ApiProxy.v2.TestConsole\Company.Product.ApiProxy.v2.TestConsole.csproj" (24) on node 1 (default targets).

A: Does it work if you open a command line and execute
nuget push foo.nupkg your-api-key -source http://servername:8080/tfs/TCol/_packaging/Product/nuget/v3/index.json


text:
Q: newline in
Possible Duplicate:
How can I use a carriage return in a HTML tooltip?

I'd like to know if it's possible to force a newline to show in the tooltip when using title property of a TD.
something like

Can this be done?

A: Using
 Works in Chrome to create separate lines in a tooltip.

A: One way to achieve similar effect would be through CSS:
Cell content.

    This is the popup.

    Another line of popup.

And then use the following in CSS:
td div.popup { display: none; }
td:hover div.popup { display: block; position: absolute; }

You will want to add some borders and background to make the popup look decent, but this should sketch the idea. It has some drawbacks though, for example the popup is not positioned relative to mouse but relative to the containing cell.

A: This should be OK, but is Internet Explorer specific:

As others have mentioned, the only other way is to use an HTML + JavaScript based tooltip if you're only interested in the tooltip. If this is for accessibility then you will probably need to stick to just single lines for consistency.

A: Using
 didn't work in my fb app.
However this did, beautifully (in Chrome FF and IE):

A: I use the jQuery clueTip plugin for this.

A: The Extensible Markup Language (XML) 1.1 W3C Recommendation say
« All line breaks MUST have been normalized on input to #xA as described in 2.11 End-of-Line Handling, so the rest of this algorithm operates on text normalized in this way. »
The link is http://www.w3.org/TR/2006/REC-xml11-20060816/#AVNormalize
Then you can write :

A: If you're looking to put line breaks into the tooltip that appears on mouseover, there's no reliable crossbrowser way to do that. You'd have to fall back to one of the many Javascript tooltip code samples

A: This should now work with Internet Explorer, Firefox v12+ and Chrome 28+

Try a JavaScript tooltip library for a better result, something like OverLib.

A: The jquery colortip plugin also supports

 tags in the title attribute, you might want to look into that one.


text:
Q: Recognize isolated words instead of words combinations I am trying to improve accuracy of pocketsphinx using a dictionary..
I gave a list of words like
 apple
 ball
 bottle

Many a time I noticed that it gives me a combination of these words as the result
 apple ball
 bottle ball etc

Is there a way to solve this problem? Any flag that says output only one of these words and not a combination.

A: You can use a grammar like this instead of a language model
 #JSGF V1.0;
 grammar test;
 public <result> = apple | ball | book;

For more details see cmusphinx language model tutorial
http://cmusphinx.sourceforge.net/wiki/tutoriallm


text:
Q: Vertical line in ion-item list I'm using Ionic and html and I'm trying to put a vertical line inside a ion-item in ion-list. I want something like this (the colored line after 'all-day'): https://cdn.cultofmac.com/wp-content/uploads/2015/04/IMG_1723-640x360.jpg
I have tried something like this:
<ion-list>
  <ion-item *ngFor=let item of items>

{{ item.longStringFromTSFile }}

  </ion-item>
</ion-list>

// INSIDE SCSS FILE
.verticalLine {
  width:1%;
  height:75%;
  background:green;
  margin: auto;
}

But the vertical lines sometimes is too long, as you can see from this photo: verticalLines
What I really want is this:
expected result
EDIT: Vertical line are not equals: new photo

A: Try something like example
HTML:
<ion-content padding>
<ion-list>
  <ion-item *ngFor="let item of items">
    {{item.name}}

{{item.age}}

  </ion-item>
</ion-list>

css:
.verticalLine {
  width:1%;
  height:50px;
  background:green;
  margin-top: 0;
  position: relative;
  margin-left: 10%;
}

A: try this :
.verticalLine {
  width:1%;
  height:50px;
  background:green;
  margin: auto;
}

remember setting height 75% will be proportional to how big text is it.


text:
Q: How to enter validation for a choice of a question in Google forms using script editor? I want that when someone tries to fill the checkbox, the checkbox automatically unchecks itself according to the time of the day.
Here is my code:
`
function myFunction() {
  var myForm = FormApp.getActiveForm();
  var title = myForm.getId();
  var choicesArray = [];
  var item = myForm.getItemById('xxxxxxxx').asCheckboxItem(); // xxxxxx is whatever the id is
  var choices = item.getChoices();
  var d = new Date();
  choices.forEach(function(a) {
      if (a.checked == true && a.getValue() == "First")
          if (d.getHours() >= 17)
          a.checked = false;
      if (a.checked == true && a.getValue() == "Second")
          if (d.getHours() < 17)
          a.checked = false;
  });
}

`
After creating trigger nothing happens and i am able to select both the checkboxes which shouldn't happen. Nor the trigger triggers.
if that is not possible then how to delete the second choice and only show the other one?

A: The issue is that you have put semicolons right after if. This terminates the if.
Remove the semicolons & put the statements right after if instead of the next line.
function myFunction() {
  var myForm = FormApp.getActiveForm();
  var title = myForm.getId();
  var choicesArray = [];
  var item = myForm.getItemById('xxxxxxxx').asCheckboxItem(); // xxxxxx is whatever the id is
  var choices = item.getChoices();
  var d = new Date();
  choices.forEach(function(a) {
      if (a.checked == true && a.getValue() == "First")
          if (d.getHours() >= 17); // <--- remove ;
          a.checked = false;
      if (a.checked == true && a.getValue() == "Second")
          if (d.getHours() < 17); // <--- remove ;
          a.checked = false;
  });
}

A:   function myFunction() {
    var myForm = FormApp.getActiveForm();
    var title = myForm.getId();
    var choicesArray = [];
    var item = myForm.getItemById('xxxxxxxx').asCheckboxItem(); // xxxxxx is whatever the id is
    var d = new Date();
    item.setChoices([item.createChoice(d.getHours() > 11 ? "first" : "second")]);
  });
}

then run set the trigger to run every minute or else if set onOpen it will run    only who have edit permissions not for all the people.
Thanks @Tanaike for help !!!


text:
Q: objective c : make UIPickerView separator line invisible i create a pickerView with this codes(separator line is invisible):
pickerView = [[UIPickerView alloc]initWithFrame:CGRectMake(0, 40, [Functions Dwidth], 190)];
    pickerView.delegate = self;
    pickerView.dataSource = self;
    pickerView.layer.borderWidth = 0;
    [popupView addSubview:pickerView];
.
.
.

-(NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView{
    return 3;
}

-(NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component{
    return 10;
}

-(UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view{
    .
    .
    return someView;
}

after i added this codes to my project separator line is going to visible:
[pickerView selectRow:3 inComponent:1 animated:NO];
[pickerView selectRow:2 inComponent:0 animated:NO];

how i can make it invisible again?


text:
Q: Get In Focus Pixels of an Image How to detect which pixels of an image are in focus compared to the blurry ones. Something like the 'Focus Peaking' feature lots of cameras have?
The idea is to color the pixels that are in focus so that it assists the user while clicking a picture. Looking for an implementation through Python.

A: You can find the edges, which are sharp or high contrast and then superimpose them onto the original image.
So, starting with this image:

Credit: Rita Kochmarjova - Fotolia
You can do:
#!/usr/bin/env python3

import numpy as np
from PIL import Image, ImageFilter, ImageChops

# Open input image and make greyscale copy
image = Image.open('bulldog.jpg')
grey  = image.copy().convert('L')

# Find the edges
edges = grey.filter(ImageFilter.FIND_EDGES)
edges.save('edges.png')

# Draw the sharp edges in white over original
RGBedges = Image.merge('RGB',(edges,edges,edges))
image.paste(RGBedges, mask=edges)

# Save
image.save('result.png')

You can see the effect most clearly in the stones at water's edge.
Here is the intermediate edges.png. You could dilate the white pixels somewhat, or threshold to make the in-focus parts more heavily defined.

Here it is with the edges dilated a little to make them more obvious:
#!/usr/bin/env python3

import numpy as np
from PIL import Image, ImageFilter
from skimage.morphology import dilation, square

# Open input image and make greyscale copy
image = Image.open('bulldog.jpg')
grey  = image.copy().convert('L')

# Find the edges
edges = grey.filter(ImageFilter.FIND_EDGES)

# Define a structuring element for dilation
selem = square(3)
fatedges = dilation(np.array(edges),selem)
fatedges = Image.fromarray(fatedges)
fatedges.save('edges.png')

# Draw the sharp edges in white over original
RGBedges = Image.merge('RGB',(fatedges,fatedges,fatedges))
image.paste(RGBedges, mask=fatedges)

# Save
image.save('result.png')

You can also do it in Terminal with ImageMagick without writing any code:
magick bulldog.jpg \( +clone -canny 0x1+10%+30% \) -compose overlay -composite  result.png

Or this, which is more similar to the Python:
magick bulldog.jpg \( +clone -canny 0x1+10%+30% \) -compose lighten -composite  result.png