text:
Q: Best way to extract word or phrase region on image from point for it's further recognition? The solution must be universal (working with different fonts and colors) and stable.
Input data is point with X, Y coordinates and output data is rectangle or more comples shape, which contains word or phrase.

Now i am using tesseract recognition of entire image with hocr option, then extract all rectangles from output html and finally find the nearest to point reactangle. Code shown below.
But it's inefficiently, beacuse of entire image recognition.
Off course, it's possible to recognize not entire image, but part, but it's not a clear solution too, because of different font sizes and useless words recognitions all the same.
UPDATE
public class WordRecognizerTesseractHocr
{
    const string HelperFileName = "temp";

    public string NextVariant()
    {
        Bitmap.Save(HelperFileName + ".png", ImageFormat.Png);
        var startInfo = new ProcessStartInfo("tesseract.exe", HelperFileName + ".png temp hocr");
        startInfo.WindowStyle = ProcessWindowStyle.Hidden;
        var process = Process.Start(startInfo);
        process.WaitForExit();

        var result = GetNearestWord(File.ReadAllText(HelperFileName + ".html"), Position);

        return result;
    }

    public string GetNearestWord(string tesseractHtml, Point position)
    {
        var xml = XDocument.Parse(tesseractHtml);

        RectsWords = new Dictionary<Rectangle, string>();

        var ocr_words = xml.Descendants("span").Where(element => element.Attribute("class").Value == "ocr_word").ToList();
        foreach (var ocr_word in ocr_words)
        {
            var strs = ocr_word.Attribute("title").Value.Split(' ');
            int left = int.Parse(strs[1]);
            int top = int.Parse(strs[2]);
            int width = int.Parse(strs[3]) - left + 1;
            int height = int.Parse(strs[4]) - top + 1;
            RectsWords.Add(new Rectangle(left, top, width, height), ocr_word.Value);
        }

        var nearestWords = RectsWords.OrderBy(rectWord => Distance(position, rectWord.Key));

        return nearestWords.Count() != 0 ? nearestWords.First().Value : string.Empty;
    }

    public static double Distance(Point pos, Rectangle rect)
    {
        if (pos.X < rect.Left)
        {
            if (pos.Y < rect.Top)
                return Math.Sqrt((rect.X - pos.X) * (rect.X - pos.X) + (rect.Top - pos.Y) * (rect.Top - pos.Y));
            else if (pos.Y < rect.Top + rect.Height)
                return rect.Left - pos.X;
            else
                return Math.Sqrt((rect.X - pos.X) * (rect.X - pos.X) +
                    (rect.Top + rect.Height - 1 - pos.Y) * (rect.Top + rect.Height - 1 - pos.Y));
        }
        else if (pos.X < rect.Left + rect.Width)
        {
            if (pos.Y < rect.Top)
                return rect.Top - pos.Y;
            else if (pos.Y < rect.Top + rect.Height)
                return 0;
            else
                return pos.Y - (rect.Top + rect.Height - 1);
        }
        else
        {
            if (pos.Y < rect.Top)
                return Math.Sqrt((rect.X + rect.Width - 1 - pos.X) * (rect.X + rect.Width - 1 - pos.X) +
                    (rect.Top - pos.Y) * (rect.Top - pos.Y));
            else if (pos.Y < rect.Top + rect.Height)
                return pos.X - (rect.Left + rect.Width - 1);
            else
                return Math.Sqrt((rect.X + rect.Width - 1 - pos.X) * (rect.X + rect.Width - 1 - pos.X) +
                    (rect.Top + rect.Height - 1 - pos.Y) * (rect.Top + rect.Height - 1 - pos.Y));
        }
    }

    public IDictionary<Rectangle, string> RectsWords
    {
        get;
        protected set;
    }
}

A: Here's something that may work. It should be pretty fast, but it's likely to be easily hurt by noise.
First get a deskewed image of the text, in whatever format is easiest for you to work in.
Next, get the point you care about in x,y.
Starting from the y cooridnate, look at full rows up and down until you see several fully empty rows. These will mark the top and bottom of the row of text for the point you specified. These are the bounds of the word rectangle in y.
Repeat the same thing for x, but look for columns to get the bounds of the word rectangle in x.
Now you should have the bounds for the whole word, and you can easily get the word from that.


text:
Q: Integrate "doubly radial" function over product of $\ell_2$ balls I have some function $ f: \mathbb{R}^n\times \mathbb{R}^n\to\mathbb{R}$ I wish to integrate over the cartesian-product of any "nice" (your choice) bounded subset $\Omega\subseteq\mathbb{R}^n\times \mathbb{R}^n$.
The function is "doubly radial" in the sense that $f(x, y) = g(\lVert x\rVert_2, \lVert y\rVert_2)$ for some $g : \mathbb{R}^2\to\mathbb{R}$.
This function does not factor as $f(x, y) = h(\lVert x\rVert_2)\ell(\lVert y\rVert_2)$ for radial functions $h$ and $\ell$, i.e. the coordinates are "dependent".
Is there some simple way to express $\int_\Omega f(x,y)d\vec x d\vec y$ in terms of the function $g$?
If $f$ were a standard radial function, the solution would be to integrate over an $\ell_2$ ball in polar coordinates, e.g. in this question.
I am unsure what the right coordinates to choose for this situation are though.

redpajama_set_name: RedPajamaStackExchange


text:
Q: DATABASE is mounted but 11g doesn't recognize that it's not I'm trying to enable archivelog on a database with
ALTER DATABASE ARCHIVELOG;

And then get

ORA-01126: database must be mounted in this instance and not open in
  any instance

So I ran
ALTER DATABASE MOUNT

and get

ORA-01100: database already mounted

A: After configuring archival destination shut down the database gracefully and mount it in order to enable the archive log mode.
SQL> shutdown immediate
SQL> Startup mount
SQL> alter database archivelog;
SQL> alter database open;


text:
Q: Detecting the Javascript Function which is called I have an url which i am displaying in my iPad screen by using UIWebView. Now that page contains a bar chart, on selection of which a particular javascript function is getting called present in html file.
The webpage contains "N" number of javascript functions.
So how can i know that which function is getting called ?
I want to retrieve that function name in my native objective-c .

A: Try this:
function getItem(){
   var functionName =   arguments.callee.name;
   alert(functionName)  //outputs 'getItem'
}

getItem();


text:
Q: Not creating class object - Ruby on Rails I am trying to create a User class in Ruby On Rails App, and when I call
NETWORKING::User.new(1,"Testing") , it returns *** ArgumentError Exception: wrong number of arguments (2 for 0)
Not sure why?
class NETWORKING::User
   mattr_writer :id, :name

 class << self

    def initialize(id, name)
        @id = id
        @fullname = name

    end

end
end

A: class << self serves no purpose here except to break your code. Remove it:
class NETWORKING::User
  attr_accessor :id, :name

  def initialize(id, name)
    @id = id
    @fullname = name
  end
end


text:
Q: Accessing a SMB share without a password When accessing SMB shared that are password-protected, smbclient works just fine.
But when I'm trying to access shared that have no password protection (public shares), smbclient prints:
tree connect failed: NT_STATUS_ACCESS_DENIED

How can I access those shares?
I'm trying to access Windows 7 from my Ubuntu 12.10

A: if your mount point is /home/myuser/mountpoint and shared folder is named sharefolder. You should try  mount -t cifs //<your shareserver name or ip>/sharefolder -o username=guest,password="" /home/myuser/mountpoint

A: Answering quite an old question, I can do this using smbclient like this:
$ smbclient //host/share -U " "%" "
Domain=[WORKGROUP] OS=[Windows 2000] Server=[Windows 2000 LAN Manager]
smb: \>

This is from a fedora 21 host connecting to a solaris clone (omnios), but should be the same to a windows host.

A: Could you check which security option is given in your smb.conf. By default security = user  option will be enabled under Standalone Server option .User level of security asks for username/passwd in windows while if you keep the security = share it wont ask for credentials or can access share without password.
This option can also be appended to your local share definitions.

A: From here:
by default network access is denied to accounts which don't have a
password... you can change this option in the group policy

Well, appears it's not possible. Microsoft probably thought this is clever..

A: This is an old question, but I fixed this problem for guest account access by enabling the following policy in Group Policy Management:
Default Domain Policy > Computer Configuration > Policies > Windows Settings > Security Settings > Local Policies > Security Options > Accounts: Guest account status
Even though it is not defined, it is disabled by default and prevents enumeration of the share.

A: In my case this syntax was working great on smbclient Version 4.3.11-Ubuntu to copy a file on another linux server  using smb share:
smbclient '//server.domain.local/share' -U 'myuser%' -c 'put "/tmp/filen_to_copy.txt" "subfolder\copied_file.txt"'

I think it works with Windows server w/o AD.

A: @bernie had the right idea. The following command works following this syntax:
smbclient -L '//10.10.16.165/' -U '%' OR smbclient '//10.10.16.165/SHARE' -U '%'


text:
Q: Dynamics CRM. Delete row from subgrid using JS How can I delete a row from a subgrid using Javascript?
    var grid = Xrm.Page.getControl("Produktrader").getGrid();
    grid.getRows().forEach(function (row) {
        var rowData = row.getData();
        if (rowData != null) {
              //delete row here
        }
    }
}

A: If you want to delete the record in JavaScript you will need to make a REST call to delete the record from the database, and then refresh the page. You can't just delete the record from the subgrid.
Sample: Create, retrieve, update, and delete using the OData endpoint with JavaScript and jQuery

A: I'll add to James' answer in that after you perform the Delete, you should trigger a subgrid refresh via javascript
Xrm.Page.getControl("Produktrader").refresh();


text:
Q: intel-xdk: not able to get contacts list I am not able to get contacts list.
HTML Code:
<!DOCTYPE html>

    <meta http-equiv="Content-type" content="text/html; charset=utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0, user-scalable=0" />

intel.xdk.contacts.get event is not fired. Is it a bug ?

A: I was not calling intel.xdk.contacts.getContacts() inside onDeviceReady. Found this from the post here.

A: Hi i am getting same problem. But I am able to get contacts in Phone after deploying (Sony xperia ion).
This is my code.
I set the permission for contacts.

<!DOCTYPE html>

<meta http-equiv="Content-type" content="text/html; charset=utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta http-equiv="Pragma" content="no-cache">

<link href="css/icons.css" rel="stylesheet" type="text/css">
<link href="css/af.ui.css" rel="stylesheet" type="text/css">

            Hello World

        Home

        Back

test

Side Menu


text:
Q: Swift - Using Decodable to decode JSON array of just strings I have a sample JSON where its just an array of strings and has no keys and would like to use the Decodable protocol to consume the JSON and create a simple model out of it.
The json looks like this:
{ "names": [ "Bob", "Alice", "Sarah"] }

Just a collection of strings in an simple array.
What I'm unsure about is how do I use the new Swift Decodable protocol to read this into a model without a key.
Most of the examples I've seen assume the JSON has a key.
IE:
// code from: Medium article: https://medium.com/@nimjea/json-parsing-in-swift-2498099b78f

struct User: Codable{
       var userId: Int
       var id: Int
       var title: String
       var completed: Bool
}

do {
    //here dataResponse received from a network request
    let decoder = JSONDecoder()
    let model = try decoder.decode([User].self, from:
                 dataResponse) //Decode JSON Response Data
    print(model)
} catch let parsingError {
    print("Error", parsingError)
}

This above example assumes that the json is a key-value; how can I use the decodable protocol to de-code the JSON without keys?
With thanks

