text:
Q: populating jquery datatable ajax txt file I'm a jquery/ajax newbie and going through data table examples. I'm having problems populating the data table with txt data in eclipse. I just get a loading message. Any assistance would be appreciated.

      Name
      Position
      Office
      Extn
      Start date
      Salary

/////object.txt
{
  "data": [
    {
      "name": "Tiger Nixon",
      "position": "System Architect",
      "salary": "$320,800",
      "start_date": "2011/04/25",
      "office": "Edinburgh",
      "extn": "5421"
    },...................

A: In your code sample, you had the line,
"columns": [{ "data": "name" },{ "data": "position" },{ "data": "office" },{ "data": "extn" },{ "data": "start_date" },{ "data": "salary" }]
Simply change the columns to "columnDefs" which refers to the column defaults option in the datatable plugin.
And also, you are calling the data-table plugin on an id called "example" which you have not defined. So give your table an id="example"
So the final code should look like

$(document).ready(function() {
  $('#example').dataTable({
    "ajax": 'array.txt',
    "columnDefs": [{   /* changed this */
      "data": "name"
    }, {
      "data": "position"
    }, {
      "data": "office"
    }, {
      "data": "extn"
    }, {
      "data": "start_date"
    }, {
      "data": "salary"
    }]
  });
});
<link href="//cdn.datatables.net/1.10.5/css/jquery.dataTables.css" rel="stylesheet" />

      Name
      Position
      Office
      Extn
      Start date
      Salary

Now this above code snippet WILL NOT work because the path to the array.txt is wrong. Copy the array.txt file locally. Fiddle or code snippet does not allow the ajax requests through them.
Here is the sample array.txt (copied from the data table website @ https://www.datatables.net/examples/ajax/data/arrays.txt )
Hope this helps. Happy coding :)
Screenshot on my local machine


text:
Q: How to convert text file to xml file? Here is the situation, I have downloaded a text file from a server, it looks like this:
Home
Address
Suburb
State
Post Code
Latitude
Longitude
Phone
Fax
Curfew Hours Start
Curfew Hours End
Website

FirstHome Address
"123 Street sd"
FirstHome Address
HMH
2223 "Addresss,dsdsd"
-54.000012
120.000000
(03) 1232 1242
(03) 1232 3244
Mon-Sun 10pm
"Mon-Sun 6am"
http:www.dsdsdsfirsthome.com

2ndHome
2903 Building 1
2ndHome
2HMF
3875    "2nd Adddedere"
-00.00001
002.323232
(03) 2223 2323
(03) 1233 4343
http:dsdd

asdsfadf.com

And Now I need to convert it to an XML File that should be like this:

Any Ideas?  thank you in advance.
I used BufferedReader to read the textfile from the sdcard and StreamResult to write the XML file. And then executed this:
TransformerConfigurationException, SAXException {
SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory.newInstance();
th = tf.newTransformerHandler();
Transformer serializer = th.getTransformer();
serializer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");       serializer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");  serializer.setOutputProperty(OutputKeys.INDENT, "yes");
th.setResult(aStreamResult);
th.startDocument();
atts = new AttributesImpl();
th.startElement("", "", "Homes", atts);

after that, while loop is called:
while ((aString = aBufferedReader.readLine()) != null){
process(word)
}

The method process(word) is this:
TransformerHandler th;
AttributesImpl atts;
public void process(String s) throws SAXException {
String[] elements = s.split(" ");
atts.clear();
th.startElement("", "", "Home", atts);
th.startElement("", "", "1stHome", atts);
th.characters(elements[0].toCharArray(), 0, elements[0].length());
th.endElement("", "", "1stHome");
th.startElement("", "", "Address", atts);
 th.characters(elements[0].toCharArray(), 0, elements[0].length());
th.endElement("", "", "Address");
th.endElement("", "", "Home");
}

After that just close the tags by calling closeXML();
public void closeXML() throws SAXException {
th.endElement("", "", "Homes");
th.endDocument();
}

The problem is that I read it line by line..

A: Extract the text form the file first. and then you can create xml document with tags as below using the W3C DOM. Modify the code accordingly.
http://www.mkyong.com/java/how-to-create-xml-file-in-java-dom/. Example of how to create a xml file.
 public class modifyXML {

   public modifyXML()
{
 try {

DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder docBuilder = docFactory.newDocumentBuilder();

    // root elements
Document doc = docBuilder.newDocument();
Element question = doc.createElement("question");
doc.appendChild(rootElement);

    Node  option= doc.createElement("option1");
    option.setTextContent("option1");
    question.appendChild(option);

//set up a transformer
TransformerFactory transfac = TransformerFactory.newInstance();
Transformer trans = transfac.newTransformer();

    //create string from xml tree
    StringWriter sw = new StringWriter();
    StreamResult result = new StreamResult(sw);
    DOMSource source = new DOMSource(doc);
    trans.transform(source, result);
    String xmlString = sw.toString();

    OutputStream f0;
byte buf[] = xmlString.getBytes();
f0 = new FileOutputStream("pathofxmlfile"+filename);
for(int i=0;i<buf .length;i++) {
   f0.write(buf[i]);
}
f0.close();
buf = null;
 }
 catch(SAXException e) {
e.printStackTrace();
 }
 catch(IOException e) {
    e.printStackTrace();
 }
 catch(ParserConfigurationException e) {
   e.printStackTrace();
 }
 catch(TransformerConfigurationException e) {
   e.printStackTrace();
 }
 catch(TransformerException e) {
   e.printStackTrace();
 }

}
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to store file with unicode characters using paperclip I'm using paperclip gem to process some images and store them to Amazon S3. Each image represents person's name. I want to add support for names with unicode characters as well, but I can't make it work because of paperclip fails to upload a file with unicode characters in its name.
I can't just change Ñ to N before uploading, because then I'll overwrite an image that was uploaded with letter N.
Eg.
Two users: NUÑO and NUNO. I can't just tell paperclip to upload NUÑO.jpg as NUNO.jpg because that will overwrite previous NUNO.jpg.
Here's my pretty much standard production/staging environment configuration:
config.paperclip_defaults = {
  :storage => :s3,
  :url => ':s3_domain_url',
  :path => 'assets/:class/:id/:style.:extension',
  :s3_credentials => {
    :bucket => ENV['AWS_BUCKET'],
    :access_key_id => ENV['AWS_ACCESS_KEY_ID'],
    :secret_access_key => ENV['AWS_SECRET_ACCESS_KEY_ID']
  }
}

And here's related class with image attachment:
class NameSpread < ActiveRecord::Base
(...)
  has_attached_file :rendered_image,
    default_url: lambda { |attach| attach.instance.processing_image },
    path: lambda { |attach| attach.instance.save_path },
    styles: { (..) },
    processors: [ :name_spread_processor ],
    default_style: :spread
(...)
end

Here's save_path method:
def save_path
  if Rails.env.production? || Rails.env.staging?
    "assets/:class/#{gender}/#{name}/:style.jpg"
  else
    "#{Rails.root}/public/assets/:class/#{gender}/#{name}/:style.jpg"
  end
end

This is the part that gets messed up: #{name}
Any ideas?

A: After two days of debugging, I found the solution.
I updated from ruby 1.9.2 to 2.0.0 and now everything works...


text:
Q: Merge multiple rows into a column while replacing the keys with a 'name' field from the original table I've got a join table that has 'account_id' and 'group id' in it, both represented by a GUID. I'm trying to merge the columns so we get a single 'account_id' with all of it's 'group_id's merged to a single Colum/row, but display the actual name of the account and group.
Tables
Account
account_id   Name
1            Henry
2            Smith

Group
Group_id   Group_nameName
3            User
4            Admin

Account_Group_Join_Table
account_id   group_id
1            3
1            4
2            3

Desired Result:
Name    Groups
Henry   Dev,User
Smith   User, Admin

Code so far to return 'account_id' with 'group_id' grouped to single row/column
select account_id,
  stuff((SELECT distinct ', ' + group_id
           FROM account_group_join t2
           where t2.account_id = t1.account_id
           FOR XML PATH('')),1,1,'') [Groups]
from account_group_join t1
group by account_id

A: You just need to join to your group table in the subquery so you can get the name rather than the ID. You also may as well just select from Account in the outer query and avoid an additional join to account to get the name:
SELECT  a.account_id,
        a.Name,
      STUFF((SELECT DISTINCT ', ' + g.group_nameName
               FROM account_group_join AS ag
                    INNER JOIN [Group] AS g
                        ON g.group_id = ag.group_id
               WHERE ag.account_id = a.account_id
               FOR XML PATH('')),1,1,'') AS [Groups]
from Account AS a;

n.b. I've changed your aliases from t1 and t2 to something that kind of represents the table I am aliasing, you'll find this much easier especially when working with larger queries. More reading here: Bad Habits to Kick : Using table aliases like (a, b, c) or (t1, t2, t3)


text:
Q: Looping the rows incrementing by 3 PHP and MYSQL I am having some difficulties to take the columns from database incremented by 3.
I have some columns in my table : 1 2 3
The columns are automatically incremented when user submits information.
So the second columns for the second data will be: 4 5 6
I make the table headings this way:
<?php

$a=1;
while ($a <= $FinalLoopColumns) {

    echo "".'CustomerName'.$a."	";
    echo "".'Pieces'.$a."	";
    echo "".'Date'.$a."	";

    $a++;
}

?>

So I need to insert data to "CustomerName" 1 and 4,  Pieces 2 and 5 and Date 3 and 6.
If I had to show my numbers from and array I would do it this way for the CustomerName:
$CustomerName=array(1,2,3,4,5,6);
for ($i=0; $i < sizeof($Musteri); $i+=3) {
    echo $CustomerName[$i];
}

So I assume I need to take the columns as array and then loop them to find the numbers for each value.
What is the best way to take the data this way from the database and inserting it to the table with while loop using array ? (or doing in another way)
Thanks !


text:
Q: What is the difference between Application.streamingAssetsPath and Application.persistentDataPath?How are they used? I have doubt regarding certain concepts between these two. For Application.streamingAssetsPath, I should create a StreamingAssets folder in my project, so that I can save files to it and later reload it. So what is the role of Application.persistentDataPath and the role of Application.streamingAssetsPath?
If I have assets and data (Position, health etc) to be saved and later reload them in mobile devices (Android and IOS) and PC. Which is the best option?
Below I save using Application.streamingAssetsPath
using (FileStream fs = new FileStream(Application.streamingAssetsPath + "/Position.json", FileMode.Create))
    {
        BinaryWriter filewriter = new BinaryWriter(fs);
        filewriter.Write(JsonString);
        fs.Close();

    }

A: Generally, use Application.persistentDataPath for data that was not available during build time and will be modified after being distributed (and should never be modified by a game update), and use Application.streamingAssetsPath for game data that exists before your build that you want to be able to read with IO systems during the game (and might be modified in a game update). For example, player save data likely should be placed in Application.persistentDataPath and dialogue files might be placed in Application.streamingAssetsPath.
The biggest technical difference is that usually Application.persistentDataPath can be saved in a location separate from the game data, so that an uninstall or update of the game will not cause a player to lose their data. Most of the difference is in intent, in that Application.persistentDataPath is intended for saving data between runs of a game, and Application.streamingAssetsPath is intended to allow developers to have game files that can be accessed by path name.

If you are storing the current position, current health, and current status of a character that you are keeping track of, you will want Application.persistentDataPath. If you are storing the data for the starting position, maximum health, and other stats of a character that you will use for initialization, Application.streamingAssetsPath would be a better pick.


text:
Q: Android 3.2 missing dialer? I am using the Android 3.2 emulator. I can't find the dialer. Hitting F3 does not bring up the telephone app. Many other things don't work. For example, in the Settings app, I can't go into individual settings page (like Language and input). Is this thing half cooked?

A:
I can't find the dialer.

Android 3.2 is for tablets. There is no dialer.

For example, in the Settings app, I can't go into individual settings page (like Language and input).

Launch Settings and click on "Language & input" on the left.
If by this you meant:
startActivity(new Intent(android.provider.Settings.ACTION_LOCALE_SETTINGS));

that too works on my copy of the Android 3.2 emulator.


text:
Q: Sampling from categorical distribution when the sorting step is ignored The commonly used algorithm to sample from categorical distribution is

*

*sort the vector of cumulative probabilities $\boldsymbol{p} = (p_1,p_2,\dots,p_n)$ in decreasing order from the categories appearing with greatest, to the ones appearing with lowest probabilities, to obtain the permuted
  vector $\boldsymbol{p}_{\pi}$,

*sample $u$ from uniform distribution on $(0,1)$,

*accept the lowest $k$ such that $p_{\pi(k)} \ge u$ as $X$ (where $\pi(k)$ is position of $k$ in permuted vector $\boldsymbol{p}_{\pi}$).

What the sorting (i.e. starting at mode) does it makes the number of comparisons to make before stopping smaller, so it should be more efficient* then the "naive" algorithm using unsorted probabilities (ordinary inverse transform).
However my question is: does ignoring the sorting step have any other effect on the algorithm besides decreasing the performance of the algorithm (I guess not, but I'm looking for justification)? Moreover, how much (when) does it actually change in terms of performance?
* - I made some benchmark tests on this but they did not give any conclusive results.

A: The algorithm recommended in the question is not guaranteed to be the most efficient in terms of comparisons (even ignoring the number of comparisons done during the sorting phase.)  Consider the following algorithm:

*

*(Initialization). Calculate the cumulative probabilities $p_k, \space k = 0,\dots, K$,

*Sample $u$ from the Uniform distribution on $(0,1)$,

*Find the smallest $k$ such that $p_k > u$ using binary search (https://en.wikipedia.org/wiki/Binary_search_algorithm).

This works because the cumulative probabilities are ordered, and it takes on average $\log_2 K-1$ comparisons to find the answer no matter what the distribution of the probabilities is.  The worst-case performance is $\log_2 K + 1$ for the worst possible choice of $u$, regardless of distribution.  The algorithm presented in the OP has a worst-case expected performance of $K/2$, achieved when all the $p_k$ are equal, but a best-case performance arbitrarily close to $1$ (when one of the $p_k$ has a probability very near $1$.)  It can take as many as $K-1$ comparisons for any given $u$ no matter what the distribution is.
Note that for distributions with nonincreasing probabilities, such as the Geometric, the actual order of the elements of the vector being searched is the same for the two algorithms, and is the same as the order of the values themselves.  The recommended algorithm becomes a linear search on the vector of cumulative probabilities, which makes for easy comparisons between the two.  Interestingly enough, if the lower bound on the values is 0, the expected number of comparisons is equal to the expected value of the variate + 1!  We can see that by observing that, in order to return a given value $x$, $x+1$ comparisons must have been made to reach that position in the list (the first position corresponding to $x=0$); and, given that the generator works, it must be that the probability of returning $x$ is equal to $p_x$.  Therefore the probability of making $x+1$ comparisons is $p_x$, so the expected value of the number of comparisons is $\text{E}x+1$.  Obvious alterations can be made for other lower bounds.
Clearly (in this case) if $\text{E}x+1 \geq \log_2K-1$ we would prefer the binary search algorithm.  This comparison can obviously be extended to the general case by calculating the expected value of a variate on $[1, \dots, K]$ with probabilities $q_k$ corresponding to the sorted probabilities $p_j$ from the original distribution on whatever the range of $j$ was.
It would seem that the more heavily the distribution is concentrated in a small fraction of values, the better the recommended algorithm will be, but if you want something with guaranteed good performance both in terms of expected comparisons across distributions and worst-case comparisons, the binary search approach may be better.  (Of course, if $K$ is small enough, a linear search on the CDF will outperform a binary search in runtime if not comparison count, as it avoids calculating and tracking the upper and lower bounds of the interval in which the answer is known to lie.)

A: Rather than expressing this algorithm in terms of search of a value satisfying an inequality, you can express it equivalently as a simple sum of indicators.  Since you are interested in efficiency, it is also useful to vectorise the algorithm, allowing you to generate $m$ independent sample values.  With this setup, the algorithm can be expressed as follows:

Vectorised sampling algorithm:

*

*You have a probability vector $\boldsymbol{p} = (p_1,...,p_n)$.

*Sort this by permutation $\pi$ to get $\boldsymbol{p}_* = (p_{\pi(1)},...,p_{\pi(n)})$.  (If you don't want to sort then you can just take $\boldsymbol{p}_* =\boldsymbol{p}$.)

*Calculate the cumulative permuted probabilities $(F_1,...,F_{n-1})$ given by:
  $$F_k \equiv \sum_{i=1}^{k} p_{\pi(i)}.$$

*Simulate continuous uniform random variables $U_1,...,U_m \sim \text{IID U}(0,1)$.

*Set $K_1,...,K_m$ as follows:
  $$\pi(K_i) \equiv 1 + \sum_{k=1}^{n-1} \mathbb{I}( U_i > F_k ).$$
  Note: In the summation formula, once you get a single zero indicator, all later indicators are zero, so you can terminate the sum early, as soon as you get a zero indicator.

From this re-statement of the sampling algorithm, we can see that the benefit of sorting the probabilities into decreasing order is that the partial sums of the reordered probabilities start with the biggest values and so they increase rapidly early on.  This makes it more likely that you will get to a zero indicator earlier, which allows you to terminate the sum, thereby saving some computational time.

However my question is: does ignoring the sorting step have any other effect on the algorithm besides decreasing the performance of the algorithm?

I can't see any other difference.  Mathematically the algorithm works regardless of the permutation used (including no permutation).  Thus, the only difference seems to be one of computational efficiency.

... how much (when) does it actually change in terms of performance?

Presumably you get an efficiency gain from sorting when the computational cost of applying and reversing the permutation $\pi$ is smaller than the computational gain from ending the summations earlier in the last step of the algorithm.  Hence, you are more likely to get a larger computational gain when the number of categories $n$ is large and/or the number of samples $m$ is large.  That is, the sorting step in the algorithm will tend to be more efficient when you are generating a larger number of samples from a categorical variable with a larger number of categories.

A: The ordering of the cumulative distribution is not needed, but its there automatically.
Let $(\phi_1,\ldots,\phi_n)$ be the categorical distribution and $p_i=\sum_{k=1}^i\phi_k$ the entries of the cumulative distribution. Now, since $p_1\le \ldots \le p_i\le p_{i+1}\le \ldots p_n$, the probability that a uniformly drawn $u\in (0,1)$ is in $(p_i,p_{i+1})$ is exactly $p_{i+1}-p_i=\phi_i$.
Even if the cumulative ordering is not ordered, that is you have $(p_{\pi(1)},\ldots,p_{\pi(n)})$, you would have to determine the $\pi(k)$ such that $p_{\pi(k)}=\max\{p_{\pi(i)}: p_{\pi(i)}\le u\}$ (max, because I sorted incresingly). Since the position of $p_{\pi(k)}$ in the unsorted cumulative distribution is $k$, you would chose $\phi_k$.


text:
Q: Converting factor to numeric I have a 3 million row, 500 column dataset. Although the columns are numeric, when importing from csv file, all are treated as factor, not numeric. I am trying to convert them back to numeric with the command
wikifixedn<-as.numeric(as.character(wikifixed))

wikifixed is the dataframe.
It's taking forever... My MacBook Pro, with 16GB ram and 2.3GHz Core i7 has been churning at this for more than an hour. Can I see somewhere how far along am I in the process or if the process is moving along? Is here another, faster method to deal with the conversation problem?
BTW: I tried, when importing the csv file, to force the columns to be treated as numeric using
> wikifixed<-read.csv('~/OneDrive/kredible/finaldata/wutao/wikipediausers.csv', header = TRUE, stringsAsFactors=F)

Yet, when checking I get
> is.numeric(wikifixed)
[1] FALSE

A: See here
https://stat.ethz.ch/R-manual/R-devel/library/utils/html/read.table.html
you probably should create a vector for colClasses
read.table(file, header = FALSE, sep = "", quote = "\"'",
       dec = ".", numerals = c("allow.loss", "warn.loss", "no.loss"),
       row.names, col.names, as.is = !stringsAsFactors,
       na.strings = "NA", colClasses = NA, nrows = -1,
       skip = 0, check.names = TRUE, fill = !blank.lines.skip,
       strip.white = FALSE, blank.lines.skip = TRUE,
       comment.char = "#",
       allowEscapes = FALSE, flush = FALSE,
       stringsAsFactors = default.stringsAsFactors(),
       fileEncoding = "", encoding = "unknown", text, skipNul = FALSE)

stringsAsFactors
logical: should character vectors be converted to factors? Note that this is overridden by as.is and colClasses, both of which allow finer control.
colClasses
character. A vector of classes to be assumed for the columns. Recycled as necessary, or if the character vector is named, unspecified values are taken to be NA.
Possible values are NA (the default, when type.convert is used), "NULL" (when the column is skipped), one of the atomic vector classes (logical, integer, numeric, complex, character, raw), or "factor", "Date" or "POSIXct". Otherwise there needs to be an as method (from package methods) for conversion from "character" to the specified formal class.
Note that colClasses is specified per column (not per variable) and so includes the column of row names (if any).
ALSO see here in case you want to go to data.table because you may run into more issues.
fread in R imports a large .csv file as a data frame with one row
require(data.table)
fread("pre2012_alldatapoints.csv", sep = ",", header= TRUE)

and read
the data.table FAQ at
https://github.com/Rdatatable/data.table/wiki


text:
Q: Get publish profile returns unauthorised user I'm trying to debug a web API on azure and need to access the logs from FTP
Whenever I try and download the publish profile in order to learn my FTP connection details, I get an error page saying credentials were incorrect
How can this be if I'm already logged in?

A: Make sure you have privileged permissions to the resources which you are trying to access.
Incase if you haven't set the credentials for your Web API, suggest you set the credentials first using the azure portal.
Select your Azure Web App/API -> under deployment credentials set your FTP deployment credentials. For more details, you can refer the below screenshot.

You could also use Get-AzurePublishSettingsFile PowerShell cmdlet to download the publish settings profile file.


text:
Q: Capture pid of a process started from a terminal with its unique command line I'm trying to get the process id of multiple processes run from a multiple tmux windows. Each processes started have their unique command line. I think only the command line is unique as there can be multiple processes with same name. what i did currently is
process_pid=$(ps --no-headers aux | grep "${process_cmd_line}" | grep -v grep | awk '{print $2}' | tr '\n' '')

This works for me. But i want to know if this is the correct approach to do this. I know there are output format specifiers. Any example to do the same with the format specifier or an improvement over the code above?


text:
Q: Need some hint for a coffescript/jQuery iteration I tried
alert x for x in $("p").text()

to alert paragraph by paragraph... but instead it alert letter by letter (lol, wtf...). Then I tried this
alert x.text() for x in $("p")

but it doesnt work either. Can you help me to iterate for all the texts of paragraphs? Thank you in advance and happy new year!!!!

A: Try:
alert x.innerText for x in $('p')
How does this work? Firstly, let's transpile it to JS. According to the CoffeeScript website, it transpile's this code to:
var i, len, ref, x;

ref = $('p');
for (i = 0, len = ref.length; i < len; i++) {
  x = ref[i];
  alert(x.innerText);
}

Proof that this transpiled code works: JSFiddle.
What does this code do?
Firstly, we call the jQuery library passing a selector p, which will fetch all the paragraphs to the ref variable as an object.
In the loop, depending on the number of paragraphs fetched, it will loop that many times. The variable x is given the value of the current p in the object. Then, we alert the innerText property of the the x object which represents the p in HTML.

A: Ok, I solved the question and I realized how newbie Im, lol. The objects of jQuery are objects, not arrays, then when I do something like
alert x.text() for x in $("p")

x are the values of the object $('p') that is something different that thinking $('p') as a kind of array of paragraphs. Then the solution is something like this
for x,i in $('p')
  alert $('p').eq(i).text()

P.S.: maybe with the full documentation about the internal structure of the jQuery DOM I can try something different, but by now this works perfectly.


text:
Q: Return records beetwen 2 years in MongoDB I have written this code here I want to The list of the movies released between 1967 and 1995, by displaying only title and year.
But no document is being found even if they accept the condition
 db.collection.aggregate({
      "$project": {
        "title": 1
      }
    },
    {
      "$match": {
        "year": {
          "$gt": 1967,
          "$lt": 2020
        }
      }
    })

Here is the collection
{
    "_id": "movie:90",
    "title": "The Dark Knight Rises",
    "year": 2012,
    "genre": "Science-fiction",
    "summary": "Il y a huit ans, Batman a disparu dans la nuit : lui qui était un héros est alors devenu un fugitif. S'accusant de la mort du procureur-adjoint Harvey Dent, le Chevalier Noir a tout sacrifié au last_name de ce que le commissaire Gordon et lui-même considéraient être une noble cause. Et leurs actions conjointes se sont avérées efficaces pour un temps puisque la criminalité a été éradiquée à Gotham City grâce à l'arsenal de lois répressif initié par Dent.Mais c'est un chat – aux intentions obscures – aussi rusé que voleur qui va tout bouleverser. À moins que ce ne soit l'arrivée à Gotham de Bane, terroriste masqué, qui compte bien arracher Bruce à l'exil qu'il s'est imposé. Pourtant, même si ce dernier est prêt à endosser de nouveau la cape et le casque du Chevalier Noir, Batman n'est peut-être plus de taille à affronter Bane…",
    "country": "USA",
    "director": {
      "_id": "artist:266",
      "last_name": "Nolan",
      "first_name": "Christopher",
      "birth_date": "1970"
    },
    "actors": [
      {
        "_id": "artist:22",
        "first_name": "Morgan",
        "last_name": "Freeman",
        "birth_date": "1937",
        "role": "Lucius Fox"
      }

A: You have to revert the order of your aggregation operations since your $project will only leave one property title so there is no way to filter by year afterwards:
db.collection.aggregate([
    {
        "$match": {
            "year": {
                "$gt": 1967,
                "$lt": 2020
            }
        }
    },
    {
        "$project": {
            "title": 1,
            "year": 1
        }
    }])

Mongo Playground

A: db.movies.find({year: {$gte:1967, $lte:1995} },{title:1,year:1,"director.last_name":1 }).sort({year:1})


text:
Q: Проблема с языком при парсинге сайта При парсинге страницы данные упорно выдает на китайском языке, хотя в html шаблоне стоит en
from bs4 import BeautifulSoup
import requests

#headers = {"Accept-Language": "en-US,en;q=0.5"}
url = "https://www.joytoy.com/warhammer/6719.html"
page = requests.get(url).content

soup = BeautifulSoup(page, "lxml")

items = soup.find("div", class_="product_right clearfix")
print(items.text.strip())

Ответ:
极限战士入侵者
spot-goods
¥599

比例: 1:18
兵人高:120mm
材质: ABS PVC
产品重量: 0.25kg
包装尺寸: 254*208*176
发布时间: 9,2021
适用年龄: 17+
UPC:6973130371286

A: Вот рабочий код, который вернёт вам то что Вам нужно:
from bs4 import BeautifulSoup
from selenium import webdriver
import time
from selenium.webdriver.chrome.options import Options

url = 'https://www.joytoy.com/warhammer/6719.html'

headers = {
    "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.82 Safari/537.36",
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9",
}

def get_result(url, headers):

    chrome_options = Options()
    chrome_options.binary_location = "/opt/google/chrome/google-chrome"
    options = webdriver.ChromeOptions()
    options.add_argument('--headless')
    options.add_argument('--no-sandbox')
    driver = webdriver.Chrome(options=chrome_options, executable_path=".../chromedriver_linux64/chromedriver")
    driver.get(url)
    time.sleep(10)  # Можно ждать до загрузки страницы, но проще подождать 10 секунд, их хватит с запасом
    html = driver.page_source

    soup = BeautifulSoup(html, "lxml")

    items = soup.find("div", class_="product_right clearfix")
    print(items.text.strip())

def main():
    get_result(url=url, headers=headers)

if __name__ == "__main__":
    main()

Вывод:
ULTRAMARINES INCURSORS
In-stock
$119.99

Product Scale: 1:18
Soldier Size:120mm
Material: ABS PVC
Weight: 0.25kg
Packing size(mm): 254*208*176
Release: 9,2021
Applicable Age: 17+
UPC:6973130371286


text:
Q: Why isn't phaser.js able to load an image from a third-party domain? I'm learning phaser.js, and I cant even load the image.
Here is the code:
// Need state. All game logic goes in state

var GameState = {

    // Load all your images. Thats what the preload function is
    preload : function(){
        //Load Image
    this.load.image( 'background', 'https://encrypted-tbn3.gstatic.com/images?q=tbn:ANd9GcSMxwX5oTml7qBFmUD3vEIzEhqLQfakBVjmkQezA8HKs4KnT-2Q' );

    },

    //Execute after everything is loaded
    create: function(){
        //From top left param = (x,y)
        this.background = this.game.add.sprite(0,0, 'background');

    },

    update: function(){

    }

}

// New Game instance, 3rd parameter WEBGL or CANVAS automatic  GL
var game = new Phaser.Game(640,360,Phaser.automatic);

// add state to game

// First just a name, second par is the actual Object
game.state.add('GameState', GameState);
game.state.start('GameState');

And here is the image that clearly shows that it doesen't load:

A: Your image isn't showing up because Phaser can't make use of cross-origin images, so all images need to be loaded from the same origin. In practice, this means that instead of loading the image directly from gstatic.com, you need to first download the image to your computer, then move it to your Phaser project folder and load it using a relative path.
For more information, please see the Wikipedia article on the Same-Origin Policy.


text:
Q: improving the count() performance in MySQL I have a mysql query like below.
   SELECT `indexVal`, COUNT(`indexVal`)
   FROM `key_word`
   WHERE `hashed_word` IN ('001','01v','0ji','0k9','0vc','0@v','0%d','13#' ,'148' ,
                           '1e1','1sx','1v$','1@c','1?b','1?k','226','2kl','2ue',
                           '2*l','2?4','36h','3au','3us','4d~')
   GROUP BY `indexVal`

This query take 5 seconds to generate the results! I even have a compound index created with ALTER TABLE key_word ADD INDEX (hashed_word, indexVal). Please note that my query is counting how many times indexVal appeared in the "search" and not how many times it appears in the "table".
My table is having 3 columns, 28 million records, future table will have billions of records. I am using InndoDB, I just selected it. Below is my table Show Create Table result
CREATE TABLE `key_word` (
 `primary_key` bigint(20) NOT NULL AUTO_INCREMENT,
 `indexVal` int(11) NOT NULL,
 `hashed_word` char(3) NOT NULL,
 PRIMARY KEY (`primary_key`),
 KEY `hashed_word` (`hashed_word`,`indexVal`)
) ENGINE=InnoDB AUTO_INCREMENT=28570982 DEFAULT CHARSET=latin1

I ran the above select query with Explain command. Below is the result

So how can I speed up this? I prefer to have the result in less than 1 second. I appreciate your advice.
PS: I don't need the result to be in any order.

A: Try an index with reversed orders of columns:
create index xx on key_word( `indexVal`,`hashed_word`);

This may help prevent from using the filesort by the optimizer,
but I don't think that this can help to speed up the query by 500% from 5 sec to less than 1 sec.
You probably need a faster hardware.


text:
Q: FAST and BLAZOR - How to change the Color Palette of fluent-design-system-provider with Blazor I am evaluating the new Microsoft fast.design https://www.fast.design/ with fluent-design-system-provider and trying to customize the accent color for Blazor project but no luck...
This is what I did so far as per the official documentation (https://www.fast.design/docs/design-systems/fast-frame):
In my asp.net core Blazor Server Project's _Host.cshtml
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>Title </title>
    <base href="~/" />
    <link rel="stylesheet" href="css/bootstrap/bootstrap.min.css" />
    <link href="css/site.css" rel="stylesheet" />
    <link href="Test.Main.styles.css" rel="stylesheet" />

    <fluent-design-system-provider use-defaults>
        <component type="typeof(App)" render-mode="ServerPrerendered" />

            <environment include="Staging,Production">
                An error has occurred. This application may no longer respond until reloaded.
            </environment>
            <environment include="Development">
                An unhandled exception has occurred. See browser dev tools for details.
            </environment>
            Reload

    </fluent-design-system-provider>

After this in my site.js I am trying to generate and replace the color pallete as mentioned in the documentation https://www.fast.design/docs/design-systems/fast-frame#generating-and-replacing-palettes
import { parseColorHexRGB } from "@microsoft/fast-colors";
import { createColorPalette } from "@microsoft/fast-components";

// Initialization
(function () {
    const palette = createColorPalette(parseColorHexRGB("#28EBD7"));
    const provider = document.querySelector("fluent-design-system-provider");

    // change the neutral color pallete
    provider.neutralPalette = palette;
})();

I get the following error,
Uncaught TypeError: Failed to resolve module specifier "@microsoft/fast-colors". Relative references must start with either "/", "./", or "../".
How do i resolve this ?

A: As far as I know, the import is used in the client application (such as Angular, Teactjs), instead of Asp.net Core Blazor. If you are create a Client application, you could check the Fast Integrations.
To integrate Fast with Asp.net Core Blazor, after installing the Fast using the following command:
npm install --save @microsoft/fast-components

You can locate the single file script build in the following location:
node_modules/@microsoft/fast-components/dist/fast-components.min.js

Copy this to your wwwroot/script folder and reference it with a script tag as described above. Code in the Razor page like this:

More detail information, see Fast Integrations for Asp.net Core Blazor.

A: I missed to add the complete path to the fluent components js files, referencing the correct path works well!
import { neutralLayerL1Behavior, parseColorString } from "https://unpkg.com/@fluentui/web-components";
import { createColorPalette } from "https://unpkg.com/@microsoft/fast-components";

export function initDesignSystemProvider() {

    const designSystemProvider = document.querySelector("fluent-design-system-provider");

    var accentBaseColor = "#204320";
    const accentPalette = createColorPalette(parseColorString(accentBaseColor));
    designSystemProvider.accentBaseColor = accentBaseColor;
    designSystemProvider.accentPalette = accentPalette;

}


text:
Q: SIGABRT when launching app with CoreData on iPhone 3.1.3 I am using CoreData on my iPhone app. When I test the app on a old 1g iPhone running iOS 3.1.3 I get a SIGABRT in this method
#pragma mark - Application's Documents directory

/**
 Returns the URL to the application's Documents directory.
 */
- (NSURL *)applicationDocumentsDirectory
{
    return [[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject];
}

*** -[NSFileManager URLsForDirectory:inDomains:]: unrecognized selector sent to instance 0x106920
2011-04-08 23:49:26.311 TestApp[963:207] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[NSFileManager URLsForDirectory:inDomains:]: unrecognized selector sent to instance 0x106920'
2011-04-08 23:49:26.321 TestApp[963:207] Stack:...

I am using XCode 4. It seems like the selector is not supported, however I thought they were saying that CoreData should work on iOS > 3.....so why are does the code that is generated along with it not working...

A: URLsForDirectory is only available in iOS 4.0 and later

A: Because the code is NOT related to Core Data but to an Foundation method on the NSFileManager class which is available since iOS 4.0.


text:
Q: Add gutter on masonry with the bootstrap3 grid I'm having trouble with coding gutter on masonry with the bootstrap3 grid.
This is my jsfiddle.   https://jsfiddle.net/shelly_W/bg67fdjm/

Masonry - Bootstrap 3 grid media queries

1

2

3

4

5

6

7

8

Source is: https://masonry.desandro.com/
What I'm trying to achieve is having 15px gutters between the masonry grid. I want to create a space between grid 1 and grid 2. I don't want padding on either of the outer container div edges of grid 1 or grid 2.
I attempted to insert a 15px gutter by js, but this approach breaks the bootstrap responsive columns.
I've been trying to work this out for some time, but I can't figure out the right approach. Does anyone have any suggestions on how I might resolve this issue?
Please let me know if you need any further information.
Thank you in advance for your help!

A: All you have to do is remove your current padding declarations on your .grid-size selector and use margin-bottom instead.
.grid-size {
    margin-bottom: 4%;
}

You can use a static value if you'd prefer; I used it a percentage here because you're going for a responsive design.
Here you can see your fiddle updated and in action.

A: If you want a solution that goes all the way to the edges and maintains a 15px gutter, you can keep your padding and use the CSS calc() method to adjust for the responsive container.
.grid-sizer { width:calc(33.33% - 10px); }
.grid-item { width: calc(33.33% - 10px); }
.grid-item--width2 { width: calc(66.66% - 5px); }

Then you just need to add media queries to your CSS to responsively change the width of the items:
@media (max-width: 500px) {
  .grid-sizer { width:calc(50% - 7.5px); }
  .grid-item { width: calc(50% - 7.5px); }
  .grid-item--width2 { width: 100%; }
}
@media (max-width: 350px) {
  .grid-sizer { width:100%; }
  .grid-item { width: 100%; }
}

Check out this fiddle:
JSFiddle


text:
Q: Standardization with Interface in .Net I have a weird question about OOP and interfaces which messed up my mind while trying to find best design.
There are two different classes which make same work (for example sending message) at different environments. These two environments use different parameters to define recipient; one is using mail address and the other one is using user name.
So both the classes have same but slightly different methods for sending message.
MessageSenderViaMailManager.cs
public bool SendMessage(string recipientMailAddress, string message) {
..
}

MessageSenderViaUsernameManager.cs
public bool SendMessage(string recipientUserName, string message) {
..
}

There are other similar methods in both classes, responsible for same work but may require different parameters.
To make usable these managers with an interface, i created one which name is IMessageSenderManager and contains a definition like this.
public bool SendMessage(string recipientUserName, string recipientMailAddress, string message);

So both SendMessage methods in my classes were changed to this:
public bool SendMessage(string recipientUserName,string recipientMailAddress, string message) {
 ..
}

With this new SendMessage method, i can use appropriate parameter to use as recipient (mail address or username). This seems ok, but implemantation looks like weird. Because i have to send all parameters, without knowing which will be used at runtime while coding. For example:
// Sending message via username implementation
string userName = GetUserNameFromSomeWhere();
string mailAddress = GetUserMailFromSomeWhere();
IMessageSenderManager manager = MessageSenderFactory();
manager.SendManager(userName, mailAddress, "This messaged sent by your user name");

Like code above, sending message by mail address looks similar.
In my opinion this is not a good design so i started to think for a better solution. Bacause if i want to implement another MessageSender provider which uses different descriptor for recipient, i have to add another parameter to my interface, so to all classes.
I thought, i could change two recipient parameters with one general recipient parameter and send appropriate value for context. But i am trying to use this in dynamic enviroment and the way (via user name or mail) will be determined in runtime, so i couldn't use this.
I am planing to make this, a flexible library which can be used decoupled or unit test friendly for other developers and i don't want to confuse them with meaningless parameters or with bad design.
Is there any better design for a situation like this?
EDIT:
Actually by my mistake, i forgot very big and important part of my question, i am sorry for this.
As you can see from answers there are some alternatives to solve my first problem which described above. But then?
I mentioned in code, interface is returned from MessageSenderFactory() method but i don't know which message sender manager returned. So i have two options,

*

*Write if condition to check which manager is returned from method and send mandatory parameters for that manager with proper values and send others empty.

*Send all parameters with proper values regardless of manager, so both of them can work without problem. But in future, if another manager is added than i will need to send extra parameters for that manager, everytime.

*Is there another way which i couldn't think yet?

Also other methods than SendMessage may require different parameters according to manager which is unknown at runtime. For example:
MessageSenderViaMailManager's AddContact method may require parameters below:

*

*Contact Name

*Contact Mail

*Contact Phone Number

*Contact MailType (rich, plain)

or MessageSenderViaUserNameManager's AddContact method may require parameters below:

*

*Contact Name

*Contact Mail

*Contact User Name

*Contact Message Platform (Twitter, facebook, vs)

*Contact Sender Name

So this makes everything very complicated.
How my IMessageSenderManger's AddMethod should be? Should it contain all parameters? Should i overload it? Or should i put common parameters in method and make other parameters which vary by manager anonymous (like HtmlHelper in MVC)
I know this is question isn't very solid and i am not good at describing in English.
GitHub EDIT:
I created a small example and uploaded to github, i hope this can help me to explain my question better
https://github.com/bahadirarslan/InterfaceDesign

A: Why not have you interface as follows:
public bool SendMessage(string recipient, string message) {
..
}

Then within the logic of each class you add some code to validate the recipient information, so for example you implementation that expects an e-mail address, add validation to check what you are passed is a valid e-mail address.
Then in your implementation that expects a username, validate you can find the user.
You could always implement that checking in your factory so it knows which class to create.

A: I would create a class MailMessage which contained a recipients property. Then on that MailMessage class have 2 overloads of an AddRecipient method. One for each of the ways you are adding recipients.

A: Update: Former answer redacted for clarity.
I've changed the code to utilize your structure.
public static class MessageSenderManagerFactory
{
  public static IMessageSenderManager Create(IRecipient recipient)
  {
    return new MessageSenderManager { Recipient = recipient };
  }
}

public interface IMessageSenderManager
{
  public IRecipient Recipient { get; set; }
  bool SendMessage(string message);
}

public class MessageSenderManager : IMessageSenderManager
{
  public IRecipient Recipient { get; set; }

  public bool SendMessage(string message)
  {
    // At this point you construct the actual message and sending mechanism.
    // You'll have all the information you need in the TheUser property of Recipient.
    // The following is an example how this can be implemented but since you have not
    // provided what information you need to send or HOW you send the message I can't
    // be more specific.

    var messageToSend = new Message(message);
    messageToSend.Address = Recipient.GetRecipientAddress();

    messageToSend.Send();
  }
}

public interface IRecipient
{
  public string GetRecipientAddress();
}

public abstract class RecipientBase
{
  public User TheUser { get; set; }
  private RecipientBase() { }
  protected RecipientBase(string userId) { TheUser = FindUserById(userId); }
}

public class MailRecipient : RecipientBase, IRecipient
{
  public MailRecipient(string userId) : base(userId) { }
  public string GetRecipientAddress() { return TheUser.Mail; }
}

public class UserNameRecipient : RecipientBase, IRecipient
{
  public UserNameRecipient(string userId) : base(userId) { }
  public string GetRecipientAddress() { return TheUser.UserName; }
}

So when you have the user id you use one of the following lines depending the type of recipient (as you do with switch-case in your git example):
var manager = MessageSenderManagerFactory.Create(new MailRecipient(userId));
var manager = MessageSenderManagerFactory.Create(new UserNameRecipient(userId));

The logic of which type of Recipient to use should not be based on the users id. There should be a flag or setting in the database or User object that specifies this.
Then to send the message:
manager.SendMessage(message);

Disclaimer: Code not tested.

A: Design is always the result of a specific set of requirements. It's no different with OO: there are virtually infinite ways to implement a library that can send e-mails in various circumstances. Which design/implementation is good depends entirely on your situation. So asking 'what design is best' is meaningless unless you reveal some more details about your requirements:
Why do you want/need to redesign what you have already implemented?
Nonetheless, I agree that tha abstraction you have chosen (one method with multiple parameters, which are optional or mutual exclusive depending on which information the client had), seems poor. Generally, methods and classes are best designed simply and straightforward, such that every parameter makes sense. In other words: your first design with two different classes is, IMHO, better than your second one, because it better aligns with the Single Responsibility Principle.


text:
Q: Create a group id when grouping by several variables I would like to create an id variable to identify the unique groups according to several variables.
For example, I have the data cars from sashelp.cars, and I would like to identify unique groups of Make - DriveTrain and Cylinder with the id variable grp_id. So the same Make and same DriveTrain with a different number of Cylinder would be considered as a new group (and hence, a new value in the id variable grp_id).
I tried the following, but this would reset the id variable to 1 when there is a new case, nor really considering every unique combination of Make + DriveTrain + Cylinder as a different group id.
data cars; set sashelp.cars; run;

proc sort data=cars; by Make DriveTrain Cylinders; run;
data cars; set cars;
grp_id + 1;
by Make DriveTrain Cylinders
if first.Make or first.DriverTrain or first.Cylinders then grp_id = 1;
run;

Any idea on how to create this grp_id variable using several variables as the criteria?

A: You want each combination to have a unique group id.  Don't reset the group id.  If you were also assigning a seq number within the group, you would reset the sequence variable.
When to reset.  For combinations, increment the group id when the last listed by variable is tagged as having state first.
Example:
proc sort data=sashelp.cars out=cars;
  by Make DriveTrain Cylinders;
run;

data cars;
  set cars;
  by Make DriveTrain Cylinders;

  if first.Cylinders then grp_id + 1;

  * this answer gives you bonus information ! ;
  if first.Cylinders
    then seq_in_group = 1;
    else seq_in_group + 1;
run;

Note: Conceptually BY defines a hierarchy of n variables.  When a variable in the hierarchy changes value, during a serial pass through the data, its state is set first.varm=1.  Additionally all the subordinate levels first. automatic variables will have the same state.  In other words, this assertion is true: first.varm+1=1 ... first.varn=1.

A: As an alternative, here is a hashing approach that does not require sorting.
data cars;
   if _N_ = 1 then do;
      declare hash h ();
      h.definekey ('Make', 'DriveTrain', 'Cylinders');
      h.definedata ('grp_id');
      h.definedone();
   end;

   set sashelp.cars;

   if h.find () ne 0 then grp_id + 1;
   h.replace();
run;

A: Using your own code, you only have to make a small change
data cars;
   set sashelp.cars;
run;

proc sort data=cars;
   by Make DriveTrain Cylinders;
run;

data cars;
   set cars;
   by Make DriveTrain Cylinders;
   if first.Make or first.DriveTrain or first.Cylinders then grp_id + 1;
run;


text:
Q: Tfidfvectorizer from sklearn - how to get matrix I would like to get matrix out of Tfidfvectorizer object from sklearn. Here is my code:
from sklearn.feature_extraction.text import TfidfVectorizer
text = ["The quick brown fox jumped over the lazy dog.",
        "The dog.",
        "The fox"]

vectorizer = TfidfVectorizer()
vectorizer.fit_transform(text)

Here is what I tried and got back errors:
vectorizer.toarray()

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last) <ipython-input-117-76146e626284> in <module>()
----> 1 vectorizer.toarray()

AttributeError: 'TfidfVectorizer' object has no attribute 'toarray'

another attempt
vectorizer.todense()

---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-118-6386ee121184> in <module>()
----> 1 vectorizer.todense()

AttributeError: 'TfidfVectorizer' object has no attribute 'todense'

A: Note that vectorizer.fit_transform returns the term-document matrix that you want to obtain. So save what it returns, and use todense, as it will be in sparse format:

Returns: X : sparse matrix, [n_samples, n_features].
  Tf-idf-weighted document-term matrix.

a = vectorizer.fit_transform(text)
a.todense()

matrix([[0.36388646, 0.27674503, 0.27674503, 0.36388646, 0.36388646,
         0.36388646, 0.36388646, 0.42983441],
        [0.        , 0.78980693, 0.        , 0.        , 0.        ,
         0.        , 0.        , 0.61335554],
        [0.        , 0.        , 0.78980693, 0.        , 0.        ,
         0.        , 0.        , 0.61335554]])

A: .fit_transform itself returns a document term matrix. So, you do:
matrix = vectorizer.fit_transform(text)

matrix.todense() use to convert the sparse to dense matrix.
matrix.shape will give you the shape of matrix.


text:
Q: can anyone suggest good document to learn batch apex? That has in depth details about all database class methods? I have looked through several blogs and couldn't find a detailed document that includes all methods of Database class. I could only get detail of start, execute and finish. I am interested in details about Database.BatchableContext, Database, Database.Batchable, update and every other that exists for that class.

A: Don't go to blogs for this kind of thing, go straight to the source: documentation! Batch apex is well documented. Start with the linked references in the Apex Developer Guide and work through the relevant Trailhead modules. Here are some references you should examine:

*

*Database Class

*

*executeBatch(batchClassObject)
  Submits a batch Apex job for execution corresponding to the specified class.

*executeBatch(batchClassObject, scope)
  Submits a batch Apex job for execution using the specified class and scope.

*Batchable Interface

*

*execute(jobId, recordList)
  Gets invoked when the batch job executes and operates on one batch of records. Contains or calls the main execution logic for the batch job.

*finish(jobId)
  Gets invoked when the batch job finishes. Place any clean up code in this method.

*start(jobId)
  Gets invoked when the batch job starts. Returns the record set as an iterable that will be batched for execution.

*start(jobId)
  Gets invoked when the batch job starts. Returns the record set as a QueryLocator object that will be batched for execution.

*BatchableContext Interface
You'll likely never need to call the methods on this parameter, but it has two:

*

*getChildJobId()
  Returns the ID of the current batch job chunk that is being processed.

*getJobId()
  Returns the batch job ID.

*Using Batch Apex Unit


text:
Q: Singleton in Kotlin I want to implement "singleton" pattern in Kotlin. I wrote something like this.
class MySingleton {
    companion object {
        val instance = MySingleton
    }
}

But now users can create instances.
val mySingleton = MySingleton()

I want allow only this way.
val instance = MySingleton.instance

How can I ban using a constructor of my class?

A: if you use an object instead of a class you may have better luck
ie.
object MySingleton {
    val thingA = 0
}


text:
Q: How to inject service to the factory class / Java Hi I was wondering what if Addition() has some variable. Let's say Addition(SomeService service). How to inject it in this example?
public class OperatorFactory {
    static Map<String, Operation> operationMap = new HashMap<>();
    static {
        operationMap.put("add", new Addition());
        operationMap.put("divide", new Division());
        // more operators
    }

    public static Optional<Operation> getOperation(String operator) {
        return Optional.ofNullable(operationMap.get(operator));
    }
}

I took it from here: https://www.baeldung.com/java-replace-if-statements
I am trying to replace my "ifology" to what's above but when I inject something it is always null. For instance:
    public class OperatorFactory {
        private static SomeService service;
        static Map<String, Operation> operationMap = new HashMap<>();
        static {
            operationMap.put("add", new Addition(service));
            operationMap.put("divide", new Division());
            // more operators
        }

        public static Optional<Operation> getOperation(String operator {
            return Optional.ofNullable(operationMap.get(operator));
        }
    }

service is always null...

A: Your design is poor.
You should make Addition and Division independent services (@Service) and thus, they can take whatever dependencies are needed in their constructors (auto-wired) and can be injected anywhere.
Your factory class would also be a service (@Service) and would consume whatever beans it wants to know about in its autowired constructor.
Managing dependency chains manually is a rabbit hole you don't want to go down.


text:
Q: Proof that $M(x)$ is little o of x? Let $M(x)$ be Mertens' function. Seeking contradiction, assume that $M(x)$ is not $o(x)$.
Then, since $M(x) = O(x)$, putting this statement together with the negation of $o(x)$, through the inequality definitions of both notations, one can get that $M(x) = \Theta(x)$.
Using Abel's lemma: $$\sum_{n\le x} \frac{\mu(n)}{n} = \frac{M(x)}{x} + \int_1^x \frac{M(t)}{t^2}dt$$ Replacing $M(x)$ by $\Theta(x)$ on the integral we get $$O(1) + \int_1^x \Theta(\frac{1}{t})dt = \Theta(log x)$$ So $\sum_{n\le x} \frac{\mu(n)}{n}$ grows like $log (x)$ and therefore is unbounded, but using dirichlets hyperbola method, one can get that $$1 = x\sum_{n\le x} \frac{\mu(n)}{n} + O(x)$$ Which means the sum is actually bounded, so we get a contradiction implied by our original assumption that $M(x)$ is not $o(x)$, therefore it must be $o(x)$.
Does this proof work or is there anything in it that fails?

A:
In general
  $$ f\in\Theta(g)\not\to \sum_{k=1}^nf(k)\in \Theta\left(\sum_{k=1}^ng(k)\right),$$
  and even less does the similar claim with integrals hold.

As a counterexample (even with $f$ non-negative), consider
$$ f(n)=\begin{cases}n,&n\text{ is a power of }2\\0,&\text{otherwise}\end{cases},$$
and $ g(n)=2n-1$ (so $\sum g(k)=n^2$). Then clearly $f\in O(g)$ and $f\notin o(g)$.
But for $2^m\le n<2^{m+1}$, we have
$$\sum_{k=1}^nf(n)=\sum_{j=0}^m2^j=2^{m+1}-1<2n,$$
so that $$\sum_{k=1}^nf(n)\in o\left(\sum_{k=1}^ng(n)\right).$$
Therefore, your computations do not allow the conclusion that $\sum \frac{\mu(n)}n$ is unbounded.


text:
Q: Inline Assembly Code Does Not Compile in Visual C++ 2010 Express I have some assembly merge sort code that I obtained from Github and I am trying to embed it into Inline Assembly in C++, but it won't compile and keeps returning these errors:

1>c:\users\mayank\desktop\assembly\assembly\main.cpp(147): error
  C2415: improper operand type

The code that I am attempting to run is this:
#include <iostream>
#include <cmath>
#include <stdio.h>

using namespace std;
const int ARRAYSIZE = 30;

int main()
{
    int arr[ARRAYSIZE];
    int temp_arr[ARRAYSIZE];
    int number;

    for(int x = 0; x < ARRAYSIZE; x++)
    {
        number = (rand() % 99) + 1;
        arr[x] = number;
    }
/*
READ_ARR_LEN:
    __asm
    {
        // Read the length of the array
        //GetLInt [30]      // Size of input array
        //PutLInt [30]
    }

GET_ARRAY:
    __asm
    {
         //intel_syntax
         // Get values in arr from the user
         mov   EAX, arr
         mov   ECX, ARR_LEN
         call  Read_Arr

         // Run Merge Sort on the array
         mov   EAX, arr
         mov   EBX, temp_arr
         mov   ECX, ARR_LEN
         call  Merge_Sort

        // EXIT
    };;
*/
Merge_Sort:
    __asm
    {
        // EAX - Array start
        // ECX - array length

        // Arrays of size 0 or 1 are already sorted
        cmp   ARRAYSIZE, 2
        jl    Trivial_Merge_Sort

        // Merge_Sort (first half)
        // Length of the first half
        // ECX /= 2
        push  ARRAYSIZE
        shr   ARRAYSIZE, 1
        call  Merge_Sort
        pop   ARRAYSIZE

        // Merge_Sort (second half)
        push  arr
        push  EBX
        push  ARRAYSIZE

        // Length of the second half
        // ECX = ECX - ECX/2
        mov   EDX, ARRAYSIZE
        shr   EDX, 1
        sub   ARRAYSIZE, EDX
        imul  EDX, 4
        // Start index of the second half
        // EAX = EAX + (ECX/2) * 4
        add   arr, EDX
        push  EDX
        call  Merge_Sort
        pop   EDX

        pop   ARRAYSIZE
        pop   EBX
        pop   arr

        pushad
        // Merge (first half, second half)
        // Length of first half = ECX/2
        // Length of second half = ECX - ECX/2
        mov   EDX, ECX
        shr   ECX, 1
        sub   EDX, ECX

        // Start of second half = EAX + (ECX/2) * 4
        mov   EBX, EAX
        mov   EDI, ECX
        imul  EDI, 4
        add   EBX, EDI
        // Index of temp array = 0
        sub   EDI, EDI
        call  Merge
        popad

        // Copy back the merged array from temp_arr to arr
        call  Merge_Copy_Back_Temp

        ret
    };

Trivial_Merge_Sort:
    __asm
    {
        // In case of arrays of length 0 or 1
        ret
    };
Merge:
    __asm
        {
        // Merge two arrays contents.
        // The final merged array will be in temp_arr
        // Merging is done recursively.

        // Arguments:
        // EAX - First array's start
        // EBX - Second array's start
        // ECX - Length of first array
        // EDX - Length of second array
        // EDI - Index in temp array
        pushad

        // Handle the cases where one array is empty
        cmp   ARRAYSIZE, 0
        jz    First_Array_Over
        cmp   EDX, 0
        jz    Second_Array_Over

        // Compare first elements of both the arrays
        push  ARRAYSIZE
        push  EDI
        mov   ARRAYSIZE, [arr]
        mov   EDI, [ARRAYSIZE]
        cmp   ARRAYSIZE, EDI
        pop   EDI
        pop   ARRAYSIZE

        // Pick which ever is the least and update that array
        jl    Update_First_Array
        jmp   Update_Second_Array
    };

Update_First_Array:
   __asm
   {
        // min_elem = min (first elements of first array and second array)
        // Put min_elem into the temp array
        push  dword ptr [EAX]
        pop   dword ptr [temp_arr + EDI * 4]
        add   EAX, 4
        dec   ECX
        inc   EDI

        // Recursively call Merge on the updated array and the
        // other array
        call  Merge
        popad
        ret
   };

Update_Second_Array:
   __asm
   {
       // min_elem = min (first elements of first array and second array)
        // Put min_elem into the temp array
        push  dword ptr [EBX]
        pop   dword ptr [temp_arr + EDI * 4]
        add   EBX, 4
        dec   EDX
        inc   EDI

        // Recursively call Merge on the updated array and the
        // other array
        call  Merge
        popad
        ret
   };

Merge_Copy_Back_Temp:
   __asm
   {
        // Copy back the temp array into original array
        // Arguments:
        // EAX - original array address
        // ECX - original array length
        pushad

        // For copying back, the destination array is EAX
        mov   EBX, EAX
        // Now, the source array is temp_arr
        mov   EAX, temp_arr
        call  Copy_Array
        popad
        ret
   };

Trivial_Merge:
   __asm
   {
        // Note: One array is empty means no need to merge.
        popad
        ret
   };

First_Array_Over:
   __asm
   {
        // Copy the rest of the second array to the temp arr
        // because the first array is empty
        pushad
        mov   EAX, EBX
        mov   ECX, EDX
        mov   EBX, temp_arr
        imul  EDI, 4
        add   EBX, EDI
        call  Copy_Array
        popad
        popad
        ret
   };

Second_Array_Over:
   __asm
   {
    // Copy the rest of the first array to the temp arr
    // because the second array is empty
    pushad
    mov   EBX, temp_arr
    imul  EDI, 4
    add   EBX, EDI
    call  Copy_Array
    popad
    popad
    ret
   };
Copy_Array:
   __asm
   {
    // Copy array to destination array
    // EAX - Array start
    // EBX - Destination array
    // ECX - Array length

    // Trivial case
    cmp   ECX, 0
    jz    Copy_Empty_Array

    push  ECX
    sub   EDI, EDI
   };
copy_loop:
   __asm
   {
    // Copy each element
    push  dword ptr [EAX + EDI * 4]
    pop   dword ptr [EBX + EDI * 4]
    inc   EDI
    loop  copy_loop

    pop   ECX
    ret
   };

Copy_Empty_Array:
   __asm
   {
    ret
   };

Read_Arr:
   __asm
   {
        // EAX - array start
        // ECX - array length
        mov   ESI, EAX
        sub   EDI, EDI
   };
loop1:
   __asm
   {
        // Read each element
        lea eax,[esi+edx*4]
        inc   EDI
        loop  loop1
        ret
   };

    return 0;
}

A: (Update: In the original code posted in the question there were attempts to address memory as DWORD [address], which is incompatible with the syntax used by Visual C++'s inline assembler as I point out in my answer below.)
Visual C++ uses MASM syntax for its inline assembly, so you need to use DWORD PTR instead of just DWORD. That's what's causing these compilation errors.
See e.g. this table from The Art of Assembly.

A: This looks like the code is from this github repository.
In that code, GetLInt is actually a NASM macro which is included in an external macro definition file and calls a function proc_GetLInt, which in turn is provided in an object file io.o, the source code is not there. The problem is therefore simply that

*

*you didn't realize that GetLint is external code that you're missing

*even if you took all files from that repository, it would work because NASM macros don't work directly in VC++ inline assembly

*even if you fixed the macro problem, you still don't have the GetLInt function because it is provided as a linux object file only, you'd have to write it yourself

How do you fix this?
That code was meant to provide a self-contained assembler program that handles all input/output on its own. Since you're inlining it in VC++, you have much more powerful I/O handling at your hands already. Use those instead, i.e. make sure that the values you want to sort are already in arr before the inline assembly starts.
Then, looking at the code: Merge_Sort expects the start of your array in EAX, and its length in ECX. You can get both from your C++ code. When you do that, you no longer need the READ_ARR_LEN and GET_ARRAY blocks from the assembler code.
I am rather reluctant to reproduce parts of the code with modifications as I cannot find a licence file on github that would say I may do so. Let me try to describe: You need to manually move the pointer to arr into EAX and the content of ARRAYSIZE into EBX at the very start of the assembler routine. (*) As I can see, you have already taken care of filling the array with numbers, so there's nothing you need to do there.
Then you need to remove all unnecessary assembler functions and calls to them. You also should either condense all your separate __asm blocks into one or use external variables to conserve and restore registers between blocks (or read the tutorial here, but just using one block works and is less hassle).
Finally, you have to be careful with the stack frames: every call has to have a matching ret. This is easy to stumble over as the merge sort procedure is recursive.
(*) Careful with VC++'s way of treating variables in inside asm blocks, be sure to actually use pointers when you need them.
So all in all, porting this to VC++ is not a trivial task.


text:
Q: Почему у меня значение Current Asia Population выдается с буквой Е,да и вообще неправильно? package casting02;

public class Casting02 {
    public static void main(String[] args) {

        long currentWorldPop = 7_000_000_000L;
        System.out.println("Current World Population: " +currentWorldPop);

        //World population in 1950,  Source: United Nations Population Division
        //2.52 Billion
        int africaPop   =   221_000_000;
        long asiaPop     =  1_402_000_000;
        int europePop   =   547_000_000;
        int americasPop =   339_000_000;
        int oceanaPop   =    13_000_000;
        System.out.println("World Population in 1950: "
                +(africaPop +asiaPop +europePop +americasPop +oceanaPop));

        //The current population of Asia is an estimated 60% of the world population
        double percentAsia = (float)0.6;
        double currentAsiaPop  =currentWorldPop * percentAsia;
        System.out.println("Current Asia Population: " +currentAsiaPop);

    }
}

Все заработало,когда я изменил строчку таким образом
long currentAsiaPop = (long)(currentWorldPop * percentAsia);

Кто-нибудь может объяснить как так получилось?

A: Используйте BigDecimal, вот пример:
long currentWorldPop = 7_000_000_000L;
BigDecimal percentAsia = new BigDecimal("0.6");
BigDecimal currentAsiaPop  = percentAsia.multiply(BigDecimal.valueOf(currentWorldPop));
System.out.println("Current Asia Population: " + currentAsiaPop);

Или
long currentWorldPop = 7_000_000_000L;
double percentAsia = 0.6D;
double currentAsiaPop  = currentWorldPop * percentAsia;
System.out.println("Current Asia Population: " + new DecimalFormat("#").format(currentAsiaPop));

Неправильно считалось, потому что вы при определении percentAsia делали приведение типов, в этом случае теряется точность.

A: Можно выводить через System.out.printf:
System.out.printf("Current Asia Population: %.2f\n", currentAsiaPop);

Вместо %.2f при выводе подставится ваше число, в данном случае выведется в формате с точкой с 2 знаками после точки (например, 4200000166.89).
Другой вариант, форматировать строку с помощью класса MessageFormat:
System.out.println(MessageFormat.format("Current Asia Population: {0, number, #.##}", currentAsiaPop));

Вывод будет аналогичный.


text:
Q: How to serialize request.POST data? My story: Getting bank details from users (i want safe here )

*

*getting the information from form

*serialize it ( don't know how to do this )

*encrypt

*save encrypted value into table field.

The second point bit confused me. How to serialize it .? ( ? through django.core.serializers or pickle )
I tried without serialize like save request.POST['value'] into var {} then convert var into encrypt and save to db.
But when i decrypt this value from db i am getting "{'bank_details': u'email@gmail.com'}" I know i can't use this unless i remove the "".
Tell me How to serialize request.POST data ?

A: you can use json module.
Here is link for it.
https://docs.python.org/2/library/json.html
....
# you can save your data into json format
data = json.dumps(request.POST['value'])
# then you can do some encrypted work and save it to db
data=encrypted(data)
db_connect.save(data)
# now you can get data from db which is still in the form "{1:22}"
# with json.loads you will never see "" again
new_data = db_connect.get(data)
new_data = json.loads(new_data)
print new_data
....


text:
Q: First cohomology group of direct products Let $p$ be a prime number and H be a finite group with $|H|=p-1$ and consider $\varphi: H \times Z_{p^k} \rightarrow Aut(Z_{p^k})$ as a non-trivial action of $H \times Z_{p^k}$ on $Z_{p^k}$ such that $Z_{p^k} \subset Ker(\varphi).$
How can I compute the first cohomology group $H^1(H \times Z_{p^k}, Z_{p^k})$ for the above action? I want to know this group is trivial or not?
Update: Is there any relation between $H^1(H \times Z_{p^k}, Z_{p^k})$ and product of $H^1(H, Z_{p^k})$ and $H^1(Z_{p^k}, Z_{p^k})$ in general?

A: Are you familiar with the inflation restriction exact sequence?
If $N \unlhd G$ and $G$ acts on module $A$, then
$$0 → H^1(G/N, A^N) → H^1(G, A) → H^1(N, A)^{G/N} → H^2(G/N, A^N) →H^2(G, A)$$
is exact. Taking $N=H$ in your example, we have $A^N=0$, and $|N|$ and $|A|$ are coprime (I am assuming that $Z_{p^k}$ denotes a cyclic group of order $p^k$), so $H^1(N,A)=0$, and hence $H^1(G,A)=0$.


text:
Q: LinkedHashSet loop from some element onwards (Java). I am using a LinkedHashSet in my code and at some point I need to iterate and run an algorithm in all the elements of the HashSet from an element onwards.
So if my set contains numbers 1,2,3,4,5. I want to start the loop from the 3 and not the 1. Is this possible?
Thanks.

A: There are two possible meanings to 'start the loop from 3'. You could mean you want only items that are equal or greater than 3 in the list. Or you could mean that you want to skip the first 2 items when sorted in a specific order. I would recommend you make your meaning explicitly clear in your code. If you are using Java 8 then streams provide a good mechanism to do this:
myHashSet.stream()
    .sorted(myComparator)
    .skip(2)
    .collect(Collectors.toList());

or
myHashSet.stream()
    .filter(n -> n >= 3)
    .collect(Collectors.toList());

A: You could copy it into an ArrayList so that you might use subList(int, int); and then you might use a for-each loop like
HashSet<Integer> set = new LinkedHashSet<>(Arrays.asList(1, 2, 3, 4, 5));
for (Integer i : new ArrayList<>(set).subList(2, set.size())) {
    System.out.println(i);
}

Alternatively, you could use the same method to directly get an Iterator like
HashSet<Integer> set = new LinkedHashSet<>(Arrays.asList(1, 2, 3, 4, 5));
Iterator<Integer> iter = new ArrayList<>(set).subList(2, set.size())
        .iterator();
while (iter.hasNext()) {
    System.out.println(iter.next());
}

Both output (the requested)
3
4
5

A: If you use a TreeSet instead of a LinkedHashSet, you could use the method tailSet(). If you use it this way: mySet.tailSet(3), it will return a view of your set (that is also a Set), containing only 3, 4, 5.


text:
Q: How to find whether a text contains zero? I want to check in a piece of text whether that text contains "0" or not.
I cannot use string.__contains(" 0") as this is bad coding, or if I can use this, I do not have enough points to back to my senior, that this is the only way. Or if you can let me know some points?
The other way we found out is to extract from each row, and extract the number from it, convert it into integer and then check if the value is greater than 0. But this is little time consuming.
The string could contain a number like 2560 which should be ignored in this search.
Please tell me some alternative. I don't want that integer conversion.
For example:
abc : 1234
def : 1230  >>> This kind of text should return False

abc : 1234
def : 0  >>>> This kind of text should return True, as it contains 0.

A: At first, I thought you could just use in:
if "0" in myString:
  print "%s contains 0" % myString

However, this doesn't seem to be what you want to do, when re-reading your question. This will detect the 0 in a row such as:
abc: 200

Which I guess you don't want to do. You need to use something a bit more sophisticated. I would probably go with some simple manual code, rather than using regular expressions as suggested in a different answer. Here's how:
def is_row_zero(row):
  parts = row.split(":")
  value = parts[1].strip()
  if value == "0":
    print "%s is 0, not allowed" % parts[0]
    return True
  return False

It's possible the regular expression approach is faster, so that might be worth investigating depending on your workload and performance goals.

A: Use regular expressions to find a pattern:
>>> import re
>>> re.findall('\W(0)\W', 'alsdkjf 0 asdkfs0asdf   0   ')
['0', '0']

Where \W(0)\W matches zero surrounded by non-alphanumeric characters ('\W').
Your example:
>>> re.findall('\W(0)\W', 'abc : 1234 def : 1230 ')
[]
>>> re.findall('\W(0)\W', 'abc : 1234 def : 0 ')
['0']

A: There are many ways to find this in Python...
if " 0 " in [string variable]:
    do something...

is one option, You could turn the " 0 " into a variable to make it more generic.
Regular expressions might be preferable, perhaps. But is overkill really.

A: If I read your question correctly, the input is a text file like:
label : value
label : value
...

I suggest you read the file line by line and use either regular expressions:
for line in open("filename.txt"):
    if re.match(r"\S+ : 0$", line):
        print "The row's value is zero"

Or use .endswith:
for line in open("filename.txt"):
    if line.endswith(" 0"):
         print "The row's value is zero"

A: If what you're looking for is just "0", then:
string == '0'

If there may be whitespace around:
string.strip() == '0'

A: Your question isn't exactly clear, did you want a zero only if it's not part of a number?
You could check all 0's in the string, and see if its adjacent characters are digits.
something such as:
def has_zero(s):
    if "0" not in s:
        return False
    if s=="0":
        return True
    if s[0]=="0" and not s[1].isdigit():
        return True
    if s[-1]=="0" and not s[-2].isdigit():
        return True
    return any(s[i]=="0" and not (s[i-1].isdigit() or s[i+1].isdigit()) for i in range(1,len(s)-1))

print has_zero("hell0 w0rld")
#True
print has_zero("my number is 2560")
#False
print has_zero("try put a zer0 in here with number 100")
#True
print has_zero("0")
print has_zero("10")
print has_zero("01")
print has_zero("a0")
print has_zero("0a")
print has_zero("00")


text:
Q: How to pick an item from an array and keep on cycling through by using Javascript? I actually want to pick an item from the array (A or B or C) and display it in a block. Then changes at 2 second interval and keep on cycling through.
<script type="text/javascript">
        var arr = ["A","B","C"];
        setInterval(function ChangeText() {
            var span = document.getElementById("spnChanger")
            var i = Math.floor(Math.random() * 3)
            span.innerHTML = arr[i]
        }, 2000);
</script>

*

*Such as if A is randomly picked, A will be shown at first, followed by B and C and then back to A and loop endlessly

*Such as if B is randomly picked, B will be shown at first, followed by C and A and then back to B and loop endlessly

*Such as if C is randomly picked, C will be shown at first, followed by A and B and then back to C and loop endlessly
But all i can get is a random item from the array every time which cannot continuously go through the cycle.
Can anyone help? Thanks

A: You can definitely condense this a bit, but I left separate lines so you can more easily see what's going on;
var arr = ["A", "B", "C"];
var idx = Math.floor(Math.random() * 3); //initialize the index
var span = document.getElementById("spnChanger"); //this isn't changing, so you can look it up outside of the timer
setInterval(() => {
  span.innerHTML = arr[idx];
  idx++;
  idx %= 3; //this is the mod based on the length of arr, this handles wrapping to the start
}, 2000);

A: I'm gonna use randojs.com to answer your question, so if you'd like to use my code, copy and paste this into the head tag in your HTML document:
<script src="https://randojs.com/1.0.0.js"></script>

And then you can use this nice short code:
var arr = ["A", "B", "C"];
var index = rando(arr).index;
setInterval(function(){
    if(arr.length > 0){
        document.getElementById("spnChanger").innerHTML = arr[index++ % arr.length];
    }
}, 2000);

It doesn't matter how many items are in your array. This code will account for it automatically.


text:
Q: Any way to use rma() outputs with broom package? I am doing meta-analysis research and really fond of the metafor package in R.
However, to be able to leverage all the great things you can do with R, for example managing many different models in a nested data.frame (Thanks to Hadley Wickham and David Robinson) I need to be able to use output from the metafor package rma()-models with broom.
Does anybody now how to do this. I am aware of the fact that it is not supported out of the box in broom (yet) but would very much appreciate a work-around so far.
Many thanks!

A: Here is a very basic example of creating a new method for tidy that can handle rma class objects:
tidy.rma <- function(x) {
  return(data.frame(summary(x)$fit.stats))
}

This creates method rma for function tidy, and we define it to return a data.frame containing the fit statistics of the rma object.
You could instead make the tidy.rma function return a data.frame type object with any data you see fit. Mind you, you could have it return your favorite yo' momma joke and have it have nothing to do with the input rma model object at all. The tidy.rma method is completely your's to decide what it does.
Using the tidy function just like normal:
### Example from metafor package:
data(dat.bcg)
dat <- escalc(measure="RR", ai=tpos, bi=tneg, ci=cpos, di=cneg, data=dat.bcg)
mod <-rma(yi, vi, data=dat, method="REML")
### And call tidy()
tidy(mod)

Provides a nice data.frame of the fit statistics:
             ML      REML
ll   -12.68777 -12.20237
dev   37.16141  24.40474
AIC   29.37554  28.40474
BIC   30.50544  29.37456
AICc  30.57554  29.73808


text:
Q: fit_transform error using CountVectorizer So I have a dataframe X which looks something like this:
X.head()

    0    My wife took me here on my birthday for breakf...
    1    I have no idea why some people give bad review...
    3    Rosie, Dakota, and I LOVE Chaparral Dog Park!!...
    4    General Manager Scott Petello is a good egg!!!...
    6    Drop what you're doing and drive here. After I...
    Name: text, dtype: object

And then,
from sklearn.feature_extraction.text import CountVectorizer
cv = CountVectorizer()
X = cv.fit_transform(X)

But I get this error:
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-61-8ff79b91e317> in <module>()
----> 1 X = cv.fit_transform(X)

~/anaconda3/lib/python3.6/site-packages/sklearn/feature_extraction/text.py in fit_transform(self, raw_documents, y)
    867
    868         vocabulary, X = self._count_vocab(raw_documents,
--> 869                                           self.fixed_vocabulary_)
    870
    871         if self.binary:

~/anaconda3/lib/python3.6/site-packages/sklearn/feature_extraction/text.py in _count_vocab(self, raw_documents, fixed_vocab)
    790         for doc in raw_documents:
    791             feature_counter = {}
--> 792             for feature in analyze(doc):
    793                 try:
    794                     feature_idx = vocabulary[feature]

~/anaconda3/lib/python3.6/site-packages/sklearn/feature_extraction/text.py in <lambda>(doc)
    264
    265             return lambda doc: self._word_ngrams(
--> 266                 tokenize(preprocess(self.decode(doc))), stop_words)
    267
    268         else:

~/anaconda3/lib/python3.6/site-packages/sklearn/feature_extraction/text.py in <lambda>(x)
    230
    231         if self.lowercase:
--> 232             return lambda x: strip_accents(x.lower())
    233         else:
    234             return strip_accents

~/anaconda3/lib/python3.6/site-packages/scipy/sparse/base.py in __getattr__(self, attr)
    574             return self.getnnz()
    575         else:
--> 576             raise AttributeError(attr + " not found")
    577
    578     def transpose(self, axes=None, copy=False):

AttributeError: lower not found

No idea why.

A: You need to specify the column name of the text data even if the dataframe has single column.
X_countMatrix = cv.fit_transform(X['text'])

Because a CountVectorizer expects an iterable as input and when you supply a dataframe as an argument, only thing thats iterated is the column names. So even if you did not have any errors, that would be incorrect. Lucky that you got an error and got a chance to correct it.


text:
Q: Does git reset --keep HEAD do nothing? So, I have read that the git reset --keep works like --hard but remains unstaged changes.
So, if I just git reset --hard, I will get into the original HEAD state with clear index.
So, there is a question: Does the git reset --keep HEAD do nothing? Or what is the difference?
If I do the git reset --keep HEAD~1, will it work like there is no HEAD~1 commit but I have made the changes on files?

A: Does this answer your question?

--keep

Resets index entries and updates files in the working tree that are different between <commit> and HEAD. If a file that is different between <commit> and HEAD has local changes, reset is aborted.

The --hard option forcibly overwrites local changes, and --keep ... keeps them ... by refusing to do anything that would overwrite a local change.


text:
Q: SQL Error: ORA-00933: SQL command not properly ended in Oracle Update query I have SYSTEM_SQL_CHECK table in which i have saved sql in CHECK_SQL column. This column is Varchar data type. Now i want to update particular sql.I have written below update sql query but it gives an error SQL Error: ORA-00933: SQL command not properly ended. I also tried to query with double quote but then it gives an error as  SQL Error: ORA-00972: identifier is too long.
    Update RATOR_MONITORING_CONFIGURATION.SYSTEM_SQL_CHECK SET CHECK_SQL = 'select count(*) as CNT from O2_SDR_Header
where id = (select max(id) from O2_SDR_Header where id > 2012000000000000 and sp_id = 'SP602')
And sp_id = 'SP602' and FILE_CREATED_DATE > (SYSTIMESTAMP - INTERVAL '2' HOUR)'
WHERE SYSTEM_SQL_CHECK_ID = 604;

A: This code should be like this : sp_id = 'SP602' to sp_id = ''SP602''
and this '2' to ''2''
your final code should be like this
 Update RATOR_MONITORING_CONFIGURATION.SYSTEM_SQL_CHECK SET CHECK_SQL = 'select count(*) as CNT from O2_SDR_Header
where id = (select max(id) from O2_SDR_Header where id > 2012000000000000 and sp_id = ''SP602'')
And sp_id = ''SP602'' and FILE_CREATED_DATE > (SYSTIMESTAMP - INTERVAL ''2'' HOUR)'
WHERE SYSTEM_SQL_CHECK_ID = 604;

A: you need to escape you single quote, as below
Update RATOR_MONITORING_CONFIGURATION.SYSTEM_SQL_CHECK SET CHECK_SQL = "select count(*) as CNT from O2_SDR_Header
where id = (select max(id) from O2_SDR_Header where id > 2012000000000000 and sp_id = ''SP602'')
And sp_id = ''SP602'' and FILE_CREATED_DATE > (SYSTIMESTAMP - INTERVAL '2' HOUR)"
WHERE SYSTEM_SQL_CHECK_ID = 604;


text:
Q: Securing IIS sub folders and files I have an ASP.NET Application running on IIS windows 2008R2 Server, everything is working ok however users are able to access the direct files in subfolders. What i am looking for is a way to prevent the users from accessing anything outside of the default document.
I have tried removing the security to the sub folders and files but this leads to an issue that the application cannot gain access to the files in sub folders.
The application pool is running under application pool identity and the folders have the permission only for the application pool identity.
I have also tried many other variations but i cannot seem to remove the access to these files without causing the application not to work.


text:
Q: What happens after you call document.getElementById() in javascript? I am trying to refresh some div in my website dynamically.
 //code changing the source
 document.getElementById('#chatbox').src = document.getElementById('#chatbox').src;   //refreshes the chatbox
 alert("HERE");

The alert() function does not get executed after getElementbyId() is called.
What is going on?

A: You are trying to access src of undefined as there is probably no element with the id "#chatbox".
Remove the hash and it should work:
document.getElementById('chatbox').src

To debug take a look at your javascript error console or try
alert(document.getElementById('#chatbox')) // undefined

A: That's because it should be
document.getElementById('chatbox')

Perhaps you are confusing this with jQuery. With jQuery, you would use:
$('#chatbox')


text: Q: Google Search Console "linked from" obsolete sitemap Why does Google Search Console show "linked from" links that are from sitemap entries that are no longer part of the sitemap? I have pages from 10 years ago that show up that haven't been part of my sitemap for a decade, but they still show "linked from" the sitemap.


text:
Q: How to check if website is secure using PHP I'm quite new in security (certificates) and not understand how it works.
I have IIS server and certificate is installed. I can open my website in two different ways:
http://website and
'https://website'.
When I open it as http then in address bar I can see that says website is not secure if i open it as https then padlock appears.
But I'm  not understand where is security in this case. How to control it with php?
I can check if site has $_SERVER['HTTPS'] != 'on' and then let user to access but if i remove certificate from the server i still can access as 'https' but browser says that is not secure site but $_SERVER['HTTPS'] still showing as on
How can i control security?

A: If you access a web page via https the browser encodes you request with SSL.
If you access a web page via http it is not encoded.
The certificate is just the proof for the user that the encoding is safe. The variable $_SERVER['HTTPS'] just says whether the user accessed the page via https or http.


text:
Q: How to take the output of grep and write it to a new file I want to take the output of the grep command on a file, create a new file and save that grep output to the new created file, can someone please point me to the right direction in how I would do that?

A: The path you choose depends a great deal on how simple you want it to be.
Perhaps the simplest method is the use of system:
#include <stdio.h>
#include <stdlib.h>

int main (void) {
        system ("grep a *.c >outfile.txt");
        return 0;
}

though you also could construct the command dynamically if you have different arguments to grep or a non-fixed output file.

Beyond that, you could use popen() (if available on your implementation - it's not mandated by ISO but is instead a POSIX thing) along with fgets() or fgetc() to read the output of that command and do whatever you want with it:
#include <stdio.h>

int main (void) {
    int chr;

    FILE *echo = popen ("echo hello there", "r");
    if (echo != NULL) {
        while ((chr = fgetc (echo)) != EOF)
            putchar (chr);
        fclose (echo);
    }
    return 0;
}

The next step up from there may be to not rely on an external grep at all but instead include something like PCRE (Perl-compatible regular expressions) into your own code, giving you much finer control over what happens.


text:
Q: Show that $\phi:A_4\longrightarrow GL_3(\mathbb{C})$ is a irreducible representation Given the representation $\phi:A_4\longrightarrow GL_3(\mathbb{C})$ with:
$$\phi_{(123)}=\begin{bmatrix}
 0 & 0 & 1\\
 1 & 0 & 0\\
0 & 1 & 0
\end{bmatrix}\, \text{and} \,\, \phi_{(12)(34)}=\begin{bmatrix}
 0 & 1 & -1\\
 1 & 0 & -1\\
0 & 0 & -1
\end{bmatrix}$$
Show that the representation is irreducible.

with so few information about the whole elements of the representation and its character I came to the conclusion that the fastest way might be , by simply calculating all the $\phi_{(123)}$-invariant subspaces and all the $\phi_{(12)(34)}$-invariant subspaces and
see that there is no possible intersection hence no common invariant submodule which implies $\phi$ has to be irreducible no matter how the rest of the representation looks like. This worked fine, but is it the most elegant way given only the informations above?

A: Calculate the value of the character on the conjugacy classes, eg. from your information we have $\chi (123)=\chi(132)=0$, $\chi(12)(34)=-1$, $\chi(1)=3$. So the inner product evaluates to $\frac{1 \times 3^2+3\times (-1)^2}{12}=1$ hence it is an irreducible representation.

A: If $\phi$ was reducible, then there would be a $2$-dimensional subspace $T$ of $\Bbb R^3$ and a $1$-dimensional subspace $O$ which would be invariant with respect to the action $\phi$ and such that $\Bbb R^3=T\bigoplus O$. But then $O$ would be of the form $\Bbb Cv$, for some common eigenvector of the given matrices. However, there are no such eigenvectors: the $1$-dimensional invariant subspaces of the second matrix are $\Bbb C(a,b,a+b)$ (with $a,b\in\Bbb C$ and $a$ and $b$ aren't both $0$), and $\Bbb C(1,1,0)$, and neither $(a,b,a+b)$ nor $(1,1,0)$ is an eigenvector of the first matrix.


text:
Q: Assessing variable importance from coefficients and p-Values of linear regression Is it correct to say that if the significance of a variable is very high (p<0.001) and the coefficient is very large that the variable is important in a general sense?
If not can you give an example?
Thank you

A: "Important in a general sense" is hard to define, but if your interest is in trying to make causal inferences you will have a problem if a particular variable just happens to correlate with a truly "important" variable.
The answer from @TheJiminySea on this Cross Validated page has an amusing example with predictor variables "Years of work experience" and "Number of carrots eaten in one's lifetime". These 2 variables are likely to be highly correlated, but for predicting things like income "Years of work experience" is presumably the "important" variable. Nevertheless, if you did analyses with "Number of carrots ..." as the predictor of income you might still get highly significant p-values and large coefficients.
So you have to be careful in what you mean by "important".


text:
Q: R select values for each group For each combination of WEEK and GROUP I wish to find the day (1 or 2) when SCORE is lowest for TYPE == 'M' and then keep the TYPE == 'M' and TYPE == 'E' value on that same day.
HAVE = data.frame("WEEK" = c(1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4),
"GROUP" = c('A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B'),
"SCORE" = c(29, 10, 19, 11, 28, 38, 23, 27, 32, 19, 32, 26, 35, 27, 39, 51, 43, 12, 35, 29, 14, 47, 12, 36, 17, 11, 24, 19, 19, 12, 33, 7),
"DAY" = c(1, 1, 2, 2, 1, 1, 2, 2, 1, 1, 2, 2, 1, 1, 2, 2, 1, 1, 2, 2, 1, 1, 2, 2, 1, 1, 2, 2, 1, 1, 2, 2),
"TYPE" = c('M', 'E', 'M', 'E', 'M', 'E', 'M', 'E', 'M', 'E', 'M', 'E', 'M', 'E', 'M', 'E', 'M', 'E', 'M', 'E', 'M', 'E', 'M', 'E', 'M', 'E', 'M', 'E', 'M', 'E', 'M', 'E'))

WANT=data.frame("WEEK"=c(1, 1, 2, 2, 3, 3, 4, 4, 1, 1, 2, 2, 3, 3, 4, 4),
"GROUP"=c('A', 'A', 'A', 'A', 'A', 'A', 'A', 'A', 'B', 'B', 'B', 'B', 'B', 'B', 'B', 'B'),
"SCORE"=c(19, 11, 23, 27, 32, 19, 35, 27, 35, 29, 12, 36, 17, 11, 19, 12),
"DAY"=c(2, 2, 2, 2, 1, 1, 1, 1, 2, 2, 2, 2, 1, 1, 1, 1),
"TYPE"=c('M', 'E', 'M', 'E', 'M', 'E', 'M', 'E', 'M', 'E', 'M', 'E', 'M', 'E', 'M', 'E'),
"SCORE.MIN"=c(1, NA, 1, NA, 1, NA, 1, NA, 1, NA, 1, NA, 1, NA, 1, NA))

I have 'HAVE' and wish to create 'WANT'
For each combination of WEEK and GROUP, select the DAY when TYPE = M and SCORE is lowest. This I am able to do by
WANT.ATTEMPT = HAVE %>%
group_by(WEEK, GROUP) %>%
mutate(SCORE.MIN = ifelse(TYPE == 'M', min(SCORE), NA))

HOWEVER what I wish for is the dataset WANT where as you see I group by WEEK and GROUP and find the DAY when SCORE is minimum for TYPE == 'M' but I also keep the SCORE for TYPE == 'E' for the same day

A: Update to prevent ties.
You can do:
HAVE %>%
  group_by(WEEK, GROUP) %>%
  filter(DAY == first(DAY[SCORE == min(SCORE[TYPE == 'M'])]) | TYPE == 'E') %>%
  filter(DAY %in% DAY[TYPE == 'M']) %>%
  ungroup()

# A tibble: 16 x 5
    WEEK GROUP SCORE   DAY TYPE
   <dbl> <chr> <dbl> <dbl> <chr>
 1     1 A        19     2 M
 2     1 A        11     2 E
 3     2 A        23     2 M
 4     2 A        27     2 E
 5     3 A        32     1 M
 6     3 A        19     1 E
 7     4 A        35     1 M
 8     4 A        27     1 E
 9     1 B        35     2 M
10     1 B        29     2 E
11     2 B        12     2 M
12     2 B        36     2 E
13     3 B        17     1 M
14     3 B        11     1 E
15     4 B        19     1 M
16     4 B        12     1 E

A: We could also arrange first before grouping and then do the filter
library(dplyr)
HAVE %>%
   arrange(WEEK, GROUP, TYPE != 'M', SCORE) %>%
   group_by(WEEK, GROUP) %>%
   filter(DAY %in% DAY[TYPE == "M"][1]) %>%
   ungroup

-output
# A tibble: 16 × 5
    WEEK GROUP SCORE   DAY TYPE
   <dbl> <chr> <dbl> <dbl> <chr>
 1     1 A        19     2 M
 2     1 A        11     2 E
 3     1 B        35     2 M
 4     1 B        29     2 E
 5     2 A        23     2 M
 6     2 A        27     2 E
 7     2 B        12     2 M
 8     2 B        36     2 E
 9     3 A        32     1 M
10     3 A        19     1 E
11     3 B        17     1 M
12     3 B        11     1 E
13     4 A        35     1 M
14     4 A        27     1 E
15     4 B        19     1 M
16     4 B        12     1 E


text:
Q: Initializing a ref array in Mongoose Say I have the following schemas:
var promoGroupSchema = new Schema({
    title: String,
    offers: [{Schema.Types.ObjectId, ref: 'Offer']
});

and
var offerSchema = new Schema({
    type: String
});

How do you initialize a promoGroup with new offers? The following won't work since save() is asynchronous. Now, I know I could put a function as a parameter of the save function, but that gets ugly with more offers.
var offer1 = new offerSchema({
    type: "free bananas!"
});

var offer2 = new offerSchema({
    type: "free apples!"
});

offer1.save();
offer2.save();

var newPromoGroup = new promoGroupSchema({
    title: "Some title here",
    offers: [offer1._id, offer2._id]
});

From what I read, Mongoose gives the object an _id as soon as you create them, can I rely on those?

A: You should access _id in the save callback. If you have a lot of offers to group, using a library like async will make your life easier.
var myOffers = [...]; // An array with offers you want to group together

// Array of functions you want async to execute
var saves = myOffers.map(function(offer) {
    return function(callback) {
        offer.save(callback);
    }
}

// Run maximum 5 save operations in parallel
async.parallelLimit(saves, 5, function(err, res) {
    if(err) {
        console.log('One of the saves produced an error:', err);
    }
    else {
        console.log('All saves succeeded');
        var newPromoGroup = new promoGroupSchema({
            title: "Some title here",
            offers: _.pluck(myOffers, '_id') // pluck: see underscore library
        });
    }
});

You could also try to use Promises.