text:
Q: Замена входящих данных с сохранением нужных Возникла такая проблема, что при обработке текста мне нужно заменить везде где присутствует некий код, например:
Текст[img|http://img.img/]Текст2[img|http://img2.img2]

нужно заменить везде на  и со вторым аналогично. У меня есть код, который вполне работает, но работает он правильно только тогда, когда принимает только одну строку [img], а другая не обрабатывается. Вот код:
$patternImg = '/\[(img)\|(.*)\]/i';
$replacementImg = '';
$text = preg_replace($patternImg, $replacementImg, $text);

Как правильно решить эту задачу уже не знаю :(
 Буду признателен за объяснения и помощь в решении данной проблемы.

A: В круглые скобки вашего шаблона нужно добавить квантификатор ?:
$text = 'Текст[img|http://img.img/]Текст2[img|http://img2.img2]';

$patternImg = '~\[img\|(.*?)\]~i';
$replacementImg = '';
$text = preg_replace($patternImg, $replacementImg, $text);

var_dump($text);

Результат:
ТекстТекст2


text:
Q: How can I make a case-insensitive compare with expl3? I am in the process of writing a macro which takes a 4 digit hex value and does something based on the input. I want to achieve, that a user can use uppercase or lowercase characters for the hex code. What already works is:
\documentclass{article}
\usepackage{expl3,xparse}
\ExplSyntaxOn
\NewDocumentCommand{\actionForHEX}{m}{%
    \str_case:nnF {#1}
    {
        {E085} {This is E085}
        {E086} {This is E086}
    }
    {Unknown}
}
\ExplSyntaxOff

\begin{document}
Works: \actionForHEX{E085}

Does not work: \actionForHEX{e085}
\end{document}

So in principal I can define actions, but I do not understand the use of \str_flipcase:n to allow the case to work for lowercase as well.
Based on Expandable case insensitive switch case for string comparison I tried something, but this had no success at all:
\ExplSyntaxOn
\NewDocumentCommand{\actionForHEX}{m}{%
    \str_case_e:nn { \str_foldcase:e { #1 } }
    {
        {E085} {This is E085}
        {E086} {This is E086}
    }
}
\ExplSyntaxOff

Ok, based on your input I tried my luck again, but it seems I still don't understand something. This is my new approach:
\documentclass{article}

\usepackage{expl3,xparse}

\ExplSyntaxOn
\NewDocumentCommand{\actionForHEX}{m}{%
    \str_case:nnF { \str_foldcase:n { #1 } }
    {
        {e085} {This~is~E085}
        {e086} {This~is~E086}
    }
    {Cannot~find~it}
}
\ExplSyntaxOff

\begin{document}
Does not work: \actionForHEX{E085}

Does not work: \actionForHEX{e085}
\end{document}

This results in Canot find it for both calls of \actionForHEX

A: As explained in the comments by cgnieder you need to compare against e085 and e086, respectively, since you are comparing against the case-folded input (\str_foldcase:n { #1 }). Broadly speaking, case folding is based on lowercase, so the input E085 gets folded into e085 and that's what you need to compare against.
Because we apply a macro to the input, we can't directly compare the strings with as normal n arguments. We need to make sure that \str_foldcase:n { #1 } is expanded first.
This can be done as in Skillmon likes topanswers.xyz's answer to Expandable case insensitive switch case for string comparison with \str_case_e:nn
\ExplSyntaxOn
\NewDocumentCommand{\actionForHEX}{m}{%
  \str_case_e:nn { \str_foldcase:n { #1 } }
    {
        {e085} {This~is~E085}
        {e086} {This~is~E086}
    }
}
\ExplSyntaxOff

That command will fully expand all involved strings with the new e-type expansion. (So \str_foldcase:n { #1 } is expanded, which is nice. And e085 and e086 are expanded as well, which is a bit pointless).
We can avoid the the expansion of e085 and e086 by generating the en-variant of \str_case:nn, which only expands \str_foldcase:n { #1 }
\ExplSyntaxOn
\cs_generate_variant:Nn \str_case:nn { e }

\NewDocumentCommand{\actionForHEX}{m}{%
  \str_case:en { \str_foldcase:n { #1 } }
    {
        {e085} {This~is~E085}
        {e086} {This~is~E086}
    }
}
\ExplSyntaxOff

If you are using an old system where e-type expansion is not available, you can try x-type expansion.
\documentclass{article}
\usepackage{expl3,xparse}

\ExplSyntaxOn
\cs_generate_variant:Nn \str_case:nn { x }

\NewDocumentCommand{\actionForHEX}{m}{%
  \str_case:xn { \str_foldcase:n { #1 } }
    {
        {e085} {This~is~E085}
        {e086} {This~is~E086}
    }
}
\ExplSyntaxOff

\begin{document}
\actionForHEX{E085}

\actionForHEX{e085}

\actionForHEX{E086}

\actionForHEX{e086}
\end{document}

On older systems \str_fold_case:n (introduced before November 2016, see l3news10) may work instead of \str_foldcase:n (which replaced \str_fold_case on 2019-11-26).

If you want to include an F non-matching branch at the end, it is better to generate the variants with \prg_generate_conditional_variant:Nnn (thanks to Phelype Oleinik for explaining that in the comments). For e-type expansion that would look as follows
\documentclass{article}
\usepackage{expl3,xparse}

\ExplSyntaxOn
\prg_generate_conditional_variant:Nnn \str_case:nn { e } { F }

\NewDocumentCommand{\actionForHEX}{m}{%
  \str_case:enF { \str_foldcase:n { #1 } }
    {
        {e085} {This~is~E085}
        {e086} {This~is~E086}
    }
    {Not~matched}
}
\ExplSyntaxOff

\begin{document}
\actionForHEX{E085}

\actionForHEX{e085}

\actionForHEX{E086}

\actionForHEX{e086}

\actionForHEX{E087}
\end{document}

It would be analogous for x-type expansion (and possibly \str_fold_case:n on older systems).

redpajama_set_name: RedPajamaStackExchange


text:
Q: Conversion of JSON to Avro failed: Failed to convert JSON to Avro: Unknown union branch I am trying to send a JSON message to a Kafka topic using Kafka-rest service to serialize JSON as an Avro object, but the JSON message is failed to get accepted by Kafka-rest with the following error:
Conversion of JSON to Avro failed: Failed to convert JSON to Avro: Unknown union branch postId

I suspect that there is an issue with the Avro schema I am using as it is a nested record type with nullable fields.
Avro schema:
{
  "type": "record",
  "name": "ExportRequest",
  "namespace": "com.example.avro.model",
  "fields": [
    {
      "name": "context",
      "type": {
        "type": "map",
        "values": {
          "type": "string",
          "avro.java.string": "String"
        },
        "avro.java.string": "String"
      }
    },
    {
      "name": "exportInfo",
      "type": {
        "type": "record",
        "name": "ExportInfo",
        "fields": [
          {
            "name": "exportId",
            "type": {
              "type": "string",
              "avro.java.string": "String"
            }
          },
          {
            "name": "exportType",
            "type": {
              "type": "string",
              "avro.java.string": "String"
            }
          },
          {
            "name": "exportQuery",
            "type": {
              "type": "record",
              "name": "ExportQuery",
              "fields": [
                {
                  "name": "postExport",
                  "type": [
                    "null",
                    {
                      "type": "record",
                      "name": "PostExport",
                      "fields": [
                        {
                          "name": "postId",
                          "type": {
                            "type": "string",
                            "avro.java.string": "String"
                          }
                        },
                        {
                          "name": "isCommentIncluded",
                          "type": "boolean"
                        }
                      ]
                    }
                  ],
                  "default": null
                },
                {
                  "name": "feedExport",
                  "type": [
                    "null",
                    {
                      "type": "record",
                      "name": "FeedExport",
                      "fields": [
                        {
                          "name": "accounts",
                          "type": {
                            "type": "array",
                            "items": {
                              "type": "string",
                              "avro.java.string": "String"
                            }
                          }
                        },
                        {
                          "name": "recordTypes",
                          "type": {
                            "type": "array",
                            "items": {
                              "type": "string",
                              "avro.java.string": "String"
                            }
                          }
                        },
                        {
                          "name": "actions",
                          "type": {
                            "type": "array",
                            "items": {
                              "type": "string",
                              "avro.java.string": "String"
                            }
                          }
                        },
                        {
                          "name": "contentTypes",
                          "type": {
                            "type": "array",
                            "items": {
                              "type": "string",
                              "avro.java.string": "String"
                            }
                          }
                        },
                        {
                          "name": "startDate",
                          "type": "long"
                        },
                        {
                          "name": "endDate",
                          "type": "long"
                        },
                        {
                          "name": "advancedSearch",
                          "type": [
                            "null",
                            {
                              "type": "record",
                              "name": "AdvancedSearchExport",
                              "fields": [
                                {
                                  "name": "allOfTheWords",
                                  "type": {
                                    "type": "array",
                                    "items": {
                                      "type": "string",
                                      "avro.java.string": "String"
                                    }
                                  }
                                },
                                {
                                  "name": "anyOfTheWords",
                                  "type": {
                                    "type": "array",
                                    "items": {
                                      "type": "string",
                                      "avro.java.string": "String"
                                    }
                                  }
                                },
                                {
                                  "name": "noneOfTheWords",
                                  "type": {
                                    "type": "array",
                                    "items": {
                                      "type": "string",
                                      "avro.java.string": "String"
                                    }
                                  }
                                },
                                {
                                  "name": "hashtags",
                                  "type": {
                                    "type": "array",
                                    "items": {
                                      "type": "string",
                                      "avro.java.string": "String"
                                    }
                                  }
                                },
                                {
                                  "name": "keyword",
                                  "type": {
                                    "type": "string",
                                    "avro.java.string": "String"
                                  }
                                },
                                {
                                  "name": "exactPhrase",
                                  "type": {
                                    "type": "string",
                                    "avro.java.string": "String"
                                  }
                                }
                              ]
                            }
                          ],
                          "default": null
                        }
                      ]
                    }
                  ],
                  "default": null
                }
              ]
            }
          }
        ]
      }
    }
  ]
}

Json message:
   {
        "context": {
            "user_id": "1",
            "group_id": "1",
            "organization_id": "1"
        },
        "exportInfo": {
            "exportId": "93874dd7-35d7-4f1f-8cf8-051c606d920b",
            "exportType": "json",
            "exportQuery": {
                "postExport": {
                    "postId": "dd",
                    "isCommentIncluded": false
                },
                "feedExport": {
                    "accounts": [
                        "1677143852565319"
                    ],
                    "recordTypes": [],
                    "actions": [],
                    "contentTypes": [],
                    "startDate": 0,
                    "endDate": 0,
                    "advancedSearch": {
                        "allOfTheWords": [
                            "string"
                        ],
                        "anyOfTheWords": [
                            "string"
                        ],
                        "noneOfTheWords": [
                            "string"
                        ],
                        "hashtags": [
                            "string"
                        ],
                        "keyword": "string",
                        "exactPhrase": "string"
                    }
                }
            }
        }
    }

I would appreciate it if someone could help me to understand what the issue is.

A: Both of your JSON and Avro looks good.
You are facing the issue because JSON doesn't conform to Avro's JSON encoding spec.
So, if you convert your JSON accordingly, it will somehow look like this
{
  "context": {
    "user_id": "1",
    "group_id": "1",
    "organization_id": "1"
  },
  "exportInfo": {
    "exportId": "93874dd7-35d7-4f1f-8cf8-051c606d920b",
    "exportType": "json",
    "exportQuery": {
      "postExport": {
        "com.example.avro.model.PostExport": {
          "postId": "dd",
          "isCommentIncluded": false
        }
      },
      "feedExport": {
        "com.example.avro.model.FeedExport": {
          "accounts": [
            "1677143852565319"
          ],
          "recordTypes": [],
          "actions": [],
          "contentTypes": [],
          "startDate": 0,
          "endDate": 0,
          "advancedSearch": {
            "com.example.avro.model.AdvancedSearchExport": {
              "allOfTheWords": [
                "string"
              ],
              "anyOfTheWords": [
                "string"
              ],
              "noneOfTheWords": [
                "string"
              ],
              "hashtags": [
                "string"
              ],
              "keyword": "string",
              "exactPhrase": "string"
            }
          }
        }
      }
    }
  }
}


text:
Q: Magento 2 order shipment tracking details How to get tracking information from order shipment in magento 2?

A: You can get all tracking details using this code :
$tracksCollection = $order->getTracksCollection();

foreach ($tracksCollection->getItems() as $track) {

     echo $track->getTrackNumber(); // Tracking number
     // You can get other details here.

}


text:
Q: Static extension methods and Project Roslyn It has been noted here (and quite rightly so) that extension methods in .NET are just syntactic sugar for static method calls on instance variables.
However in relation to this question, I am wondering why extension methods for static access were omitted from the language specification?
As well as being a .NET (C#) developer, I am also a JavaScript developer, and you can model the equivalent of static method extensions in JavaScript - Hence my reasoning for delving a little deeper into this argument. (I am well aware that .NET and JavaScript are two exceptionally different languages!)
Let's examine the syntax for an extension method and how it compiles:
public static string Hash(this string value)
{
    // some logic here...
}

string x = "Hello World";

x.Hash();

compiles to
public static string Hash(string value)
{
    // some logic here...
}

string x = "Hello World";

Hash(x);

If you try to create a variable for a static type
class MyClass
{
    Console c; // error!
}

You can't!
If you try to pass a static type as a method parameter
public void DoThis(Console c) // error!
{
}

You can't!
So this defines the limitation of the language specification however in terms of an extension method, I can see the implementation being something along these lines...
public static void WriteLineInGreen(static Console c, string formatString, params object[] args)
{
    c.ForeGround = ConsoleColor.Green;
    c.WriteLine(formatString, args);
}

Console.WriteLineInGreen("Hello World {0}, {1}, {2}", ":-)", 1234, true);

Okay, it's not possible...why am I STILL asking? Answer..."Project Roslyn". Do you think this is something we might see along with all of the other language specification changes that will be implemented in Project Roslyn?
EDIT Anyone with any interest in Roslyn language extensions should watch this: https://channel9.msdn.com/Events/Build/2014/2-577

A: You cannot create an instance of a static type. var c = new Console(); does not work. Therefore, you cannot have an argument with a static type. In Console c, what would c be? The syntax of your proposed static type extension method would have to be something like this:
public static void WriteLineInGreen(static Console, string formatString,
                                    params object[] args)
{
    Console.ForeGround = ConsoleColor.Green;
    Console.WriteLine(formatString, args);
}

I think that the language specification changes related to Roslyn are due to the fact that language specification inconsistencies and inaccuracies have been found while working on Roslyn. It seems not very plausible to me that any new C# language features are related to Roslyn.
Update: Well, I was wrong on this last point. As @svick points out in his comment, the much better structure of the new compiler makes it easier to implement language changes.
Another important reason is that the language and compiler development has become open source. Microsoft invites the community to participate. (See: C# 7 Work List of Features.)


text:
Q: Confusion in creating table design I am using Mysql and I have two tables-
BusDetails
    +-------+-----------+
    | busId | BusName   |
    +-------+-----------+
    | 1     | A TRAVELS |
    | 2     | B TRAVELS |
    | 3     | C TRAVELS |
    +-------+-----------+

AreaDetails
+--------+----------+
| cityId | cityName |
+--------+----------+
| 1      | ABC      |
| 2      | DEF      |
| 3      | GHI      |
| 4      | JKL      |
+--------+----------+

Now I have to create third table which will map bus table to city table. Suppose busId 1 stops at cityId 2 and 3 and bustId 2 stops at cityId 1 and 4. To create this scenario I have 2 options-
first option-
+-------+--------+
| busId | areaId |
+-------+--------+
| 1     | 3,2    |
| 2     | 4,1    |
+-------+--------+

second option-
+-------+--------+
| busId | areaId |
+-------+--------+
| 1     | 2      |
| 1     | 3      |
| 2     | 1      |
| 2     | 4      |
+-------+--------+

In future when there will be large number of records then which table will give better performance and why ?

A: The first option is poor because comma-separated lists do not get indexed. If you want to find all the busses in area 2, you would have to use
SELECT busID
FROM bus_areas
WHERE FIND_IN_SET('2', areaID)

This will have to perform a full table scan, parse the areaID column on each row, and test whether 2 is a member of the resulting array.
With the second version you can do:
SELECT busID
FROM bus_areas
WHERE areaID = 2

If you have an index on areaID, this will be extremely efficient.
If you wanted to know how many busses are in each area, it's easy with the second option:
SELECT areaID, COUNT(*)
FROM bus_areas
GROUP BY areaID

With the first option it would be more cumbersome:
SELECT cityID, COUNT(*)
FROM areaDetails a
JOIN bus_areas ba ON FIND_IN_SET(a.cityID, ba.areaID)
GROUP BY cityID

This will be very inefficient because it has to perform M*N FIND_IN_SET operations, and as I explained above this cannot be indexed. Notice that I had to join with the areaDetails table because there's no way to enumerate all the areas in the comma-separated lists in SQL.

A: The answer depends upon your use.
Although first option is not recommended but if you have very large data and you are not planning to perform wide range of Database operations (probably for self or small project) you can use it.
Second options has it's own advantage and recommended by relational model. It will give you more flexibility and scalability as this minimize redundancy.

A: Dear Second Table Is Better For All Reason Baecause At long time you have big data second type in save so many rows but better for getting report easy in easy for SQL query easy. you can all type join easy.


text:
Q: How do I prevent ShowDialog from stealing focus from other applications? In my application, the ShowDialog() method of a custom form is called after some work is done. The problem is that if the user switches to another application while my application is doing its work, the dialog steals focus to that application, and this can lead to unpredictable behavior. The expected behavior would be the dialog showing in my application foreground, but not on top of another application, and have my application's Taskbar item to blink.
Is there a way to prevent the ShowDialog() method from stealing focus? Or should I use another approach?

A: Use Form.ShowWithoutActivation property (override it in your class to return true). This way you can still use ShowDialog().
MSDN article

A: In C#, you use ShowDialog() to show a form stealing focus as you say. And Show() to show without stealing focus. I'm not sure if it's the same in VB.NET.

A: You can set the property
me.TopMost = false

Link

A: If you really want this you probably have to use Show.  Keep your own property on the form
DialogResult Result;
Probably default it to cancel so if the form is closed it will be treated as a cancel.  Then you only need to set it when the user clicks OK.


text:
Q: Где тут ошибка? У меня на сервере не работал код, я засунул его в компилятор. Компилятор говорит что надо убрать точку с запятой вот тут: $file = 'Data/Users/'.$_COOKIE['id'].'/img.txt';
Вот полная версия неработуещего отрывка:
if (move_uploaded_file($_FILES['filename']['tmp_name'], 'Data/Users/'.$_COOKIE['id'].'/'.$_FILES['filename']['name']) {
$file = 'Data/Users/'.$_COOKIE['id'].'/img.txt';
$f = fopen($file, 'w');
fwrite($f, $_FILES['filename']['name']);
fclose($f);
}

A: if (move_uploaded_file($_FILES['filename']['tmp_name'], 'Data/Users/' . $_COOKIE['id'] . '/' . $_FILES['filename']['name'])) {
    $file = 'Data/Users/' . $_COOKIE['id'] . '/img.txt';
    $f = fopen($file, 'w');
    fwrite($f, $_FILES['filename']['name']);
    fclose($f);
}

Закрывающая скобка ) для if в самой первой строке
Используйте стоящие IDE (программа где вы пишите) для предотвращения подобных ошибок, они очень помогают


text:
Q: Aliases on guest machine with Ansible I want to add some aliases on a guest machine running through Vagrant. My provisioner is Ansible, and it would be great if I can add the aliases with a task on the playbook, I would prefer not having to modify my Vagrantfile.
I have tried both these in a role:
command: alias serve='pub serve --hostname=0.0.0.0'
shell: "alias serve='pub serve --hostname=0.0.0.0'"
but none of them has worked. The first raises an exception which I think comes from the ''. The second one simply doesn't add the alias.

A: The shell option looks right but it will only create the alias for the session. Then when you connect to it after the provisioning then it won't exist. I'm also unsure if further plays in the playbook will be able to use it as they may use another SSH session.
To add it permanently you will need to add it to the relevant .bashrc or .bash_aliases (which is then sourced by .bashrc) depending on your Linux flavour/version.
To do this you could simply use:
shell: echo "alias serve='pub serve --hostname=0.0.0.0'" >> ~/.bash_aliases

But this would not be idempotent and rerunning the Ansible playbook or the Vagrant provisioning (which would rerun the Ansible playbook) would add duplicate lines each time.
Instead you should use the lineinfile module with something like:
- name: Add serve alias for foo user
  lineinfile:
    path=/home/foo/.bashrc
    line="alias serve='pub serve --hostname=0.0.0.0'"
    owner=foo
    regexp='^alias serve='pub serve --hostname=0.0.0.0'$'
    state=present
    insertafter=EOF
    create=True

The above play will add the alias line to the end of the foo user's .bashrc file (creating the file if it doesn't exist for some reason). When you rerun it, it attempts to match the regexp value (this might need tweaking with escaping parts) and if it matches it then it will replace it with the line value.

A: Thanks to this answer by , After you add alias line by:
- name: Add serve alias for foo user
  lineinfile:
    path=/home/foo/.bashrc
    line="alias serve='pub serve --hostname=0.0.0.0'"
    owner=foo
    regexp='^alias serve='pub serve --hostname=0.0.0.0'$'
    state=present
    insertafter=EOF
    create=True

You need to source the file also:
- name: Source .bashrc
  shell: "source /home/foo/.bashrc"
  args:
    executable: /bin/bash


text:
Q: R individual pca scores different than SAS and SPSS when scale is applied I had previously posted this as a question to my original question regarding scaling but this was deemed inappropriate and deleted with a request to submit as a new question, so here we are!
Myself and my colleagues were performing PCA using r (prcomp), SAS, and SPSS. We all used scale and centering. All three produced the same variable/factor loading (different terminology between programs). No issue there.
However, the individual's scores produced in R are different than SAS and SPSS. When I applied scale(to.my.pca) the results were the same as SAS and SPSS. So, it appears that scale.=TRUE in R isn't passing to the individual scores. Can anyone using r and SAS or r and SPSS confirm this?
Many thanks!

A: R, SAS, and SPSS use different algorithms to find optimum coordinate system to set up the Eigen values and corresponding Eigen vectors for PCA. Thus, results could vary from software to software.
For example, in a 2 dimension coordinate system (applying PCA on two features) rotating x-axis counter clockwise or rotating y-axis clockwise can give you different Eigen value / vectors hence the features of PCA.


text:
Q: Combining multiple php files The current code provided on previous question is working. I need help to modify it so I can tell it what php files to combine.
The code below combines every .php file it finds in a directory.
(ie: Need to combine only the following pages, page1.php, page2.php, page3.php, page4.php, page5.php, page6.php, page7.php, page8.php, page9.php, page10.php, page11.php, page12.php )
Thanks in advance.
<?php

foreach (glob("*.php") as $filename) {
  $code.=file_get_contents("./$filename");
}
file_put_contents("./combined.php",$code);

?>

A: If you know the file names and they are not going to change then you can do this:
<?php
$files = array("a.php", "b.php", "c.php");
$comb;
foreach ($files as $k)
{
    $comb .= file_get_contents("./".$k);
}
file_put_contents("./combined.php",$comb);
?>

If you are getting them from a form submission then do something like this:
<?php
$files = array();
foreach ($_POST['files_to_combine'] as $k)
{
    $files .= $k;
}
$comb;
foreach ($files as $k)
{
    $comb .= file_get_contents("./".$k);
}
file_put_contents("./combined.php",$comb);
?>

** As a security note please make sure to sanitize your inputs if you use the second method! this code is only a proof of concept to make it simple to understand and use.

A: I have no idea why I get negative on my question asking to have it modified seeing how the programmer that answered it copied it from another site.
I don't do this for a living and have no plans too. These are personal
things I try to do to make my job go easier and without paper.
So here is the answer.
 <?php

 $txt1 = file_get_contents('page-001.php');
 $txt1 .= "\n" . file_get_contents('page-002.php');
 $txt1 .= "\n" . file_get_contents('page-003.php');

 $txt1 .= "\n" . file_get_contents('page-004.php');
 $txt1 .= "\n" . file_get_contents('page-005.php');
 $txt1 .= "\n" . file_get_contents('page-006.php');

 $txt1 .= "\n" . file_get_contents('page-007.php');
 $txt1 .= "\n" . file_get_contents('page-008.php');
 $txt1 .= "\n" . file_get_contents('page-009.php');

 $txt1 .= "\n" . file_get_contents('page-010.php');
 $txt1 .= "\n" . file_get_contents('page-011.php');
 $txt1 .= "\n" . file_get_contents('page-012.php');

 $fp = fopen('newcombined.php', 'w');
 if(!$fp)
    die('Could not create / open text file for writing.');
    if(fwrite($fp, $txt1) === false)
      die('Could not write to text file.');

      echo 'Text files have been merged.';
?>


text:
Q: Generic function for adding convenience constructors into the core data base I would like to create a function that would handle any type of object which have overriden init functions. As far I've got working with only overriden init function but if i want to do smth else with these objects every time i have to write extra code with some logic parts. To avoid that and makes code clean i have to make generic functions witch going to have as an argument T.Type.
This is my sample code which shows working parts :
import Foundation
import CoreData

extension Sample {

    @nonobjc public class func fetchRequest() -> NSFetchRequest<Sample> {
        return NSFetchRequest<Sample>(entityName: "Sample");
    }

    @NSManaged public var smth: String
    @NSManaged public var smth1: Double

    convenience init(smth: String, smth1: Double, insertIntoManagedObjectContext _context: NSManagedObjectContext!) {
        let _enitity = NSEntityDescription.entity(forEntityName: "Sample", in: _context)
        self.init(entity: _entity, insertInto: _context)
        self.smth = smth
        self.smth1 = smth1
    }

}

And then I initialize the object like this :
    let _context = DataBaseController.getContext()

let _sample: Sample = Sample(smth: smth, smth1: smth1 insertIntoManagedObjectContext: _context)
    DataBaseController.saveContext()

By following exapmle from here : Example
I've implemented these functions :
func addRecord<T: NSManagedObject>(_ type : T.Type) -> T {
        let _entityName = T.description()
        let _context = DataBaseController.persistentContainer.viewContext
        let _entity = NSEntityDescription.entity(forEntityName: _entityName, in: _context)
        let _record = T(entity: _entity!, insertInto: _context)
        return _record
    }

    func recordsInDataBase<T: NSManagedObject>(_ type : T.Type) -> Int {
        let _records = allRecords(T.self)
        return _records.count
    }

    func allRecords<T: NSManagedObject>(_ type : T.Type, sort: NSSortDescriptor? = nil) -> [T] {
        let _context = DataBaseController.persistentContainer.viewContext
        let _request = T.fetchRequest()
        do {
            let _results = try _context.fetch(_request)
            return _results as! [T]
        } catch {
            print("Error : \(error)")
            return []
        }
    }

My question is : How could I invoke my overriden init function from the class with passing also these 2 extra arguments which is smth and smth1?
let _sample = DataBaseController.Instance.addRecord(...)

Thanks in advance!
EDIT :
Is it going to be like this ? :
let _sample = DataBaseController.Instance.addRecord(Sample.self.init(smth: smth, smth1: smth1, insertIntoManagedObjectContext: _context))

A: You can't do that.
In the example you linked, it is showing how to save and query the database using neat little functions. You can't magically pass extra parameters to the functions and expect them to be accepted and used to create the new "record".
The answerer actually showed you how to use the functions if you scroll down a bit:
let name = "John Appleseed"

let newContact = addRecord(Contact.self)
newContact.contactNo = 1
newContact.contactName = name

That is how you use addRecord. You call addRecord, pass in WhateverType.self and assign the return value to a variable. After that, you set the variable's property directly, not by using the initializer.
I have come up with this (not very elegant) solution:
extension NSManagedObject {
    func initialize(with properties: [String: Any]) {

    }
}

class Sample : NSManagedObject {
    override func initialize(with properties: [String : Any]) {
        self.smth = properties["smth"] as! String
        self.smth1 = properties["smth1"] as! Double
    }

    @NSManaged var smth: String
    @NSManaged var smth1: Double

    convenience init(properties: [String: Any], insertIntoManagedObjectContext _context: NSManagedObjectContext!) {
        let _enitity = NSEntityDescription.entity(forEntityName: "Sample", in: _context)
        self.init(entity: _enitity!, insertInto: _context)
    }
}

Now all NSManagedObject has this initialize(with:) method. So in the addRecord method, you can call that to initialize a new managed object with desired properties:
func addRecord<T: NSManagedObject>(_ type : T.Type, properties: [String: Any]) -> T {
    let _entityName = T.description()
    let _context = DataBaseController.persistentContainer.viewContext
    let _entity = NSEntityDescription.entity(forEntityName: _entityName, in: _context)
    let _record = T(entity: _entity!, insertInto: _context)
    _record.initialize(with: properties)
    return _record
}

Example usage:
addRecord(Sample.self, properties: ["smth": "Hello", "smth1": 1])

The bad thing about this is of course that there is no type safety. Every property you pass to addRecord is of type Any.


text:
Q: ADO Recordset filter comparing two fields How can I filter a recordset by comparing two fields?
For a given ADO Recordset with n fields (Field1, Field2,...,Fieldn)
I used to filter a field against a value:
rs.Filter = "Field1 = 'something'"

But what I need to do is something like this:
rs.Filter = "Field1 = Field2"

Is that possible?

A:
The criteria string is made up of clauses in the form FieldName-Operator-Value
Value is the value with which you will compare the field values (for example, 'Smith', #8/24/95#, 12.345, or $50.00). Use single quotes with strings and pound signs (#) with dates. For numbers, you can use decimal points, dollar signs, and scientific notation. If Operator is LIKE, Value can use wildcards. Only the asterisk (*) and percent sign (%) wild cards are allowed, and they must be the last character in the string. Value cannot be null.

This suggests that comparing fields to each other is not supported.  Value must be a literal.


text:
Q: How to Implement modifiable activation function in the neuron class in java? I'm learning the concept of neural networks. I decided to try making the neuron class by myself. What is the best way to implement different activation functions in my code? Now it uses only the binary step function.
It's my first try in coding neural networks so if you have any suggestions about my code, or it is completely dumb, please let me know.
Here is my code:
public class Neuron {

// properties
    private ArrayList<Neuron> input;
    private ArrayList<Float> weight;
    private float pot, bias, sense, out;
    private boolean checked;

// methods
    public float fire(){
        pot = 0f;
        if (input != null) {
            for (Neuron n : input){
                if (!n.getChecked()){
                    pot += n.fire()*weight.get(input.indexOf(n));
                } else {
                        pot += n.getOut()*weight.get(input.indexOf(n));
                } // end of condition (checked)
            } // end of loop (for input)
        } // end of condition (input exists)
        checked = true;
        pot -= bias;
        pot += sense;
        out = actFunc(pot);
        return out;
    } // end of fire()

    // getting properties
    public float getPot(){return pot;}
    public boolean getChecked(){return checked;}
    public float getOut(){return out;}

    // setting properties
    public void stimulate(float f){sense = f;}
    public void setBias(float b){bias = b;}
    public void setChecked(boolean c){checked = c;}
    public void setOut(float o){out = o;}

    // connection
    public void connect(Neuron n, float w){
        input.add(n);
        weight.add(w);
        }
    public void deconnect(Neuron n){
        weight.remove(input.indexOf(n));
        input.remove(n);
    }

    // activation function
        private float actFunc(float x){
            if (x < 0) {
                return 0f;
            } else {
                return 1f;
            }
        }

// constructor
    public Neuron(Neuron[] ns, float[] ws, float b, float o){
        if (ns != null){
            input = new ArrayList<Neuron>();
            weight = new ArrayList<Float>();
            for (Neuron n : ns) input.add(n);
            for (int i = 0; i < ws.length; i++) weight.add(ws[i]);
        } else {
            input = null;
            weight = null;
        }
        bias = b;
        out = o;
    }

    public Neuron(Neuron[] ns){
        if (ns != null){
            input = new ArrayList<Neuron>();
            weight = new ArrayList<Float>();
            for (Neuron n : ns) input.add(n);
            for (int i = 0; i < input.size(); i++) weight.add((float)Math.random()*2f-1f);
        } else {
            input = null;
            weight = null;
        }
        bias = (float)Math.random();
        out = (float)Math.random();
    }

}

A: First, define interface of any activation function:
public interface ActivationFunction {
    float get(float f);
}

Then write some implementations:
public class StepFunction implements ActivationFunction {
    @Override
    public float get() {return (x < 0) ? 0f : 1f;}
}

public class SigmoidFunction implements ActivationFunction {
    @Override
    public float get() {return StrictMath.tanh(h);}
}

Finally, set some implementation to your Neuron:
public class Neuron {
    private final ActivationFunction actFunc;
    // other fields...

    public Neuron(ActivationFunction actFunc) {
        this.actFunc = actFunc;
    }

    public float fire(){
        // ...
        out = actFunc.get(pot);
        return out;
    }
}

as following:
Neuron n = new Neuron(new SigmoidFunction());

Note, neural netoworks are using signal propagation through neurons, where weights are produced. Computing of weight depends also on first derivative of an activation function. Therefore, I would extend ActivationFunction by method, which will return first derivative at specified point x:
public interface ActivationFunction {
    float get(float f);
    float firstDerivative(float x);
}

So the implemenations will look like:
public class StepFunction implements ActivationFunction {
    @Override
    public float get(float x) {return (x < 0) ? 0f : 1f;}

    @Override
    public float firstDerivative(float x) {return 1;}
}

public class SigmoidFunction implements ActivationFunction {
    @Override
    public float get(float x) {return StrictMath.tanh(x);}

    // derivative_of tanh(x) = (4*e^(2x))/(e^(2x) + 1)^2 == 1-tanh(x)^2
    @Override
    public float firstDerivative(float x) {return 1 - Math.pow(StrictMath.tanh(x), 2);}
}

Then, use actFunction.firstDerivative(x); in fire() method where weight is being computed.


text:
Q: Can ping anther PC is same network connected by switch I have two PC in same subnet and connected via switch. When I do arp -a the other IP address is shown but I cant ping the other PC.

A: It is shown in arp, but maybe it is cached, and currently not reachable. Try the following command, which outputs its current cache state:
ip neigh

For example, on my personal laptop, I have a wireless adapter (wlan0) and a wired one (eth0), both connected to the same network (my home router). With arp -a it displays
? (192.168.1.1) en xx:xx:xx:xx:xx:xx [ether] en wlan0
? (192.168.1.1) en xx:xx:xx:xx:xx:xx [ether] en eth0

and with ip neigh it shows
192.168.1.1 dev wlan0 lladdr xx:xx:xx:xx:xx:xx STALE
192.168.1.1 dev eth0 lladdr xx:xx:xx:xx:xx:xx REACHABLE

As seen with ip neigh, the wireless one is in the STALE state, cause it is not being used, but arp -a does not displays it.


text:
Q: APPNAME does not have an architecture that iPad Retina can execute My app (made for iPads only) will test run in all iPad sims except iPad Retina. Build succeeds and I get a dialog that says:

APPNAME does not have an architecture that iPad Retina can execute

I found two other similar questions for iPhone 6 and iPhone 5 but neither answer resolves my issue.
In my Build Settings I have:
Architectures                 : Standard architectures (armv7,arm64) - $(ARCHS_STANDARD)
Base SDK                      : Latest iOS (iOS9.2)
Build Active Architecture Only: No
Supported Platforms           : iOS
Valid Architectures           : arm64 arm7 arm7s

What else is needed to diagnose this issue?


text:
Q: Return message if string is found or added added to file I want to check if a string exists within a text file and if it exists, return the message string exists. If it does not exist, add the string to the file and return string added.
I got it working with no message:
<?php

$path = '../test/usersBlacklist.txt';
$input = $_POST["id"];

if ($input) {
    $handle = fopen($path, 'r+');

    while (!feof($handle)) {
        $value = trim(fgets($handle));

        if ($value == $input) {
            return false;
        }
    }

    fwrite($handle, $input);
    fclose($handle);
    return true;
}

if (true) {
    echo 'added';
} else {
    echo 'exists';
}

?>

A: As @NigelRen mentioned use answer from this question and then use this to append:
if( strpos(file_get_contents($path),$input) !== false) {
    echo "found it";
}
else{
    file_put_contents($path, $input, FILE_APPEND | LOCK_EX);
    echo "added string";
}

A: This code has no sense, a solution is maybe to create a function :
function checkI($input) {
    $handle = fopen($path, 'r+');

    while (!feof($handle)) {
        $value = trim(fgets($handle));

        if ($value == $input) {
            return false;
        }
    }

    fwrite($handle, $input);
    fclose($handle);
    return true;
}

and then:
if (checkI($input)) {
    echo 'added';
} else {
    echo 'exists';
}

Your if(true) , it ll be always true.

A: If you are trying to append some value to a file that already has some data in it than it would be better to use "a+" flag instead of "r+"
As noted in the php docs:

'a+'  Open for reading and writing; place the file pointer at the end of the file. If the file does not exist, attempt to create it. In this mode, fseek() only affects the reading position, writes are always appended.

More info here: https://secure.php.net/manual/en/function.fopen.php
And also like CBroe said using return outside of a function won't help you a better way would be something like this:
$input = $_POST["id"];
function doesLineExist($input){
   $path = '../test/usersBlacklist.txt';

   if ($input) {
       $handle = fopen($path, 'r+');

       while (!feof($handle)) {
         $value = trim(fgets($handle));

         if ($value == $input) {
           return false;
         }
       }

     fwrite($handle, $input);
     fclose($handle);
     return true;
   }
 }

$doesExist = doesLineExist($input);
if($doesExist){
    echo "Added"
 }else{
   echo "Exists"
 }


text:
Q: Formik Material UI Keyboard Date Picker Not Formatting Text Input I am trying to create a DatePicker component to be used in Formik forms.
The initial value being passed in to this field is a Date, however I dont want to display any value until the user types or selects a date from the Picker.
How can I accomplish this?
Component:
import React from 'react';
import { Field, useField } from 'formik';
import { KeyboardDatePicker } from 'formik-material-ui-pickers';
import { Grid }  from '@material-ui/core';

export interface DatePickerInputProps {
    sm: any,
    name: string,
    label: string,
    required?: boolean,
    disabled?: boolean,
    disableFuture?: boolean,
    disablePast?: boolean,
    minDate?: Date,
    maxDate?: Date
}

export default function DatePickerInput( props: DatePickerInputProps ) {
    const [ field, meta, helpers ] = useField(props.name);
    const errorText = meta.error;
    const showErrorText = !!meta.value ? !!meta.touched && !!errorText : !!errorText;

    return (
        <Grid item sm={props.sm || 12}>
            <Field
                autoOk
                component={KeyboardDatePicker}
                name={props.name}
                label={props.label}
                disabled={props.disabled}
                required={props.required}
                error={showErrorText}
                helperText={showErrorText ? errorText : null}
                fullWidth
                format='MM/dd/yyyy'
                inputVariant='filled'
                InputLabelProps={{
                    shrink: true
                }}
                disableFuture={props.disableFuture}
                disablePast={props.disablePast}
                minDate={props.minDate}
                maxDate={props.maxDate}
            />
        </Grid>
    )
}

Form Example:
...

<Formik
    initialValues={{ date: new Date() }}
>
    {({ values, errors }) => {
        return (
            <Form>
                <DatePickerInput
                    sm={6}
                    name={date}
                    label={'date'}
                />
            </Form>
        )
    }}
</Formik>

A: Basically when you are defining initialValues in Formik, you can set it as date:null,it should work.
<Formik
    initialValues={{ date: null}}
>

rest should work fine.


text:
Q: Will the "for" loop not have an effect on something I'm looping over? My title is probably worded horribly, let me explain what I mean. So I essentially have a list of lists, and I want to go through and mark which list indices have a certain property. This is how I have it written out:
For[j = 1, j <= Length[list], j++,
 For[k = j + 1, k <= Length[list], k++,
  If[list[[j]][[1]] < list[[k]][[1]] &&
  list[[j]][[2]] < list[[k]][[2]] &&
  list[[j]][[2]] > list[[k]][[1]], Append[bad, j]]]]

"bad" is supposed to be an empty list, which afterwards will have a list of the indices I care about. However, after I run this function, "bad" is still an empty list. It works fine if instead of appending, I simply print the indices j, k. Is there a reason for this?
Maybe I should also mention this is what a typical "list" looks like:
list = {{1, 2}, {3, 5}, {4, 6}}

A: I noted in comments that the simple answer to your question is that Append does not rewrite bad; you need AppendTo.
But here is a more "Mathematica"-like way to consider. Its main disadvantage is that it actually calculates the test for j >= k as well as j < k, and then throws away the result you don't need.
Position[UpperTriangularize[
  Outer[(#1[[1]] < #2[[1]] && #1[[2]] < #2[[2]] && #1[[2]] > #2[[
        1]]) &, list, list, 1], 1], True, {2}]

(*  {{1, 2}, {2, 3}}  *)

Some things to note about this solution:

*

*I have used the optional fourth argument of Outer to get Mathematica to see list as a vector of elements (that just happen to be lists) rather than treating it as a matrix. The result of the Outer function is a matrix of True and False values.

*I then zero out the ones we don't need using UpperTriangularize, including its second argument, which makes sure the lead diagonal is also zeros.

*Finally, I extract the indices (your j and k) for which the value is True using Position.  Again note that I've used an option (third) argument to tell Mathematica at what level of the list I should be looking for the True values.
I'm sure there are other solutions that other members could provide.

Follow-up
I suspect the Outer construct is the one you are having trouble understanding, so here are some examples to build up to the version I used.
list=Range[5];

Outer[(#1<#2)&,list,list]//TableForm

False   True    True    True    True
False   False   True    True    True
False   False   False   True    True
False   False   False   False   True
False   False   False   False   False

Now try a matrix
list2=RandomInteger[{0,10},{5,2}]
(*{{8,8},{2,0},{5,0},{3,4},{10,6}} *)

Here's an example using the fourth argument of Outer, to show how it knits together each row, not each element, to create a n-by-n matrix, where n is the length of list2.
Outer[(#1[[1]]<#2[[2]])&,list2,list2,1]//TableForm
False   False   False   False   False
True    False   False   True    True
True    False   False   False   True
True    False   False   True    True
False   False   False   False   False

If I just removed that fourth argument, the command above would record an error because it would then be working on the lowest-level elements of the list list2.  So instead I would need to write the following.
Outer[(#1<#2)&,list2,list2]
{{{{False,False},{False,False},{False,False},{False,False},{True,False}},
 {{False,False},{False,False},{False,False},{False,False},{True,False}}},
 {{{True,True},{False,False},{True,False},{True,True},{True,True}},
 {{True,True},{True,False},{True,False},{True,True},{True,True}}},
 {{{True,True},{False,False},{False,False},{False,False},{True,True}},
 {{True,True},{True,False},{True,False},{True,True},{True,True}}},
 {{{True,True},{False,False},{True,False},{False,True},{True,True}},
 {{True,True},{False,False},{True,False},{False,False},{True,True}}},
 {{{False,False},{False,False},{False,False},{False,False},{False,False}},
 {{True,True},{False,False},{False,False},{False,False},{True,False}}}}

The result in that case is a tensor with Dimensions {5, 2, 5, 2}.

A: My take, assuming speed matters:
fnrO = Module[{r = Range@Length@#, lt = #, p1, c, rr,ll=Length@#},
    rr = Reap[For[j = 1, j < ll, j++,
       lt = Rest@lt;
       p1 = Pick[r[[j + 1 ;;]], BitOr @@ UnitStep[Subtract[#[[j]], Transpose@lt]], 0];
       If[p1 =!= {},c = Tr[BitXor[1, UnitStep[Subtract[lt[[p1 - j, 1]], #[[j, 2]]]]]];
        If[c =!= 0, Sow[{j, c}]]];]];
    If[rr[[2]] === {}, {}, rr[[2, 1]]]] &;

On your tiny example:
list = {{1, 2}, {3, 5}, {4, 6}};
result = fnrO@list
Join @@ ConstantArray @@@ result

{{2,1}}
{2}

I took the liberty of condensing the output into pairs, first element the index in the list, second element the count found. Using Join @@ ConstantArray @@@... on the result returns the same format as your code (i.e., repeated indices when there's more than one "hit").
Quick performance comparison against your code and existing answers (on the cigar lounge squirrel-book, so expect 5-10X faster for all on real hardware), using RandomInteger[10, {len, 2}] to generate test cases:

This is just a quick-n-dirty first pop, my gut tells me there's a clever bottom-up approach that s/b much faster, pondering now...

A: This seems twice as fast as your loop. I don't doubt faster solutions are out there.
list = RandomInteger[{1, 10}, {400, 2}];
f[l1_, l2_, idx_] := Catch[Scan[If[l1[[1]] < #[[1]] < l1[[2]] < #[[2]], Throw[idx]] &,
                                l2]; Sequence @@ {}]

MapIndexed[f[#1, list[[#2[[1]] + 1 ;;]], #2[[1]]] &, list]


text:
Q: Add-remove class dynamically
Edu

Ref

Con

css
.m2Act, .m2Pass{
    float:left;
    margin:5px;
    cursor:pointer;
}
.m2Act{
 background:yellow;
}
.m2Pass{
    background:red
}

js
$('.m2Pass').hover(function(){
    $('.m2Act').removeClass().addClass('m2Pass');
    $(this).removeClass().addClass('m2Act');
})

All this works, but when the cursor is away - I need to have a previous state of each div. This doesn't happen. divs remains in the new, hovered state. I already tried with mouseenter and mouseleave without success.
FIDDLE

A: $('.m2Pass').hover(function(){
    $('.m2Act').removeClass().addClass('m2Pass');
    $(this).removeClass().addClass('m2Act');
},function(){

 // revert the properties in this function

}
)

A: You should :

*

*Use the second argument of hover() for hover out

*Keep a trace of your initial active item

Updated code :

Edu

Ref

Con

$('.m2Pass').hover(
    function(){
        $('.m2Act').removeClass('m2Act').addClass('m2Pass');
        $(this).removeClass('m2Pass').addClass('m2Act');
    },
    function(){
        $('.m2Act').removeClass('m2Act').addClass('m2Pass');
        $('.initial').removeClass('m2Pass').addClass('m2Act');
    }
);

Updated Fiddle
EDIT :
As mentioned by Simon in comments, you can use toggleClass() instead of removeClass() and addClass(), to simplify your code :
$('.m2Pass').hover(
    function(){ $('.m2Act').add(this).toggleClass('m2Act m2Pass'); },
    function(){ $('.m2Act, .initial').toggleClass('m2Act m2Pass'); }
);


text:
Q: Zend: Invalid Controller error when controller ported from dev to prod -- dev is identical copy of prod ! I'm starting to run out of ideas -- so this is either deep and mysterious or really really obvious.
My dev site is a 99.9% identical copy of prod. (DB passwords are different).
I've added to the dev site:
1 controller in blah/contollers/NewThingController.php
1 model in blah/models/NewThing.php
a few new views in blah/views/scripts/newview1.phtml, newview2.phtml etc...

All these things work absolutely fine on dev.
FTP'd files to the prod host. Used all the same paths on prod as dev. Changed permissions to match everything else on prod host. Chown'd to the same owner as everything else on prod host.
restarted Apache on prod host.
I keep getting the error:
An error occurred
Page not found
Exception information:

Message: Invalid controller specified (NewThing)
Stack trace:

#0 /var/www/library/Zend/Controller/Front.php(954): Zend_Controller_Dispatcher_Standard->dispatch(Object(Zend_Controller_Request_Http), Object(Zend_Controller_Response_Http))
#1 /var/www/library/Zend/Application/Bootstrap/Bootstrap.php(97): Zend_Controller_Front->dispatch()
#2 /var/www/library/Zend/Application.php(366): Zend_Application_Bootstrap_Bootstrap->run()
#3 /var/www/index.php(25): Zend_Application->run()
#4 {main}

Request Parameters:

array (
  'controller' => 'NewThing',
  'action' => 'newview1',
  'module' => 'MYMODULENAME',
)

Ironically the controller/action/module specifications are exactly correct. And the various bits are all where they are supposed to be.
This is starting to feel like a parallel universe.
I'd be much obliged for any suggestions you might have.
Thanks for reading.

A: For them what stumbles upon this page later ...
!#!@$@%!#@! !!!
It was a difference in how Windows and Linux handle character case in file names, and how that plays hell with the Zend page-loading/routing/dispatching facility on Windows.
Note that the controller file name is NewThingController.php and the class name is MYMODULENAME_NewThingController. (Zend Framework 1.11.1)
I was trying to navigate to a page at the address:
http://website/NewThing/actionname

This is just fine and dandy on the WindowsXP/Apache install of Zend and works. It fails however on Ubuntu Linux -- and one can assume any other Linux/Unix.
Strictly speaking I don't think is should be OK on Windows, but it is.
On Linux however, this is rejected. Mounted on Linux, Zend insists on the orthodox URL:
http://website/new-thing/actionname

... at least for the CamelCase controller FileName and ClassName that I am employing.
Now I am going to kick the cat.


text:
Q: How to add and remove part of javascript code through a javascript event I am implementing the address autocomplete functionality in onkeyup() event of the asp.net textbox.
I want the autocomplete functionality to kick in only after the user enters a minimum of 7 characters.
It works fine for the first time. However once the user clears the input box, then the autocomplete works even when a single character is entered.
This is because the javascript code which implements it is already there. It will work as desired again after a page reload.
Is there anyway to make it work without a page reload.
Following is my code:
<asp:textbox id="txtAddressInput" runat="server" autocomplete="false" onkeyup="input_onchange(this)"></asp:textbox>
<script>
        function input_onchange(me) {
                if (me.value.length > 7) {
                autocomplete = new google.maps.places.Autocomplete(
                (document.getElementById('txtAddress')),
                { types: ['geocode'] });
        }
            google.maps.event.addDomListener(document.getElementById('txtAddress'), 'keydown', function (e) {
                if (e.keyCode == 13 && $('.pac-container:visible').length) {
                    e.preventDefault();
                }
        });
    }
<script>

A: Based on your code it looks like you just need an else statement clearing the autocomplete object.  Something like
else if (me.value.length < 7 && autocomplete != null) {
    autocomplete = null;
}

Also your if statement will require a minimum of 8 characters, not 7 (you're using > instead >=)


text:
Q: Pandas count distinct multiple columns in a dataframe and group by multiple columns I found the answer its
test2 = test_pd.groupby(by = ['ID'])['country','color'].nunique().reset_index()
idk why this question was marked as duplicate  when the link provided by rafael didnt answer the question
I have a data frame with 3 columns:
   country    color    ID
0  Germany    Red      12
1  France     Red      13
2  US         Blue     11
3  France     Red      11

If I want to find out the number of distinct countries and colors per ID in SQL it would be
select  ID
  , count(distinct(country)) as num_countries
  , count(distinct(color)) as num_color
from table_name
group by ID;

The result will look like this
   ID    num_countries   num_color
0  12         1              1
0  11         2              2
0  13         1              1

How do I achieve the same result in Pandas?

A: Use DataFrame.groupby.nunique:
df_unique=df.groupby('ID')['country','color'].nunique().add_prefix('num_').reset_index()
print(df_unique)

   ID  num_country  num_color
0  11            2          2
1  12            1          1
2  13            1          1

A: You want nunique():
df.groupby('age_cd', as_index=False).nunique()


text:
Q: How do I avoid IFERROR testing for empty arrays in FILTER function? I want to count the results of a FILTER in excel. Usually I do something like
IF(
    IFERROR(
            SUM(
                FILTER( range, condition)
            )
    , -1) <> -1,
    COUNTA(FILTER( range, condition)),
    0
)

Because if your filter returns with an empty array, it throws an error. When you do a COUNTA on it it will return 1... how do I prevent this without stating my filter function twice?
How do I get a counta of empty filter to return zero?


text:
Q: Naming convention for actually choosing the words in Python, PEP8 compliant I'm looking for a better way to name everything in Python.  Yes, I've read PEP8, Spolsky's wonderful rant, and various other articles.  But I'm looking for more guidance in choosing the actual words.
And yes I know

A Foolish Consistency is the Hobgoblin
  of Little Minds.

But, you can keep consistent with PEP8 etc, and still not have consistent variable/method/class names which are easy to remember.  By consistent, I mean that if you were presented with the same decision twice, you would produce the same name.
As an example, there are multiple PEP8 compliant ways to name the items below:

*

*number of columns in the table

*current column number

*column object

*sum of column

Yeah, sure, it is easy to make a decision to use something like num_col and count_col rather than col_num and col_count (or v.v.).  But, I would like to see an example that has seen some testing/refining over time. I often start with a given convention, and then it starts to break down as I venture into a new area.
I guess what I am looking for is not only what the prefix/root/tag/suffix should do (which was partly covered for Apps Hungarian in the Spolsky article), but (many) examples for each, or a rule for generating each.

A: I believe that the need for complex variable naming conventions goes away with good object-oriented design. In the Spolsky article, much focus is on how variable naming helps preventing errors. I believe that those errors will more often occur when you have many variables in the same scope; this can be avoided by grouping data into objects - then, a single naming context will have only few variables, which don't need combined names.
The other purpose of a naming convention is to better remember the names. Again, object-orientation helps (by hiding much data from users that look from the outside); what you then need is a convention for naming methods, not data. In addition, tools can help which provide you with a list of names available in a certain scope (again, those tools rely on object-orientation to do their job).
In your specific example, if column is an object, I would expect that len(table) gives me the number of columns in a table, sum(column) or column.sum() gives me its sum; and the current column is just the variable in the for loop (often c or column).

A: Remember that in English, when two ambiguous words are next to each other, the first one becomes an adjective which describes the second one. Try to stick to this rule and always name things with two components where the first component decribes the second.
For instance col_num is a number. What kind of number? A column number.
Next rule is the word of. It is a nice short word so please do not leave it out. Same goes with pluralization. And past tense ending in -ed or -d. Maybe even -ing.
For instance, num_col is a column. What kind? A number column. If you really wanted to refer to the number of columns, you should write num_of_cols. Received date is recd_date or rcvd_date, not rec_date or rcv_date.
English speaking readers are very sensitive to -s and -d at the end of words, as well as of in the middle of a phrase, so don't assume that such short bits of text would be missed. That is very unlikely because we are programmed from a very young age to notice a handful of word endings.
Try for consistency, and keep a glossary or data dictionary of any words, or word fragments that you use. Don't use the same fragment for two different things. If you are using recd to mean received, and you need a variable name for recorded, then either write it out in full or come up with a new abbreviation and put it in the glossary. If you use a relational database, try to be consistent with the naming convention used there. Let the dba know what you are doing and tell them where to find your glossary.

A: The universe is multi-dimensional.
You have at least two dimensions to each variable name.
"Total", "Count", "Of Columns", "In a Table"
"Current", "Index", "", "Of a Column"
"Current", "Column", "", ""
"Sum", "Of Something", "", "In a Column"
Rats.  It's irregular.
Worse, we can pick anything as the "Primary" dimension and pick any sequence of other features as "secondary" dimensions.
Even worse, we could have a truly complex thing.  "Total", "Count", "of Non-Underscore", "Columns", "In Tables", "With Even-Length Names", "From a Dictionary", "Keyed by", "Mother's Maiden Name".
Frankly, there's no possible schema for variable names that encompasses "all" knowledge in a systematic, repeatable form.
Keep trying though.  It's always fun and games until someone finds a counter-example.
You can keep trying or you can simply use simple, clear names.  If your scope of names is small (a small method function, for example), there's nothing to "remember".  It's all perfectly visible in the 20 lines of code that make up the method function.


text:
Q: how to update property in nested mongo document I want to update a particular property in a nested mongo document
{
    "_id" : ObjectId("55af76e60b0e4b318ba822ec"),
    "make" : "MERCEDES-BENZ",
    "model" : "E-CLASS",
    "variant" : "E 250 CDI CLASSIC",
    "fuel" : "Diesel",
    "cc" : 2143,
    "seatingCapacity" : 5,
    "variant_+_fuel" : "E 250 CDI CLASSIC (Diesel)",
    "make_+_model_+_variant_+_fuel" : "MERCEDES-BENZ E-CLASS E 250 CDI CLASSIC (Diesel)",
    "dropdown_display" : "E-CLASS E 250 CDI CLASSIC (Diesel)",
    "vehicleSegment" : "HIGH END CARS",
    "abc" : {
        "variantId" : 1000815,
        "makeId" : 1000016,
        "modelId" : 1000556,
        "fuelId" : 2,
        "segmentId" : 1000002,
        "price" : 4020000
    },
    "def" : {
        "bodyType" : 1,
        "makeId" : 87,
        "modelId" : 21584,
        "fuel" : "DIESEL",
        "vehicleSegmentType" : "E2"
    },
    "isActive" : false
}

This is my document. If I want to add or update a value for key "nonPreferred" inside "abc", how do I go about it?
I tried it with this query:
db.FourWheelerMaster.update(
    { "abc.modelId": 1000556 },
    {
        $Set: {
            "abc": {
                "nonPreferred": ["Mumbai", "Pune"]
            }
        }
    },
    {multi:true}
)

but it updates the whole "abc" structure, removed all key:values inside it and kept only newly inserted key values like below
"abc" : {
    "nonPreferred" : [
        "Mumbai",
        "Pune"
    ]
},

Can anyone tell me how to update only particular property inside it and not all the complete key?

A: Instead of using the $set operator, you need to push that array using the $push operator together with the $each modifier to append each element of the value separately as follows:
db.FourWheelerMaster.update(
    { "abc.modelId": 1000556 },
    {
        "$push": {
            "abc.nonPreferred": {
                "$each": ["Mumbai", "Pune"]
            }
        }
    },
    { "multi": true }
)


text:
Q: Multi table GROUP BY query optimisation Currently I have a multi table/column GROUP BY query which is pretty slow.  Below is the tables schema used by the query:
report Table
                                                                Table "report"
       Column       |           Type           |                           Modifiers                           | Storage  | Stats target | Description
--------------------+--------------------------+---------------------------------------------------------------+----------+--------------+-------------
 id                 | integer                  | not null default nextval('dashboard_report_id_seq'::regclass) | plain    |              |
 county             | character varying(200)   | not null                                                      | extended |              |
 district           | character varying(200)   | not null                                                      | extended |              |
 report_name        | character varying(500)   | not null                                                      | extended |              |
Indexes:
    "dashboard_report_pkey" PRIMARY KEY, btree (id)

question Table
                                                       Table "question"
   Column    |          Type          |                            Modifiers                            | Storage  | Stats target | Description
-------------+------------------------+-----------------------------------------------------------------+----------+--------------+-------------
 id          | integer                | not null default nextval('dashboard_question_id_seq'::regclass) | plain    |              |
 name        | character varying(255) | not null                                                        | extended |              |
 label       | character varying(255) | not null                                                        | extended |              |
 report_type | character varying(255) | not null                                                        | extended |              |
Indexes:
    "dashboard_question_pkey" PRIMARY KEY, btree (id)

questionanswer Table
                                                           Table "questionanswer"
   Column    |          Type          |                               Modifiers                               | Storage  | Stats target | Description
-------------+------------------------+-----------------------------------------------------------------------+----------+--------------+-------------
 id          | integer                | not null default nextval('dashboard_questionanswer_id_seq'::regclass) | plain    |              |
 answer      | character varying(255) | not null                                                              | extended |              |
 question_id | integer                | not null                                                              | plain    |              |
 report_id   | integer                | not null                                                              | plain    |              |
Indexes:
    "dashboard_questionanswer_pkey" PRIMARY KEY, btree (id)
    "dashboard_questionanswer_6f78b20c" btree (report_id)
    "dashboard_questionanswer_7aa0f6ee" btree (question_id)
Foreign-key constraints:
    "dashboard_que_report_id_4c2a87ee585b6121_fk_dashboard_report_id" FOREIGN KEY (report_id) REFERENCES dashboard_report(id) DEFERRABLE INITIALLY DEFERRED
    "dashboard_question_id_522f82097923c241_fk_dashboard_question_id" FOREIGN KEY (question_id) REFERENCES dashboard_question(id) DEFERRABLE INITIALLY DEFERRED
Has OIDs: no

Query:
SELECT
    "report"."county",
    "report"."district",
    "report"."report_name",
    "question"."report_type",
    COUNT(DISTINCT "questionanswer"."report_id")
FROM "questionanswer"
    INNER JOIN "question" ON ( "questionanswer"."question_id" = "question"."id" )
    INNER JOIN "report" ON ( "questionanswer"."report_id" = "report"."id" )
WHERE
    "question"."name" = 'touch'
GROUP BY
    "report"."county",
    "report"."district",
    "report"."report_name",
    "question"."report_type" ;

I'm not sure where to start with optimising this query, at the moment it is fairly slow on my system ~300 ms. I did try individually indexing all the columns referred by the GROUP BY clause but that didn't help the query time either.
So basically user submits reports, the data of which is stored in reports, each report has multiple QuestionAnswers, which are stored in QuestionAnswer Table. The Question meta data is in Question table. The QuestionAnswer table records will be large next comes Report table data, the Question table has a set of only 40 questions. The objective of the query is to figure out per county, district and report type for a specific question how many reports we have that have answered that question.
My Postgres Sql version is PostgreSQL 9.3.5.
Query plan is here.
My machine hardware spec is MacOSX 10.9.5 4-Core 8 GM RAM SSD, encrypted file system.
Would indexing all the columns referred by GROUP BY help?
Or should I go for a multicolumn index?

A: I do wonder, why you have the report_type as attribute of the question?
Be that as it may, your objective:

The objective of the query is to figure out per county, district and
  report type for a specific question how many reports we have that have
  answered that question.

Why would you include report_name in GROUP BY step? That conflicts with your definition. I think you should remove that:
SELECT r.county, r.district, q.report_type
     , count(DISTINCT r.id) AS reports
FROM   question q
JOIN   questionanswer qa ON qa.question_id = q.id
JOIN   report         r  ON qa.report_id = r.id
WHERE  q.name = 'touch'
GROUP  BY 1,2,3;

Also, as long as you restrict the query to a single question, there is only one report_type in the result per definition. Including it in the result and GROUP BY clause doesn't change the numbers.
As for performance: either create a UNIQUE constraint on (question_id, report_id) (in that order!) like I suspect you should have:
ALTER TABLE questionanswer ADD CONSTRAINT qa_uni UNIQUE (question_id, report_id);

Or, barring that, at least create an index on (question_id, report_id).
Why is the order of columns in the index / constraint important?

*

*Is a composite index also good for queries on the first field?
With the UNIQUE constraint in place, the query gets considerably cheaper:
     , count(*) AS reports

As long as you have only 40 questions you don't need an index on question.name, but as long as you select questions by name, you should still have a UNIQUE constraint on that column.
The PK on report does the rest.

Related query if you really want to count distinct counties and districts per question:
SELECT q.id, q.name, q.report_type
     , count(DISTINCT r.county)      AS distinct_counties
     , count(DISTINCT r.district)    AS distinct_districts
FROM   question q
JOIN   questionanswer qa ON qa.question_id = q.id
JOIN   report         r  ON qa.report_id = r.id
WHERE  q.name = 'touch'
GROUP  BY 1;  -- the PK column covers the whole table


text:
Q: Filling in non-continuous data with zeroes - MATLAB If i've got a non-continuous dataset in the form of:
 x      y
7500   1.4
7501   1.45
7502   1.34
7510   1.67
7511   1.54
7512   1.89

What is the quickest way to fill in all the intervening x-values with zeroes? Or to do so between a range i.e. specify a range of 7490-7515 and the output is:
 x      y
7490   1.4
7491   0
7492   0
7493   0
7494   0
7495   0
7496   0
7497   0
7498   0
7499   0
7500   1.4
7501   1.45
7502   1.34
7503   0
7504   0
7505   0
7506   0
7507   0
7508   0
7509   0
7510   1.67
7511   1.54
7512   1.89
7513   0
7514   0
7515   0

A: Initialize it with zeros and then assign the nonzero data points into it.
x2 = [7490:7515]';  % #'
y2 = zeros(size(x2));
[tf,ix] = ismember(x,x2);
y2(ix(tf)) = y(tf);

If you know all x are present in x2, you can skip the (tf) subsetting. And if all your x values are integers >= x2(1), you can optimize away the expensive ismember() by doing an index shift, like so.
[lo,hi] = deal(7490, 7515);
x2 = [lo:hi]';  % #'
y2 = zeros(size(x2));
ix = x - lo + 1;
y2(ix) = y;

A: This should be pretty efficient as it uses one lightweight function call to zeros, which is just necessary in this case and another lightweight call to numel. Rest of the code is all about matrix-indexing. Here's the code -
%// Define range
range1 = 7490:7515

%// Setup output array and initialize the first column with range values
out = [range1.' zeros(numel(range1),1)]  %//'

%// Put A(:,2) values into the second column of output array indexed by the
%// offsets decided by the first column of A w.r.t. the starting range value
out( A(:,1)-range1(1)+1 , 2) = A(:,2)

Please note that it assumes A as the input non-continuous dataset.

If you want to go a bit experimental, you can use a hacky pre-allocation scheme to do something like this -
range1 = 7490:7515

clear out
out(numel(range1),2) = 0
out(:,1) = range1
out( A(:,1)-range1(1)+1 , 2) = A(:,2)


text:
Q: width not changing div at all Strange issue here which I can't see the problem with! I'm setting the width of the entire element using the class sale_container. But it's width is not changing at all!
See JSFiddle Demo
CSS:
/*Sale styles*/
.add_sales input {
    background:none;
    border:none;
    color:#FFF;
}
.sales_toolbar input {
    width:30px;
}
.sale_container {
    width:500px;
    border:2px solid #FFF;
}
.sale_image {
    height:200px;
    width:200px;
    background-size:cover;
    border-radius:10px;
}
.sale_image_container {
    border:solid #000 1px;
    float:left;
    border-radius:10px;
    background-color:#353535;
}
.sale_image_container p {
    margin:10px;
}
.sales_toolbar {
    float:right;
}

HTML:
<form class="add_sales" name="add_sales" action="php/process_sales.php" method="post">

KR

            <input type="text" readonly value="KRR" id="50_selected" />

</form>

It seems to be working on the JSFiddle, but when I preview it in Chrome, it looks like this:

A: It's possible that additional styles are being included from an alternate CSS source. Have you tried using Inspect Element to view the div, and see if it has any unexpected styles being applied? Chrome natively has the feature built-in if you right-click any element.
Glad to help.

A: Set position to absolute of sale_container to change width.
.sale_container{
   width: 300px;
   position: absolute;
   border: 2px solid #E97676;
}

Use firebug (http://getfirebug.com/) to inspect html element and css attributes.


text:
Q: ZK MVVM binder save with EL-Expression How to do this with zk MVVM
i want to save a bean
but with condition
if the type is personal than save into personal, else into company

<textbox value="@save(vm.personal ? vm.masterCifPersonal.cifId : vm.masterCifCompany.cifId)" width="100px" maxlength="10"/>

but when binder save into bean, this exception appear

Illegal Syntax for Set Operation

A: My tip is to modify your code and use a temporary var:
<textbox value="@save(vm.temp)" width="100px" maxlength="10"/>

and modify your setter as
void setTemp(Long temp) {
    if(personal) {
        masterCifPersonal.cifId = temp;
    } else {
        masterCifCompany.cifId = temp;
    }
}

A: another solution could be :
ZK 8 and higher :
<if test="@load(vm.personal)">
    <textbox value="@save(vm.masterCifPersonal.cifId)"/>
</if>
<if test="@load(not vm.personal)">
    <textbox value="@save(vm.masterCifCompany.cifId)"/>
</if>

ZK 6.5 an higher:
<textbox value="@save(vm.masterCifPersonal.cifId)" visible="="@load(vm.personal)"/>
<textbox value="@save(vm.masterCifCompany.cifId)" visible="="@load(not vm.personal)"/>

Difference:
The if tag will not render the other tag into the dom while using the visible attribute will render it in the dom.
If personal isn't dynamic you could use the if attribute of the Textbox but the usage is then : if="${vm.personal} because binding will not work
Like this the textbox isn't also rendered into the DOM.


text:
Q: Error when using a forked gem (active_admin) from Github I'm experiencing a really weird issue. When I fork the active_admin gem and use the forked, unchanged version it gives me the following error:
Sprockets::CircularDependencyError in Active_admin/devise/sessions#new
/Users/Victor/.rvm/gems/ruby-1.9.2-p180/bundler/gems/active_admin-916ecdd04e3c/app/assets/javascripts/active_admin/base.js has already been required

Extracted source (around line #12):

9:     <%= stylesheet_link_tag style.path, style.options %>
10:   <% end %>
11:   <% ActiveAdmin.application.javascripts.each do |path| %>
12:     <%= javascript_include_tag path %>
13:   <% end %>
14:
15:   <%= csrf_meta_tag %>

When I use the original version there are no errors. How is this possible if the two versions are identical?

A: Yes.you can remove the line
//= require_directory ./

in
/.rvm/gems/ruby-1.9.2-p180/bundler/gems/active_admin-916ecdd04e3c/app/assets/javascripts/active_admin/application.js

A: Remove active_admin.js from your app/assets/javascripts folder - it looks like it is no longer needed.


text:
Q: Issue On Adding Class to Specific  with a Class Can you please take a look at This Demo and let me know why I am not able to add .sale class to last columns of table which has a class of .item using .find()
$(function () {
    $('td:nth-child(6) ,td:nth-child(7)').find("item").addClass("sale");
});

A: You are missing a dot in item. It should be
$(function () {
    $('td:nth-child(6) ,td:nth-child(7)').find(".item").addClass("sale");
});

http://jsfiddle.net/poz1f1a3/2/
The css
.item {
    background-color: grey;
    height:45px;
    width:65px;
}
.sale {
    background-color: yellow;
}


text:
Q: Resampling an ndarray by a non time related element I currently have a time series in an ndarray. The time series contains number of sales of a product along with the price of the product. The timeseries data is 24/7 however in off hours the data gets really stochastic because there are less buyers and sellers. What I want to do is resample the time series so that it keeps its current temporal order, but rows that have low numbers of sales get collapsed in to one row, where as a row that has many sales will form multiple rows so that the ndarray that is returned has an equal number of sales in every row. For instance I set number of sales to 1,000, if a row contains 3,000 sales it returns three rows of 1,000 sales, if a row has less than 1,000 sales it gets added to the following row until there are sufficient sales to make a row of 1,000 sales. There are a lot of options available to resample by a time related variable but I'm not finding any for a non-time related variable such as sales. This is the code I have but it doesn't work very well since it lacks the ability to break up rows that are larger than the frequency set so the results aren't equal:
def gen_modifiedsales(sales, frequency=100):
    times = sales[:,0]
    prices = sales[:,1]
    volumes = sales[:,2]
    ans = np.zeros(shape=(len(prices), 6))
    candle_counter = 0
    vol = 0
    lasti = 0
    for i in range(len(prices)):
        vol += volumes[i]
        if vol >= frequency:
            ans[candle_counter][0] = times[i]                          # time
            ans[candle_counter][1] = prices[lasti]                     # open
            ans[candle_counter][2] = np.max(prices[lasti:i+1])         # high
            ans[candle_counter][3] = np.min(prices[lasti:i+1])         # low
            ans[candle_counter][4] = prices[i]                         # close
            ans[candle_counter][5] = np.sum(volumes[lasti:i+1])        # volume
            candle_counter += 1
            lasti = i+1
            vol = 0
    return ans[:candle_counter]

Ultimately what I'd like is to turn a timeseries that looks like this:
Datetime          Price      Volume

2017-12-15 09:30  57.06      3

2017-12-15 09:31  57.04      1

2017-12-15 09:32  57.02      4

To something like this
Datetime              Price  Volume
2017-12-15 09:05:14   100    57.103306666666796

2017-12-15 11:26:11   100    57.07302666666672

2017-12-15 23:32:03   100    57.14208000000028

Or put another way in the city I live we have vendors downtown, they sell things 24 hours a day, if you need to buy 50 pairs of shoes at 10:30 am the price of the shoes will be very fair, there's a lot of competition to sell the shoes, but if you want to buy 50 pairs of shoes at 1:30 in the morning you'll have to pay a lot to buy the shoes since there are far fewer people selling shoes. So during the day time when many shoes are sold the prices tend to be less stochastic, where as at night time they are more stochastic and volatile. In a standard time series based on time alone as frequency night time hours will play a very large role, even though they represent comparatively few sales (after all not many people go downtown to buy shoes in the early morning). By resampling the data for the number of shoes sold the night time hours that are more stochastic and volatile get shrunk, and the day time hours that are less stochastic get increased importance.


text:
Q: Why am I getting supplied argument is not a valid MySQL result resource error I am trying to display blogs on a certain page here is my code:
<?php
$query = "SELECT * FROM `Blogs` WHERE `Author` = '".$prof->id."' && `id` != '" . mysql_real_escape_string($_GET['id']) . "' && `status` = 'active' LIMIT 6" && "ORDER BY `date` DESC, `time` DESC ";

$request = mysql_query($query,$connection);

while($result = mysql_fetch_array($request)) {
    echo "
";
    echo "
";
    echo "";
    echo "";
    echo "";
    echo "
";
    echo "
";
    echo "";
    echo stripslashes($result['blogTitle']);
    echo "";
    echo "
";
    echo "";
    echo "on " . date("M d, Y",strtotime($result['date']));
    echo "";
    echo "
";
    echo "
";
}

?>

and I am getting this error:
note: line 118 is while($result = mysql_fetch_array($request)) {
Warning: mysql_fetch_array(): supplied argument is not a valid MySQL result resource in /home/content/l/l/0/blah/html/BlogProfile.php on line 118

A: Check the result of mysql_query to see if your SQL doesn't contain errors. E.g. you can print the error like this:
// Check result
if (!$result) {
    $message  = 'Invalid query: ' . mysql_error() . "\n";
    $message .= 'Whole query: ' . $query;
    die($message);

}
The " && " part of your Query string looks suspicious. enough. Why did you use quotes on it? Now It's not part of your Query string. Check the escaping of your query. Try this:
$query = "SELECT * FROM `Blogs` WHERE `Author` = '".$prof->id."' && `id` != '" . mysql_real_escape_string($_GET['id']) . "' && `status` = 'active' LIMIT 6 && ORDER BY `date` DESC, `time` DESC ";

A: The end of your SQL is the problem.
$query = "SELECT * FROM `Blogs` WHERE `Author` = '".$prof->id."' && `id` != '" . mysql_real_escape_string($_GET['id']) . "' && `status` = 'active' LIMIT 6" && "ORDER BY `date` DESC, `time` DESC ";

Should be
$query = "SELECT * FROM `Blogs` WHERE `Author` = '".$prof->id."' && `id` != '" . mysql_real_escape_string($_GET['id']) . "' && `status` = 'active' ORDER BY `date` DESC, `time` DESC LIMIT 6";

A:  $query = "SELECT * FROM `Blogs` WHERE `Author` = '".$prof->id."' && `id` != '" . mysql_real_escape_string($_GET['id']) . "' && `status` = 'active' LIMIT 6" && "ORDER BY `date` DESC, `time` DESC ";

Should probably be
 $query = "SELECT * FROM `Blogs` WHERE `Author` = '".$prof->id."' && `id` != '" . mysql_real_escape_string($_GET['id']) . "' && `status` = 'active' ORDER BY `date` DESC, `time` DESC  LIMIT 6";


text:
Q: Invalid CRL distribution points in certs after CA migration I have recently migrated an Enterprise CA from a Windows Server 2003 box to a Windows Server 2012 R2 box using the Active Directory Certificate Services Migration Guide.
The CA was running entirely on the one machine, and looks as though it was a typical "next, next, finish" install done without any thought or planning because they realised they needed a CA at some point.
The guide recommends that you name the destination server the same as the source server if possible. However, it include additional steps that should be carried out if the source and destination have different names. I completed these additional steps during the migration.
However, I am left with an issue which the guide doesn't seem to address. When the CA was originally deployed, the CPD and AIA URLs were left as the out-of-box defaults. This means the CDP and AIA URLs in already issued certificates reference the old machine by name, e.g:
http://server01.ad.contoso.com/CertEnroll/crl.crl
I'm no expert with AD CS, but I gather best practice is to break that dependency by using something like:
http://crl.contoso.com/CertEnroll/crl.crl
... but it's too late now the certificates have been issued.
I'm guessing the Migration Guide on TechNet assumes you've followed best practice when deploying your CA, meaning you wouldn't hit this issue.
So, my question is, what's the best way to address the issue? I've seen a couple of people suggesting I should create a CNAME pointing the old CA server name to the new CA server. Others have said I can select each of the Certificate Templates within MMC and ask it to re-issue the certificates associated with them. I'm unsure whether either of these is really the best approach.


text:
Q: The properity of $\mathbb{R}^4$ that has infinitely many differential structures is related to Yang-Mills field? I heard a saying that $\mathbb{R}^4$ having infinitely many differential structures which are not diffeomorphic to each other has a relationship with Yang-Mills field. Does anyone can explain it, and give me some references.

A: A concise account of the Donaldson's theorem relating smooth structures on 4-manifolds to the Yang-Mills theory can be found in the following review by C. Nash (section 5). This theorem is based on previous theorems proven by mathematicians.
Donaldson's theorem sets a much more strict characterization on the allowed forms of the intersection matrix of smoothable 4-manifolds. (Please see the intersection matrix definition in equation 5.1.).
In the proof Donaldson used the fact that the number of singularities in the one instanton moduli space is equal to the number of unit eigenvalues of the intersection matrix.
Later, Donaldson investigated higher instanton moduli spaces and discovered invariants which are sensitive to the smooth structure. Witten found a topological field theory (based on the Seiberg-Witten moduli space) whose correlation functions give these invariants. This was a great achievement, since, it was hard to compute these invariants using to the existing methods. The references to these works are given in Nash's article.


text:
Q: Declared base class/interface or implementation when creating objects? Here I have this question. Let's say code 1 is Java with runtime polymorphism and code 2 is Java without runtime polymorphism.
Code 1:
class A {
    void run() { System.out.println("A is running"); }
}

class B extends A{
    void run(){ System.out.println("B is running with A!");}

    public static void main(String args[]){

        A a = new B(); //referenced to class A
        a.run();

    }
}

Code 2:
class A {
    void run(){System.out.println("A is running");}
}

class B extends A{
    void run(){ System.out.println("B is running with A!");}

    public static void main(String args[]){
        B a = new B(); //referenced to the same constructor class
        a.run();
    }
}

Even though these two codes give the exact same results, it is well known that runtime polymorphism is really important in OOP. I need an explanation/reason of using code 1 instead of using code 2.

A: Let's take this case :
You have multiple classes inheriting from the same base class, you want to call their shared function run() on all of them, even though they are different classes.
You'll have to do this:
interface A{
    void run();
}

class B implements A{
void run(){ System.out.println("B is running with A!");}

class C implements A{
void run(){ System.out.println("C is running with A!");}

public static void main(String args[]){
    Array<A> objects = new Array<A>();
    objects.put(new B()); //Object are stored as instances of "A"
    objects.put(new C());
    objects.put(new B());
    for (A obj : objects)
        obj.run();//Calls everything
}

A: Take advantage of polymorphism is not needed in OOP in every cases.
Polymorphism  is a mechanism which brings flexibility when flexibility is needed.
For example, in your case, writing :
B a = new B();

or
A a = new B()

depends if you need and have interest to reference the base class rather than the subclass as declared type for your variable.
Referencing the base class (here A) allows many things among these (it is not exhaustive but frequent use cases) :

*

*masking the implementation (via factory or injection dependency). In this way, you can change the implementation (returning a C or D which extends A) without breaking calls of client code. In your code, you don't perform that but in real applications you can have this need.

*If you have processings common to A and B classes, you may propose a method which takes as parameter a instance of type A.
Example : public void doProcess(A instance)
In this case, if you declare B a = new B(), the code will not compile
if you pass this instance to that method as  semantically, a B instance is a A but a A instance is not
necessarily a B
Often, we can read that declaring the interface rather that the implementation is a good practice. In fact, it is in most of cases but in some other cases, it is not. Just one example, if you need to use a TreeMap, you will not declare the interface Map because the behavior of TreeMap is very specific and have special requirements, so you may want to stress on. When you instantiate a classic HashMap, generally, you don't care precising HashMap as declared type  since  its interface is enough. You have no interest to create a stronger coupling with the implementation.


text:
Q: The maximum amount of all values for a given alphabet and a text of length N Say, I have a code/password like this:
abcde123 --> 8 characters

Where only letters and digits are allowed. How do I calculate the amount of all its possible values? I'm doing this the following way:
1) 26 letters + 10 digits = 36 full alphabet
2) 8 length ** 36 full alphabet = 324518553658426726783156020576256 values

Is this correct?

A: You are forgetting that a <> A so as long as your password system is case dependent you have A-Za-z0-9 as possible characters, (in the ASCII letters and numbers), which gives 62 possible characters for each position - if your password is a fixed length, say 8 this gives:
62 ** 8 = 218,340,105,584,896

possible combinations.
The basic rule is that each character has 62 possiblities, (more or less depending on the actual language alphabet and what are classed as letters), so for the first you have 62 possibilities, for the second another 62 so 62*62 and so on.
Of course if you have a variable length password of up to N characters the formula is:
sum(62**n for n in 0..N)

This gives:
1  Length 0 has only one possibility
62 Length 1
3,844
238,328
14,776,336
916,132,832
56,800,235,584
3,521,614,606,208
218,340,105,584,896
-------------------
221,919,451,578,091
-------------------