A: The corresponding struct of this JSON is
struct User: Decodable {
   let names: [String]
}

and decode
let model = try decoder.decode(User.self, from: dataResponse)

and get the names with
let names = model.names

or traditionally without the overhead of JSONDecoder
let model = try JSONSerialization.jsonObject(with: dataResponse) as? [String:[String]]

A: For this simple structure of json , i guess it's better not to create any structs and use
let model = try decoder.decode([String:[String]].self, from: dataResponse)
print(model["names"])

the json fiting for your model is
{

    "names": [{
          "userId": 2,
         "id": 23,
         "title": "gdgg",
         "completed": true

    }]
}

struct Root: Codable {
    let names: [User]
}

struct User: Codable {
    let userId, id: Int
    let title: String
    let completed: Bool

}


text:
Q: How to split a String sentence into words using split method in Java? I need to split some sentences into words.
For example:
Upper sentence.
Lower sentence. And some text.

I do it by:
String[] words = text.split("(\\s+|[^.]+$)");

But the output I get is:
Upper, sentence.Lower, sentence., And, some, text.

And it should be like:
Upper, sentence., Lower, sentence., And, some, text.

Notice that I need to preserve all the characters (.,-?! etc.)

A: in regular expressions \W+ match one or more non word characters.
http://www.vogella.com/tutorials/JavaRegularExpressions/article.html
So if you want to get the words in the sentences you can use \W+ as the splitter.
String[] words = text.split("\\W+");

this will give you following output.
Upper
sentence
Lower
sentence
And
some
text

UPDATE :
Since you have updated your question, if you want to preserve all characters and split by spaces, use \s+ as the splitter.
String[] words = text.split("\\s+");

I have checked following code block and confirmed that it is working with new lines too.
String text = "Upper sentence.\n" +
            "Lower sentence. And some text.";
    String[] words = text.split("\\s+");
    for (String word : words){
        System.out.println(word);
    }

A: The expression \\s+ means "1 or more whitespace characters". I think what you need to do is replace this by \\s*, which means "zero or more whitespace characters".

A: You can split the string into sub strings using the following line of code:
String[] result = speech.split("\\s");

For reference: https://alvinalexander.com/java/edu/pj/pj010006

A: Replace dots, commas, etc... for a white space and split that for whitespace
String text = "hello.world this   is.a sentence.";
String[] list = text.replaceAll("\\.", " " ).split("\\s+");
System.out.println(new ArrayList<>(Arrays.asList(list)));

Result: [hello, world, this, is, a, sentence]
Edit:
If is only for dots this trick should work...
String text = "hello.world this   is.a sentence.";
String[] list = text.replaceAll("\\.", ". " ).split("\\s+");
System.out.println(new ArrayList<>(Arrays.asList(list)));

[hello., world, this, is., a, sentence.]

A: Simple answer for updated question
    String text = "Upper sentence.\n"+
            "Lower sentence. And some text.";

[just space] one or more OR  new lines one or more
    String[] arr1 = text.split("[ ]+|\n+");
    System.out.println(Arrays.toString(arr1));

result:
 [Upper, sentence., Lower, sentence., And, some, text.]


text:
Q: change value at specific location in a tibble I have a df
df = data.frame(col1=1:4, col2 = 5:8, col3 = 9:12)
I want to change the value in row2, col2 to 44
In base R, I use df["2","col2"] = 44, how do I do this in tidyverse?
df = data.frame(col1=1:4, col2 = 5:8, col3 = 9:12)
df
df["2","col2"]=44
df

A: A possible solution:
library(dplyr)

df %>%
  mutate(col2 = ifelse(row_number() == 2, 44, col2))

#>   col1 col2 col3
#> 1    1    5    9
#> 2    2   44   10
#> 3    3    7   11
#> 4    4    8   12

A: You could maybe use the rows_update() function from dplyr?
rows_update(df, tibble(col1=2, col2=44))

# Matching, by = "col1"
# A tibble: 4 x 3
   col1  col2  col3
  <int> <int> <int>
1     1     5     9
2     2    44    10
3     3     7    11
4     4     8    12


text:
Q: FTC Double Derivative of Two Integrals I need help working through this FTC problem I've encountered. It looks like such:
$$\frac{d^{2}}{d x^{2}}\left(\int_1^{\sin (x)}\left(\int_1^t\sqrt{1+u^2} d u\right)dt\right)$$
I know that in such cases, you can just substitute the bounds of the leftmost integral for the bounds of the right integral, then just multiply the derivative of the upper bound times $f(\text{upper bound})$. This can be seen here.
$$\frac{d^{2}}{d x^{2}}\left(\int_1^{x}\left(\int_1^{sin(t)}\sqrt{1+u^4} d u\right)dt\right)$$
However, I'm not sure how to handle it when the $\sin(x)$ is in the outer integral. My first thought is to do $\arctan()$ of something to get it in the form of $x$ for substitution, but I really don't know. Any help would be appreciated.

A: By the fundamental theorem of calculus, if $g(u)$ is a "nice" function and you define the function $F(x)$ by
$$
F(x) = \int_0^x g(u) du,
$$
then
$$
\frac{d}{dx} F(x) = g(x).
$$
In your problem, you are differentiating a function that looks like
$$
(F \circ \sin)(x) = F(\sin x) = \int_0^{\sin x} g(u) du.
$$
To differentiate functions like this, you would use the chain rule. And in particular,
$$
\frac{d}{dx} F(\sin x) = F'(\sin x) \cos x.
$$
Fortunately, as we noted above, you know the derivative of $F$. In your case, you happen to have an annoying function $g(u)$ and you will be wanting to compute a second derivative --- you'll need to use the fundamental theorem of calculus (twice total), the chain rule (twice total), and the product rule in the second derivative.

A: Consider the functions $F(x) = \int_1^{\sin x} t \, dt$ and $G(x) = \int_1^x \sqrt{1 + u^2} \, du.$ Observe that we have $$F(G(x)) = \int_1^{\sin x} \int_1^t \sqrt{1 + u^2} \, du \, dt,$$ hence by the Chain Rule, it follows that $$\frac{d^2}{d^2 x} \int_1^{\sin x} \int_1^t \sqrt{1 + u^2} \, du \, dt = \frac{d^2}{d^2 x} F(G(x)) = \frac d {dx} \biggr[ F'(G(x)) G'(x) \biggl] \phantom{blah blah blah bl}$$ $$\phantom{\frac{d^2}{d^2 x} \int_1^{\sin x} \int_1^t \sqrt{1 + u^2} \, du \, dt = \frac{d^2}{d^2 x} F(G(x))}= F'(G(x)) G''(x) + F''(G(x)) [G'(x)]^2.$$ Further, by the Fundamental Theorem of Calculus, we have that $F'(x) = \sin x \cos x$ and $G'(x) = \sqrt{1 + x^2}.$ Can you finish the solution from here? (Hint: you will need to implement the Product Rule to compute $F''(x)$ and the Chain Rule to compute $G''(x).$)


text:
Q: Ошибка версии приложения; Error "application_version" При запуске выскакивают ошибки:
C:\AndroidProjects\***\app\build\intermediates\instant-run-support\debug\dependencies\AndroidManifest.xml
Error:(2) resource string/common_application_version (*** :string/common_application_version) not found.
Error:failed processing manifest.
Error:java.util.concurrent.ExecutionException: java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
Error:java.util.concurrent.ExecutionException: com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
Error:com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details
Error:Execution failed for task ':app:transformDexWithInstantRunDependenciesApkForDebug'.
> com.android.build.api.transform.TransformException: com.android.ide.common.process.ProcessException: Failed to execute aapt

Это мой манифест:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
      package="***"
      android:versionCode="2"
      android:versionName="@string/common_application_version">

Это манифест который создается при сборке gradle:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
  package="ru.SoftMasters.ILSARMobileMonitor"
  android:versionCode="2"
  android:versionName="@string/common_application_version"
  split="lib_dependencies_apk">
</manifest>

Это string на который и ругается студия:
<string name="common_application_version">1.11.0</string>

Пожалуйста, кто сталкивался с подобной ошибкой подскажите как вы это исправляли...
Заранее спасибо всем за участие!


