text:
Q: How can I display rsync progress from a log file without the carriage returns? I have a log file from rsync command with progress on.  When running this progress updates the display information on the same line.  When I capture the output from this command I get a file that displays normally with cat on a terminal (all the backspaces and re-edits are replayed) but I want to be able to use grep  on the file and process it so I see all the backspace edit commands. How can I process the file to remove all the progress updates and just get a file that has the final edits?

A: If you want to see what your captured file looks like without the progress lines overwriting the previous ones:
sed 's/\r/\n/g' capture-file

which might yield something like this:
created directory /some/dest/dir
filename

       32768   0%    0.00kB/s    0:00:00
     6717440  21%    6.38MB/s    0:00:03
    13139968  41%    6.25MB/s    0:00:02
    19791872  62%    6.28MB/s    0:00:01
    26214400  82%    6.24MB/s    0:00:00
    31784420 100%    6.25MB/s    0:00:04 (xfer#1, to-check=0/1)

sent 31788388 bytes  received 31 bytes  3346149.37 bytes/sec
total size is 31784420  speedup is 1.00

If you want to see just the final step of the progress message and eliminate the previous ones:
sed 's/.*\r/\n/g' capture-file

Which might look like this:
created directory /some/dest/dir
filename

    31784420 100%    6.25MB/s    0:00:04 (xfer#1, to-check=0/1)

sent 31788388 bytes  received 31 bytes  3346149.37 bytes/sec
total size is 31784420  speedup is 1.00

You can run rsync with the --log-file=name option to capture log information in a file. Replace "name" with the name that you want. You can control the information that gets logged using the log-file-format option (see the log format section in man rsyncd.conf for details).
On my system the default rsync log file looks like this:
2009/11/01 17:19:20 [23802] building file list
2009/11/01 17:19:20 [23802] created directory /some/dest/dir
2009/11/01 17:19:25 [23802] <f+++++++++ filename
2009/11/01 17:19:25 [23802] sent 31788388 bytes  received 31 bytes  3346149.37 bytes/sec
2009/11/01 17:19:25 [23802] total size is 31784420  speedup is 1.00

A: First, I'm guessing the progress indicators are important for you to keep for various reasons, because the simplest solution is to just turn them off.  Secondly, I'm assuming there is no way to tell rsync to write out a log with everything but the progress indicators to a separate file from what it shows on the screen.  Lastly, I'm assuming that you do not want any of the progress indicator stuff at all in the log file you later process with other tools.
Given these two assumptions, you can strip out the progress indicators by basically looking through each line for \b or \r characters and tossing all lines that have those characters.  This can be as simple as a grep command line that looks like this:
grep -ve "$(echo -ne '[\b\r]')" logfile

This presupposes you have a shell that supports "$(...)" style argument substitution and an echo command that supports the -e arguments.


text:
Q: ACE_OS::read_n() return 0 even some data received I uses ACE_OS::read_n() to read some data from stdin (ACE_STDIN). My code example:
ACE_Message_Block *head = new ACE_Message_Block(BUFSIZ);
size_t bytes_trans = 0;
ssize_t nbytes = ACE_OS::read_n(
    ACE_STDIN,
    mblk->wr_ptr(),
    mblk->size(),
    &bytes_trans);

If I start my program with command ./a.out <<< "hello", it finds EOF after data and return 0. So, I can detect data received only if check bytes_trans variable.
Is it correct ACE_OS::read_n() behavior?

A: Just looked at the ACE doxygen documentation

Receive len bytes into buf from handle (uses the  call, which uses the  system call on UNIX and the  call on Win32). If errors occur, -1 is returned. If EOF occurs, 0 is returned. Whatever data has been read will be returned to the caller through bytes_transferred

Looking at the implementation (note the below code is from ACE 5.6.7... that's the source I have handy)
ssize_t
ACE_OS::read_n (ACE_HANDLE handle,
                void *buf,
                size_t len,
                size_t *bt)
{
  size_t temp;
  size_t &bytes_transferred = bt == 0 ? temp : *bt;
  ssize_t n = 0;

  for (bytes_transferred = 0;
       bytes_transferred < len;
       bytes_transferred += n)
    {
      n = ACE_OS::read (handle,
                        (char *) buf + bytes_transferred,
                        len - bytes_transferred);

      if (n == -1 || n == 0)
        {
          return n;
        }
    }

  return ACE_Utils::truncate_cast<ssize_t> (bytes_transferred);
}

So it seems that it calls multiple times to ACE_OS::read() accumulating the received bytes in the bytes_transferred
If all goes well, the return value will be the same as the contents of the bytes_transferred
If read() returns 0 or -1, read_n() will return 0 or -1, and the bytes_transferred content will be the number of bytes read so far.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Preparing dataset for analysis with T-SNE A little of the background story.. I am trying to get a qualitative/quantitative judgement on whether there exists a useful solution(if any) that a convolutional neural network can arrive at for a set of synthetic images containing 3 classes.
Now, I am trying to run TSNE on a folder containing 3195 RGB images of resolution 256x256.
First question I would like to ask is, am I converting my image folder into an appropriate format for usage with TSNE? The python code can be seen here  https://i.stack.imgur.com/79gNy.png.
Secondly, I managed to get the t-sne to run, although I am not sure if I am using it correctly, which can be seen here. https://i.stack.imgur.com/ZtOlR.png . The sourcecode is basically just a slight modification from Alexander Fabisch's MNIST example on Jupyter Notebook(apologies, however I cannot post more than two links since reputation <10.)
So, I would like to ask whether is there anything blatantly wrong for forcing a TSNE architecture used for MNIST dataset on a set of RGB images?
Lastly, I encountered a difficulty for the code in the second imgur link posted above with the below code,
imagebox = offsetbox.AnnotationBbox(
            offsetbox.OffsetImage(X[i].reshape(256, 256)), X_embedded[i])

The first argument for offsetbox.AnnotationBbox is a 256x256 image(because my image resolution is such), which basically covers up my entire screen, obscuring the results), but I get an error when i try to change it:
ValueError: total size of new array must be unchanged

So, how can I reduce the size of the images being plotted?(or other ways to work around the issue)

A: Well.. solved everything using the C++ codes provided for bh-tsne. Kindly close this thread, apologies for any inconvenience caused.


text:
Q: Web app to a packaged app with Dart I've been struggling with this for a few hours now. I've looked around and I believe I'm doing everything correctly, but it's just not working. Just for fun, I'm taking the sample Dart stopwatch and making it into a Chrome packaged app. It works flawlessly in both Dartium Chrome(via dart2js) when it's a simple web app, however as a packaged app it works in neither. The dart code simply doesn't work. Are there additional steps I need to perform to make Dart work in a web app?
Thank you very much for any help you can provide!

A: There are a few caveats when writing a packaged app in Dart. One is related to symlinks (packaged apps don't like them, and pub uses them), and the other is related to dart2js (you need to compile with the --disallow-unsafe-eval flag).
If you're using the Editor, you can create a new chrome packaged app from the wizard. This will set up a project that handles both issues above. I'd do that and make sure it runs, and then copy your web app into that project.


text:
Q: Jboss 7.1.1 IllegalArgumentException: Empty name segment is not allowed for env I've got

Failed to process phase INSTALL of deployment
(...)
Caused by: java.lang.IllegalArgumentException: Empty name segment is not allowed for env
          at org.jboss.msc.service.ServiceName.of(ServiceName.java:85) [jboss-msc-1.0.2.GA.jar:1.0.2.GA]
          at org.jboss.msc.service.ServiceName.append(ServiceName.java:112) [jboss-msc-1.0.2.GA.jar:1.0.2.GA]

When trying to deploy a jar containing MDB during Arquillian testing. How to solve this?

A: I used the example Arquillian Testing JMS section which had
@Resource(mappedName = "/ConnectionFactory")
private ConnectionFactory factory;

It looks like resource name path cannot contain empty parts. I added jms prefix and it deploys fine.
@Resource(mappedName = "java:/ConnectionFactory")
private ConnectionFactory factory;

A: There can be issue with ear structure, check jboss-app.xml
all modules should be valid, need to avoid examples like this:
<module>
    <service><!-- [INSERT SERVICE NAME HERE] --></service>
</module>

Or duplication jboss-app, like jboss-appp-ref.xml etc.
Also all JNDI names should have segment depends on EE 6 spec.
In Annotations, Lookups etc.
Standard:
java:/yourJndiName

PS: there's jboss 7 recommendation to use resources name segment like:
java:jboss/datasources/yourDataSource
java:jboss/mail/yourMailSource


text:
Q: Odd behavior of long Document annotation type in UIMA Ruta script I have the following types:

*

*SpecialDocument inheriting from uima.tcas.Annotation (or uima.tcas.DocumentAnnotation, ideally) with a feature specialFeature of type uima.cas.String

*SomeAnnotation inheriting from uima.tcas.Annotation
I have a rule that is successfully firing:
Document{ -> MARK(SpecialDocument)};
I know it is firing because I get a SpecialDocument annotation with the Document's text out of it.
But when I try to do anything with it moving forward, i.e. use it in subsequent rules, the rules do nothing.
For the very same rules that are not firing when I create a SpecialDocument from an existing Document, they do fire when I create a SpecialDocument from something else!!!
So, for instance:
Document{ -> MARK(SpecialDocument)}; // creates a SpecialDocument
SomeAnnotation -> SpecialDocument; // creates a SpecialDocument

// This sets specialFeature for every SpecialDocument EXCEPT the one created ƒrom Document.

SpecialDocument{ -> SETFEATURE("specialFeature", "whatever")};

// This marks a new annotation of SomeOtherAnnotation, again for every SpecialDocument EXCEPT the one I care about!!!

SpecialDocument{ -> MARK(SomeOtherAnnotation)};

EDIT I've noticed that this seems to be more about the length of the annotation than the type - when I do short documents, it works as expected.
What on Earth is going on here? Is this a bug or am I going nuts?


text:
Q: jQuery referring to an external template script by ID When I use jQuery to refer to a script ...
var template = _.template( $('#homeTemplate').html(), args );

... it works, but only when the script is in  like this ...

If I move it to an external file like this ...

It stops working. Why? And how do I fix this?

A: The second method doesn't work as homeTemplate's innerHTML is an empty string. The solution is using the first working method or loading the template via Ajax.

A: I can see where the confusion is coming from - The only reason template content is typically put in a script tag is because that prevents browser from accidentally generating that HTML in the DOM.
Including js/templates/hometemplate.js will not generate an DOM element that you can select using jQuery.
Use AJAX instead to grab the content from js/templates/hometemplate.js:
$.ajax({
    url : 'js/templates/hometemplate.js'
}).done(function(data) {
    _.template(data,args);
});

A: The


text:
Q: Quantum simulation of molecular spectroscopy: why? Molecular spectroscopy, e.g. through light-matter interaction, is a powerful tool to measure molecular properties such as bond lengths, energy levels, vibration frequencies, ... which give insights about the molecule's structure.
The simulation of molecular spectra can be challenging on classical computers, as it requires to solve an intrinsically quantum problem. One has to compute wavefunctions, estimate their overlaps (Frank-Condon factors), etc. All this are hard problems, whose complexity can be related to the one of boson sampling.
However, ideas have been proposed and implemented in proof of principle experiments, to simulate spectra of small molecules on quantum simulators. The idea is based on performing beam-splitter, squeezing and displacement transformations (Doktorov transformation) on a number of bosonic modes, to then measuring the resulting state. Typically, the parameters for this transformations are obtained from an harmonic approximation of the potential energy surfaces (PES), that are computed numerically under some approximations (Born–Oppenheimer).
What I'm missing is, what do we really learn from these simulated spectra? What can they be useful for? Is it the point that one can look at transition that e.g. would require unavailable lasers or measurement precision? Or what else?
One of my main point of confusion is that they are based on computed PES, and approximations. So can they really give any insight on the real physical system? And if yes, why are these impossible to obtain from the real system itself?


text:
Q: Is the extension of the Abel-Jacobi map to the smooth locus of the minimal regular model of a curve an immersion? Let $S$ be the spectrum of a discrete valuation ring with generic point $\eta$. Let $C/\eta$ be a smooth connected curve with an $\eta$-valued point, and let $\mathcal{C}/S$ be the smooth locus of the minimal proper regular model of $C$ over $S$. Let $N/S$ denote the Neron model of the Jacobian of $C_\eta$, and let $\alpha:C \rightarrow N_\eta$ denote the Abel-Jacobi map.
Now by the Neron mapping property, we obtain a (unique) extension of $\alpha$ to $\overline{\alpha}:\mathcal{C} \rightarrow N$.
Question:
Is the map $\overline{\alpha}$ necessarily an immersion?
If the genus is 1, we are OK! In general, I cannot think of a reason why this should be true, but I also cannot think of a counterexample.
I started thinking about this question from the point of view of Serre's book `Algebraic groups and class fields', ie as a question about line bundles on singular curves. I wanted to use such a result in my thesis, but in the end found an alternative approach. However, I am still curious...
Thank you for your time.

A: See my article:
http://arxiv.org/abs/math/9806173
Best regards, Bas Edixhoven.
P.S. Thanks to Liu Qing who drew my attention to this.


text:
Q: Setting brightness of IR light in Kinect One (v2) I've written an application based upon the Kinect One (known as Kinect v2, which is not the Kinect for Xbox 360).
After some testing, I got errors in my data, due to the brightness of IR lights.
In both IRview, and DepthView, the too bright reflections cannot be handled
I can put a sunglass in front of the IR camera, and all still works.
Including depth sensing still works, as it is based on time of flight not the brightness of the light.
So using a sunglass sure is a hack that works, but as a coder i dont like that. Is it possible to set the brightness by use of the SDK or some other coding Hack?
I've been thinking that maybe the lights will disable, or dimm their brightness when using the long IR reader
ea working with:
infraredFrameLongExposureReader.FrameArrived += InfraredFrameLongExposureReader_FrameArrived;

But i could not see much of a difference between the long exposure version and the normal exposure methods.
So I'm kinda out of clues... is there a way to adjust the IR brightness??

A: You can't. Not in the official Mircosoft SDK, not in libfreenect2, the open source SDK for Kinect2.
You can't change any of the hardware settings. Not the IR brightness, not the exposure time of either IR or RGB camera, nothing.
Using the long exposure IR frame, you will get an even brighter IR image, but nothing else will change.
So your best bet is the hardware hack you already figured out: put sunglasses over the IR camera (or the IR emitters).


text:
Q: Consume Realex JSON request -Spring MVC, Spring Boot I need some help with writing a controller to consume a JSON response from a payment system (Realex).
So far, I have the following from the Realex documentation but can't figure out how to write the controller - i'm new to Spring Boot/Spring MVC.
RealexHpp realexHpp = new RealexHpp("Shared Secret");
HppResponse hppResponse = realexHpp.responseFromJson(responseJson);
// responseJson will be the Java variable containing the JSON response string
String result = hppResponse.getResult();
String message = hppResponse.getMessage();
String authCode = hppResponse.getAuthCode();

So far, i have written:
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.realexpayments.hpp.sdk.RealexHpp;
import com.realexpayments.hpp.sdk.domain.HppResponse;

@Controller
public class PaymentController {

@RequestMapping(value = "/enrolment/confirmation", method = RequestMethod.GET,  consumes = "text/plain")
public String process(@RequestBody String responseJson, Model model) throws Exception {

    RealexHpp realexHpp = new RealexHpp("secret");
    HppResponse hppResponse = realexHpp.responseFromJson(responseJson);
    // responseJson will be the Java variable containing the JSON response string
    String result = hppResponse.getResult();
    String message = hppResponse.getMessage();
    String authCode = hppResponse.getAuthCode();

    System.out.println("Result: "+result);
    System.out.println("Message: "+message);
    System.out.println("AuthCode: "+authCode);

    model.addAttribute("result", result);
    model.addAttribute("message", message);
    model.addAttribute("authcode", authCode);

    return "enrolment/confirmation";

    }
}

A: Looks like Spring MVC isn't the right tool here.
See: https://github.com/realexpayments/rxp-hpp-java
It's expecting you to use their SDK to generate the repsonseJson:
HppRequest hppRequest = new HppRequest()
                    .addAmount(100)
                    .addCurrency("EUR")
                    .addMerchantId("merchantId");

RealexHpp realexHpp = new RealexHpp("mySecret");
String requestJson = realexHpp.requestToJson(hppRequest);
You might want to be using Spring MVC to capture the parameters for the request.


text:
Q: (php) Passing a class member to a function which calls a class function I'm starting to learn php and am using a maze generator to test my knowledge. Each vertex is a member of class Grid in a 2D array ($gridlist[$x][$y])
There is a class variable for each direction (NSEW) and for 'visited'. A constructor sets all variables to 0. I've included a function in the class to set the connectors between vertices, so calling $gridlist[2][2]->set_connect("N") will set the Nconnect variable to 1.
To connect two points together, each side of the connection needs to be set, so I wrote a function (not in the class) to do this:
function connect_twoV2($a, $b, $d){
    $c = $gridlist[$a][$b];
    switch ($d){
        case "N":
            $c->set_connect("N");
            $e = $gridlist[$a][$b-1];
            $e->set_connect("S");
            break;
        case "S":
            $c->set_connect("S");
            $e = $gridlist[$a][$b+1];
            $e->set_connect("N");
            break;
        case "E":
            $c->set_connect("E"); ///This is line 170
            $e = $gridlist[$a+1][$b];
            $e->set_connect("W");
            break;
        case "W":
            $c->set_connect("W");
            $e = $gridlist[$a-1][$b];
            $e->set_connect("E");
            break;
    }
}

However, when I run the file, which contains this call:
connect_twoV2(1, 2, "E");

I get:
Fatal error: Call to a member function set_connect() on a non-object in C:\XAMPP\xampplite\htdocs\phptest\zMaze3.php on line 170
Can anyone tell me why the class function call doesn't work on $c?
Many thanks
ht
(php 5.3.1 on xampp 1.7.3, testing with IE8)

A: $gridlist is a variable declared outside of your function and therefor is not accessible from inside of it. You can solve this one of two ways:
1) Use the (evil) global keyword:
global $gridlist;
$c = $gridlist[$a][$b];

2) Pass it as a parameter to your method (preferred method)
function connect_twoV2($gridlist, $a, $b, $d){


text:
Q: Как заполнить трехмерный массив с помощью BufferedReader? Возник такой вопрос: есть входные данные - размерность массива, допустим x y z, нужен заполнить массив этой размерности, данные поступают в следующем порядке, x блоков по y*z, между каждым блоком пробел, вот что у меня получилось:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;

public class Main {

    static int i;
    static int j;
    static int t;

    public static void main(String[] args) throws IOException {
        Scanner s = new Scanner(System.in);
        BufferedReader reader = new BufferedReader(new InputStreamReader(
                System.in));

        i = s.nextInt();
        j = s.nextInt();
        t = s.nextInt();

        int[][][] A = new int[i][j][t];
        int[][][] S = new int[i][j][t];

        for (int x = 0; x < i; ++x) {
            for (int y = 0; y < j; y++) {
                String[] mass = reader.readLine().split(" ");
                for (int z = 0; z < t; z++) {
                    S[x][y][z] = Integer.parseInt(mass[z]);
                }
            }
        }

        print(S);

        A[0][0][0] = S[0][0][0];

        for (int x1 = 0; x1 < i; ++x1) {
            for (int y = 0; y < j; ++y) {
                for (int z = 0; z < t; ++z) {
                    A[x1][y][z] = S[x1][y][z] - sum(A, x1, y, z);
                }
            }
        }

        // print(A);
    }

    static int sum(int[][][] A, int i, int j, int t) {
        int rez = 0;

        for (int x = 0; x <= i; ++x) {
            for (int y = 0; y <= j; ++y) {
                for (int z = 0; z <= t; ++z) {
                    if (x != i || y != j || z != t) {
                        rez += A[x][y][z];
                    }
                }
            }
        }
        return rez;
    }

    static void print(int[][][] a) {

        for (int x = 0; x < i; ++x) {
            for (int y = 0; y < j; ++y) {
                for (int z = 0; z < t; ++z) {
                    System.out.print(a[x][y][z] + " ");
                }
                System.out.println();
            }
            System.out.println();
        }
    }
}

Как мне все это дело правильно организовать?


text:
Q: Load csv file into mysql gives error when the value is in timestamp Can anyone help?
I have a csv file that has timestamp column, 'created_at' like 1594960002.
Now, I loaded this csv file to the table and it gave me warnings for every rows.
Data truncated fo column 'created_at' at row xx.

Also I could see that loaded value was turned into 0000-00-00 in the table.
To test, I changed 'created_at' value in csv file to datetime value.
something like '2020-02-02'.
When I loaded this file, error was gone.
I am not sure why I got the warning in the first case, because 'created_at' column in the table is defined as TIMESTAMP type. Do I still need to add datetime value even if it's defined as timestamp??

A: You must convert the number to a timestamp
Here a Sample:
The CSV file
root@localhost:~# cat imp.csv
1,"Bernd",61,"DE11",1594960002
2,"Peter",22,"AB12",1594960003
3,"Alex",37,"XX54",1594960053
root@localhost:~#

Truncate table for test
MariaDB [bernd]> truncate users;
Query OK, 0 rows affected (0.02 sec)

MariaDB [bernd]>

Import the CSV an show the table
MariaDB [bernd]> LOAD DATA LOW_PRIORITY LOCAL INFILE '/root/imp.csv' INTO TABLE users
    -> CHARACTER SET utf8
    -> FIELDS TERMINATED BY ','
    -> OPTIONALLY ENCLOSED BY '"'
    -> ESCAPED BY '"'
    -> (`id`,
    -> `name`,
    -> `age`,
    -> `contact_id`,
    -> @created_at)
    -> SET created_at = FROM_UNIXTIME(@created_at);
Query OK, 3 rows affected (0.02 sec)
Records: 3  Deleted: 0  Skipped: 0  Warnings: 0

MariaDB [bernd]> select * from users;
+----+-------+------+------------+---------------------+
| id | name  | age  | contact_id | created_at          |
+----+-------+------+------------+---------------------+
|  1 | Bernd |   61 | DE11       | 2020-07-17 04:26:42 |
|  2 | Peter |   22 | AB12       | 2020-07-17 04:26:43 |
|  3 | Alex  |   37 | XX54       | 2020-07-17 04:27:33 |
+----+-------+------+------------+---------------------+
3 rows in set (0.00 sec)

MariaDB [bernd]>


text:
Q: Is there an equivalent of EXPLAIN that will work in front of an ALTER TABLE query? It looks like the MySQL EXPLAIN prefix only works in front of certain queries. Is there an equivalent of EXPLAIN that will work in front of an ALTER TABLE query?
I would love to be able to find out how long my planned ALTER TABLE statement is likely to take.
Background: I have a table from someone else that contains 300 columns of data. I know that I'm only going to need to use a few of those columns, and in order to figure out which columns I need, I'm planning to do a full-text search for a few key words. But in order to do that, I need to add a full-text index. And since I'm new to this size of data set, I'm not entirely sure that this is a realistic plan. I'm hoping something like EXPLAIN (or, more likely, a substitute tool from this thread) might help determine that.

EDIT: In answer to a couple questions below, I should mention that this table has about 4 million rows and is on a local testing machine. So I can just run this thing blindly if needed. I just don't prefer to if possible. Thanks for all the good information so far.

A: Most "Alter table" will trigger the copy to tmp table operation, which it will create temp table with new schema, then lock table, copy data from old table to new table, then rename, drop old table.
So most time consumed is copy to temp table, it's depend on how big of that table if the server have enough memory. Use show table status to check how big of the table (data_length+ index_length), sample on other table to know the transfer speed on your mysql server, then you can estimate how long it will take.
Another way  mentioned on mysql doc about explain on DML, but I didn't got result, maybe not finished yet :
http://dev.mysql.com/doc/refman/5.6/en/explain.html
As of MySQL 5.6.3, permitted explainable statements for EXPLAIN are SELECT, DELETE, INSERT, REPLACE, and UPDATE. Before MySQL 5.6.3, SELECT is the only explainable statement.


text:
Q: How to wrap content with a tag? When I click one of the li item I want to open a div that contains a form:

$(settings.dom.wrapperID).wrap('');

This is text 1 ...

This is text 2 ...

This is text 3 ...

This is text 4 ...

If I make an normal a tag and put #login-box in the link works fine, but not with jQuery.

A: Sure, by adding http:// right before your link, like this:
$(settings.dom.wrapperID).wrap('');


text:
Q: Can the count() function work for getting the number of rows with a specific name? I have a table types like this :
id     cat
_________

1        A

2        B

3        A

4        A

5        B

and the code i use to query the Database is something like this:
$query="SELECT*FROM types";

$res=myslqi_query($conn,$query)

while($row=myslqi_fetch_assoc($res){

          if($row['cat']==A){

               echo count($row['cat'];

               };

};

i get an error with this type of code by the count()function .
Is it possible that insted of Displaying like AAA together just ti be able to display a number insted like 3 what i just want ?

A:
Is it possible that insted of Displaying like AAA together just ti be able to display a number insted like 3 what i just want
be able to display the totall amount of the values in the 'cat' field only as a number . So if the are three Values with A that the result to be just the number 3

Try
<?php
$rows = [
 ['id'=>1, 'cat'=>'A'],
 ['id'=>2, 'cat'=>'B'],
 ['id'=>3, 'cat'=>'A'],
 ['id'=>4, 'cat'=>'A'],
 ['id'=>5, 'cat'=>'B']
];

print_r( array_count_values( array_column($rows,'cat') ) );

Output
Array
(
   [A] => 3
   [B] => 2
)

Sandbox
Where the value is the number of occurrences of each 'cat'
I don't know if that is what you want, but it's like magik..  No that was a joke it's just code.
Array Column returns only the values from a single column in a multi-dimensional array, so for this example it returns
[
   'A',
   'B',
   'A',
   'A',
   'B'
]

Then array count values, counts all the occurrences of each value in a single array, and gives us the result show at the beginning.
For this you need the whole results of the data from the database, So you can fetch them all with this while($row=myslqi_fetch_assoc($res){ and add each row to result $rows[] = $row in the loop, or you can just do $rows =mysqli_fetch_all($res,MYSQLI_ASSOC)
http://php.net/manual/en/function.array-column.php
http://php.net/manual/en/function.array-count-values.php
Of course you could also do this just in MySQL
SELECT count(id) as total FROM types GROUP BY cat.

But whatever...
Cheers Hope it helps.


text:
Q: How to provide path to service key file in index.js file, for firebase-auth? I am trying to give the path of serviceAccountKey.json file in my index.js file because I am unable to register the new users and uploading the DP of logged in users(the users can logg in if the account is created from the firebase manually) because of the error 400. I pasted the serviceAccountKey.json file in (Firebase) functions folder, which is different from public folder and my Index.js file is also in the same folder (functions folder).
The image describes the directory of my project

I am giving the path as
var serviceAccount = require("/serviceAccountKey.json");
Okay, so for more details, I am pasting the complete code of Index.js file-
const functions = require('firebase-functions');
const express = require('express');

var admin = require("firebase-admin");

var serviceAccount = require("/serviceAccountKey.json");

admin.initializeApp({
  credential: admin.credential.cert(serviceAccount),
  databaseURL: "I DON'T THINK IT IS COMPULSORY TO TYPE URL IN STACKOVERFLOW"
});

const app = express();
app.get('/', (request, response)=>{

     response.send(index.html);

});

exports.app=functions.https.onRequest(app);

And I am getting the error-
Error parsing triggers: Cannot find module '/serviceAccountKey.json'

Any Idea?

A: As this is a file in the current path you can do it like:
var serviceAccount = require("./serviceAccountKey.json")

Also I would recommend you to take a look at the docs for paths here: https://nodejs.org/api/path.html


text:
Q: No hint path defined for [mail] Laravel 5.4 I am trying to show my markdown email on view, but there's something wrong on my mail view, it shows like
ErrorException in FileViewFinder.php line 112:
No hint path defined for [mail]. (View: /opt/lampp/htdocs/ppsb_new/core/resources/views/emails/tagihan.blade.php)

and my markdown mail view
@component('mail::message')
# TAGIHAN PEMBAYARAN

Berikut tagihan anda untuk pembayaran

@component('mail::button', ['url' => ''])
wut ?
@endcomponent

Gunakan kode tagihan tersebut untuk membayar tagihan.

Thanks,

{{ config('app.name') }}
@endcomponent

and there's also vendor on my views who have their components.

A: if you have your email views in ...views/mail, that is how you can specify it:
app('view')->addNamespace('mail', resource_path('views') . '/mail');

A: To use Markdown mailable messages, you have to update the build method of your Mailable class and instead of view(), you have to use markdown().
Like this:
public function build()
{
    return $this->markdown('emails.registered');
}

A: If you have a View not found issue with laravel mail. After trying the accepted answer and it doesn't work, check yourtemplate.blade.php markdown file and ensure you are not closing @endcomponent twice without a opening @component

A: You need to call the markdown() method in the build() method of your mailable - not the view() method. See the example below:
/**
 * Build the message.
 *
 * @return $this
 */
public function build()
{
    return $this->markdown('view-to-mail');
}

A: I had the same problem, then used this syntax and worked as a charm

@component('mail.html.message')
# Introduction

The body of your message.

@component('mail.html.button', ['url' => config('app.url')])
Button Text
@endcomponent

Thanks,

{{ config('app.name') }}

@endcomponent

Where my folder structure views/mail/html for markdown messages.
and my App\Mail\NewEmail.php
<?php

namespace App\Mail;

use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Mail\Mailable;
use Illuminate\Queue\SerializesModels;

class NewEmail extends Mailable
{
    use Queueable, SerializesModels;

    /**
     * Create a new message instance.
     *
     * @return void
     */
    public function __construct()
    {
        //
    }

    /**
     * Build the message.
     *
     * @return $this
     */
    public function build()
    {
        return $this->markdown('mail.new-message'); // -> pointing to views/mail/new-message.blade.php containing above message
    }
}

A: Try using a custom email view template, like this:
You received a message from : {{ $name }}

Name: {{ $name }}

Email: {{ $email }}

Message: {{ $user_message }}

A: If you want to use markdown in php blade file, then call view by markdown()
Or if you want to call blade file by view(), remove markdown syntax from blade file and use plane html.

A: I used caffeinated/modules for laravel5.2.
If you are similar to me you can run this:
php artisan module:list

+------+-------+-------+-------------------------------------+----------+
| #    | Name  | Slug  | Description                         | Status   |
+------+-------+-------+-------------------------------------+----------+
| 9001 | Frame | Frame | this is a basic frame for both web. | Disabled |
| 9001 | Index | Index | this is web default index           | Enabled  |
| 9001 | Admin | Admin | This is admin of meixin project     | Enabled  |
+------+-------+-------+-------------------------------------+----------+

All right, you can see the disabled option.
php artisan module:enable Frame

Module is already enabled.
That's all, hope this helps.


text:
Q: RemoveAllViews not removing views I try to remove all child views of a linear layout but nothing is removed, the weird thing is the same code is working in another application. Here's the sample code of the method that populate the choiceHolder whenever a tab in it is selected (I remove all view and mark the selected one and populate basing on that:
/** a method to fill the upper bar where we choose the {@link CategoriesMyBox}
 * @param category
 */
private void fillNavigationBar( CategoriesGetter category) {
    TextView categoryTxt = new TextView(getActivity());
//      categoryTxt.setAllCaps(true);
        LinearLayout.LayoutParams txtParams;
        if (category.isSelected() /*|| (category.getId_categorie()==0 && allselected)*/) {
        txtParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        txtParams.gravity = Gravity.CENTER;
        categoryTxt.setGravity(Gravity.CENTER);
        categoryTxt.setTextSize(categoryTxt.getTextSize());
        txtParams.setMargins(10, 0, 10, 0);
        categoryTxt.setPadding(5, 5, 5, 5);
        if (category.getId_categorie() == 0) {
            categoryTxt.setText(getResources().getString(R.string.all_boxs));
        }else {
            categoryTxt.setText(category.getName_categorie());
        }
        categoryTxt.setTextColor(Color.GREEN);
        categoryTxt.setBackgroundDrawable(getResources().getDrawable(R.drawable.back_categories_selected));
//          categoryTxt.setBackgroundColor(Color.parseColor("#E3E8E6"));
        categoryTxt.setTag(category);

    }else {

        txtParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        txtParams.setMargins(10, 0, 10, 0);
        categoryTxt.setGravity(Gravity.CENTER);
        categoryTxt.setPadding(5, 5, 5, 5);
        txtParams.gravity = Gravity.CENTER;
        if (category.getId_categorie() == 0) {
            categoryTxt.setText(getResources().getString(R.string.all_boxs));
        }else {
            categoryTxt.setText((category.getName_categorie()));
        }
        categoryTxt.setTextColor(Color.GRAY);
        categoryTxt.setBackgroundDrawable(getResources().getDrawable(R.drawable.back_categories));
//          categoryTxt.setBackgroundColor(Color.parseColor("#777777"));
        categoryTxt.setTag(category);
    }
    choiceHolder.addView(categoryTxt, txtParams);
    categoryTxt.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            CategoriesGetter cat = (CategoriesGetter)v.getTag();
            id_cat = cat.getId_categorie();
            for (int i = 0; i < categories.size(); i++) {
                categories.get(i).setSelected(false);
            }
                cat.setSelected(true);
    //              choiceHolder.removeAllViews();
            /*for(int i=0; i<((ViewGroup)choiceHolder).getChildCount(); ++i) {
                View nextChild = ((ViewGroup)choiceHolder).getChildAt(i);
                choiceHolder.removeView(nextChild);
            }*/
            while (((ViewGroup)choiceHolder).getChildCount() >0) {
                View nextChild = ((ViewGroup)choiceHolder).getChildAt(0);
                choiceHolder.removeView(nextChild);
            }
//              choiceHolder.removeAllViewsInLayout();
            for (int i = 0; i < categories.size(); i++) {

                fillNavigationBar(categories.get(i));
            }
            callbackCategory.selectCategory(cat.getId_categorie());

        }
    });
}

choiceHolder is a LinearLayout.
and here's a picture showing the problems :
Well all my application is behaving the same way even when updating the list inside i can still see the list that was before.

A: the solution i found for this problem is remove the fullScreen theme tag from the activity in the AndroidManifest it was like this :
<application
    android:name="com.paperpad.mybox.ApplicationInit"
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity
        android:name="com.paperpad.mybox.activities.SplashActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>

    <meta-data
        android:name="com.crashlytics.ApiKey"
        android:value="023e7fe8a4a93f93ffe7510201929d081b125313" />

    <activity
        android:name="com.paperpad.mybox.activities.BoxsMainActivity"
        android:configChanges="orientation|keyboardHidden|screenSize"
        android:label="@string/title_activity_boxs_main"
        android:theme="@style/FullscreenTheme" >
    </activity>
    <activity
        android:name="com.paperpad.mybox.LoginActivity"
        android:label="@string/title_activity_login"
        android:windowSoftInputMode="adjustResize|stateVisible" >
    </activity>
</application>

by removing android:theme="@style/FullscreenTheme" from the activity BoxsMainActivityall worked. hope this helps someone...

A: The best way to make sure something runs via a view is to run it via a post:
e.g
someView.post(new Runnable(){
    @Override
    public void run()
    {
        someView.removeAllViews();
    }
}

A: Have you tried using .invalidate() or .postInvalidate() on the choiceHolder?

A: In your xml file you can define for the same positions in your page more layouts , Let s say you have  a surface of the buttom of the page , you can define Layout 1 and Layout 2 with the same properties and one will have visibility gone , in your code you will change this at some actions and you will switch the visibility .

A: The problem could be that choiceHolder must be declared as "final" to be called in "onClick" - placing the View calls in a runnable so that it is not declared as final should fix it. There's not a compiler error because it's valid to call a method and the method call could still result in the view appearing on the screen even though the parent layout ("choiceHolder") did not retain a reference to it that allows you to remove it.


text:
Q: FATAL: Listen error: unable to monitor directories for changes I am trying to watch a sass directory .I created sass project using the following command on my ubuntu 16.4 system
 compass create sass

And got the result
directory sass/  directory sass/sass/  directory sass/stylesheets/     create sass/config.rb     create sass/sass/screen.scss     create sass/sass/print.scss     create sass/sass/ie.scss
        write sass/stylesheets/ie.css
        write sass/stylesheets/print.css
        write sass/stylesheets/screen.css

    ********************************************************************* Congratulations! Your compass project has been created.

    You may now add and edit sass stylesheets in the sass subdirectory of your project.

    Sass files beginning with an underscore are called partials and won't be compiled to CSS, but they can be imported into other sass stylesheets.

    You can configure your project by editing the config.rb configuration file.

    You must compile your sass stylesheets into CSS when they change. This can be done in one of the following ways:
      1. To compile on demand:
         compass compile [path/to/project]
      2. To monitor your project for changes and automatically recompile:
         compass watch [path/to/project]

    More Resources:   * Website: http://compass-style.org/   * Sass: http://sass-lang.com   * Community: http://groups.google.com/group/compass-users/

    To import your new stylesheets add the following lines of HTML (or equivalent) to your webpage: <head>   <link href="/stylesheets/screen.css" media="screen, projection" rel="stylesheet" type="text/css" />   <link href="/stylesheets/print.css" media="print" rel="stylesheet" type="text/css" />   <!--[if IE]>
          <link href="/stylesheets/ie.css" media="screen, projection" rel="stylesheet" type="text/css" />   <![endif]--> </head>

And i try to watch this using compass watch results an error as shown bellow

Compass is watching for changes. Press Ctrl-C to Stop. FATAL: Listen error: unable to monitor directories for changes. Visit
        https://github.com/guard/listen/wiki/Increasing-the-amount-of-inotify-watchers
        for info on how to fix this.
        bharathi@bharathi-H81M-S:~/share/springwisev2/wp-content/themes/Springwise
        2016/library/sass$ compass watch

A: Just try to execute this from your console:
echo fs.inotify.max_user_watches=524288 | sudo tee -a /etc/sysctl.conf && sudo sysctl -p

Hope this will work for you
.
References: click_here


text:
Q: How to repair SD card that was unplugged during formatting? I tried to format my SD card on my Windows computer but unfortunately I pulled it out during the process. Now it can't be recognized. I tried to wipe it using disk utility on Mac OS X but after it's done and I click "check disk" I get the message:

Partition map needs repairing: there is a problem with file system of
  the system EFI partition.

This may be not the exact message you get in english - I translated it. How to repair the card? Using the "repair disk" button in disk utility it goes without problem but after unmounting, ejecting and putting the card in the card reader again yields the same problems.
EDIT: I tried everything I found on the net - no success. Now I get the following message in disk utility:
** /dev/disk1s1
Invalid BS_jmpBoot in boot block: ffffff

Any idea?


text:
Q: How to create a two column grid using CSS grid? I'm trying to create a fairly simple layout, and I want to avoid using floats. My simplified HTML is as follows, and so now I'm trying to create a two column layout, in which I would like to have item B on the left, and items A, C and D on the right (underneath eachother). The Code I tried using is:

.container {
  display: grid;
  grid-template-areas: 'left right';
}

.item-b {
  grid-area: left;
}

.item:not(.item-b) {
  grid-area: right;
}

A

B

C

D

But here, the items on the right are being placed on top of eachother. Is there any way to place them underneath eachother? Here is a fiddle with the same code: https://jsfiddle.net/b85h7g03/
Also, when you look at the fiddle, why are the items not 50% of the with of the container anymore?
(By the way, the reason I'm not placing item B above item A in my HTML, is because on mobile item B needs to be below item A)
Edit: I just updated my fiddle: https://jsfiddle.net/b85h7g03/2/ I forgot to mention that item B has a flexible height and can get very long. For reference: This is the layout I want, but without floats: https://jsfiddle.net/hLx3709v/

A: Here you go by using flex

CSS
* {
  box-sizing: border-box;
}
body, html {
  margin: 0;
  padding: 0;
}
.container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  flex-wrap: wrap;
}
.children {
  width: calc(50% - 10px);
  margin: 5px;
  background: #D8D8D8;
  flex: 1;
}
.children:first-child {
  flex: 0 0 calc(100% - 10px);
  border: 2px solid #44C0FF;
}


text:
Q: How can I speed up xmlhttp requests (VBA)? Should I be using arrays? For my work, I regularly need to compare a table of ~2000 meds to a website to see whether their substance IDs (an 8-digit number) still exist / have changed. I tried to automate the process using VBA (allowed at work because it comes with excel) and xmlhttprequests. I got it to work, but the process is ever so slow (sometimes excel freezes for up to 10 minutes) and I want to speed things up. Mind you, I'm only an amateur and not a programmer.
This is my code:
Sub PZN_Check_XHR()

Dim xmlhttp As Object
Dim url As String
Dim pzn As String
Dim ZelleA As Range
Dim ZelleB As Range
Dim a As Range

Set a = Worksheets("Treatments").Range("H2:H" & Cells(Rows.Count, "H").End(xlUp).Row)
Set xmlhttp = CreateObject("MSXML2.serverXMLHTTP")

'Begin Loop, define PZN (substance IDs), define cells
For Each ZelleA In a
    pzn = ZelleA.Value
    Set ZelleB = Cells(ZelleA.Row, 10)
    Set ZelleC = Cells(ZelleA.Row, 8)

    'Add a link to our intranet database for all the substance IDs in Column H)
    If ZelleC.Value <> 0 Then
        ZelleC.Hyperlinks.Add Anchor:=ZelleC, Address:="http://ukb648/list.php?st=" & pzn & "&aufruf=1"
    End If

    'URL of the website I want to check
    url = "https://www.arzneimittel-datenbank.de/search/" & pzn

    xmlhttp.Open "GET", url, True
    xmlhttp.Send
    Do While xmlhttp.readyState <> 4
        DoEvents
    Loop

       If InStr(1, xmlhttp.responseText, "<title>Arzneimittel-Datenbank") <> 0 Then
            ZelleB.Interior.ColorIndex = 3
            ZelleB.Value = "PZN not found"
            ZelleB.Hyperlinks.Add Anchor:=ZelleB, Address:="http://ukb648/list.php?st=" & Left$(Worksheets("Treatments").Cells(ZelleA.Row, 2), InStr(1, Worksheets("Treatments").Cells(ZelleA.Row, 2), " "))
        Else
            'Print result to ZelleB
            ZelleB = Mid(xmlhttp.responseText, InStr(1, xmlhttp.responseText, "<title>") + 7, (InStr(1, xmlhttp.responseText, "</title>") - InStr(1, xmlhttp.responseText, "<title>") - 32))
            ZelleB.Interior.ColorIndex = 4
            Worksheets("Treatments").Cells(ZelleA.Row, 11) = Worksheets("TradeNames").Cells(ZelleA.Row, 3)
            Worksheets("Treatments").Cells(ZelleA.Row, 12) = Worksheets("TradeNames").Cells(ZelleA.Row, 5)
    End If

Next ZelleA

End Sub

This code takes about 1-2 seconds per row to execute, and my table has about 2000 rows (and will grow to >10.000 rows in the forseeable future). Is there a way to speed this up? Maybe reading the data into an array first, and work from there? If yes, how so? Or did I screw up the loop somehow?
Thank you so much for your time!
Edit: Some sample PZNs (as requested by "Foxfire And Burns And Burns", thank you for your time): 04516999, 03300613, 02358177, 02197219, 02530357, 00886110, 03355873, 04920298
Unfortunately, I don't have enough reputation yet to upvote your comments. However, I will try your ideas and provide feedback if anything works.


text:
Q: React client side Google api Calendar 403 I have this working on local host and events are pulled through from Google Calendar. When i deploy and test the calendar integration it fails with a 403 :
domain: "global", message: "The request is missing a valid API key.", reason: "forbidden"

Everything is server side and I have attempted to use Auth0 for login (which works perfectly), but then extend that authentication to Google calendar. It seemed to be working until I deployed!
React function runs on component mount:
        window.gapi.load('client:auth2', () => {

            gapi.client.init({
                apikey: API_KEY,
                clientId: CLIENT_ID,
                discoveryDocs: DISCOVERY_DOCS,
                scope: SCOPES,
            })

            gapi.client.load('calendar', 'v3', () => console.log('Loaded Calendar v3'))
            gapi.auth2.getAuthInstance().then(() => {...

A: I think the capitalization of apikey is off, try:
gapi.client.init({
          apiKey: API_KEY,
          clientId: CLIENT_ID,
          discoveryDocs: DISCOVERY_DOCS,
          scope: SCOPES
})


text:
Q: How to create a default profile and launch outlook client(GUI) using Microsoft.Office.Interop.Outlook I was trying to launch Outlook with default profile or create default profile  using  Microsoft.Office.Interop.Outlook assembly file. but i'm getting following error while launch my outlook application.
Error message: The property "http: //schemas.microsoft.com/mapi/proptag/0x7C070102" is unknown or can not be found.
And i'm new to this assembly. Also suggest any other framework to achieve my goal
 Outlook.Application OutlookClient()
    {
        Outlook.Application oOutlook = null;
        Outlook.NameSpace oNS = null;
        oOutlook = new Outlook.Application();
        oNS = oOutlook.GetNamespace("MAPI");
        oNS.Logon("My profile", "myprofilepassword", false, false);
        oOutlook = Marshal.GetActiveObject("Outlook.Application") as Outlook.Application;
        return oOutlook;
    }

A: First, there is no need to initialize the Application instance object twice in the code:
oOutlook = new Outlook.Application();

and
oOutlook = Marshal.GetActiveObject("Outlook.Application") as Outlook.Application;

Second, there is no need to use the Logon method.
Here is what MSDN states for that:

Use the Logon method only to log on to a specific profile when Outlook is not already running. This is because only one Outlook process can run at a time, and that Outlook process uses only one profile and supports only one MAPI session. When users start Outlook a second time, that instance of Outlook runs within the same Outlook process, does not create a new process, and uses the same profile.
If Outlook is already running, using this method does not create a new Outlook session or change the current profile to a different one.
If Outlook is not running and you only want to start Outlook with the default profile, do not use the Logon method. A better alternative is shown in the following code example, InitializeMAPI: first, instantiate the Outlook Application object, then reference a default folder such as the Inbox. This has the side effect of initializing MAPI to use the default profile and to make the object model fully functional.

Sub InitializeMAPI ()

  ' Start Outlook.
  Dim olApp As Outlook.Application
  Set olApp = CreateObject("Outlook.Application")

  ' Get a session object.
  Dim olNs As Outlook.NameSpace
  Set olNs = olApp.GetNamespace("MAPI")

  ' Create an instance of the Inbox folder.
  ' If Outlook is not already running, this has the side
  ' effect of initializing MAPI.
  Dim mailFolder As Outlook.Folder
  Set mailFolder = olNs.GetDefaultFolder(olFolderInbox)

  ' Continue to use the object model to automate Outlook.
End Sub

Starting in Outlook 2010, if you have multiple profiles, you have configured Outlook to always use a default profile, and you use the Logon method to log on to the default profile without prompting the user, the user will receive a prompt to choose a profile anyway. To avoid this behavior, do not use the Logon method; use the workaround suggested in the preceding InitializeMAPI example instead.
So, your code should look like the following one:
Outlook.Application OutlookClient()
{
    Outlook.Application oOutlook = null;
    Outlook.NameSpace oNS = null;
    oOutlook = new Outlook.Application();

    // optional
    oNS = oOutlook.GetNamespace("MAPI");
    Outlook.MAPIFolder folderInbox = oNS.GetDefaultFolder(olFolderInbox)

    return oOutlook;
}

See the C# app automates Outlook (CSAutomateOutlook) sample code.


text:
Q: Connection Strings and Configuration Files Currently, I am learning how to configure my .NET projects using configuration file.
According to MS example, connection string is represented in config file as <connectionStrings> element:
<?xml version='1.0' encoding='utf-8'?>
  <configuration>
    <connectionStrings>
      <clear />
      <add name="Name"
       providerName="System.Data.ProviderName"
       connectionString="Valid Connection String;" />
    </connectionStrings>
  </configuration>

Looked up <connectionStrings> element schema in MS documentation "Configuration File Schema", but it is not there. I am missing something ?

A: You can find it here in this site:
http://msdn.microsoft.com/en-us/library/system.configuration.configurationmanager.connectionstrings%28v=vs.110%29.aspx


text:
Q: What is self-referencing structure in C? struct LinkedList
{
    int data;
    struct LinkedList *next;
};

In the code, within the definition of struct LinkedList there is a pointer to the structure itself.
How does it work?

A: So, the code
struct LinkedList
{
    int data;
    struct LinkedList *next;
};

defines a struct type containing two members named data and next, with the next member storing the address of a different object of the same type.  Given the code:
struct LinkedList Node1 = { .data = 1, .next = NULL };
struct LinkedList Node0 = { .data = 0, .next = &Node1 };

you get something that sort of looks like this:
Node0              Node1
+---+--------+    +---+------+
| 0 | &Node1 |--->| 1 | NULL |
+---+--------+    +---+------+

(Note that you would never create a linked list this way, this is just for illustration).
This is possible for two reasons:

*

*C allows you to declare pointers to incomplete types;

*Pointers to struct types all have the same size and representation.

This is an example of a self-referential data type, which simply means that the type stores a reference (pointer) to a different object of the same type.

A: What you talk about are recursive data structrues and the question is how to let a data structure reference itself.
In C this can be done by declaring a pointer to itself in the definition of the data structure, "self" meaning a thing of its own type.
Note that when you write the expression, the data structure is not yet complete. Therefore it is not possible to let a data structue contain an occurence of itself, for once because the definition is not yet completely known and for two because the data strutcure would be never ending containing an occurrence of itself, itself,...
But you can declare a pointer to itself. The compiler now only allocates storage for the pointer and if you later assign/dereference the pointer it knows the storage pointed to contains an occurrence of itself. That is what you do in your example.

A: A self-referential pointer which points to the address of whatever it is a part of. So for example,
typedef struct node {
   char data[30];
   struct node *this;
   struct node *next;
} Node;

*this is a self-referential pointer if it is assigned to whatever is applied to.
,and

Clearly a Cell cannot contain another cell as it becomes a never-ending recursion.

However a Cell CAN contain a pointer to another cell.
Refer this post as well.


text:
Q: bash: ls -l with grep I have this:
find . -type f -exec file {} + | grep ASCII

This is the output:

I want to know if is possible to show the size of the files and their path, for all files that file indicates as ASCII.

A: This uses cut to extract the filename from the output of file | grep ASCII, and then pipes it into xargs stat -c ... to display only filename and size:
find . -type f -exec file {} + | grep  ASCII | cut -d: -f1 | xargs -d'\n' -r stat -c '%n %s'

If you want the size before the filename, use '%s %n' in the stat command.
It will cope with filenames that contain any character except : or newline. It assumes a GNU system (for -d and that stat syntax). It could give false positives if ASCII is present in the file path.

A: I would use a shell loop instead. If you are using bash, you can make ** recurse into subdirectories by running shopt -s globstar. As explained in man bash:
globstar
    If set, the pattern ** used in a pathname expansion con‐
    text will match all files and zero or  more  directories
    and  subdirectories.  If the pattern is followed by a /,
    only directories and subdirectories match.

So, with that in mind, you could use the following loop:
shopt -s globstar
for file in **; do
    [ -f "$file" ] && file "$file" | grep -q "ASCII" && stat -c '%n %s' "$file"
done

A: With zsh:
isascii() [[ $(file -b --mime-encoding - < ${1-$REPLY}) = us-ascii ]]
zmodload zsh/stat
zstat -n +size -- **/*(D.L+1+isascii)

Broken down:

*

***/* recursive globbing, a feature introduced by zsh in the early 90s and later copied by some other shells like ksh93, fish, bash, yash and tcsh.

*(...), glob qualifier: another 90s feature but still unique to zsh as of today. Allows to further specify which files are included in the glob based on file metadata or to change the expanded value. Here:

*

*D: include Dot (hidden) files

*.: include only regular files

*L+1: only bother considering files that are more than 1 byte large (as otherwise file won't tell you anything about them)

*+isascii: calls the isascii command for each matching file to decide whether to include the file.

*isascii is defined as a function that calls file on $REPLY (that's how file names are passed for functions called by glob qualifiers, functions may modify it or return more files in the $reply array). We use ${1-$REPLY} here so we can also use that function on a file given as argument, and don't modify $REPLY, just return the decision via the exit status.
With -b and --mime-encoding, file (at least the implementation from libmagic) outputs only the guessed encoding. It's a lot more reliable than calling grep ASCII on the output of file the-file,
as ASCII may occur there in the file path or other information extracted from the file.

A: Try this:
for file_name in find . -type f -exec file {} + | grep ASCII | awk -F ':' '{print $1}'; do  ls -lrth ${file_name}; done


text:
Q: Why does uWSGI fail to start in Docker? I am relatively new to using uWSGI to serve Python applications and I am attempting to start a uWSGI process in emperor mode with a vassal, but every time I try to start uWSGI inside of Docker with the following command (as root):
# /usr/local/bin/uwsgi --ini /etc/uwsgi/emperor.ini

What I get as a response is:
[uWSGI] getting INI configuration from /etc/uwsgi/emperor.ini
2.0.13.1

The emperor.ini configuration file looks like:
# files/etc/uwsgi/emperor.ini
[uwsgi]
emperor = /etc/uwsgi/apps-enabled
die-on-term = true
log-date = true

While the only vassal's configuration looks like:
# files/etc/uwsgi/apps-enabled/application.ini
[uwsgi]
app_dir = /var/www/server
plugin = python
master = true
callable = app
chdir = %(app_dir)
mount = /=%(app_dir)/start.py
protocol = uwsgi
socket = :8079
uid = www-data
gid = www-data

buffer-size = 32768
enable-threads = true
single-interpreter = true
processes = 1

stats = 127.0.0.1:1717

(NB: The filenames above are given in terms of where they live relative to the Dockerfile which will then copy them to the correct locations, basically removing the prefix files)
Currently the uWSGI Docker image I'm using is built off of an ubuntu:trusty base image (though I've tried ubuntu:latest and alpine:latest and encountered the same problem), and although I am attempting to launch the uWSGI process with supervisor, as stated previously, it also fails when run directly from the command line. In the Docker image I'm installing uWSGI using pip but have also tried using apt-get with the same result.
I should also mention that I've tried different versions of uWSGI 2.0.13.1 and 1.9.something with the same result, if that helps.
# Dockerfile
FROM ubuntu:trusty
MAINTAINER Sean Quinn "me@mail.com"

RUN apt-get update \
 && apt-get install -y \
      ack-grep git nano \
      supervisor \
      build-essential gcc python python-dev python-pip

RUN sed -i 's/^\(\[supervisord\]\)$/\1\nnodaemon=true/' /etc/supervisor/supervisord.conf \
 && sed -i 's/^\(\[supervisord\]\)$/\1\nloglevel=debug/' /etc/supervisor/supervisord.conf \
 && sed -i 's/^\(files = .*\)$/;\1/' /etc/supervisor/supervisord.conf \
 && sed -i 's/^\(\[include\]\)$/\1\nfiles = \/etc\/supervisor\/conf.d\/*.conf/' /etc/supervisor/supervisord.conf

ENV UWSGI_VERSION 2.0.13.1

RUN pip install uwsgi==${UWSGI_VERSION}

RUN mkdir -p /etc/uwsgi \
 && mkdir -p /etc/uwsgi/apps-available \
 && mkdir -p /etc/uwsgi/apps-enabled \
 && mkdir -p /var/log/uwsgi

COPY files/etc/supervisor/conf.d/uwsgi.conf /etc/supervisor/conf.d/uwsgi.conf
COPY files/etc/uwsgi/emperor.ini /etc/uwsgi/emperor.ini

VOLUME /etc/uwsgi/apps-enabled
VOLUME /var/www

ENTRYPOINT ["/usr/bin/supervisord"]
CMD ["-c", "/etc/supervisor/supervisord.conf"]

As mentioned, the supervisord process attempts to launch the uWSGI process using the following supervisor configuration.
# files/etc/supervisor/conf.d/uwsgi.conf
[program:uwsgi]
command=/usr/local/bin/uwsgi --ini /etc/uwsgi/emperor.ini
user=root

The application Python files are mounted in a subdirectory of /var/www and the application uWSGI configuration is mounted into /etc/uwsgi/apps-enabled.
The bizarre thing is, if I install supervisor and uWSGI on a new Ubuntu VM (outside of Docker) with all of the configuration and files in place I can see uWSGI properly process the emperor.ini and read the vassal .ini files. I haven't yet attempted to add nginx into the equation because I want to make sure uWSGI is starting and reading configuration files correctly first and foremost.
Is there any way to increase the logging or ascertain why I'm only seeing what appears to be the version number of the uWSGI binary? It's like the uWSGI process is completely ignoring command line options. I feel like I'm missing something that should be obvious.
Thanks in advance for any help anyone can give!

A:
tl;dr don't use UWSGI_VERSION as an environment variable, apparently it forces uWSGI to only print the version number instead of start?

I believe I solved my own issue!
After experimenting with other uWSGI images on Docker's hub, I found that they were also running into the same issue so I began to look further into possible configuration issues. I tried changing permissions among other things.
I noticed however that when I used jpetazzo/nsenter to enter the running container that I saw uWSGI start (rather than simply output the uWSGI version information as highlighted above). When entering using docker exec, uWSGI would only print the version information. After playing around a bit more, I discovered that issuing the command su - from within the container launched using docker exec I again saw uWSGI start.
After some inspection, I discovered several differences in the environment variables between the root user in one shell vs. another. It led me to the UWSGI_VERSION environment variable, which appears to have been the culprit because removing UWSGI_VERSION allowed uWSGI to start.
I modified my Dockerfile to use UWSGI_PIP_VERSION instead as the environment variable to indicate the version of uWSGI to install, which seems to be a safe alternative to UWSGI_VERSION. YMMV.


text:
Q: How to set a letter limit within a digit string I tried some explanations that I read here in the forum but I could not succeed
I would like to set a limit of letters within a digit string
for example, a limit of up to three letters:
example : AAA12348
 example: 12AAA234
 example: 1234A568

A: The following pattern will only allow a maximum of 3 letters within each string. It anchors at the beginning of the string and then asserts that it is not followed by four letters, separated by anything.
^(?!.*[A-Za-z].*[A-Za-z].*[A-Za-z].*[A-Za-z]).*$
https://regex101.com/r/pQmili/2
Edit: If you also wish to disallow a set of certain other characters such as ! and #, you can create an additional negative lookahead group containing a character set of those characters.
^(?!.*[A-Za-z].*[A-Za-z].*[A-Za-z].*[A-Za-z])(?!.*[!#]).*$
https://regex101.com/r/pQmili/3

A: I'm guessing that here we wish to fail two of our inputs and pass only one of them:
((\D+?)\d{1,3}(\D+?))

Demo
RegEx Circuit
jex.im visualizes regular expressions:


text:
Q: Converting onClick event to tap event of jquery mobile <input type="text" autofocus id="emailid"/>
<input type="button" value="@" id="@"  onclick="insertat()" />

<script type="text/javascript">
  function insertat() {
    emailId.value += "@";
  }
</script>

I have a text box and a button with "@" symbol which when clicked inserts @ symbol in the text box.
However, The onClick event seems to respond slow and displays performance issues on Android tablets. How do i convert the onClick events to tap event using jQuery Mobile.
Any help would be appreciated.


text:
Q: Are PGP keys as good for certificates as X.509 keys? I'm working on a decentralized transaction processing system that needs both authentication and general encryption, and I have a design decision to make: should I use PGP or X.509 certificates?
While the world tends to use X.509 for authentication (especially in browsers), they are based on the principle of having a central authority vouch for each certificate, meaning the system would need a CA and anyone who wants to participate in the system would need to have their keys signed by that CA.
PGP, on the other hand, is based on a "Web of Trust", where parties who want to communicate merely need to have any trusted party in common who will sign both keys. A CA isn't necessary in this case.
My overall design goals prefer the Web-of-Trust model, to keep the system decentralized, but I may also have customers who prefer a centralized model, and I don't want to prohibit that possibility. Is there anything stopping the Web-of-Trust principle from working with X.509? Likewise, is it easy and straightforward to mimic CAs in the PGP cryptosystem? Are they interchangeable in practice?
(For some reason, this is making me think of the false dichtomy: "I'm trying to bang in a nail, should I use a beer bottle or the heel of a shoe?")

A: PGP keyservers can act as an authoritative point of trust(similar to a CA).  The thing I like about PGP keys/keyservers is that I choose which sources to trust to build this web.  In most modern OSes and applications using x509/CA/web-browser model there are "chain of trust" issues where there are several ways to fool/break the chain.  Alternately, you can run your own CA, but if you do and someone with a signing certificate from an automatically imported one(an isp/foreign government for example) could break your chain of trust trivially.  You wouldn't even know.


text:
Q: Hibernate error node to be traverse cannot be null Hi guys i have a question regarding this annoying error. Below it's my code
String updateDefaultBU = "update ClientUserVO  set defaultBUnit = :yes where id = (select      max(cu1.id) from ClientUserVO cu1 where cu1.user.id = :userId and cu1.defaultBUnit = :no)";
updateDefaultBU = " and not exists (select cu2.id from ClientUserVO cu2 where cu2.user.id    = :userId and cu2.defaultBUnit = :yes) ";
Query updateQuery = session.createQuery(updateDefaultBU);
updateQuery.setString("yes", "Y");
updateQuery.setString("no", "N");
updateQuery.setLong("userId", userID);

I don't seem to understand where does it find a not that could not be traversed, also this error is very general and it could happen for various reasons, could you tell me what i am doing wrong?
Thanks

A: In your second assignment of updateDefaultBU you are changing the content of the variable completely and not concatenating with the first assignment (as I assume you want to do).
It is possible that you get the error because you run updateQuery.setString("no", "N") but the second assignment has no :no value in it.
Try changing the second line to updateDefaultBU.concat(" <your string> ")
Also have you tried to debug to see exactly where the error is happening?


text:
Q: How can I transform a value after it was extracted? I am using Portia to extract info from a page. However, one of the values extracted is not in a format that I can use.
More specifically, I want to extract a numeric value which uses a dot instead of a comma to denote thousands e.g. "1.000" instead of "1,000".
Is it possible to extract and then transform with Portia? I can set a regex to extract numbers but is it possible to replace them too?
What I'm doing now is that I export the data to csv and then use sed to replace the numbers in question.
Thanks

A: Check: How do I use Python to convert a string to a number if it has commas in it as thousands separators?
import locale
locale.setlocale( locale.LC_ALL, 'de_DE.UTF-8' )
locale.atoi('1.000')
# 1000

Basically it's string to number with the correct format mask


text:
Q: Java: Drawing with if-else statements I am having trouble getting if-else statement to draw correct colors for my program. I'm under the impression that the if-statements are not organized correctly with the else statement and the "setColor," I am stumped on how to make the black render as yellow. The best way to describe it is to show it.
I'd appreciate any help!
My output (wrong):

Goal output (right):

My code:
import java.awt.*;

public class IfGridEx3 {
    public static void main(String[] args) {
        DrawingPanel panel = new DrawingPanel(400, 400);
        panel.setBackground(Color.blue);
        Graphics g = panel.getGraphics();

        int sizeX = 40;
        int sizeY = 40;
        for (int x = 0; x < 10; x++) {
            for (int y = 0; y < 10; y++) {
                int cornerX = x*sizeX;
                int cornerY = y*sizeY;

                if (x > 1)
                    if (x < 8)
                        if (y > 1)
                            if (y < 8)
                                g.setColor(Color.green);
                            else
                                g.setColor(Color.yellow);

                g.fillRect(cornerX+1, cornerY+1, sizeX-2, sizeY-2);
                g.setColor(Color.black);
                g.drawString("x="+x, cornerX+10, cornerY+15);  // text is positioned at its baseline
                g.drawString("y="+y, cornerX+10, cornerY+33);  // offsets from the corner do centering
            }
        }
    }

}

A: Your else is based only on result of last if, so g.setColor(Color.yellow); will be invoked only if all conditions
            if (x > 1)
                if (x < 8)
                    if (y > 1)

will be true (otherwise condition in last if will not even be tested),
and result evaluation of condition from last if
                        if (y < 8)

will be false. It means, that else will not be invoked if previous 3 conditions are false, which is why you are seeing some areas unset.
To solve this problem you can create single condition for center area
if (x > 1 && x < 8 && y > 1 && y < 8){
    g.setColor(Color.green);
} else {
    g.setColor(Color.yellow);
}

A: Try this :
 if((x>=2 && x<=7) && (y>=2 &&y<=7))
//fill color green
else
//fill yello color


text:
Q: How to keep your physical server environment manageable Anybody who's ever worked with servers and even a small LAN environment knows (or should know) how messy things can get. Cables, routers, hubs, servers and so on.
Everything crawling where it shouldn't go, and good luck finding that one cable that's preventing John's PC to connect to the rest of the Intranet when John works on the first floor and the servers where you need to check it are on the third floor.
So, for everyone here who works in environments like this: how do you keep it clean? A clean environment means at least some improvement in efficiency, so what are you tricks? What are the absolute do's and don'ts and why?
Or do you enjoy some Spaghetti?

A: Hmmm, that's disgusting - but thanks for posting a picture worth-a-thousand-words. 8)

*

*Set a standard and stick to it, for example...

*

*In every rack, the bottom X RUs are reserved for switches

*Public interfaces will be green

*Private interfaces will be red

*Use racks that have facilities for cable management on the doors.

*Use the same model of rack globally

*Label all cables (at both ends) with a barcode (or similar) writer

*Label the Racks as per the grid that they are if you look at them plane-view

*Inventory everything

*Don't let staff walk in and walk out of the server room

*

*Only operations team should be allowed to touch the servers

*Only the networks team should be allowed to touch the cables

A: Label both ends of every cable.
The cable should clearly show where each end is going, and you should be as specific as possible.
For example, a label in our data center looks like this:
<-- ATL-SW-1 PORT 23
SERVER-01 NIC 2 -->

The same label is put on both ends of the cable so no matter which end you are looking at you know exactly where the end point is.
With this simple process even a mess of spaghetti cables can easily be handled. The biggest problem with spaghetti cables is when you are forced to hand trace a cable to its end point.
However I do recommend cable management to avoid the physical mess :-)

A: Use velcro tie wraps when running horizontal cable.

A: *

*Set a simple coloring standard for cables, and stick by it, for example:

*

*Blue for intranet

*Green for public/DMZ

*Red for VOIP telephony (if applicable)

*Gray for bridging and servers

*Label both ends of cables with a good description of where they're going (server/socket).

*Use a label printer, and use quality nylon-based stickers, plain paper stickers wear out and fall off really fast.

*Don't use longer-than-required cables. If it's a short reach, use a short cable. Saves gobs of space and mess.

*Try not to have cables hanging in front of the panels/switches. Route them from the panel, through the back of the rack, and back in front to the switch/server.

*Immediately replace cables with broken lock-pins on the end. (this is more of a general advice)

*Install rack cable management accessories like hair-comb-like attachments to the back of the network jacks panel and door/sidewall mounted clips and straps.

*When having numerous cables going to/from the same location (like multiple blade server cables going to a switch) - enclose them in a cable organizer. This can drastically reduce the amount of cabling you have to untangle when looking/moving something.

*Same goes for cabling that goes outside the server room. Whether it goes above or below the (acoustic) ceiling - try to have a snake-tray or similar cable grouping system, don't just let the cables lie "naked".

A: It's an obvious one, but use rackmount servers and KVM switches.
Set things up so that your cable runs can be as short as possible.  If you can get a space of 1U left between each patch panel in the rack, that's a great place to put switches and it means that you can use quarter meter lengths with no trailing whatsoever, and no need for cable management either (you don't need to manage what isn't there).
Separate things out into different racks if possible.  If not, at least arrange them so that, for example, all switches for the first floor are physically located together.
FULLY DECOMMISSION OLD GEAR!  If a switch dies, don't leave it in the rack and put a new one in wherever you have space - haul it out of there.

A: Label the front AND the back of your machines

A: *

*Reduce the number of physical servers by using virtualization.

*Use meaningful server names that would allow you to easily locate the server. e.g., elements in the periodic table (that's an idea from Stackoverflow)

*Use a cable tie to group similar cables.

A: Blades help.

A: Nearly everything you can do has been mentioned already. It all comes down to being methodical and strict. Having to hand trace a cable at 2 am, armed only with a tile lifter and a torch is no fun at all.
One addition is to make sure that every cabinet door can be closed, i.e. no bodge jobs connecting device together that bypass the structured cabling. If one is allowed, then others will follow and ultimately you end up with a mess. Before any changes are made, make sure that you can achieve it with structured cabling. If not, you need to re-plan it properly, free up dead ports etc. If not you'll end up with a 20m cable chucked over the top of a row of cabs that is doing something important.

A: I primarily work in a startup environment. My current organization is a startup, and a previous business model was consulting startups. The biggest key to organization was outsourcing data center operations to dedicated hosting companies like Rackspace and Servepath, and also using cloud and virtualization technologies such as Amazon EC2 and KVM.
I haven't had to trace a cable in almost a year, and finding systems is a matter of looking at the master server that tracks all the nodes that check in for their configuration.
It's much nicer than a previous position where our servers were at a hosting center, but we had to physically manage everything (which resulting in cable messes, despite best efforts and proper labelling).


text:
Q: How do I share a USB DVD Writer on a Linux host machine with a virtualised windows guest using Virt-manager? I am using openSUSE Tumbleweed, and the windows guest is a Windows 10 instance.
I tried to share the drive by passing through the USB host device but I could not find it on Windows. I looked around and found guides for VirtualBox but performance is important in my case so near-native virtualisation is my only option.
My system (laptop) has an i7 6820HQ and IOMMU so passthrough should not be problematic.


text:
Q: Proving a version of the maximum principle
Suppose $U=\Omega \times (0,\infty),~\Omega$ is a bounded domain in $\mathbb{R}^n$ and $u \in C^{2,1}(\overline{U})$ satisfies
  $$u_t \leq \Delta u+cu~~\text{in}~U,$$
  where $c \leq 0$ is a constant.

Question: If $u \geq 0,$ show that the weak maximum principle holds for $u.$
I'm still stuck in proving this. Any help is much appreciated.

A: If you examine Evans' proofs in this section, then you'll notice that it's not particularly important that the coefficients $a^{ij}$, $b^i$, and $c$ are continuous. What is important to his proofs is that the coefficients are bounded in $U_T$, $T<\infty$. Evans obtains this simply from continuity of the coefficients and compactness of $U_T$, but if you assume the coefficients are a priori bounded then this isn't necessary. You should be able to derive your desired result by noting this and proving the weak maximum principle (via exactly Evans' proof) for all $U_T$, $0<T<\infty$.
As for $c\leq 0$ vs $c\geq 0$, note the sign on the second-order coefficients of $L$, versus the coefficients of the Laplacian. Everything should work fine after properly accounting for the change in sign between the hypotheses of each theorem.
Edit: In fact, as Jeff has kindly pointed out to me, the equation in question is constant-coefficient, so Evans' theorem can almost be used without modification. The main modification needed is to deal with the infinite time interval; again, this can be done essentially by proving the weak maximum principle on every $U_T$ for $T$ finite, then letting $T\to\infty$.


text:
Q: How to I get Json.NET to throw an exception when JSON doesn't contain a property How to I get Json.NET to throw an exception when JSON doesn't contain a property, which is a member of the object (during deserialization)?
ie, i'm looking for the inverse functionality to JsonSerializerSettings.MissingMemberHandling.
Edit / Solution from DBC:
use Json.NET require all properties on deserialization
Json.NET require all properties on deserialization


text:
Q: OData v4 Web API support for Composite Keys I am building an OData Web Service using WebAPI and OData v4.
I was able to get the service to support composite keys through overriding the SelectAction method of the EntityRoutingConvention. However, in previous version of OData this was not needed. I personally believe it's pretty messy and I feel like I am reinventing the wheel.
Is there any other way?

A: Use attribute routing.
An example:
Model:
public class Product
{
    [Key]
    public int ID { get; set; }

    [Key]
    public string Name { get; set; }
}

Controller method for identifying the entity using composite keys:
[EnableQuery]
[ODataRoute("Products(ID={key1},Name={key2})")]
public IHttpActionResult Get([FromODataUri] int key1, [FromODataUri] string key2)
{
    // You business logic for retrieving the entity from your storage using the two keys and return
}

Request sample:
GET http://host/service/Products(ID=1,Name='Car')

No need to override routing convention.

A: You can do this with the prefix "key" out of the box:
[EnableQuery]
public IHttpActionResult Get([FromODataUri] int keyID, [FromODataUri] string keyName)
{
    // You business logic for retrieving the entity from your storage using the two keys and return
}

I just checked with Microsoft.AspNet.OData v7.0.1
You can find it their source https://github.com/OData/WebApi/blob/master/samples/AspNetCoreODataSample.Web/Controllers/PeopleController.cs


text:
Q: Does python class special method require special name? class Dog:
    def __init__(self,name):
        self.char=name
    def __str__(self):
        return self.char

>>> spok=Dog("dsakj")
>>> print(spok)
dsakj

class Dog:
    def __init__(self,name):
        self.name=name
    def __str__(self):
        return self.name

>>> spok=Dog("akjds")
>>> print(spok)
akjds

class Dog:
    def __init__(self,name):
        self.name=name
    def __info__(self):
        return self.name

>>> spok=Dog("dnask")
>>> print(spok)
<__main__.Dog object at 0x0000000002FF5320>

The only thing changed in the third is the name then it didn't work out.

A: When you print an object, the 'toString' method (__str__) gets called implicitly. Without that method (which you are missing in your third example), Python does not know how to convert an arbitrary object to a string.

A: Special methods are called by functions. If you want to write your own function info you could make like this:
def info(obj):
   if hasattr(obj,'__info__'):
       return obj.__info__()
   raise Exception('Not informable object')

class Dog:
   def __init__(self, name):
      self.name = name

   def __info__(self):
      print 'Informational note about class named : %s'%self.name

sparky = Dog('sparky')
info(sparky)

'Informational note about class named : sparky'

edit for informational sake
The open nature of python allows you to do things like that even when you have coding conventions like this one PEP 0008, Thanks @Daniel for the advice


text:
Q: Laravel using Foundation 5 with Elixir, sass not compiling so page does not format First time doing this. I am not able to see why I cannot correctly compile my sass Foundation files. My gulp commands executes with no errors, but my page does not format. If I replace my compiled css link in the <head> with links to the Foundation css files then it formats OK.
My gulpfile.js looks like this:
var elixir = require('laravel-elixir');

elixir.config.css.autoprefix.options.browsers = ['last 4 versions'];

elixir(function(mix) {

    // Compile CSS
    mix
        /* Copy the Foundation JS folder from bower_components to a js/foundation folder */
        .copy(
            'vendor/bower_components/foundation/scss', 'resources/assets/sass'
        )
        /* Copy the Foundation JS folder from bower_components to a js/foundation folder */
        .copy(
            'vendor/bower_components/foundation/js', 'resources/assets/js/foundation'
        )
        /* Build css files here */
        .sass(
            'app.scss', // Source files
            'public/css/app.css' // Destination folder
        )
        .scripts(
            'foundation/vendor/modernizr.js', 'public/js/modernizr.js', 'resources/assets/js'
        )
        .scripts([
                'foundation/vendor/fastclick.js',
                'foundation/vendor/jquery.js',
                'foundation/foundation.js',
                'app.js'
            ], // Source files
            'public/js/app.js' // Destination file
        )
        .version([
            'public/css/app.css',
            'public/js/modernizr.js',
            'public/js/app.js'
        ]);

});

My header file contains these links (which resolve OK with the compiled files in inspect).
<link href="{{ elixir('css/app.css') }}" rel="stylesheet" />
<script src="{{ elixir('js/modernizr.js') }}"></script>
<script src="{{ elixir('js/app.js') }}"></script>

I have copied into a public/temp folder the Foundation files so I can link in <head> to test. If I replace the elixir calls to the hard links to foundation.css the formatting on the page works.
<link href="temp/css/normalize.css" rel="stylesheet" />
<link href="temp/css/foundation.css" rel="stylesheet" />
<script src="temp/js/vendor/jquery.js"></script>
<script src="temp/js/vendor/fastclick.js"></script>
<script src="temp/js/foundation.js"></script>

My footer contains the Foundation initialization:
<script>
    $(document).foundation();
</script>

My app.scss looks like this:
/* Import Normalize.scss */
@import 'normalize';

/* Import the Foundation settings.scss page */
@import 'settings';

/* Import the Entire Foundation framework */
@import 'foundation';

I can confirm the files needed for the sass compilation are present and in the correct folders.
resources/
   /assets
      /css
         /foundation
            /components
            _functions.scss
         _settings.scss
         app.scss
         foudnation.scss
         normalize.scss

The $gulp # command runs OK giving no errors.
$ gulp #
[14:53:11] Using gulpfile f:\Projects\flyer\gulpfile.js
[14:53:11] Starting 'default'...
[14:53:11] Starting 'copy'...

Fetching Copy Source Files...
   - vendor/bower_components/foundation/scss/**/*

Saving To...
   - resources/assets/sass

[14:53:11] Finished 'default' after 58 ms
[14:53:11] Finished 'copy' after 126 ms
[14:53:11] Starting 'copy'...

Fetching Copy Source Files...
   - vendor/bower_components/foundation/js/**/*

Saving To...
   - resources/assets/js/foundation

[14:53:11] Finished 'copy' after 96 ms
[14:53:11] Starting 'sass'...

Fetching Sass Source Files...
   - resources\assets\sass\app.scss

Saving To...
   - public/css/app.css

[14:53:12] gulp-notify: [Laravel Elixir] Sass Compiled!
[14:53:12] Finished 'sass' after 691 ms
[14:53:12] Starting 'scripts'...

Fetching Scripts Source Files...
   - resources\assets\js\foundation\vendor\modernizr.js

Saving To...
   - public/js/modernizr.js

[14:53:13] gulp-notify: [Laravel Elixir] Scripts Merged!
[14:53:13] Finished 'scripts' after 708 ms
[14:53:13] Starting 'scripts'...

Fetching Scripts Source Files...
   - resources\assets\js\foundation\vendor\fastclick.js
   - resources\assets\js\foundation\vendor\jquery.js
   - resources\assets\js\foundation\foundation.js
   - resources\assets\js\app.js

Saving To...
   - public/js/app.js

[14:53:13] gulp-notify: [Laravel Elixir] Scripts Merged!
[14:53:13] Finished 'scripts' after 83 ms
[14:53:13] Starting 'version'...

Fetching Version Source Files...
   - public\css\app.css
   - public\js\modernizr.js
   - public\js\app.js

Saving To...
   - public\build

[14:53:13] Finished 'version' after 94 ms

The output file is in:
public/
   /build
      /css
         app.css.map
         app-122456abc.css

And It appears in inspect OK, and it is not empty
<link href="/build/css/app-122456abc.css" rel="stylesheet" />

What am I missing? Thanks!

A: Well, insanity has set in... for some reason my scss files were corrupt. Yes, it took me all this time to figure it out... I downloaded the master branch of Foundation 5, manually copied the files across to the Laravel Project and it all worked. Not sure why the bower download is giving me bad files. All the above works fine if you are using F5 on Laravel, so hope this helps someone else miss out on insanity!


text:
Q: Rearrange list of tuples by another sorted enumerated list I have one list of tuples:
a = [(10, 11), (5, 5), (2, 3), (6, 7), (8, 3), (9, 2)] and one simple list with values b = [10, 9, 10, 2, 8, 3]. Then I enumerate the second list and sort it for some purposes.
b_enumerated = list(enumerate(b))
# [(0, 10), (1, 9), (2, 10), (3, 2), (4, 8), (5, 3)]
b_sorted = sorted(b_enumerated, key=lambda x: x[1], reverse=True)
# [(0, 10), (2, 10), (1, 9), (4, 8), (5, 3), (3, 2)]

Now I want to rearrange my first list according to the second sorted list, so I expect to get [(10, 11), (2, 3), (5, 5), (8, 3), (9, 2), (6, 7)] (tuples of the original list in index order of the ordered list: 0, 2, 1, 4, 5, 3), where, for example, my enumerated first list is [(0, (10, 11)), (1, (5, 5)), (2, (2, 3)), (3, (6, 7)), (4, (8, 3)), (5, (9, 2))].
How can I achieve the expected result? Maybe I need to use some sort of indexing, because sorting zipped lists didn't help.
Thanks.

A: If the purpose is to sort a with the reversed order of b, you don't need to enumerate b and sort the enumerated sequence to build an intermediary list of b_sorted in the first place.
Instead, you can zip b with a for sorting and then output only the second item in the resulting sequence of tuples:
[t for _, t in sorted(zip(b, a), reverse=True)]

This returns:
[(10, 11), (2, 3), (5, 5), (8, 3), (9, 2), (6, 7)]

A: Quick Answer
a_sorted =  [a[i[0]] for i in b_sorted]

Brief Explanation
You're basically trying to say 'send a[0] to a_sorted[0], send a[1] to a_sorted[2] ... send a[i] to a_sorted[b_sorted[i][0]]'.
This can be done with the code
a_sorted =  [a[b_sorted[i][0]] for i in range(len(b_sorted))]

which works fine but can be shortened and arguably neatened by instead iterating over b_sorted.
a_sorted =  [a[i[0]] for i in b_sorted]


text:
Q: asymptotics of sum of $\ln$ Let $(z_n)_{n\in\mathbb N}$ and $(u_n)_{n\in\mathbb N}$ be sequences of complex numbers such that: $\lim_{n\to+\infty}|z_n|=+\infty$, $\lim_{n\to+\infty}|u_n|=+\infty$, $|u_n|=o(|z_n|)$ and $(|u_n|)_{n\in\mathbb N}$ is non-decreasing. I want to prove that
$$\sum_{k=0}^{n-1}\ln|z_n-u_k|\underset{n\to+\infty}{\sim} n\ln|z_n|.$$
I did not manage to prove that. Any proof or hint will be welcome. Thanks in advance.

A: Since $|u_n|=o(|z_n|)$ for $n\to \infty$ and since $|u_k|$ is non-decreasing, we have for sufficiently large $n$ and $k\le n$
$$\left|\frac{u_k}{z_n}\right|\le 1/2 \tag1$$
With $n\ge k$ chosen so that $(1)$ holds, application of the triangle inequality reveals
$$\frac12\le 1-\left|\frac{u_k}{z_n}\right| \le \left|1-\frac{u_k}{z_n}\right|\le 1+\left|\frac{u_k}{z_n}\right|\le \frac32\tag 2$$

Now, write the summand, $\log\left(\left|z_n-u_k\right|\right)$, as
$$\log(|z_n-u_k|)=\log(|z_n|)+\log\left(\left|1-\frac{u_k}{z_n}\right|\right)\tag 3$$
we find that
$$\begin{align}
\left|\sum_{k=0}^{n-1}\log\left(\left|z_n-u_k\right|\right)\right|&=n\log(|z_n|)+\sum_{k=0}^{n-1}\left|\log\left(\left|1-\frac{u_k}{z_n}\right|\right)\right|\\\\
&\le n\log(|z_n|)+n\log(2)\\\\
&\sim n\log(|z_n|)
\end{align}$$
as was to be shown!

A: I had misread the question. For any $\epsilon > 0,$ there exists an $N$ such that for all $n\geq N,$ $|u_n/z_n| < \epsilon,$ and the same is true for all $k\leq n,$ by monotonicity. So,
$$\left|\sum_{k=0}^{n-1} \log |z_n - u_k| - n \log|z_n|\right| =
\left|\sum_{k=0}^{n-1}\log(1-\frac{u_k}{z_n}) \right|\leq n\epsilon.$$
Now, divide through by $n\log |z_n|$ to get
$$\frac{\left|\sum_{k=0}^{n-1} \log |z_n - u_k|\right|}{n \log|z_n|}-1\leq \epsilon/|z_n|\leq \epsilon,$$for $n>N,$ and also large enough so that $|z_n|>1.$


text:
Q: Pass Parameter to SimpleHTTPRequestHandler I have to pass a parameter to SimpleHTTPRequestHandler class, so I used class factory to create a custom handler as below.
def RequestHandlerClass(application_path):

  class CustomHandler(SimpleHTTPRequestHandler):

    def __init__(self, request, client_address, server):

        SimpleHTTPRequestHandler.__init__(self, request, client_address, server)
        self._file_1_done = False
        self._file_2_done = False
        self._application_path = application_path

    def _reset_flags(self):

        self._file_1_done = False
        self._file_2_done = False

    def do_GET(self):

        if (self.path == '/file1.qml'):
            self._file_1_done = True

        if (self.path == '/file2.qml'):
            self._file_2_done = True

        filepath = self._application_path + '/' + self.path  # Error here

        try:
            f = open(filepath)
            self.send_response(200)
            self.end_headers()
            self.wfile.write(f.read())
            f.close()
        except IOError as e :
            self.send_error(404,'File Not Found: %s' % self.path)

        if (self._file_1_done and self._file_2_done):
            self._reset_flags()
            self.server.app_download_complete_event.set()
  return CustomHandler

This is my httpserver using the custom handler
class PythonHtpServer(BaseHTTPServer.HTTPServer, threading.Thread):

  def __init__(self, port, serve_path):
    custom_request_handler_class = RequestHandlerClass(serve_path)
    BaseHTTPServer.HTTPServer.__init__(self, ('0.0.0.0', port), custom_request_handler_class)
    threading.Thread.__init__(self)
    self.app_download_complete_event = threading.Event()

  def run(self):
    self.serve_forever()

  def stop(self):
    self.shutdown()

and I start the server with
http_server = PythonHtpServer(port = 8123, serve_path = '/application/main.qml')

The server starts, but I get this error
AttributeError: CustomHandler instance has no attribute '_application_path'

Basically, from the error, the server did start but I don't know why it is not creating the attributes ( or the init is not called ). Please tell me where I am going wrong. Any help would be welcome.

A: IMHO the simplest way is to make _application_path a static attribute of the class. It is declared only at class declaration time, and can be used transparently by instances of the class:
def RequestHandlerClass(application_path):

  class CustomHandler(SimpleHTTPRequestHandler):

    _application_path = application_path   # static attribute

    def __init__(self, request, client_address, server):

        SimpleHTTPRequestHandler.__init__(self, request, client_address, server)
        self._file_1_done = False
        self._file_2_done = False

    def _reset_flags(self):
        ...

That way every new instance of the custom handler class will have access to the application path as self._application_path.

A: Conceptually, you've written something like this (in this e.g., application_path ~= var):
def createClass(var):
    class MyClass:
        def __init__(self):
            self.var = var
        def func(self):
            # use var in some way
            print (self.var)
    # Return class definition
    return MyClass

So the class is written to save the variable var when an instance of MyClass is created. However, by the time the function finishes, the variable is destroyed, and since the class only returns a class definition and not a class instance, an instance of MyClass does not get created by the time the original variable var is destroyed, and thus the variable var never actually gets saved by MyClass.
INSTEAD, you can add var as an argument to the MyClass.__init__ function, and create a generator class to handle creation of MyClass instances, like so:
class MyClass:
    def __init__(self, arg1, arg2, var):
        (self.arg1, self.arg2, self.var) = (arg1, arg2, var)
    # Insert other methods as usual

class MyClassGenerator:
    def __init__(self, var):
        self.var = var
    def make(self, arg1, arg2):
        return MyClass(arg1, arg2, var)

A: The issue here that BaseHttpRequestHandler (and thus its subclass,  SimpleHttpRequestHandler) never makes it out of its __init__ method:

*

*HttpServer calls the SimpleHttpRequestHandler's constructor, which percolates up to the parent class' BaseHttpHandler__init__...

*BaseHttpHandler.__init__ calls handle, which is overridden in...

*BaseHttpRequestHandler.handle, which loops forever (given default options).

Thus, if you want to pass info along to your handler, you have to do it before calling the super's __init__.  I'm probably several years too late to help you, but for future readers, you can just switch the order of your __init__:
class CustomHandler(http.server.SimpleHTTPRequestHandler):

  def __init__(self, *args, **kwargs):
    self._file_1_done = False
    self._file_2_done = False
    self._application_path = application_path
    super().__init__(*args, **kwargs)

I'd probably also use functools.partial instead of wrapping the whole thing in a function:
class CustomHandler(http.server.SimpleHTTPRequestHandler):

  def __init__(self, application_path, *args, **kwargs):
    self._file_1_done = False
    self._file_2_done = False
    self._application_path = application_path
    super().__init__(*args, **kwargs)

...

custom_request_handler_class = functools.partial(CustomHandler, serve_path)
BaseHTTPServer.HTTPServer(('0.0.0.0', port), custom_request_handler_class)

It's probably not a great idea to call super().__init__ at the end of your init in general (since it might mess up initialization), but here it seems like Python is kind of forcing your hand.