text:
Q: On the (derived) dual to the James construction. Background
If $X$ is a based space then the James construction on $X$ is the space $J(X)$ given by
$$
X \quad \cup \quad  X^{\times 2} \quad \cup \quad   X^{\times 3} \quad \cup \quad \cdots
$$
in which we identify a $k$-tuple of points $(x_1,\dots ,x_k)$ whose $j$-th coordinate is the basepoint with the $(k-1)$-tuple given by dropping the $j$-th coordinate. Then $J(X)$ is the (reduced) free monoid on the points of $X$ and for $X$ a connected based CW complex, one has a natural weak equivalence
$$
J(X) \quad \simeq \quad \Omega \Sigma X  .
$$
Let $J_k(X) \subset J(X)$ be the subspace represented by $k$-tuples of points of $X$ or less.  Then $J(X) = \cup_k J_k(X)$ and $J_k(X)$ is obtained from $J_{k-1}(X)$ by means of the pushout of
$$
J_{k-1}(X) \quad \leftarrow \quad X(k) \quad \overset{\subset} \to \quad X^{\times k} ,
$$
where $X(k) \subset X^{\times k}$ be the set of tuples such that at least one of the coordinates is the basepoint.
Since is $X$ a CW complex, the inclusion $X(k) \subset X^{\times k}$ is a cofibration.
If it hadn't been a cofibration, we could have instead taken a homotopy pushout
of the diagram with $X(k)$ replaced by the space $X(k)'$ which is given as a
homotopy colimit of the punctured $k$-cube of spaces $X^T$, where
$T \subsetneq \lbrace 1,\cdots k \rbrace$, where the maps $X^T \to X^S$ for $T \subset S$
are given by inserting the basepoint in those coordinates corresponding to those indices
$i \in T-S$.
This will result in a derived version of $J(X)$. It seems to me that the derived version has the same homotopy type when $X$ is CW since in this case $X(k)' \simeq X(k)$
and the homotopy pushout has the same homotopy type as  the pushout of the above displayed diagram.
More Background
I have an urge to Hilton-Eckmann dualize the above. For a based space $X$, we can define a tower of spaces
$$
\cdots \to L_3(X) \to L_2(X) \to L_1(X) = X ,
$$
in which $L_k(X)$ is obtained from $L_{k-1}(X)$ as a homotopy pullback of a diagram of the form
$$
X^{\vee k} \to  X\langle k \rangle \leftarrow L_{k-1}(X)
$$
where $X\langle k \rangle$ is the homotopy inverse limit of the punctured cube given by
$T \mapsto X^{\vee T}$ (for $T \subsetneq \lbrace 1,\cdots k \rbrace$) where the maps
$X^{\vee T} \to X^{\vee S}$ are given by projections.  Here $X^{\vee T}$ means
those functions $T \to X$ wish are supported on a single point in $T$ (the point is not fixed and all other points map to the basepoint of $X$), i.e., it is identified with the $|T|$-fold wedge of copies of $X$.
The map $L_{k-1}(X) \to X\langle k \rangle$ in the diagram
can be given a simple description of this map here, but I will omit it for reasons of space. For example, when $k=2$, it amounts to a map $X \to X \times X$. This is just the diagonal.
In particular, $L_2(X) = \text{holim}(X \to X \times X \leftarrow X \vee X)$. It is well known that
$$
L_2(X) \quad \simeq \quad \Sigma \Omega X
$$
when $X$ is connected.
The Question
Define $L(X)$ to be the homotopy inverse limit $\text{holim}_k L_k(X)$. Then
$L(X)$ is Hilton-Eckmann dual to the derived version of the James construction. It is
a kind of "derived free comonoid on the points of $X$."
Question: What can be said about the homotopy type of $L(X)$?
That is, does $L(X)$ have a simpler description in terms of the functors we know and love?
(Disclaimer: I once asked an abbreviated version of this question on Don Davis' list about a decade ago, but received no identifiable answers. The post can be found here: http://www.lehigh.edu/~dmd1/jk730.txt )


text:
Q: Python mysql.connector doesn`t return all rows The table contains 21.756 rows. Python script returns only 20.715 rows (-1041). Excluding any column from SELECT statements results in correct number of rows.

*

*Python = 3.9.0

*MySQL Percona 5.7.29

Query in MySQL Workbench
SELECT
id,               -- int
title,            -- varchar(1000)
auctionId,        -- varchar(50)
sellingMethod,    -- varchar(100)
auctionSubMethod, -- varchar(20)
status,           -- varchar(50)
auction_date,     -- varchar(50)
lotId,            -- varchar(100)
description,      -- text
amount            -- decimal(30,2)
FROM auctions

21576 row(s) returned
Python script:
result = []
try:
        cnx = mysql.connector.connect(user=DB_USER,password=DB_PWD,host=DB_HOST,database=DB_NAME)
        cursor = cnx.cursor(buffered=True)
        query = '''
            SELECT
            id,
            title,
            auctionId,
            sellingMethod,
            auctionSubMethod,
            status,
            auction_date,
            lotId,
            description,
            amount
            FROM auctions
            '''

        cursor.execute(query)
        rows = cursor.rowcount

        row = cursor.fetchone()
        while row is not None:
            result.append(row)
            row = cursor.fetchone()

    except mysql.connector.Error as err:
        if err.errno == mysql.connector.errorcode.ER_ACCESS_DENIED_ERROR:
            print("ERROR: Something is wrong with your user name or password")
            exit(1)
        elif err.errno ==  mysql.connector.errorcode.ER_BAD_DB_ERROR:
            print("ERROR: Database {db_name} does not exist")
            exit(1)
        else:
            print(err)
            exit(1)
    finally:
        cursor.close()
        cnx.close()
        return result

returns result = 20.715 rows
Fix that works
When I comment out or remove any column in query it results in correct number of rows returned. It does not depend which column is excluded.
query = '''
            SELECT
            id,
            title,
            -- auctionId,
            sellingMethod,
            auctionSubMethod,
            status,
            auction_date,
            lotId,
            description,
            amount
            FROM auctions
        '''

returns result = 21.576 rows
What I`ve tried with no result

*

*cursor.fetchall()

*cnx.cursor(buffered=False)

*using limit and offset: executed SELECT 3 times, incrementing offset and limit by 10000. The results are the same (10.000+10.000+715 rows)

A: Updating mysql-connector-python module resolved the issue.


text:
Q: Endpoint when using AD FS SAML token with with SharePoint 2019 I have fetched a SAML Token from AD FS for the Relying Party Trust I have set up with my local SharePoint server.
The the important part of the response from ADFS is given below.
Using this, I have been able to retrieve an access token from SharePoint by posting a url-encoded-form to http://mylocalsharepoint/_trust/default.aspx and grabbing the set-cookie - essentially emulating the action of the Login UI.
My question is, is there a better endpoint other than http://mylocalsharepoint/_trust/default.aspx (this is what the Login GUI page uses) as this is returning an entire web page but all I really need is the access token (fedAuth cookie) plus it requires a url-encoded-form -it would be great to be able to just use the XML SOAP message or at least XML.
I have found /_vti_bin/authentication.asmx but that seems to only support username and password mode.
I would really appreciate anyone pointing me in the right direction. Thanks very much.
<trust:RequestSecurityTokenResponse>
    <trust:Lifetime>
        <wsu:Created xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">2022-10-19T16:56:36.105Z</wsu:Created>
        <wsu:Expires xmlns:wsu="http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-utility-1.0.xsd">2022-10-19T17:56:36.105Z</wsu:Expires>
    </trust:Lifetime>
    <wsp:AppliesTo xmlns:wsp="http://schemas.xmlsoap.org/ws/2004/09/policy">
        <wsa:EndpointReference xmlns:wsa="http://www.w3.org/2005/08/addressing">
            <wsa:Address>urn:sharepoint:spsites</wsa:Address>
        </wsa:EndpointReference>
    </wsp:AppliesTo>
    <trust:RequestedSecurityToken>
        <saml:Assertion MajorVersion="1" MinorVersion="1" AssertionID="_3519cbe0-66fb-4bc3-9a40-91ea06cb0ad7" Issuer="http://ms-adfs.intranet/adfs/services/trust" IssueInstant="2022-10-19T16:56:36.230Z" xmlns:saml="urn:oasis:names:tc:SAML:1.0:assertion">
            <saml:Conditions NotBefore="2022-10-19T16:56:36.105Z" NotOnOrAfter="2022-10-19T17:56:36.105Z">
                <saml:AudienceRestrictionCondition>
                    <saml:Audience>urn:sharepoint:spsites</saml:Audience>
                </saml:AudienceRestrictionCondition>
            </saml:Conditions>
            <saml:AttributeStatement>
                <saml:Subject>
                    <saml:SubjectConfirmation>
                        <saml:ConfirmationMethod>urn:oasis:names:tc:SAML:1.0:cm:bearer</saml:ConfirmationMethod>
                    </saml:SubjectConfirmation>
                </saml:Subject>
                <saml:Attribute AttributeName="emailaddress" AttributeNamespace="http://schemas.xmlsoap.org/ws/2005/05/identity/claims">
                    <saml:AttributeValue>billbates@microsotofu.com</saml:AttributeValue>
                </saml:Attribute>
            </saml:AttributeStatement>
            <saml:AuthenticationStatement AuthenticationMethod="urn:oasis:names:tc:SAML:1.0:am:X509-PKI" AuthenticationInstant="2022-10-19T16:56:35.639Z">
                <saml:Subject>
                    <saml:SubjectConfirmation>
                        <saml:ConfirmationMethod>urn:oasis:names:tc:SAML:1.0:cm:bearer</saml:ConfirmationMethod>
                    </saml:SubjectConfirmation>
                </saml:Subject>
            </saml:AuthenticationStatement>
            <ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
                <ds:SignedInfo>
                    <ds:CanonicalizationMethod Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
                    <ds:SignatureMethod Algorithm="http://www.w3.org/2001/04/xmldsig-more#rsa-sha256"/>
                    <ds:Reference URI="#_3519cbe0-66fb-4bc3-9a40-91ea06cb0ad7">
                        <ds:Transforms>
                            <ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>
                            <ds:Transform Algorithm="http://www.w3.org/2001/10/xml-exc-c14n#"/>
                        </ds:Transforms>
                        <ds:DigestMethod Algorithm="http://www.w3.org/2001/04/xmlenc#sha256"/>
                        <ds:DigestValue>gTz6J3z40UUkqOf1DV3gAe4yel5AD0GVPCJ7xI6ac44=</ds:DigestValue>
                    </ds:Reference>
                </ds:SignedInfo>
                <ds:SignatureValue>ftyI5grqS01/g9zpfUuPn24xXMvJ...</ds:SignatureValue>
                <KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
                    <X509Data>
                        <X509Certificate>MIICxDCCAaygAwIBAgIQEqN9pL4STbx...</X509Certificate>
                    </X509Data>
                </KeyInfo>
            </ds:Signature>
        </saml:Assertion>
    </trust:RequestedSecurityToken>
    <trust:TokenType>urn:oasis:names:tc:SAML:1.0:assertion</trust:TokenType>
    <trust:RequestType>http://docs.oasis-open.org/ws-sx/ws-trust/200512/Issue</trust:RequestType>
    <trust:KeyType>http://docs.oasis-open.org/ws-sx/ws-trust/200512/Bearer</trust:KeyType>
</trust:RequestSecurityTokenResponse>

A: You need to developing a C# customization as Farm Solution to include a custom endpoint to your SharePoint side like an ASHX prepared to receive the given XML contract above and redirect to this new custom endpoint, the C# code needs the minimal three things:

*

*Guarantee security using CORS approach;

*Deserialize the received XML from custom authentication provider;

*And, the last one: developing custom Authorization into SharePoint side;

About the item 3, it's recommended this Microsoft Learn topic: Create a claims provider in SharePoint


text:
Q: module to show shipping methods on free product page? I need a module that looks for the user's zip code on the product page, does anyone know of a free module?

A: please try this
https://landofcoder.com/magento-2-shipping-calculator-on-product-page.html
hope this helps you :)

A: You can use this module for this:
https://github.com/mageprince/Magento2-PincodeChecker
This module is used to check the availability of Pincode for products. You can also exclude pin codes by product. You can add, edit, update and delete pin codes by admin. You can also import the bulk of pin codes via a .csv file.


text:
Q: id vs class declarations in css I have the following html structure

Header Text

Lots of text

Is there a better way to arrange the css for the above rather than use ids for all of the divs?

A: IDs can only be used once in a document. Classes can be reused throughout the document. Styles attached to IDs trump styles attached to classes.
Other than that, it's entirely up to you and the particular content you are marking up.
Looking at your sample code, I would recommend using an actual header tag instead of a div with an ID of header.

A: Why not change those to classes and have only the top level container with an ID? That way you can target it with the top level ID.
You should also remove the header DIV and use a H2 or H3 tag.

Header

Lots of text

Your CSS would look like
#content .transport {}
#content h2 {}
#content .image


text:
Q: How to use System.net.http.httpclient to create new RT(request tracker ticket) Need to develop a C# application to create new RT tickets, but the example code for c# on https://rt-wiki.bestpractical.com/wiki/REST#C.23 is not working.
I have found information from different places but none of them really have example on how to create a new rt ticket by using C# HttpClient.
Here is my attempt:
private static async void HTTP_Create()
{
        HttpClient client = new HttpClient();
        client.BaseAddress = new Uri(baseURL);

        string ticketUri = string.Format("REST/1.0/ticket/new?user={0}&pass={1}", testUser.UserName, testUser.Password);

        // Doesn't work
        var TicketDataContent = new List<KeyValuePair<string, string>>();
        TicketDataContent.Add(new KeyValuePair<string, string>("id", "ticket/new"));
        TicketDataContent.Add(new KeyValuePair<string, string>("Queue", "queue name"));
        TicketDataContent.Add(new KeyValuePair<string, string>("Requestor", "name@email.com"));
        TicketDataContent.Add(new KeyValuePair<string, string>("Owner", "owner@email.com)"));
        TicketDataContent.Add(new KeyValuePair<string, string>("Subject", "Created by C#"));
        TicketDataContent.Add(new KeyValuePair<string, string>("Text", "Ticket body with messages related to this ticket"));

        var ticketContent = new MultipartFormDataContent();
        ticketContent.Add(new FormUrlEncodedContent(TicketDataContent), "content");
        var response = await client.PostAsync(baseURL + ticketUri, ticketContent);

        Console.WriteLine("Response StatusCode: " + response.StatusCode.ToString());

        var retContent = response.Content;
        var retMsg = await response.Content.ReadAsStringAsync();

        Console.WriteLine(retMsg);
}

I got the following response:
Response StatusCode: OK
RT/4.4.2 200 Ok
# Required: id, Queue
Any help is appreciated.  Thanks!


text:
Q: Getting all branches from bitbucket I need to hand off a visual studio project that has multiple branches. Bitbucket is being used as the repo. I am trying to find a way to download the entire repo with every branch. I'm not sure if there is a solution using GIT or some feature in bitbucket that I can't find. When I try to download directly from Bitbucket I only get the master branch

A: Is there some reason why you can't just git fetch from the repository:
git fetch origin

This should pull in every remote branch to whatever local machine from which you issue this command.  If you need to access a particular branch, you could just check it out via:
git checkout some_branch

A: Open Team Explorer => Open your repository => Select 'Branches' tab => Right click your repository => click 'Create local branch from' => choose source branch from dropdown with name /origin/branchname

A: I needed to download all branches so I could send them to a client via FTP who I couldn't give repository access to. The following worked:
git archive --format zip --output ~/pathToWhereYouWantToSave HEAD


text:
Q: Drag & Drop from Infragistics Menu I would like to darg&drop from Infragistics menu like a button (in fact any UI element behind it) to the Grid.
But It seems is impossible to do.
Normally I do like
 <Border Margin="2,0" CornerRadius="5" Name="MyControl1" BorderBrush="LightGray" BorderThickness="1"  MouseLeftButtonDown="captureMyControl1_MouseLeftButtonDown" MouseLeftButtonUp="captureMyControl1_MouseLeftButtonUp" MouseMove="captureMyControl1_MouseMove">

And I can drag&drop it because it has appropriate methods.
But it seems like we cannot do this with Infragistics Ribbon Menu
and this code
<ig:XamRibbonTabItem>
 <ig:XamRibbonGroup>
  <ig:VerticalRibbonToolContainer>
     <Border Margin="2,0" CornerRadius="5" Name="MyControl1"
          <tools:ButtonToolEx

I mean I cannot see that for instance Ribbon Button has those methods or we can add Border over it.
May be my question might be redefined like this: Can we use standard SIlverlight Controls in Infragistics Menu?
Any clue?

A: FInally, I found a way to resolve that problem.
I am not gonna put the code because there lots of things but I will reference to this great link
http://www.infragistics.com/community/forums/t/39619.aspx
Now imagine that instead of  private ComboBox _combo; you can  do like
 private MyCUstomUSerControl _myCUstomUSerControl;

And this is a way to implement ANY custom user control within Infragistics Ribbon menu.
Have a nice day, folk!
public class ComboBoxTool : RibbonTool

    {

        protected override RibbonToolBaseControl ResolveToolControl()

        {

            return new ComboBoxToolControl(this);

        }

        public IEnumerable ItemsSource { get; set; }

    }

    public class ComboBoxToolControl : RibbonToolBaseControl, IRibbonControl

    {

        private ComboBox _combo;

        public ComboBoxToolControl()

        {

            this.DefaultStyleKey = typeof(ComboBoxToolControl);

        }

        public ComboBoxToolControl(RibbonToolBase tool) : base(tool)

        {

            this.DefaultStyleKey = typeof (ComboBoxToolControl);

        }

        public override void OnApplyTemplate()

        {

            base.OnApplyTemplate();

            this._combo = GetTemplateChild("Combo") as ComboBox;

            if (this._combo != null)

                this._combo.ItemsSource = ((ComboBoxTool) this.Tool).ItemsSource;

        }

    }

Then you need to define the style for the ComboBoxToolControl in your generic.xaml file:

<Style TargetType="cust:ComboBoxToolControl">

        <Setter Property="Foreground" Value="Green"/>

        <Setter Property="Template">

            <Setter.Value>

                <ControlTemplate TargetType="cust:ComboBoxToolControl">

                    <Grid x:Name="LayoutRoot" HorizontalAlignment="Stretch" Background="Transparent">

                        <Grid >

                            <ComboBox x:Name="Combo" Width="100" Height="24" />

                        </Grid>

                    </Grid>

                </ControlTemplate>

            </Setter.Value>

        </Setter>

    </Style>

At this point you should be able to add your combo box tool to the ribbon:

<igr:XamWebRibbonTabItem>

                    <igr:XamWebRibbonGroup>

                        <cust:ComboBoxTool ItemsSource="{StaticResource inventory}">

                      </cust:ComboBoxTool>

                    </igr:XamWebRibbonGroup>

 </igr:XamWebRibbonTabItem>

P.S. And have a look at this link as well http://www.infragistics.com/samples/wpf/ribbon/custom-tools


text:
Q: Android SQLite database: slow insertion I need to parse a fairly large XML file (varying between about a hundred kilobytes and several hundred kilobytes), which I'm doing using Xml#parse(String, ContentHandler). I'm currently testing this with a 152KB file.
During parsing, I also insert the data in an SQLite database using calls similar to the following: getWritableDatabase().insert(TABLE_NAME, "_id", values). All of this together takes about 80 seconds for the 152KB test file (which comes down to inserting roughly 200 rows).
When I comment out all insert statements (but leave in everything else, such as creating ContentValues etc.) the same file takes only 23 seconds.
Is it normal for the database operations to have such a big overhead? Can I do anything about that?

A: Since the InsertHelper mentioned by Yuku and Brett is deprecated now (API level 17), it seems the right alternative recommended by Google is using SQLiteStatement.
I used the database insert method like this:
database.insert(table, null, values);

After I also experienced some serious performance issues, the following code speeded my 500 inserts up from 14.5 sec to only 270 ms, amazing!
Here is how I used SQLiteStatement:
private void insertTestData() {
    String sql = "insert into producttable (name, description, price, stock_available) values (?, ?, ?, ?);";

    dbHandler.getWritableDatabase();
    database.beginTransaction();
    SQLiteStatement stmt = database.compileStatement(sql);

    for (int i = 0; i < NUMBER_OF_ROWS; i++) {
        //generate some values

        stmt.bindString(1, randomName);
        stmt.bindString(2, randomDescription);
        stmt.bindDouble(3, randomPrice);
        stmt.bindLong(4, randomNumber);

        long entryID = stmt.executeInsert();
        stmt.clearBindings();
    }

    database.setTransactionSuccessful();
    database.endTransaction();

    dbHandler.close();
}

A: If the table has an index on it, consider dropping it prior to inserting the records and then adding it back after you've commited your records.

A: You should do batch inserts.
Pseudocode:
db.beginTransaction();
for (entry : listOfEntries) {
    db.insert(entry);
}
db.setTransactionSuccessful();
db.endTransaction();

That increased the speed of inserts in my apps extremely.
Update:
@Yuku provided a very interesting blog post: Android using inserthelper for faster insertions into sqlite database

A: Compiling the sql insert statement helps speed things up.  It can also require more effort to shore everything up and prevent possible injection since it's now all on your shoulders.
Another approach which can also speed things up is the under-documented android.database.DatabaseUtils.InsertHelper class.  My understanding is that it actually wraps compiled insert statements.  Going from non-compiled transacted inserts to compiled transacted inserts was about a 3x gain in speed (2ms per insert to .6ms per insert) for my large (200K+ entries) but simple SQLite inserts.
Sample code:
SQLiteDatabse db = getWriteableDatabase();

//use the db you would normally use for db.insert, and the "table_name"
//is the same one you would use in db.insert()
InsertHelper iHelp = new InsertHelper(db, "table_name");

//Get the indices you need to bind data to
//Similar to Cursor.getColumnIndex("col_name");
int first_index = iHelp.getColumnIndex("first");
int last_index = iHelp.getColumnIndex("last");

try
{
   db.beginTransaction();
   for(int i=0 ; i<num_things ; ++i)
   {
       //need to tell the helper you are inserting (rather than replacing)
       iHelp.prepareForInsert();

       //do the equivalent of ContentValues.put("field","value") here
       iHelp.bind(first_index, thing_1);
       iHelp.bind(last_index, thing_2);

       //the db.insert() equilvalent
       iHelp.execute();
   }
   db.setTransactionSuccessful();
}
finally
{
    db.endTransaction();
}
db.close();

A: If using a ContentProvider:
@Override
public int bulkInsert(Uri uri, ContentValues[] bulkinsertvalues) {

    int QueryType = sUriMatcher.match(uri);
    int returnValue=0;
    SQLiteDatabase db = mOpenHelper.getWritableDatabase();

     switch (QueryType) {

         case SOME_URI_IM_LOOKING_FOR: //replace this with your real URI

            db.beginTransaction();

            for (int i = 0; i < bulkinsertvalues.length; i++) {
                //get an individual result from the array of ContentValues
                ContentValues values = bulkinsertvalues[i];
                //insert this record into the local SQLite database using a private function you create, "insertIndividualRecord" (replace with a better function name)
                insertIndividualRecord(uri, values);
            }

            db.setTransactionSuccessful();
            db.endTransaction();

            break;

         default:
             throw new IllegalArgumentException("Unknown URI " + uri);

     }

    return returnValue;

}

Then the private function to perform the insert (still inside your content provider):
       private Uri insertIndividualRecord(Uri uri, ContentValues values){

            //see content provider documentation if this is confusing
            if (sUriMatcher.match(uri) != THE_CONSTANT_IM_LOOKING_FOR) {
                throw new IllegalArgumentException("Unknown URI " + uri);
            }

            //example validation if you have a field called "name" in your database
            if (values.containsKey(YOUR_CONSTANT_FOR_NAME) == false) {
                values.put(YOUR_CONSTANT_FOR_NAME, "");
            }

            //******add all your other validations

            //**********

           //time to insert records into your local SQLite database
           SQLiteDatabase db = mOpenHelper.getWritableDatabase();
           long rowId = db.insert(YOUR_TABLE_NAME, null, values);

           if (rowId > 0) {
               Uri myUri = ContentUris.withAppendedId(MY_INSERT_URI, rowId);
               getContext().getContentResolver().notifyChange(myUri, null);

               return myUri;
           }

           throw new SQLException("Failed to insert row into " + uri);

    }


text:
Q: Is there required any event handling inside didUpdateToLocation method when app is in background? I am using core location framework inside my app and i added location string in UIBackgroundMode or Required background modes(in xcode 4.2) in info.plist to get updates about location when app also in background state. In documentation of this link http://developer.apple.com/library/ios/#DOCUMENTATION/iPhone/Conceptual/iPhoneOSProgrammingGuide/ManagingYourApplicationsFlow/ManagingYourApplicationsFlow.html it is stated that UIBackgroundMode(location) will notify the app when location is update when app is in background. I think if app sleeps and location updates then app will be notified about location update and it goes to background state again am i correct? OR will we required any event handling inside didUpdateToLocation method when app is in background?

A: No event handling is required in didupdatelocation method. It will notify app when location is updated.
Thanks.


text:
Q: Cannot save managed object with all attributes set I am trying to get into Core Data. I also read most of the Apple Developer documentation relating to Core Data but I have a strange problem:
I created an Xcode project called "Wishes" using Core Data so most of the things got set up automatically. I set up my xcdatamodel like this:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<model userDefinedModelVersionIdentifier="" type="com.apple.IDECoreDataModeler.DataModel" documentVersion="1.0" lastSavedToolsVersion="5059" systemVersion="13B42" minimumToolsVersion="Automatic" macOSVersion="Automatic" iOSVersion="Automatic">
    <entity name="ListenWish" representedClassName="ListenWish" parentEntity="Wish" syncable="YES">
        <attribute name="album" optional="YES" attributeType="String" syncable="YES"/>
        <attribute name="artist" optional="YES" attributeType="String" syncable="YES"/>
        <attribute name="year" optional="YES" attributeType="Integer 16" defaultValueString="0" syncable="YES"/>
    </entity>
    <entity name="Wish" representedClassName="Wish" isAbstract="YES" syncable="YES">
        <attribute name="dateAdded" attributeType="Date" syncable="YES"/>
        <attribute name="dateModified" attributeType="Date" syncable="YES"/>
        <attribute name="rating" attributeType="Integer 16" minValueString="0" maxValueString="6" defaultValueString="0" syncable="YES"/>
        <attribute name="recommendedBy" attributeType="String" indexed="YES" syncable="YES"/>
        <attribute name="title" attributeType="String" maxValueString="64" indexed="YES" spotlightIndexingEnabled="YES" syncable="YES"/>
    </entity>
    <fetchRequest name="BiggestWishes" entity="Wish" predicateString="rating == 6"/>
    <elements>
        <element name="ListenWish" positionX="-63" positionY="-0" width="128" height="88"/>
        <element name="Wish" positionX="79" positionY="-190" width="128" height="120"/>
    </elements>
</model>

So there are basically two entity descriptions: Wish & ListenWish, while Wish is the parent entitity for ListenWish.
I have also set NSManagedObject subclasses for both of these.
Now in my view controller I am trying to save a new managed object of type ListenWish using textfields like this:
DDAddWishViewController.h:
@interface DDAddWishViewController : UIViewController

@property (weak, nonatomic) IBOutlet UITextField *artistField;
@property (weak, nonatomic) IBOutlet UITextField *albumField;
@property (weak, nonatomic) IBOutlet UITextField *yearField;
@property (weak, nonatomic) IBOutlet UISlider *ratingSlider;
@property (weak, nonatomic) IBOutlet UITextField *recommendedByField;

@property (strong, nonatomic) ListenWish *wish;

- (IBAction)saveWish:(id)sender;
- (IBAction)cancel:(id)sender;

@end

DDAddWishViewController.m
...

DDAppDelegate *appDelegate = (DDAppDelegate *)[[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];

// Create a new managed object of type ListenWish
self.wish = [NSEntityDescription insertNewObjectForEntityForName:@"ListenWish" inManagedObjectContext:context];

self.wish.artist = self.artistField.text;
self.wish.album = self.albumField.text;
self.wish.year = [NSNumber numberWithInteger:[self.yearField.text integerValue]];

self.wish.title = [NSString stringWithFormat:@"%@ - %@", self.wish.artist, self.wish.album]; // line A.
self.wish.rating = [NSNumber numberWithFloat:self.ratingSlider.value];
self.wish.recommendedBy = self.recommendedByField.text; // line B.

NSError *error = nil;
if ( [self.wish.managedObjectContext save:&error]) {
    //TODO: Replace this implementation with code to handle the error appropriately.
    // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
    NSLog(@"Could not save to data store %@, %@", [error localizedDescription], [error userInfo]);
    abort();
}

Now the strange thing is: Everything would work just as expected, but only if I comment out either line A (assigning the title string) or line B (assigning the recommendedBy string).
In other words: if I keep just one of those lines, everything works (except that the saved data does not contain the respective string, of course), but if I want to keep both of them, I get an error when trying to save to the managedObjectContext: Could not save to data store (null), (null)
Also:
When I just delete the attribute "recommendedBy" using the Core Data Model Editor in Xcode and also delete every reference to it in Wish.h, Wish.m and of course in my view controller, after deleting the app and running it again I get the same error: Could not save to data store (null), (null)
What is wrong with my model? What am I doing wrong? :/

A: Your check
if ( [self.wish.managedObjectContext save:&error]) {

is wrong and should be
if (! [self.wish.managedObjectContext save:&error]) {

because the save method returns TRUE if the save succeeded, and NO in the case of
an error. If you comment out one of your lines A or B then the save fails because the
"title" and "recommendedBy" attributes are not marked as optional.


text:
Q: ng repeat not updating Hi I am a newbie to angular js and I am hoping someone can help me out with the following problem.
I have a numeric field called numAdults and I need to show a set of field (such as name, address, telephone etc ) numAdult times to get those information for each of those person.
Here is the jsfiddle for the problem jsfiddle link
Here is also an overview of code of the controller
function bookingController($scope){
$scope.numAdults = 1;
$scope.personLoop = function(){
    console.log('personLoop called')
    return new Array($scope.numAdults);
    //return new Array(2);

}

the html
Number of adults:
<input id="book_num_adults" type="text" ng-model="numAdults">

Person {{$index+1}}

       <input placeholder="name">

       <input placeholder="address">

       <input placeholder="telephone">

Can you also help me with how to transform this as an module ( not just a controller based )
Thank you in advance!

A: Your Fiddle was riddled with errors...
http://jsfiddle.net/bRgTR/5/

*

*Under Frameworks & Extensions, you need to change the 2nd dropdown from "onLoad" to one of the "No wrap" options

*Your controller definition is mangled.  It's supposed to be: .controller('name', ['depname', function (depname) { })]); -- you had your closing array misplaced.

*You should really use semi-colons.

*You don't create an array of 5 items in JavaScript like this: var a = new Array(5), that creates an array that contains a 5.  Instead, you should do var a = []; a.length = 5;


text:
Q: Using templates to track an object using opencv I am currently working on a project where I would have to detect new objects appearing on the camera feed over the background.I am cropping the images of the detected objects and storing them in a vector of matrices.When I have sufficient amount of images,I destroy the background and try to track the previous detected object.Since,I destroyed the background,the only information I have about the object to be tracked is those cropped images.So,I used matchTemplate() to find matches for the images.But,I couldn't get any matches.I am including a pic of one of the images I am using as Template

This roi was cropped from
.
Earlier, I used template matching to track my face and it worked fine

But only difference is, I provided the cropped images during face detection and in  my current algorithm roi to be used as template automatically gets cropped  from main image.
I provided images I used for both my projects.I think there maybe some problem with my automated cropped templates.I would like ,if someone points me in the right direction.
I am using opencv libraries with c++.
EDIT:
For my initial testing,I was remaining in the same position as of my templates stored to get maximum detection.But,there is no match.I am providing an image in which templates should be matched.


text:
Q: shell: failed to save error stream code to file I am trying to detect whenever the following script (random_fail.sh) fails --which happens rarely-- by running it inside a while loop in the second script (catch_error.sh):
#!/usr/bin/env bash
# random_fail.sh

 n=$(( RANDOM % 100 ))

 if [[ n -eq 42 ]]; then
    echo "Something went wrong"
    >&2 echo "The error was using magic numbers"
    exit 1
 fi

 echo "Everything went according to plan"

#!/usr/bin/env bash
# catch_error.sh

count=0  # The number of times before failing
error=0  # assuming everything initially ran fine

while [ "$error" != 1 ]; do
    # running till non-zero exit

    # writing the error code from the radom_fail script into /tmp/error
    bash ./random_fail.sh 1>/tmp/msg 2>/tmp/error

    # reading from the file, assuming 0 written inside most of the times
    error="$(cat /tmp/error)"

    echo "$error"

    # updating the count
    count=$((count + 1))

done

echo "random_fail.sh failed!: $(cat /tmp/msg)"
echo "Error code: $(cat /tmp/error)"
echo "Ran ${count} times, before failing"

I was expecting that the catch_error.sh will read from /tmp/error and come out of the loop once a particular run of random_fail.sh exits with 1.
Instead, the catch script seems to be running forever. I think this is because the error code is not being redirected to the /tmp/error file at all.
Please help.

A: You aren't catching the error code in the proper/usual manner.  Also, no need to prefix the execution with the "bash" command, when it already contains the shebang.  Lastly, curious why you don't simply use #!/bin/bash instead of #!/usr/bin/env bash .
Your second script should be modified to look like this:
#!/usr/bin/env bash
# catch_error.sh

count=0  # The number of times before failing
error=0  # assuming everything initially ran fine

while [ "$error" != 1 ]; do
    # running till non-zero exit

    # writing the error code from the radom_fail script into /tmp/error
    ./random_fail.sh 1>/tmp/msg 2>/tmp/error
    error=$?

    echo "$error"

    # updating the count
    count=$((count + 1))

done

echo "random_fail.sh failed!: $(cat /tmp/msg)"
echo "Error code: ${error}"
echo "Ran ${count} times, before failing"

A: [ "$error" != 1 ] is true if random_fail.sh prints a lone digit 1 to stderr.  As long as this doesn't happen, your script will loop. You could instead test whether there has been written anything to stderr. There are several possibilities to achieve this:
printf '' >/tmp/error
while [[ ! -s /tmp/error ]]

or
error=
while (( $#error == 0 ))

or
error=
while [[ -z $error ]]

A: /tmp/error will always be either empty or will contain the line "The error was using magic numbers".  It will never contain 0 or 1.  If you want to know the exit value of the script, just check it directly:
if ./random_fail.sh 1>/tmp/msg 2>/tmp/error; then error=1; else error=0; fi

Or, you can do:
./random_fail.sh 1>/tmp/msg 2>/tmp/error
error=$?

But don't do either of those.  Just do:
while ./random_fail.sh; do ...; done

As long as random_fail.sh (please read https://www.talisman.org/~erlkonig/documents/commandname-extensions-considered-harmful/ and stop naming your scripts with a .sh suffix) returns 0, the loop body will be entered.  When it returns non-zero, the loop terminates.


text:
Q: Function argument's default value equal to another argument Is it possible to define a function argument's default value to another argument in the same function definition? Something like:
def func(a, b=a):
  print a, b

but that didn't work.

A: No. This is not possible. The Python interpreter thinks that you want to assign the default value of argument b to a global variable a when there isn't a global variable a.
You might want to try something like this:
def func(a, b=None):
    if b is None:
        b = a


text:
Q: Como remover um constraint SQL Server Estou tendo um problema para remover uma constraint de uma tabela.
Objetivo é excluir a constraint para excluir uma tabela.
O problema é: Eu tenho uma tabela Rendimento que esta associada a Rendimento extra.
Essa tabela Rendimento esta com FK_COD_RENDA_EXTRA.
ALTER TABLE RENDIMENTO_EXTRA
DROP CONSTRAINT [COD_RENDA_EXTRA]
porém retorna a mensagem de Erro
"Mensagem 3728, Nível 16, Estado 1, Linha 2
'COD_RENDA_EXTRA' não é uma restrição.
Mensagem 3727, Nível 16, Estado 0, Linha 2
Não foi possível cancelar a restrição. Consulte os erros anteriores."

A: Pelo que entendi sua constraint é [FK_COD_RENDA_EXTRA]  na tabela Rendimento.
Altere o nome e a tabela da constraint para realizar o drop corretamente, já que este tem que ser feito na tabela que contém a FK.
ALTER TABLE [Rendimento] DROP CONSTRAINT [FK_COD_RENDA_EXTRA]


text:
Q: Mysql8 xdevapi node.js CRUD table.select problems let's see this select:
getSession(<connectionOptions>)
.then(s => { return s.getSchema('<schema>') } )
.then(s => { return s.getTable('<table>') } )
.then(t => t.select('*') // or .select('COUNT(*)')
.where('<where>')
.execute(row => myHandler(row, <other params>)));
//
function myHandler(row, <other params>) {
...
}

I have three questions and I haven't found anything after reading https://dev.mysql.com/doc/x-devapi-userguide/en and searching the internet:

*

*How can I see and handle that a select has an empty result set? In the node.js xdevapi implementation I do not get the result set, only result rows one after another so I suppose my callback is not even once called.

*Because my callback is called several times I do not know when it is called the last time i.e., when do I get the last row from the result set. How can I see and handle it?

*COUNT(*) / * is not accepted in the select string throwing an unexpected token error at the * character both cases. This is standard SQL, though. I can see that I can use session.sql('SELECT COUNT(*) FROM table') but I am curious to know why not in CRUD then?

A: *

*You are working with promises, not callbacks. so adding then after the execute will let you know that the execution finished.

*One option is: In the handler function you can push to external array or simple counter, based on your needs, when the then is called, you can refer to the counter to get the results. Second option - based on this, it looks like the last then after the execute will resolve with all the results as array. so if you need to make action only after you get all the results, do not put anything inyour handler function, just add the then and do what you need there.

*It looks like you need to use it as function, like .then(t => t.count('*') or .then(t => t.select('*').count()
P.S. I never used the xdevapi, it looks great. if you are using it only for relational operations I suggest you take a look at knex

A: For the records:
After .execute you can add a .then where you can access some useful info through functions (affected rows, generated IDs, warnings etc.) and of course you can catch the end of the execution:
.execute()
.then(info => myInfoHandler(info,<other params>)
...
if (info.getAffectedRowsCount()==0) { //empty result set
}
This way you do not need COUNT(*).


text:
Q: spring security username and password flow like sparklr do you know any implementation of spring security oaurh2 "username and password flow" server,
i will use it also from android client..ıt look sprıng securıty example but ı want to use clıent from androıd applıcatıon,please let me know how to develop
thank you so much

A: Have you tried the Spring Android project? http://www.springsource.org/spring-android
Looks like it might have what you need.  Check out Section 3 in the reference manual.


text:
Q: What may cause the speed of an app to change I am attempting to make changes to a complex image processing app which employs some C++ code and opencv. I have noticed that its speed can vary by as much as 20% from one run to the next even without me making any changes to the code. Its as if my phone was sometimes in a good mood and other times not. I guess its probably something to do with other tasks being carried out by the phone why my app is running (please tell me if you think there are other possibilities).
I wonder if there is anything I could do to make sure the app always runs at the same speed. Perhaps doing something like give my app greater priority over other tasks? Or suppress other tasks?


text:
Q: How to write a GraphQL type definition for a class whose name ends on Type I'm trying to define GraphQL type definitions. As far as I understand a class has to have a type definition named like the class, plus an appended Type. I have a class called CourseType, which leads me to this type definition:
app/graphql/types/course_type_type.rb
module Types
  class CourseTypeType < Types::BaseObject
    field :id, ID, null: false
    field :title, String, null: true
  end
end

When I try to open the GraphiQL site, I see the following error in the rails console:
Unhandled to_type_name input: {:Types=>Types::CourseTypeType} (Hash)

I assume that the problem occurs because of the class name, ending with Type, as I have another class Course, with a type definition named CourseType, which works fine.
I didn't find any similar error or documentation on this on Google. How do I have to write this correctly? Thank you.


text:
Q: Angular 5 with polyfills.ts not good working in Safari: 'undefined' is not a function I run app: ng serve --aot
My angular.cli file have "polyfills": "polyfills.ts",
My polyfills.ts:
import 'core-js/es6/symbol';
import 'core-js/es6/object';
import 'core-js/es6/function';
import 'core-js/es6/parse-int';
import 'core-js/es6/parse-float';
import 'core-js/es6/number';
import 'core-js/es6/math';
import 'core-js/es6/string';
import 'core-js/es6/date';
import 'core-js/es6/array';
import 'core-js/es6/regexp';
import 'core-js/es6/map';
import 'core-js/es6/weak-map';
import 'core-js/es6/set';
import 'core-js/es6/promise';

import 'classlist.js';

import 'core-js/es6/reflect';

import 'core-js/es7/reflect';

import 'web-animations-js';

import 'zone.js/dist/zone';

import 'intl';

import 'intl/locale-data/jsonp/en';

My app workin in browsers: Chrome, Edge, IE, Opera, Mozilla, but not working in Safari.
Safari print information:
TypeError: 'undefined' is not a function (evaluating 'i(d)')
How resolve this problem.


text:
Q: Laravel - Create and Attach - Many to Many relationship I need some help.
I have these tables: users, buys and codecs. I have a many-to-many relationship: buys, codecs, buy_codec
Tables
Schema::create('codecs', function (Blueprint $table) {
    $table->increments('id');
    $table->string('name');
    $table->timestamps();
});

Schema::create('buys', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('user_id')->unsigned();
    $table->string('name');
});

Schema::create('buy_codec', function (Blueprint $table) {
    $table->increments('id');
    $table->integer('buy_id')->unsigned();
    $table->foreign('buy_id')->references('id')->on('buys')->onDelete('cascade');

    $table->integer('codec_id')->unsigned();
    $table->foreign('codec_id')->references('id')->on('codecs')->onDelete('cascade');

    $table->timestamps();
});

Models
class Codec extends Model
{
    protected $guarded = ['id'];
    public function buy() {
        return $this->belongsToMany('App\Buy');
    }
}

class Buy extends Model
{
    protected $guarded = ['id'];
    public function codec() {
        return $this->belongsToMany('App\Codec');
    }
}

class User extends Authenticatable
{
    public function buy() {
        return $this->hasMany('App\Buy');
    }
}

I want to populate the buy table with the user_id, and to attach the codecs from the codecs table.
This is the buy create form.
{!! Form::open(['method'=>'POST', 'action'=>['UserBuyController@store', $usr->id]]) !!}

        {!! Form::label('name', 'Name:') !!}

            {!! Form::text('name', null, ['class'=>'form-control']) !!}

        {!! Form::label('codecs', 'Outbound Codecs:') !!}

            {!! Form::select('codecs[]', $codecs, null, ['class'=>'form-control', 'multiple'=>true]) !!}

    {!! Form::submit('Submit', ['class'=>'btn btn-info']) !!}

{!! Form::close() !!}

Everything works fine, if i don't attach the codecs.
UserBuyController
class UserBuyController extends Controller
{
    public function create($userId)
    {
        $codecs = Codec::lists('name', 'id');
        $usr = User::findOrFail($userId);
        return view('buy.create', compact('usr', 'codecs'));
    }

    public function store($userId, Request $request)
    {
        $usr = User::findOrFail($userId)->buy()->create($request->all());
        return view('buy.index');
    }
}

How can I create the buy record(because i need the buy id) and than attach the codecs in the pivot table?
Thanks!

A: In model, You have to mention the intermediate table.
class Codec extends Model
{
    protected $guarded = ['id'];
    public function buy() {
        return $this->belongsToMany('App\Buy', 'buy_codec', 'codec_id', 'buy_id');
    }
}

and
class Buy extends Model
{
    protected $guarded = ['id'];
    public function codec() {
        return $this->belongsToMany('App\Codec', 'buy_codec', 'buy_id', 'codec_id');
    }
}

And then in controller,
public function store($userId, Request $request)
{
        $buy = User::findOrFail($userId)->buy()->create($request->all());
        $buy->codec()->attach([codec_ids]);
        return view('buy.index');
}

You can attach more codec objects or ids using attach method.
Please refer this link
https://laravel.com/docs/5.2/eloquent-relationships#inserting-related-models

A: You can attach() or sync(). I always store pivot data with attach() function.
    $buy = Buy::findOrFail($id);
    $buyId = $request->input('codec');
    $buy->codec()->attach($buyId);

A: There are few ways you can achieve this. You can attach() or sync(). I always store pivot data with attach() function.
$usr = User::findOrFail($userId)->create($request->all());
$usr->buy()->attach($request->codecs);

or, you can inline the query:
$usr = User::findOrFail($userId)->create($request->all())->buy()->attach($request->codecs);


text:
Q: Extract string after first '/' using snowflake query I have an input table in snowflake with column contains data pattern as follows

city, state/LOCATION/designation

city state/LOCATION/designation

city, state/LOCATION

Want to extract only location and store in another column, can you help me doing this?

A: There are several ways to do this:
A) using the SPLIT_PART function:
SELECT SPLIT_PART('city, state/LOCATION/designation', '/', 2);

Reference: SPLIT_PART
B) using the SPLIT_TO_TABLE tabular function:
 SELECT t.VALUE
   FROM TABLE(SPLIT_TO_TABLE('city, state/LOCATION/designation', '/')) AS t
  WHERE t.INDEX = 2;

Reference: SPLIT_TO_TABLE
C) using REGEXP expressions:
SELECT REGEXP_REPLACE('city, state/LOCATION/designation', '(.*)/(.*)/(.*)', '\\2');

but this one doesn't work if you don't have a third term ('designation'), you need to combine with two calls and check by number of backslashes.
SELECT IFF(REGEXP_COUNT('city, state/LOCATION', '/') = 1,
           REGEXP_REPLACE('city, state/LOCATION','(.*)/(.*)','\\2'),
           REGEXP_REPLACE('city, state/LOCATION','(.*)/(.*)/(.*)','\\2'));

Reference: REGEXP_REPLACE

A: You could use SPLIT_PART, as mentioned in a previous answer, but if you wanted to use regular expressions I would use REGEXP_SUBSTR, like this:
REGEXP_SUBSTR(YOUR_FIELD_HERE,'/([^/]+)',1,1,'e')

To break it down, briefly, it's looking for a slash and then takes all the non-slash characters that follow it, meaning it ends just before the next slash, or at the end of the string.
The 1,1,'e' correspond to: starting at the first character of the string, returning the 1st match, and extracting the substring (everything in the parentheses).
Snowflake documentation is here.


text:
Q: ArcSDE 10.1 Insert/Update Trigger on Adds (A) Table (Oracle 11g) and Feature Services on ArcGIS Server I'm trying to use a trigger to update a versioned dataset in an SDE environment.
Basically, I wanted to implement a system of unique ids called GISID. Initially, when a feature is created (inserted), this GISID is generated by taking the ObjectID. We don't want to use ObjectID as our uniqueID because if a row with the an ObjectID is deleted, that object ID cannot be used in the dataset again. We have instances where some assets are tied to a GISID and it's essential the GISID stays uniform, even if we have to recreate that feature/record.
Anyway, I have a trigger that works great in an ArcMap Edit session.
PL/SQL Code here:
CREATE OR REPLACE TRIGGER "OwnerName"."A5461_GISID"
  BEFORE INSERT OR UPDATE ON OwnerName.A5461
  FOR EACH ROW
DECLARE
    gisidcntbasetbl NUMBER; --variable for count of same GISID in the basetable
    gisidcntatbl    NUMBER; -- variable for count of same GISID in the "A" table

BEGIN
    IF :new.gisid IS NULL
        OR :new.gisid = 0 THEN
      :new.gisid := :new.objectid;
      -- If statement to check if the new GISID
      -- being added is null or zero. If it is, then we give it the object ID.
    ELSE
      --Get count of GISID occurances in the base table
      SELECT Count (*)
      INTO   gisidcntbasetbl
      FROM   ES_WASTERECEPTACLES
      WHERE  ES_WASTERECEPTACLES.gisid = :new.gisid;

      --Get count of GISID occurances in the A table
      SELECT Count (*)
      INTO   gisidcntatbl
      FROM   A5461
      WHERE  A5461.gisid = :new.gisid;

     --If counts are greater than 0 then we set it to the new objectID.
      IF gisidcntbasetbl > 0
          OR gisidcntatbl > 0 THEN
        :new.gisid := :new.objectid;
      END IF;
    END IF;
END;

However, the problem arises when I go to create a feature using a web editing session using a ArcGIS Server Feature Service. Would anyone have any ideas about this? Possible pointers. The data gets written to the table accordingly, but the GISID trigger doesn't seem to run.
Update: I was able to configure the trigger the following way to get it to work with the feature service. However, I've been told by many parties that triggers on A tables is a bad idea. So I have since abandoned this method. We are using versioned views on feature classes to generate the unique IDs after hours.
TRIGGER "Ownername"."A5671_GISID"
  BEFORE INSERT OR UPDATE ON Ownername.A5671
  FOR EACH ROW
DECLARE
    gisidcntbasetbl NUMBER;
    gisidcntatbl    NUMBER;
    tblMutating Exception;
    Pragma Exception_init(tblMutating, -04091);
BEGIN
      SELECT Count (*)
      INTO   gisidcntbasetbl
      FROM   ES_WASTERECEPTACLES
      WHERE  ES_WASTERECEPTACLES.gisid = :new.gisid;

      SELECT Count (*)
      INTO   gisidcntatbl
      FROM   ES_WASTERECEPTACLES_VW
      WHERE  ES_WASTERECEPTACLES_VW.gisid = :new.gisid;

    IF :new.gisid IS NULL OR :new.gisid = 0 THEN
      :new.gisid := :new.objectid;
    ELSE
      IF gisidcntbasetbl > 0 OR gisidcntatbl > 0 THEN
        :new.gisid := :new.objectid;
      END IF;

    END IF;
EXCEPTION
  WHEN tblMutating THEN
    IF :new.gisid IS NULL OR :new.gisid = 0 THEN
      :new.gisid := :new.objectid;
    ELSE
      IF gisidcntbasetbl > 0 OR gisidcntatbl > 0 THEN
        :new.gisid := :new.objectid;
      END IF;

    END IF;
END;

A: Ok. I replicated the environment:
ArcSDE 10.1 Insert / Update Trigger on Adds (A) Table (Oracle 11g) and Feature Services on ArcGIS Server 10.1.
If the feature service is published on the default version, the trigger not run.
Otherwise if the feature service is published on the child version, the trigger run.


text:
Q: Reading from Properities.Setting.Default as per user decision I have some different settings type and assigned values which need to read it during the runtime as per the customer choice.
Type of the settings are specializedstringcollection and want to call it from the method ReadString() ;
 public static void ReadStrings(StringCollection MyString)

    {

        // Reading from settings as per user decision

        List<string> lines =Properties.Settings.Default.MyString.Cast<string>().ToList();

The code is giving an error ;

"'object' does not contain a definition for 'Cast' and the best extension method overload 'Queryable.Cast(IQueryable)'

Would you please let me know how can i read different settings types as per the user decision


text:
Q: Cannot deserialize object with Json.Net I have a very simple POCO class:
    [JsonArray]
    public class WebGame
    {
        public  int Key { get; set; }

        public string Name { get; set; }

        public string Description { get; set; }
    }

Trying to deserialize to it a json string:
  string json = @"[{'Key':'1','Name':'WebGame','Description':'bla-bla-bla'}]";
  var myDeserializedObjList = (List<WebGame>)(JsonConvert.DeserializeObject(json, typeof(List<WebGame>)));
  var game = myDeserializedObjList[0];

I get an exception:

Cannot deserialize the current JSON object (e.g. {"name":"value"})
  into type 'WebGame' because the type requires a JSON array (e.g.
  [1,2,3]) to deserialize correctly. To fix this error either change the
  JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so
  that it is a normal .NET type (e.g. not a primitive type like integer,
  not a collection type like an array or List) that can be
  deserialized from a JSON object. JsonObjectAttribute can also be added
  to the type to force it to deserialize from a JSON object.

What's wrong here?

A: Remove [JsonArray] attribute and it would work fine


text:
Q: Giving Navigation Bar Button functionality over segmented views I am having a problem with my iOS application that has Kal integrated into the application.
Heres an image of whats going on.

If you notice the classes I have implemented on the left part of the picture, you can sorta capture the way I went about this.
Anyways, I want to give the button "Today" functionality, but over all three segmented views, a perfect example is the native CALENDAR application the iPhone has preinstalled.
This tabbarcontroller is exactly the calendar app, or at least i want it to be.
I will provide any extra details if needed, i'll be sitting at my desk all weekend.
Thank you.
EDIT:
I currently have implemented the today button within the calendar_main class which is a parentviewcontroller of the other child view controllers (segmentedViews:list, day, month).
If needed, i can provide code.


text:
Q: VSCode type preview is not simplifying type I've got a fairly complicated type derived from another. In the type declaration and in type annotations the type is correctly derived:

However, when hovering actual JS variables of the specified type, the type is not simplified and instead the popup shows the chain of all the applied type modifiers:

Is there any way to force VSCode to always show the simplified type?
TS Version: 4.6.2
VSC Version: 1.65.1

A: At the moment there's no way to alter the types that VS Code shows on hover, but you can define an identity type to get rid of all the type applications.
Here's a recursive one that also properly handles functions:
// Normalize type by recursively applying any type aliases and merging explicit intersections.
type Normalize<T> =
  T extends (...args: infer A) => infer R
  ? (...args: Normalize<A>) => Normalize<R>
  : {[K in keyof T]: Normalize<T[K]>}

For example:
type A = { a: string }
type B = { b: number }
type NotNormalized = A & B // inferred type: A & B
type Normalized = Normalize<NotNormalized> // inferred type: { a: string, b: number }

The type Normalize<User> should show you the normalized User type on hover. Other versions of Normalize (often called Expand) are possible, depending whether you want to normalize only the top level or recursively, and whether you need to deal with function properties.
TypeScript playground


text:
Q: same variable referenced when creating variable Still fairly new to using Powershell variables and got a bit confused trying to understand it's syntax and functionality.
On Azure's documentation on creating a new VM, it declares the $VM variable, then uses that same variable within the next variable creation:
$vm = Set-AzureRmVMOperatingSystem -VM $vm -Windows -ComputerName myVM -Credential $cred -ProvisionVMAgent -EnableAutoUpdate
$vm = Set-AzureRmVMSourceImage -VM $vm -PublisherName MicrosoftWindowsServer -Offer WindowsServer -Skus 2016-Datacenter -Version latest
$vm = Set-AzureRmVMOSDisk -VM $vm -Name myOsDisk -DiskSizeInGB 128 -CreateOption FromImage -Caching ReadWrite

What I'm stuck on is what's going on behind the scenes when creating variables in this fashion.  Is the $vm variable being overwritten each time?  If I 'run' $vm on the powershell console at a later time, will it be able to run this sequence or will it throw an error since the first 2 instances of $vm are no longer around?
Thanks!

A: It is updating it with each subsequent call.
The $vm is created with something like:
$vm = New-AzureRmVMConfig ...

and updated with the other calls like:
$vm = Set-AzureRmVMOSDisk -VM $vm ...
$vm = Add-AzureRmVMNetworkInterface -VM $vm ...
$vm = Set-AzureRmVMBootDiagnostics -VM $vm ...

As long as you do not overwrite it somewhere else, you can use it wherever you like later in your script.

A:
Is the $vm variable being overwritten each time?

$vm have many attributs, each Azure powershell will add some information (not the same) to it, so the variable $vm will not being overwritten.
You can print it like this:
PS C:\windows\system32> $vm = New-AzureRmVMConfig -VMName myVM -VMSize Standard_D1
PS C:\windows\system32> $vm | fl *

ResourceGroupName        :
Id                       :
VmId                     :
Name                     : myVM
Type                     :
Location                 :
LicenseType              :
Tags                     :
AvailabilitySetReference :
DiagnosticsProfile       :
Extensions               :
HardwareProfile          : Microsoft.Azure.Management.Compute.Models.HardwareProfile
InstanceView             :
NetworkProfile           :
OSProfile                :
Plan                     :
ProvisioningState        :
StorageProfile           :
DisplayHint              : Compact
Identity                 :
Zones                    :
FullyQualifiedDomainName :
RequestId                :
StatusCode               : 0

Then use run other commands will add some information to it.
Hope this helps.

A: Each command that you show outputs an Azure Virtual Machine object. When you precede the command with $vm = that variable is assigned to the output of the command issued. You can use any variable (excluding a few special reserved variables) that you want. You could just as easily use $FileServer = instead of $vm = and it would work just the same, so long as you then refer to $FileServer any time that you would have referred to $vm.
The original command $vm = New-AzureRmVMConfig creates the original Azure Virtual Machine object that is captured by the variable $vm. Each successive command modifies that object, and outputs the modified version of the object. Since you capture the output each time you are indeed overwriting the variable each time, and each time it is essentially a slightly modified version of itself.
Just as you can use any variable you want, you do not need to re-use the same variable, and could use a new variable each time like:
$BaseVM = New-AzureRmVMConfig -VMName myVM -VMSize Standard_D1
$VMOS = Set-AzureRmVMOperatingSystem -VM $BaseVM -Windows -ComputerName myVM  -Credential $cred -ProvisionVMAgent -EnableAutoUpdate
$VMImage = Set-AzureRmVMSourceImage -VM $VMOS -PublisherName MicrosoftWindowsServer -Offer WindowsServer -Skus 2016-Datacenter -Version latest
$VMOSDisk = Set-AzureRmVMOSDisk -VM $VMImage -Name myOsDisk -DiskSizeInGB 128 -CreateOption FromImage -Caching ReadWrite

Then at the end you can reference $VMOSDisk to see your VM with all of the modifications applied, and even reference it against $BaseVM to see what all has changed since you initially declared the object.


text:
Q: The line is too high from the source to the destination point in Cesium In Cesium, I created an animation line which travels from the source to the destination point. I created 3 entities which are source, destination point and animation line. When I run the html file, the line is somewhat too high. Let me show you an image below.

Here is my code below.
<!DOCTYPE html>

  <meta charset="utf-8">

  <meta http-equiv="X-UA-Compatible" content="IE=edge">

  <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no">
  <title>Hello World!</title>

Can you help me?


text:
Q: Ошибка при скачивании toga python Я хочу попробовать сделать приложение на BeeWare. Однако там нужна библиотека toga, а я не могу скачать - выдаёт данную ошибку, когда я пишу pip install toga. Python у меня версии 3.10.

Помогите решить пожалуйста.


text:
Q: Function with 2 variables within a domain I have the following problem.
Find the maximum and minimum of the following function:
$$x^2 + y^2 - 4x - 2y +4$$
within the range $$x^2 + y^2 ≤ 16$$
I have ofcourse attempted this question myself. I have managed to find the minimum value. I did this by taking the derivative of the function two times, once with respect to x and once with respect to y. This gave me the point (2,1) and after substituting it back in the function gave the minimum value of -1.
Now i am trying to calculate the maximum value of the maximum value of the function which i think we can find by looking at the boundary values, x^2 + y^2 ≤ 16.
I have tried two things and still get the incorrect answer.
Attempt 1:
Substituting $$x = 4cost$$, $$y = 4sint$$.
$$16cos^2(t) + 16sin^2(t) - 4*4cost(t) - 2*4sin(t) + 4$$
$$16(cos^2(t) + sin^2(t)) - 16cos(t) - 8 sin(t) + 4$$
$$16 - 16cos(t) - 8sin(t) + 4$$
$$20 - 16cos(t) - 8sin(t)$$
By looking at the last line here, we can see that the maximum is when t = pi. This will cos(t) = -1 and sin(t) = 0
20 - 16cos(t) - 8sin(t) = 20 + 16 - 0 = 36. However 36 is incorrect and i dont understand why.
Attempt 2:
$$x^2 + y^2 ≤ 16$$
$$x^2 + y^2 = 16$$
$$y = sqrt(16-x^2)$$
Substituting this into the original equation gives:
$$x^2 + (16-x^2) - 4x - 2sqrt(16-x^2) +4$$
$$20 - 2sqrt(16-x^2) - 4x$$
By looking at this equation we can see that the maximum value is when 2sqrt(16-x^2) is 0. This happens when x = 4.
$$20 - 2sqrt(16-(4)^2) -4(4)$$
$$20 - 0 - 16 = 4$$
4 is also incorrect.
Can anyone help me with this question. I would also like to understand why I cant solve the question in the way i have attempted.
Thank you for your time. Please tell me if something was unclear.

A: Don't leave geometric intuition by the wayside. After completing the squares to get
$$f(x,y)=(x-2)^2+(y-1)^2-1$$
we see that the value of $f(x,y)$ is simply the squared distance from $(x,y)$ to $(2,1)$, minus one.
To find the maximum, we must therefore look for the point in your domain that is farthest from $(2,1)$. That's the one on the opposite end of the diameter through $(2,1)$, and its distance from $(2,1)$ is
$$ 4 + \sqrt{2^2+1^2} $$
The square of this distance is
$$ 16 + 5 + 8\sqrt5 $$
so the maximum function value is
$$ 20 + 8\sqrt5 $$

In your attempt 1, you're wrong when you claim that the maximum of $20-16\cos t-8\sin t$ is at $t=\pi$. Consider that at that point the derivative of the cosine is $0$, so a small change in $t$ does not affect that term -- the derivative of the sine is $-1$, so a $t$ slightly larger than $\pi$ will lead to a higher value for the function. So we didn't have a maximum at $t=\pi$.
In your attempt 2, I don't get at all how you conclude that " the maximum value is when $2\sqrt{16-x^2}$ is $0$".

A: Note that your $f(x,y)$ is equal to $$f(x,y)=(x-2)^2+(y-1)^2-1$$ and from here we get
$$f_{min}=-1$$ for $y=2,x=1$


text:
Q: How to update or refresh the Remove Object at index in IOS? For this scenario I created two buttons add row(UI) and delete row(programatically).If i press add row button programatically created text boxes and delete button gets iterate.While pressing delete button it deletes the entire row.Please take a look at below Images.

first Image is about the default showing of programatically created text boxes,add row(created via UI) and delete buttons.

second Image is about the add row button.If i pressed add row button text box and delete button gets iterated.

Third Image is about values entering into text box manually.

Fourth Image is about.I entered value 1 in the first text box and press delete button.then entire row gets deleted.

Fifth Image is about after I press add row button from the fourth link or screen shot,the first text box should be empty(what I am expecting) .But it fills with the value 1.
My piece of code for creating delete button and text boxes inside the cellForRowAtIndexPath method:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// table view created via storyboard.
if (tableView == self.tblview)
{
// create a delete button dynamically
UIButton *delete = [UIButton buttonWithType:UIButtonTypeRoundedRect];
delete.frame = CGRectMake(525.0f, 5.0f, 75.0f, 30.0f);
[delete setTitle:@"Delete" forState:UIControlStateNormal];
[cell addSubview:delete];
[delete addTarget:selfaction:@selector(deleterow:)forControlEvents:UIControlEventTouchUpInside];
[delete setTag:indexPath.row];

//dynamically created text fields.
UITextField *txtvalue =  [[UITextField alloc] init];
}
}

Method or Action delete row: this action performs the deletion of entire row by removeObjectAtIndex and del row defines which row.
- (IBAction)deleterow:(id)sender
{
UIButton * delete = (UIButton *) sender;
// del row defines the which row of the delete tag has been pressed.
NSInteger delRow = delete.tag;
[self.Array removeObjectAtIndex:delRow];
[self.tblview reloadData];
}

Action Add row:
- (IBAction)addRow:(id)sender
{
[self Data:[self.Array count]];
[self.tblview reloadData];
}

Where Array is the mutable array.I found out no issue with the add row  button. Then i tried something using retain syntax inside delete row action.But it doesn't works.How to rectify this issue.Please,Thanks in Advance.
The Delete row action performs the following things:
when I put the logger before the self.array it shows the values like this:
(
{
"2016-01-31" = 1;
"2016-02-01" = "";
"2016-02-02" = "";
"2016-02-03" = "";
"2016-02-04" = "";
"2016-02-05" = "";
"2016-02-06" = "";
A = x;
b = x;
C = "";
D = "";
E = "";
F = "";
G = "RED";
H = 8;
}
)

After that delete operation takes place.Before that,Is it possible to change the "2016-01-31" = 1; to  "2016-01-31" = "";In the mutable array.It's the right solution or else any other options?

A: Cells in table views are reused. With this in mind, in Cocoa's Model-View-Controller pattern, you should make sure that these cells (the "view" of Model-View-Controller) have some place to store the values as the user types them (the "model") and the view controller (the "controller") will facilitate the updating of the model as you add, delete and update rows, as well as making sure that cellForRowAtIndexPath sets the contents of those seven text fields based upon the values in your model.
But your code snippets doesn't contemplate any model (or, if this self.Array is supposed to be the model, you don't appear to do anything to (a) save the values as the user types them; nor (b) load the cell with the the values from the model when you call cellForRowAtIndexPath). As a result, when a cell is reused, whatever values that were in those text fields last may appear in those cells.

By way of example, let's imagine that I have cell prototype linked to a cell subclass that has the seven outlets for the seven labels:
@interface CustomCell : UITableViewCell

@property (weak, nonatomic) IBOutlet UITextField *textField1;
@property (weak, nonatomic) IBOutlet UITextField *textField2;
@property (weak, nonatomic) IBOutlet UITextField *textField3;
@property (weak, nonatomic) IBOutlet UITextField *textField4;
@property (weak, nonatomic) IBOutlet UITextField *textField5;
@property (weak, nonatomic) IBOutlet UITextField *textField6;
@property (weak, nonatomic) IBOutlet UITextField *textField7;

@end

@implementation CustomCell

// this is intentionally blank

@end

And then my view controller (a) populates model structure as you add rows; (b) updates model as rows are updated; and (c) removes entry from model when rows are deleted. Note, I didn't know what your model object was, but as it seemed to have seven small text fields, I assumed it might be a "phone number". If not, rename that model object to whatever is appropriate for your case.
//  ViewController.m

#import "ViewController.h"
#import "CustomCell.h"

/// Phone number model object

@interface PhoneNumber : NSObject

@property (nonatomic, strong) NSString *digit1;
@property (nonatomic, strong) NSString *digit2;
@property (nonatomic, strong) NSString *digit3;
@property (nonatomic, strong) NSString *digit4;
@property (nonatomic, strong) NSString *digit5;
@property (nonatomic, strong) NSString *digit6;
@property (nonatomic, strong) NSString *digit7;
@end

@implementation PhoneNumber

// this is intentionally blank

@end

@interface ViewController ()

/// An array of model objects

@property (nonatomic, strong) NSMutableArray<PhoneNumber *> *phoneNumbers;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    // initialize that array
    self.phoneNumbers = [NSMutableArray array];
}

// return the number of items in our array of model objects

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.phoneNumbers.count;
}

// when I populate cell, make sure to populate the seven text fields on the basis of the corresponding model object

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    PhoneNumber *number = self.phoneNumbers[indexPath.row];

    cell.textField1.text = number.digit1;
    cell.textField2.text = number.digit2;
    cell.textField3.text = number.digit3;
    cell.textField4.text = number.digit4;
    cell.textField5.text = number.digit5;
    cell.textField6.text = number.digit6;
    cell.textField7.text = number.digit7;

    return cell;
}

// I hooked up "editing change" action in the seven text fields to this method in the view controller
// which updates the model

- (IBAction)didEditingChangeTextField:(UITextField *)sender {
    CustomCell *cell = (id)[[sender superview] superview];
    NSAssert([cell isKindOfClass:[CustomCell class]], @"%@ is not CustomCell", sender);

    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    NSAssert(indexPath, @"did not find indexPath");

    PhoneNumber *phoneNumber = self.phoneNumbers[indexPath.row];

    if (sender == cell.textField1)
        phoneNumber.digit1 = sender.text;
    else if (sender == cell.textField2)
        phoneNumber.digit2 = sender.text;
    else if (sender == cell.textField3)
        phoneNumber.digit3 = sender.text;
    else if (sender == cell.textField4)
        phoneNumber.digit4 = sender.text;
    else if (sender == cell.textField5)
        phoneNumber.digit5 = sender.text;
    else if (sender == cell.textField6)
        phoneNumber.digit6 = sender.text;
    else if (sender == cell.textField7)
        phoneNumber.digit7 = sender.text;
}

// when I delete row, just delete from model object from array and then tell tableview to remove that row

- (IBAction)didTapDeleteButton:(UIButton *)sender {
    CustomCell *cell = (id)[[sender superview] superview];
    NSAssert([cell isKindOfClass:[CustomCell class]], @"%@ is not CustomCell", sender);

    NSIndexPath *indexPath = [self.tableView indexPathForCell:cell];
    NSAssert(indexPath, @"did not find indexPath");

    [self.phoneNumbers removeObjectAtIndex:indexPath.row];
    [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationMiddle];
}

// when I add row, just add to model collection and then tell table view to add that row

- (IBAction)didTapAddButton:(UIBarButtonItem *)sender {
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:self.phoneNumbers.count inSection:0];
    [self.phoneNumbers addObject:[[PhoneNumber alloc] init]];
    [self.tableView insertRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationTop];
}

@end


text:
Q: Unifying function exits with LLVM Let's say I have this function in C/C++:
int foo(int x) {

    if (x <= 1) return 1;
    return x * foo(x-1);
}

And I compile it with Clang.
Clang generates the following IR:
; Function Attrs: ssp uwtable
define i32 @_Z3fooi(i32 %x) #0 {
  %1 = alloca i32, align 4
  %2 = alloca i32, align 4
  store i32 %x, i32* %2, align 4
  %3 = load i32, i32* %2, align 4
  %4 = icmp sle i32 %3, 1
  br i1 %4, label %5, label %6

; <label>:5                                       ; preds = %0
  store i32 1, i32* %1, align 4
  br label %12

; <label>:6                                       ; preds = %0
  %7 = load i32, i32* %2, align 4
  %8 = load i32, i32* %2, align 4
  %9 = sub nsw i32 %8, 1
  %10 = call i32 @_Z3fooi(i32 %9)
  %11 = mul nsw i32 %7, %10
  store i32 %11, i32* %1, align 4
  br label %12

; <label>:12                                      ; preds = %6, %5
  %13 = load i32, i32* %1, align 4
  ret i32 %13
}

As you can see, LLVM passes optimizes out the code and creates a "return register" (where I put the return value), and a "return block" (where the return value is effectively returned).
I'm trying to get the same effect, but when I use SROA pass or the Instruction Combining pass, they translate the exits in a phi instruction:
; Function Attrs: nounwind ssp uwtable
define i32 @__HF3fooTi(i32 %x) #0 {
  %1 = icmp sle i32 %x, 1
  br i1 %1, label %2, label %3

; <label>:2                                       ; preds = %0
  br label %7

; <label>:3                                       ; preds = %0
  %4 = sub nsw i32 %x, 1
  %5 = call i32 @__HF3fooTi(i32 %4)
  %6 = mul nsw i32 %x, %5
  br label %7

; <label>:7                                       ; preds = %3, %2
  %.0 = phi i32 [ 1, %2 ], [ %6, %3 ]
  ret i32 %.0
}

My question is: which solution is faster? And which pass is Clang using to achieve this? (In the Clang source files I found the 2 passes I used, and they give me this different result)