text:
Q: Flutter - what is the best way to load 10,000 more of the list of sentences from json file I have a json file which have more than 10,000 list of sentences. I want to know what is the effective way when I click a button, it will redirect to a page and load the list of 10,000 sentences without slowing the performance or crash the memory.
Below are the sample of my code:
class _PageLoadState extends State<PageLoadState> {
  Future<BookModel> getSentencesList() async {
    final response = await rootBundle.loadString('assets/books.json');
    var data = jsonDecode(response);
    return BookModel.fromJson(data);
}

// This is the body section
Expanded(
 child: FutureBuilder<BookModel>(
   future: getSentencesList(),
   builder: (context, snapshot) {
     if (snapshot.hasData) {
       return ListView.builder(
        itemCount: snapshot.data.length,
        itemBuilder: (context, index) => Wrap(
          children: [
            Padding(
              padding: EdgeInsets.all(18.0),
              child: Text(
                snapshot.data[index].sentence.toString(),
            ),
          )
        ],
      )
  );
}

A: You can use lazy loading. Ex. You will just load 100 sentences and when the user scrolls and hits the bottom of the screen you will increment it by +100 and so on.
you can check this:
https://pub.dev/packages/lazy_load_scrollview

A: you can use the pagination for this. that easy to load a huge amount of list.
using pagination you can load the list as per requirements for example: first, you need to load only 100 items of a list, and when the user scrolls over the 100 items you can load more ,100 items.
and for that, you can use:- loadmore package
https://pub.dev/packages/loadmore

you can see the following example as a reference.


text:
Q: recovery data from internal storage I wrote an Android app. Export as signed APK sent via mail installed to device.- not at Market.
At runtime it will save they data to internal storage  with similar code:
FileOutputStream fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();

As I know - correct me if I am wrong - it is saved to /data/data/com.mycompany.myapp/FILENAME
Because it is saved with MODE_PRIVATE I am not sure if any other app from Market or mine can  see it save it. Maybe if I create an app with the same signature?
The phone it is not rooted. I have tryed many backup, copy with app and ADB shell.
App didn't saved my file, adb shell gave permission denied.
Is there any solution with programming or not to get that file?

A: I wrote a little code part to test it:
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {

    private EditText tfData;
    private Button btSave, btLoad;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tfData = (EditText) findViewById(R.id.tfData);
        btSave = (Button) findViewById(R.id.btSave);
        btLoad = (Button) findViewById(R.id.btLoad);

        btSave.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                doSave();
            }
        });

        btLoad.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                doLoad();
            }
        });
        tfData.setText("Some secret data");

        boolean btLoadVisible = false; // TODO change this value for the second build!

        if (!btLoadVisible) {
            btLoad.setVisibility(View.GONE);
        }
        else{
            btSave.setVisibility(View.INVISIBLE);
        }

    }

    private static final String FILENAME = "private.dat";

    private void doSave() {
        String text = null;
        if (tfData.getText() == null) {
            Toast.makeText(this, "Please enter a string!", Toast.LENGTH_SHORT).show();
            return;
        }
        text = tfData.getText().toString();

        if (text == null || text.length() == 0) {
            Toast.makeText(this, "Please enter a string!!!", Toast.LENGTH_SHORT).show();
        }

        FileOutputStream fos = null;
        try {
            fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
            fos.write(text.getBytes("UTF-8"));
            fos.close();
            fos = null;

            new AlertDialog.Builder(this).setTitle("Saved").setMessage("Your data is saved:\n" + text+"\nChange the build to recover it!")
            .setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int which) {
                    dialog.dismiss();
                }
            }).show();

        } catch (Exception e) {
            Log.e("doSave", "Can't save ...", e);
        } finally {
            if (fos != null) {
                try {
                    fos.close();
                } catch (IOException e) {
                    // I don't care:
                    e.printStackTrace();
                }
            }
        }

    }

    private void doLoad() {
        FileInputStream fis = null;
        try {
            fis = openFileInput(FILENAME);
        } catch (FileNotFoundException e) {
            e.printStackTrace();

            new AlertDialog.Builder(this)
                    .setTitle("FileNotFoundException")
                    .setMessage(
                            "The file with data can't be found. Or it wasn't saved at all or you have uninstalled the old app or... who knows.\nI can't recover the data, it is lost permanenty!!!")
                    .setPositiveButton("I am sad", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.dismiss();
                        }
                    }).show();
            return; // I don't like return from catch...
        }

        if (fis != null) {

            try {
                int size = fis.available();// not the best, but now I hope is possible to read 10-30 bytes without blocking
                byte[] buff = new byte[size];
                int readCount = fis.read(buff);
                if (readCount != size) {
                    Toast.makeText(this, "Dammit can't read : " + size + " bytes, only " + readCount + ". Restart app, than phone? ", Toast.LENGTH_SHORT)
                            .show();
                }
                String text = new String(buff, "UTF-8");
                tfData.setText(text);

                new AlertDialog.Builder(this).setTitle("Loaded").setMessage("Your data is recovered:\n" + text)
                        .setPositiveButton("I am happy", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        }).show();

            } catch (IOException e) {

                Log.e("doLoad", "Can't load ...", e);

                new AlertDialog.Builder(this).setTitle("IOException").setMessage("There is some error while reading the data:\n" + e.getMessage())
                        .setPositiveButton("I am sad", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int which) {
                                dialog.dismiss();
                            }
                        }).show();

            }
        }
    }

}

Clean, build, export as signed apk: eg InternalMemoryReader_save.apk

save the keystore!!!

*

*change the boolean btLoadVisible = false to boolean btLoadVisible = true .

*export apk WITH THE SAME KEYSTORE!  but diff name, eg InternalMemoryReader_load.apk  - but can be a _datasaver _factoryservice whatever. This usually it is not given to the user.

Install the first apk and do a save.

*

*do not uninstall the apk

*lets propose you are blaming of data loss, can't open it ...and once  in a mail you will receive the _load.apk from the support service. Install it without remove the old apk. It has the same package name, same signature, just diff file name.
I was able to load the data. It can be send via mail or processed there, the hardest part is done.
Conclusion:
If you are the app developer and if you have the keystore and able to sign a modified apk than you will have access to that internal, private file.
I hope I am helping somebody else to to recover his app data and not waste so much time.
If you know better solution, please let me know!

redpajama_set_name: RedPajamaStackExchange


text:
Q: "Digital computer" in the 1940s I was watching the DVD movie Imitation Game, starring Benedict Cumberbatch as Alan Turing, the British mathematician who helped crack the Nazi's enigma code in WWII. In one key scene,  Turing uses the expression digital computer to explain to Joan Clarke what 'Christopher', the machine he is making, does.  He describes it as

"... an electrical brain, a digital computer."

I think the year depicted in the movie must have been 1940. The name of Turing's creation was never called 'Christopher' that is pure dramatic/artistic license, its real name was bombe and it was a monumental deciphering machine.
Basically, I have three questions:

*

*Was Alan Turing aware of the term digital computer? Did he actually ever use it himself?

*Could one describe the British Bombe as being a digital computer? Wikipedia calls it an "electromechanical device"

*When was the term digital computer actually coined?

YouTube clip: Alan Turing explains 'Christopher'

BOUNTY INFO
I should have left a message with the bounty, too late now.
Q1. I am asking whether Turing was familiar with the term "digital computer" in the 1940s but especially before the end of World War II. Biscuit Boy's answer refers to Turing's paper, Computing Machinery and Intelligence, which is dated 1950.
Q2. Because I know nothing about the history of computers nor how they work, I am hoping the community of Stack Exchange can provide a clear-cut answer.
Q3. According to this source, the term digital computer was devised by  George Stibitz in 1942, which makes Cumberbatch's line a lexical anachronism.
Q4 Bounty bonus. The name of the first electronic digital computer.
Many cite ENIAC as being the holder of this title, but there are sources which claim the Universal Turing Machine "is the mathematical tool equivalent to a digital computer", and elsewhere:  "The first fully functioning electronic digital computer was Colossus (1943)".

A: I was going through some online articles and I'd like to thank @Josh61 for the right references. I found this detailed write-up on Word Origins from OED by Richard Holden. (I think I now know the reason why top EL&U users strictly stick to OED definitions)
The article: http://public.oed.com/aspects-of-english/word-stories/digital/

What distinguishes digital from many other terms associated with high technology is that it's not a new word. In the newly revised OED entry, the earliest evidence—in the sense 'designating a whole number less than ten'—dates from the fifteenth century. OED's original entry, published in 1897, does not record this sense. Instead, it covers senses corresponding to another sense of digit, such as: 'of or pertaining to a finger, or to the fingers or digits'—evidence for which goes back to the seventeenth century. But for most of its history, digital was a relatively unimportant term: it wasn't until the early to mid-twentieth century that the word became more significant and widespread.
In the late 1930s and early 1940s, the work of mathematicians and engineers led to the development of a new type of computing machine. As opposed to earlier analogue devices, which used a continuous quantity (such as voltage) to compute the desired quantity by analogy, these new machines operated upon data that was represented as a series of discrete digits. For example, in such a system the letter A might be represented as the binary sequence '01000001' (as it is in the ASCII encoding scheme).
Being composed of such sequences of digits, such data (and so any machine making use of it) was hence said to be "digital". Digital computers were generally considered more adaptable and powerful than their analogue counterparts, and digital computing became dominant: the computer you are reading this article on will certainly be a digital one, as will probably any other computer you have ever used. The sense of digital relating to this was covered in OED2 (1989) by the definition, 'of, pertaining to, or using digits; spec. applied to a computer which operates on data in the form of digital or similar discrete elements.'

Now, to answer your questions...
1. Was Alan Turing aware of the term digital computer? Did he actually ever use it himself?
Yes. Alan Turing developed the Turing test, and uses the term often in his seminal paper "Computer Machinery and Intelligence".

"Are there imaginable digital computers which would do well in the imitation game?

[Wikipedia]

2. Could one describe the British Bombe as being a digital computer? Wikipedia calls it an "electromechanical device"
I would say No. At least not a "digital computer". It's called electromechanical because it operated on electricity and had rotors, wires and plugboards that carried out the deciphering work. Importantly it did not operate on 0s and 1s, which is the definition of a "digital computer".

(noun). an electronic computer in which the input is discrete rather than continuous, consisting of combinations of numbers, letters, and other characters written in an appropriate programming language and represented internally in binary notation

[Collins Dictionary]
The ENIAC is widely believed to be the first ever "digital" computing device.

It was Turing-complete, digital, and could solve "a large class of numerical problems" through reprogramming

[Wikipedia]
You could probably say it was an "analog computer"!

(noun) a mechanical, electrical, or electronic computer that performs arithmetical operations by using some variable physical quantity, such as mechanical movement or voltage, to represent numbers

[Collins Dictionary]

3. When was the term digital computer actually coined?
The exact time and person who coined it remains a mystery. Etymonline suggests that both "digital" and "computer" originated in the middle of 16th century but the combined term, i.e., "a digital computer" might have its origins at the beginning of the 20th century, and a spike in usage by late 1940s, according to Ngrams.

A: In Computable Numbers (1936), Turing doesn't use the word "digital" at all.  He refers to "computing machines" and in particular the "universal computing machine", which is what we now call a Turing machine.  In modern terms, we would not usually refer to something as a computer unless it represented a concrete implementation of a Turing machine (except that strictly speaking, a Turing machine has infinite memory "tape").  The Turing machine is an abstract concept, and physical implementations of it don't necessarily have to be "digital" in any particular sense, but that's a complicated subject, and anyway all modern computers are digital.
Obviously, Turing didn't say much publicly during the war, so we don't know if he was using the term "digital computer" or not.  In 1945 he moved to the National Physical Laboratory to develop the Automatic Computing Engine (ACE), which was his choice of name in homage to Babbage's machines[1].  In [Copeland BJ ed., The Essential Turing Oxford 2004], a 1947 lecture on ACE is reprinted without further bibliographic detail; Turing describes ACE as an "electronic digital computing machine" and goes on to emphasise the significance of the word "digital".  He also refers to his earlier work on computability, saying "I was investigating what might now be described as... digital computing machines" (my emphasis).  This suggests to me that he wouldn't have used the term in 1936, but he was by 1947.  His discussion of the advantages of digital computing is essentially to do with the practical implementation of what was a purely theoretical thing in Computable Numbers, so a reasonable guess would be that he started using the word when he became involved in actually building machines; so, certainly by 1946 and probably in conversations related to the Mark 1 (Colossus) in 1943.  In any case, I don't think the word would have been unfamiliar to him at any time during the war; there's a good chance he would have been specifically aware of Atanasoff's work, for example.
The thing that struck me more about that Imitation Game line was not the word "digital" but the word "brain".  Turing thought a great deal about the essential nature of thinking, and I don't know whether he'd have casually conflated "brain" and "mind" in that way.  It'd be an interesting comment, if he'd actually said it.
The first Turing-complete computer to be designed was Babbage's Analytical Engine in 1842, and the first to actually be built was ENIAC in 1946.  The first machine with a von Neumann architecture-- very close to what we think of as a computer now-- was EDVAC in 1949. ACE wasn't completed until 1950.
The problem with counting "Colossus" as a computer is that it wasn't Turing-complete, or particularly general-purpose, so it's then hard to justify withholding the title from much older machines, especially the German Zuse Z3 from 1941.  In fact the Z3 has been shown to be technically Turing-complete, but more as a theoretical stunt than in any practical sense.  19th-century mechanical calculators could do calculations, for example, and Jacquard looms were programmable.
The Polish bombes, which were later adopted and improved by Bletchley Park, were not computers by most definitions, either now or then.  They weren't programmable, and didn't really perform any calculation except that they'd stop when they hit a certain combination of electrical settings; if we consider that computation, then many other machines, such as door locks, would qualify.

A: It boils down to what you mean by "digital" (and, to a degree, "analog").  The best-known dichotomy in the computer universe is between "digital" and "analog".  An "analog computer" is one which represents values in a computation as non-discrete voltage or current levels within an electronic circuit.  A "digital computer", on the other hand, represents values as discrete voltage or current levels (or, for that matter, something such as the position of a "stepping relay" in a mechanical device).
Of course, one can do all sorts of dancing around both terms.  One could argue, eg, that since the Bombe contained within it a simulation of (multiple) Enigma devices, it was an "analog" computer.  However, one could then make the same claim of an Macintosh that is programmed to simulate Enigma.
What most people don't understand is the meaning of "digital".  In particular it does not mean "binary" -- there were many computers built before "binary" became the default mode of operation.  Most (especially the the mechanical ones) were decimal, but a number used other bases.  "Centesimal" (base 100) was fairly popular, and a few others used ordinary Roman characters (generally with the "smarts" to do decimal arithmetic on numeric characters).  "Bi-quinary" (a rather confusing sort of two-part decimal, probably based on the abacus) was quite popular.
Even in purportedly "binary" computers, sometimes multiple bits of data are represented in a single electrical signal by using multiple discrete voltage levels.  (I don't know about now, but ca 1980 a large proportion of memory chips used this technique.)
So the main difference between "digital" and "analog" is that "digital" uses discrete voltage/current levels to represent values (and hence, if arithmetic is to be performed, the arithmetic is performed in discrete units called "digits", though those "digits" many be 1 bit, a decimal value, a centesimal value, or something else).  Analog, on the other hand, performs simple addition by using a resistor network or some such to "sum" voltages or currents -- electrically adding the values together the same way an audio mixer "adds" two microphone signals together.
And, while it's not entirely clear without further study, it appears that the Bombe did actual digital arithmetic of a sort, as the encoding algorithm apparently (based on my vague understanding) involved "rotating" character values by some amount (incrementing an "A" to a "D", say) to encrypt them.  This would have required a crude digital adder.
The harder question is whether the Bombe classifies as a "computer", in any modern sense.  This is tricky, since we now consider a "computer" to include writable program store, but that was not the case of many early devices which were referred to as "computers".

A: The ENIAC was the first major electronic general purpose computer of major significance, using valves as its computation and storage devices.  That made it orders of magnitude faster than its electromechanical predecessors.  It was completed in 1946.
An seminal earlier electromechanical computer was the Harvard Mark I, completed in 1944 but started quite earlier.
The British Colossus computers were used as early as 1944.  While not general purpose (programming was through plugs and switches), they also were electronic and digital.
With regard to electromechanical computers, Zuse's Z1 and its successors may be the earliest serious contenders.  Most certainly Zuse was the first to fully employ binary numbers (rather than decimal numbers, typically encoded in BCD or excess-3 BCD).
It took a long time before binary numbers were used to the exclusion of everything else: even Knuth's seminal "The Art of Computer Programming" series first published in 1968 specifies a hypothetical computer architecture that may be either binary or decimal.
So all of "digital", "electronic", "binary", "general-purpose", "programmable in memory" have had different origin stories and dates.

A: Two rather different projects that Alan Turing worked on appear to be involved.

*

*Turing was a key person in breaking the German ciphers during WW2. (Many other people/groups were involved also.) To that end, many devices were constructed that mimicked the German ciphering machines, using parts of what the British were able to scrap from German submarines, etc. After many tedious and failed attempts, and sometimes only intermittently, the British were thus able to decipher the communication of the German naval forces. This is unrelated to digital computer.

*Turing defined a computation model, nowadays referred to as the Universal Turing machine. Building upon his observations on how humans compute by hand, he lay down principles of step-by-step computation, including key concepts such as memory (the tape of the machine) and instruction set. Again, many other people were involved (von Neumann, to name just one). Turing's ideas on computation are given is his seminal 1936 paper On Computable Numbers, with an Application to the Entscheidungsproblem.
The universal machine, mentioned in the clip, is defined in the above paper, and served as a model for computers as known nowadays. It is not a gross exaggeration to say that Turing invented the computer. Notably, Turing realized that the operational instructions of a machine, can be read and processed by another machine; thus, a single machine can be programmed to process infinitely many tasks rather than just one.
I do not know whether the collocation "digital computer" would have been meaningful to Turing. He uses the term machine for the concept that later yielded the computer of today. I think Turing viewed computation as inherently digital; so he might have viewed the qualification digital as somewhat redundant. As such, it is just a buzzword in the movie. (That said, there is no reason to think the creators of the movie did not know exactly what they were doing; they certainly did not want to explain the Turing machine in Turing's own terms! And it appeared not much later; John von Neumann certainly used it by 1945.)
It is to be noted that computation has a distinguished history in the British Isles; one of the most notable predecessors is the Analytical Engine, of Charles Babbage and Ada Lovelace (mechanical, of course).
In that light, a quirky point about the Turing machine is that it is in fact not a machine, but rather an idea of it; it is a design, a model.

A: Digital computation dates back much further than you think, to the origin of numerals them selves; It is of interest that essentially, digital computation can be assimilated to two counting systems; that of base ten or decimal, in which we can do math whilst counting upon our fingers, using both hands. Secondly, to a base twelve system, the dozen; a method in which one can use the thumb to count upon the phalanges of one hand, surprisingly somewhat more efficient for keeping an account.
It is note worthy to remark upon the use of the fingers, and hand gestures, when measuring the degree of separation between the asters in the night sky. This is quite naturally considered as the origin of the digital counting machine. However history is so often distorted by those who decimate; That origins become aberrant, such are the dipping waters of time ...
Let us not forget that Alan Turing was solving Cypher/Cipher and his machine was replacing his fingers and phalanges with cogs cams and wheels.
I do not profess any definitive answer to your question; I do however hope that you might find food for thought, upon your quest for knowledge itself; The origin of digital computation.


text:
Q: RabbitMQ Can't receive message In the example i am using the same class than this tutorial :
https://www.rabbitmq.com/tutorials/tutorial-one-java.html
I have 2 classes :
Send.java
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Send {

    public static final String QUEUE_NAME="hello";

    public static void main(String[] args) {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection=null;
        Channel channel =null;
        try {
            connection = factory.newConnection();
            channel = connection.createChannel();
            channel.queueDeclare(QUEUE_NAME,false,false,false,null);
            String message = "Hello word toto";
            channel.basicPublish("",QUEUE_NAME,null,message.getBytes());
            System.out.println(" [ x ] Sent '"+message+"'");
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }finally {
            try {
                channel.close();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (TimeoutException e) {
                e.printStackTrace();
            }
            try {
                connection.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

and the receiv class :
import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;

public class Receiv{
    private final static String QUEUE_NAME = "hello";

    public static void main(String[] args) {
        Connection connection=null;
        Channel channel=null;
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        try {
            connection = factory.newConnection();
            channel = connection.createChannel();
            channel.queueDeclare(QUEUE_NAME, false, false, false, null);
            System.out.println(" [*] Waiting for messages. To exit press CTRL+C");
            Consumer consumer = new DefaultConsumer(channel){
                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body)
                        throws IOException {
                    String message = new String(body, "UTF-8");
                    System.out.println(" [x] Received '" + message + "'");
                }
            };
            channel.basicConsume(QUEUE_NAME, true, consumer);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }finally {
            try {
                channel.close();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (TimeoutException e) {
                e.printStackTrace();
            }
            try {
                connection.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

And i get i compile like the example but i don't see the received message
Thank you.


text:
Q: Why doesn't a pdf file view in a seperate tab in internet explorer? I have a function which display a pdf file. Im using Internet Explorer and it's upto date. I tried to do it in two computers. In one browser it asks to open through a pdf reader while other one opens a tab and display an empty page. I've tried many codes found in the internet even in stackoverflow. But nothing works as i want. Here i have added my code. Please take a look at it.

Linkbutton click event

protected void pdfViewLOP_Click(object sender, EventArgs e)
{
        Response.Write(string.Format("<script>window.open('{0}','_blank');</script>", "viewPDF.aspx"));
}

code in new page which pdf should be displayed

protected void Page_Load(object sender, EventArgs e)
{
    try
    {
         string name = Session["name"].ToString();
         string FilePath = Server.MapPath("~/filesPDF/" + name);
         WebClient client = new WebClient();
         Byte[] buffer = client.DownloadData(FilePath);
         if (buffer != null)
         {
              Response.Clear();
              Response.ContentType = "application/pdf";
              Response.AddHeader("content-length", buffer.Length.ToString());
              Response.BinaryWrite(buffer);
         }
    }
    catch (Exception ex)
    {
        WebMsgBox.Show(ex.Message);
    }
}

A: It is likely due to settings on the client machine, specifically Adobe preferences.

To change the default PDF open behavior when using a web browser:
Choose Edit—>Preferences
Select the Internet category from the list on the left
To display the PDF in the browser, check "Display in browser"
To open PDFs from the web directly in Acrobat, uncheck "Display in browser:

See this article and this article.
Also note: To display a PDF in your browser, your cache control headers must allow the browser to create a temporary copy of the PDF.  If you are setting cache hints to prevent caching (e.g. if you application contains sensitive pages) you might be better off letting the user download the PDF and view it offline.


text:
Q: Error while trying to test a JS Class using Jest I got a react app in which I have created a utility class called Logger (not a React component). I now want to create some tests for the class using Jest.
Jest is installed, and I created a file called Logger.test.js in the same folder as the class. When running npm test I get this error:

Cannot find module '../Logger' from 'Logger.test.js'

I got no file called jest.config.js anywhere, and there is nothing in the package.json file which is reserved for configuring jest (jest is only mentioned there in the dependencies).
How can I make Jest realize that the class is a module it needs to test?

A: Looks like you're trying to import from the parent folder in the error message: ../Logger . Should be './Logger'


text:
Q: Binomial sum of $n$ terms in closed form Can we calculate the given combinatorial sum in closed form?
$$ \frac{\binom{2}{0}}{1}+\frac{\binom{4}{1}}{2}+\frac{\binom{8}{2}}{3}+\frac{\binom{16}{3}}{4}+\cdots+\frac{\binom{2^n}{n-1}}{n}$$

A: It is doubtful that a closed form exists for this sum.
However, the terms grow very quickly.
For $n$ large the sum is well approximated by its last term,
$$\sum_{k=1}^n \frac{1}{k}{2^k\choose k-1} \sim \frac{1}{n}{2^n\choose n-1}.$$
For $n=13$ the error due to this approximation is one part in a million.
For $n=20$ the error is one part in ten billion.


text:
Q: Nested stream exception I would like to return permutations of strings from all strings. When i use below code, i get java.lang.IllegalStateException: stream has already been operated upon or closed. Could you please tell me what is wrong with this approach ?
public Stream<String> getMyPatterns(
        Stream<String> s1,
        Stream<String> s2,
        Stream<String> s3) {
    List<String> out = new ArrayList<String>();
    s1.collect(Collectors.toList()).forEach(item1 -> {
        s2.collect(Collectors.toList()).forEach(item2 -> {
            s3.collect(Collectors.toList()).forEach(item3 -> {
                out.add(item1 + "." + item2 + "." + item3);
            });
        });
    });
    return out.stream();
}

Sample test
Stream<String> patterns = getMyPatterns(
            Stream.of("a1", "a2"),
            Stream.of("b1", "b2"),
            Stream.of("c1", "c2"));

A: As hinted by others, you are using the Streams s2 and s3 within forEach multiple times.
On the other hand, collecting the result list before returning a Stream, is pointless. You shouldn't use forEach anyway, when there are other, more suitable operations.
You only need to collect the Stream you want to combine with the previous one. This is best accomplished by first solving it for a combination of two Streams:
public Stream<String> getMyPatterns(Stream<String> s1, Stream<String> s2) {
    List<String> s2List = s2.collect(Collectors.toList());
    return s1.flatMap(item1 -> s2List.stream().map(item2 -> item1+'.'+item2));
}

Then, you can easily use this method recursively to solve the task of combining three Streams:
public Stream<String> getMyPatterns(Stream<String> s1,Stream<String> s2,Stream<String> s3) {
    return getMyPatterns(getMyPatterns(s1, s2), s3);
}

This collects only as little as necessary, i.e. it won't collect the first Stream, so its consumption will only start when the returned Stream is consumed.
Stream<String> patterns = getMyPatterns(
    Stream.of("a1", "a2").peek(s -> System.out.println("consuming "+s)),
    Stream.of("b1", "b2"),
    Stream.of("c1", "c2"));

System.out.println("start consuming result Stream");
System.out.println(patterns.collect(Collectors.joining(", ")));

start consuming result Stream
consuming a1
consuming a2
a1.b1.c1, a1.b1.c2, a1.b2.c1, a1.b2.c2, a2.b1.c1, a2.b1.c2, a2.b2.c1, a2.b2.c2

A: Stream can be consumed or operated only once
public static Stream<String> getMyPatterns(
        Stream<String> s1,
        Stream<String> s2,
        Stream<String> s3) {
    List<String> c1 = s1.collect(Collectors.toList());
    List<String> c2 = s2.collect(Collectors.toList());
    List<String> c3 = s3.collect(Collectors.toList());
    BiFunction<String, Stream<String>, Stream<String>> func = (element, partialResultStream) -> partialResultStream.map(x -> x + "." + element);

    return c1.stream().flatMap(x -> func.apply(x, c2.stream()))
            .flatMap(x -> func.apply(x, c3.stream()));
}

Output

[c1.b1.a1, c2.b1.a1, c1.b2.a1, c2.b2.a1, c1.b1.a2, c2.b1.a2, c1.b2.a2, c2.b2.a2]

A: The stream should be consumed or operated one time, but in your solution you consume it multiple times in a loop, instead you can solve your issue like so :
public static Stream<String> getMyPatterns(Stream<String> s1, Stream<String> s2, Stream<String> s3) {

    List<String> out = new ArrayList<String>();
    List<String> c1 = s1.collect(Collectors.toList());
    List<String> c2 = s2.collect(Collectors.toList());
    List<String> c3 = s3.collect(Collectors.toList());

    c1.forEach(item1 -> {
        c2.forEach(item2 -> {
            c3.forEach(item3 -> {
                out.add(item1 + "." + item2 + "." + item3);
            });
        });
    });
    return out.stream();
}

A: You can achieve this using collections, and then transforming it to streams to avoid the reuse of them:
public static void main(String[] args) {

    Stream<String> combine = combine(Arrays.asList("1", "2", "3"), Arrays.asList("4", "5", "6"), Arrays.asList("7", "8", "9"));
    combine.forEach(System.out::println);
}

static Stream<String> combine(List<String> s1, List<String> s2, List<String> s3){
    return s1.stream().flatMap(v1 ->
                s2.stream().flatMap(v2 ->
                        s3.stream().flatMap(v3 -> Stream.of(v1 + "." + v2 + "." + v3 + ";"))
                )
            );
}


text:
Q: When is the work of a C# Parallel.ForEach done? I'm developing an MVC4 website in C#. The following code should fill a ConcurrentBag (DisplayModels) with items before passing everything to the view.
    Parallel.ForEach(model.Products, p =>
    {
        model.DisplayModels.Add(new DisplayBoardModel()
        {
            Market = model.Market,
            Product = p
        });
    });

    return View(model);

I'm finding that on any given execution DisplayModels appears to be filled to a different point. As if the ForEach is completing before each background task has returned.
My understanding of the Parallel.ForEach was that it processed each item in parallel but still blocked the calling thread until all of it's work was done. Is this not correct?
Is there something else I should be doing to stop the action returning before the model is ready? Using a normal foreach worked fine

A: The Parallel.ForEach() works fine, and completes all at once as expected.
But your model.DisplayModels.Add() probably isn't thread-safe. What collection are you using?
You could fix this by a) using a Concurrent collection for DisplayModels or b) turn the ForEach into a PLINQ query. But unless DisplayBoardModel() does some heavy CPU work (and a ctor usually doesn't) there is little point in making this parallel.
So, just use a simple foreach()

Edit, new information

each DisplayBoardModel make a database request

So this is a potential cause. Does every Db operation create its own Connection (Context)? Any chance that an exception is silently ignored?


text:
Q: Database Reconnect After Failure A program that I am currently working on collects and exports data to a SQL database. If there is a failure in the database, I have coded so that it will write the data to a CSV file. It is going to be an application that is always running with a config file that the user can change info (Such as Database connection) while the process is running. I'm having the problem of once I get into a loop of writing to a CSV file, I cannot get back to putting the data in a database until the application is restarted. Here is the relevant code:
class MethodClass
{
    public static void Method()
    {
        while (true)
        {
        ConfigurationManager.RefreshSection("appSettings");

        //Normally Running Code that Generates the Data

        //Tries to write data to database 3 times
        if (dbWrite != 2 && dbWrite != 3)
        {
             dbWrite = 0;
        }
        while (dbWrite < 2)
        {
             try
             {
                  db.TblData.InsertOnSubmit(newrecord);
                  db.SubmitChanges();
                  break;
             }
             catch
             {
                  dbWrite++;
             }
        }
        if (dbWrite == 2)
        {
             try
             {
                  db.TblData.InsertOnSubmit(newrecord);
                  db.SubmitChanges();
             }
             catch (Exception e)
             {
                  dbWrite++;
                  log.Warn("Database Write Error", e);
                  BackupMethod();
             }

        }
        if (dbWrite == 3)
        {
             try
             {
                  db.TblData.InsertOnSubmit(newrecord);
                  db.SubmitChanges();
                  dbWrite = 0;
             }
             catch
             {
                  BackupMethod();
                  log.Info("Still not writing to Database");
             }
        }
    }
}

Class ConfigVariables
{
    public static string SqlUser = ConfigurationManager.appSettings["SqlUser"];
    //Other Config Variables
}

For reference, I just checked and the issue seems to be with getting the info from my Config file while the program is running. If I change other values in the config file, they have no effect until the next time that the program is run. Just so people know, I am editing the App.exe.config file in the Debug/Release folder.
UPDATE: It seems that if I assign the variable after RefreshSection();, that it will work. However, I put the variables in a separate class for a reason. Is there a better way to do this?

A: I was able to fix the issue by creating a method in my ConfigVariables class that refreshed and reassigned the variables in a while loop on a separate thread. This allowed me to keep my variables organized in another class and not change anything with referencing them in the my code. Now I just have to do some performance testing; hopefully constantly doing this won't cause performance issues.


text:
Q: Automatically add spaces between words in a Word document I have a Word document about 200 pages. The text I pasted from a PDF lost it's spaces for some reason. How do I fix this?

A: This is quite interesting but also not easy
My real answer is to suggest you fix the issue which is how the PDF was exported!
However, this VBa may get you going. There is no undo so create a back up first
Option Explicit
Sub DoIt()

Dim maxChars As Integer
maxChars = 30                         'update for the biggest word you want to check for (max characters in the word)

Dim pos As Integer
pos = 0

Dim total As Integer
total = Len(Range.Text)

Do While (pos < Len(Range.Text))

Dim s As String
s = ""

Dim wordToUse As String
wordToUse = ""
Dim i As Integer
    For i = 1 To maxChars

    s = s + Mid(Range.Text, pos + i, 1)

    If SpellCheck(s) = True Then
        wordToUse = s
    End If

    Next i

pos = pos + Len(wordToUse)
Dim lef As String
Dim rig As String

lef = Trim(left(Range.Text, pos))
rig = Trim(Mid(Range.Text, pos + 1))

Range.Text = Trim(lef) + " " + Trim(Replace(rig, "  ", " "))

If pos >= total Then
Exit Do
End If

Loop

End Sub

Function SpellCheck(SomeWord As String) As Boolean
'credit https://stackoverflow.com/a/10776225/1221410
    SpellCheck = Application.CheckSpelling(SomeWord)
End Function

The logic is simple - keeping adding characters until you find a valid word... at that point, make sure it's not part of a word (eg and exists in land). Then add some white space to the end.
How do I add VBA in MS Office?

A: What worked for me was just select all the text in the word file and click on Clear formatting:


text:
Q: How do I center inline radiobuttons on the page? I'm trying to center a group of inline radiobuttons on my webpage but can't seem to override Claritys' CSS styling.
I've tried placing the clarity code inside a parent DIV tag using align-text:center, align-content:center, align-items: center, using a FIELDSET tag. But none of these have worked so far
<fieldset style='text-align: center'>

            <input type="radio" id="vertical-radio1" name="radio-full" value="option1" class="clr-radio">
            option 1

            <input type="radio" id="vertical-radio2" name="radio-full" value="option2" class="clr-radio">
            option 2

            <input type="radio" id="vertical-radio3" name="radio-full" value="option3" class="clr-radio">
            option 3

</fieldset>

The radiobuttons should be centered in the page.

A: One approach would be to add your own css class to the clr-control-container and set the following for its css:
.app-centered-radios {
  width: 100%;
  justify-content: center;
}

Here is a stackblitz with centered inline radio buttons: https://stackblitz.com/edit/so-56050259-center-inline-radio-buttons


text:
Q: Creating Flow Chart with Tikz Picture I am trying to create a simple image to demonstrate limits with a cat jumping towards a treat (the fish). I want the cat to be node 1 with L node 2 in the middle and the fish node 3. This is what I have so far but I can't figure out how to make node 2 to be in the middle (at the top of the curve). I also don't want a line between nodes 1 and 3. I apologize if I'm not making any sense, any help is appreciated!
\begin{tikzpicture}[->,>=stealth',auto,node distance=2in,
  thick,main node/.style={circle,draw,font=\sffamily\Large\bfseries}]
\node[main node] (1) {\Cat};
\node[main node] (2) {L};
\node[main node] (3) [right of=1] {\bcpoisson};

\draw [->] (1) -- (2)(1.north) to [out=150,in=30] (2.north);
\draw [->] (3) -- (2)(3.north) to [out=150,in=30] (2.north);
\end{tikzpicture}

A:
\documentclass[border=2mm]{standalone}
\usepackage{tikz}
\usetikzlibrary{positioning}
\usepackage{tikzsymbols,bclogo}
\begin{document}
\begin{tikzpicture}%
  [action/.style={font=\sffamily\Large\bfseries},
   actor/.style={circle,draw,inner sep=0pt,minimum width=2em},
   >=stealth,
   thick
  ]
  \node[actor] (cat) {\Cat};
  \node[actor] (fish) [right=2cm of cat] {\bcpoisson};
  \draw[->] (cat) edge[bend left] node[above,action]{L} (fish);
\end{tikzpicture}
\end{document}


text:
Q: Android ChangeOverTime method freezing at runtime (but not consistently) So I am running into a problem with a function I made to slowly change the value of a monitored variable over time that is causing all the java logic to lock up. It doesn't seem to be producing an error or make the application crash so it must be getting stuck in the while loop or something but the logging isn't firing while it is locked so I am just very confused. If anyone can help me figure out how to diagnose what is causing the freezing that would be very much appreciated
EDIT: Turns out the problem was updating the UI from another thread, I manged to get it to crash and got the error and used a CountDownTimer instead of the background thread and now it is working fine. For those curious checkout my GitHub for this project.
Function in question:
public static void changeOverTime(final MonitoredVariable<Integer> tVar, final int tTo, final long tTime, final long tUpdateFreq) {
    if (tTime < tUpdateFreq) { Log.e(TAG, "Time must be greater then update freq."); }
    if (tVar == null) { Log.e(TAG, "Container cannot be null."); }
    else {
        final Thread tBackgroundThread = new Thread(new Runnable() {
            @Override
            public void run() {
                float tSteps = tTime / tUpdateFreq; // 2000/100 = 20
                float tInterval = (tTo - tVar.get()) / tSteps; // 67-175 = -108/20 = -5.4
                float tVal = tVar.get(); //175
                while (Math.round(tVal) != tTo) { //67(After 20 Times) != 67 -> FALSE
                    Debug.Log(TAG, "EQ: " + Math.round(tVal) + "?=" + tTo);
                    tVal += tInterval; // -5.4 * 20(Times) = -108+175 = 67
                    tryToSleep(tUpdateFreq); // 100ms * 20(Times) = 2000ms total
                    tVar.set(Math.round(tVal));
                }
            }
        });
        tBackgroundThread.start();
    }
}

Supporting Function:
private static void tryToSleep(long tTime) {
    try { sleep(tTime); }
    catch (InterruptedException e) { e.printStackTrace(); }
}

Monitored Variable Class:
public class MonitoredVariable<Prototype> {
    protected Prototype mData;
    protected ChangeListener mListener;

    public MonitoredVariable(Prototype tData) {
        this(tData, null);
    }

    public MonitoredVariable(Prototype tData, ChangeListener tListener) {
        if (tListener != null) setListener(tListener);
        mData = tData;
    }

    public Prototype get() {
        return mData;
    }
    public void set(Prototype tData) {
        if (mData != tData) {
            mData = tData;
            notifyChange();
        }
    }

    public void setListener(ChangeListener tListener) {
        mListener = tListener;
    }
    public ChangeListener getListener() {
        return mListener;
    }
    public void notifyChange() {
        if (mListener != null) mListener.onChange();
    }
    public interface ChangeListener {
        void onChange();
    }
}

Usage:
public static void init() {
    MonitoredVariable.ChangeListener tUpdateBackground = new MonitoredVariable.ChangeListener() {
        @Override
        public void onChange() { updateBackgroud();
        }
    };
    mTop = new MonitoredVariable[]{
            new MonitoredVariable<>(0, tUpdateBackground),
            new MonitoredVariable<>(0, tUpdateBackground),
            new MonitoredVariable<>(0, tUpdateBackground)
    };
    mBottom = new MonitoredVariable[]{
            new MonitoredVariable<>(0, tUpdateBackground),
            new MonitoredVariable<>(0, tUpdateBackground),
            new MonitoredVariable<>(0, tUpdateBackground)
    };

    mAnimationLoop = new Handler();
    mAnimation = new Runnable() {
        @Override
        public void run() {
            Debug.Log(TAG, "RUNNING ANIMATION");
            final Random RNG = new Random();
            for (MonitoredVariable<Integer>[] tBackground: new MonitoredVariable[][] {mTop, mBottom}) {
                for (MonitoredVariable<Integer> tColor : tBackground) {
                    int tRandomColor = RNG.nextInt(255);
                    //tColor.set(tRandomColor);
                    Shift.changeOverTime(tColor, tRandomColor, 2000, 100);
                }
            }
            if(mAnimate.get()) {
                mAnimationLoop.postDelayed(mAnimation, 10000);
            }
        }
    };

    mAnimate = new MonitoredVariable<>(false, new MonitoredVariable.ChangeListener() {
        @Override
        public void onChange() {
            if (mAnimate.get()) mAnimationLoop.postDelayed(mAnimation, 0);
            else mAnimationLoop.removeCallbacks(mAnimation);
        }
    });
}

public static void setBackground(final Activity tActivity){
    final View tActivityBackground = tActivity.findViewById(R.id.background);
    mListener = new ChangeListener() {
        @Override
        public void onChange() { tActivityBackground.setBackground(mBackground); }
    };

    notifyChange();
}

 private static void updateBackgroud() {
    int tTop = Color.argb(255, mTop[0].get(), mTop[1].get(), mTop[2].get());
    int tBottom = Color.argb(255, mBottom[0].get(), mBottom[1].get(), mBottom[2].get());
    int[] colors = {tTop, tBottom};
    mBackground = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM, colors);
    mBackground.setCornerRadius(0f);
    notifyChange();
}

public static void animateBackground(boolean tAnimate) {
    mAnimate.set(tAnimate);
}

public static void notifyChange() {
    if (mListener != null) mListener.onChange();
}

public interface ChangeListener {
    void onChange();
}


text:
Q: Fire and forget with GetResponseAsync Am trying to achieve a fire and forget situation with HttpWebRequest GetResponseAsync without setting up an await on it. Are there any potential dangers am over looking?

A: Yes, there are many "potential dangers" around using fire-and-forget on ASP.NET.
In the most general case, you can only use fire-and-forget if you don't care whether the code actually gets executed or not. I have more details on my blog and so does Phil Haack.

A: One possible danger would be ASP.NET shuts the server's thread pool down , your GetResponseAsync is going to get killed and won't start itself up again even after the server wakes up


text:
Q: Is it possible to display a different hostname, when a user logs in? I have an issue where my customer used a different hostname naming convention than my company did, for the devices they purchased from us. Example:
We named the devices Lenny1, so the FQDN is lenny1.whatever.com and user@Lenny1 is what is visible to users when they log in to the device.
The customer used the name PCAP02 for this same device.  This creates confusion for users when they log in and see Lenny1 as the system name.
For very complex reasons, we cannot easily change the /etc/hosts file to use the names that our customer uses.  My question is, is there a way to spoof the system name that the customer will see, when they log in?  This change needs to be purely cosmetic, so that the users won't get confused about what system they're logging in to.

A: You can change that in the /etc/bashrc file.
Please make a backup of this file in case you make any mistakes.
Within the file, you will see this line:
[ "$PS1" = "\\s-\\v\\\$ " ] && PS1="[\u@\h \W]\\$ "

\h is the hostname of the machine. Remove that and replace it with PCAP02.
That line should then look like this:
[ "$PS1" = "\\s-\\v\\\$ " ] && PS1="[\u@PCAP02 \W]\\$ "

Save the file and enter bash and you will see user@PCAP02 in the terminal. Your customers will see the change when they SSH into the machines.


text:
Q: How do I use Angular 1.x template interpolation inside an HTML comment? I would like to populate an HTML comment with data from the scope.
Angular seems to ignore processing anything inside of an HTML comment.
For example, the following gets output verbatim in the rendered DOM, rather than interpolating the row in place.
<!-- Row id: {{ row.id }}  -->

I would like the output to be like so:
<!-- Row id: 19 -->


text:
Q: tf.reduce_mean prints strange results when reduction_indices is specified tf.reduce_mean command is used to take mean along specified axis. But if don't specify axis and use reduction indices zero then it prints middle row. Why is it so? How this reduction indices effects output values? If I print sum.eval() command why it prints [[4,5,6]]?
I also go through the documentation but it doesn't give any explanation for reduction_indices.Please clear my concept about this command.
a = tf.range(0,12)
b = tf.reshape(a,(4,3))
sum = tf.reduce_mean(b,reduction_indices=[0],keep_dims=True)
sess = tf.InteractiveSession()
print (b.eval())
print (b.get_shape())
print (sum.eval())
print (sum.get_shape())

A: reduction_indices behaves like axis.
As per the documentation of tf.reduce_mean:

reduction_indices: The old (deprecated) name for axis.

https://www.tensorflow.org/api_docs/python/tf/reduce_mean
4, 5 and 6 are just the mean of each column
 (0+3+6+9)/4 = 4
(1+4+7+10)/4 = 5
(2+5+8+11)/4 = 6


text:
Q: Why am I not correct when calculating the number of ways of selecting a pair when a five-card hand is drawn? Discrete Maths noob here.
I'm trying to calculate amount of possible choices when choosing exactly one pair out of a deck of cards.
I'm thinking that you could first choose any of the 52 cards, and that your next choice must one out of three cards (because you chose a value in your first choice), after that you can choose any out of the 48 remaining cards (subtracting the four varieties of the first card chosen), and then you can choose 1 out of 44, and lastly one out of 40.
$$
{{52}\choose{1}}\cdot{{3}\choose{1}}\cdot{{48}\choose{1}}\cdot{{44}\choose{1}}\cdot{{40}\choose{1}}
$$
But this results in a really wrong answer.
Any suggestions on how to think?

A: You're trying to calculate the number of choices which give you exactly one pair out of five cards, right?
What you've actually calculated is the number of choices where the first two cards form a pair, and the rest are all different. Since there are actually $\binom 52=10$ different choices for which two of the five cards make up the pair, you have to multiply the answer by $10$.
(edit: that is, you have to multiply by $10$ if you want the number of ordered choices of five cards which contain exactly one pair. If you just want the number of hands of five cards, unordered, you have to divide the ordered answer by $5!=120$ (the number of ways to order a given hand), so as Wen says you end up with your answer divided by $12$.)

A: Especially Lime has provided you with a nice explanation of why your answer is incorrect.
How can we calculate the number of five-card hands that contain one pair?
Such hands contain two cards of one rank and one card each of three other ranks.  There are $13$ ways to choose the rank from which the pair will be drawn.  There are $\binom{4}{2}$ ways to select two of the four cards from this rank.  There are $\binom{12}{3}$ ways to select the ranks of the other three cards in the hand from the $12$ other ranks in the deck.  There are four ways to select one card from each of these ranks.  Hence, the number of five-card hands that contain a pair is
$$\binom{13}{1}\binom{4}{2}\binom{12}{3}\binom{4}{1}^3$$


text:
Q: Ajax call returns nothing I am trying to make an ajax call on click on anchor tag dynmically generated from $.each loop for a JSON response.
For Information : #records is my table and .update is the class of anchor tag in that table.
Please be informed that the table is generated dynamically.
Now the problem is that my ajax call is returning nothing even i have checked it error: but no response received. I have tried alerting my var data just before the ajax call and it worked.So the problem starts from the ajax call. Moreover, my server side code is running fine.
// Update existing customers
            $("#records").on('click', ".update", function() {
                        var data = '?'+ $(this).attr('id');
                        $.ajax({
                            type: "GET",
                            url: "viewcustomers.php",
                            data: data,
                            success: function(response) {
                                console.log(response);
                            }
                        });
                        });

Thanks in advance.
For reference below is the code that generates the table.
 // Function to make datagrid
            function getRecords() {
                $.getJSON("viewcustomers.php", function(data) {
                    var items = [];
                    var xTd = '';
                    var xTr = '';
                    $.each(data, function(key, val) {
                        var c = 0;
                        var id = 0;
                        $.each(val, function(key1, val1) {
                            if (c == 0)
                            {
                                id = val1;
                            }
                            c++;
                            xTd += '' + val1 + '	';
                        });
                        xTd += 'Edit	';
                        xTd += 'Delete	';
                        xTr = '
' + xTd + '
';
                        items.push(xTr);
                        xTd = '';
                        xTr = '';
                    });
                    $("#records").append(items);
                });
            }

Updated the server side code:
page url : localhost/hotel/viewcustomers.php
/**
 * Fetch single row for the purpose of update / delete.
 */
if(isset($_GET['update'])){
    $customer = new Customers;
    $Id = $_GET['update'];
    $customer_single = $customer->View_Single_Customer($Id);
    echo json_encode($customer_single);
    unset($customer);

}

A: Modify it as
$("#records").on('click', ".update", function() {
  var request = '?id='+ $(this).attr('id');
  $.ajax({
    type: "GET",
    url: "viewcustomers.php" + request,
    success: function(response) {
      console.log(response);
    }
  });
});

A: This line is not used the right way var data = '?'+ $(this).attr('id');
Change it like this: var my_id = $(this).attr('id');
Then update the line data: data with data : {id:my_id}
Complete code :
$("#records").on('click', ".update", function() {
    var my_id = $(this).attr('id');
    $.ajax({
        type: "GET",
        url: "viewcustomers.php",
        data : {id : my_id},
        success: function(response) {
            console.log(response);
        }
    });
});

Or do it like this:
$("#records").on('click', ".update", function() {
    var param = '?id='+ $(this).attr('id'); /*notice that I have added "id=" */
    $.ajax({
        type: "GET",
        url: "viewcustomers.php" + param,
        /* remove the data attribute */
        success: function(response) {
            console.log(response);
        }
    });
});


text:
Q: Enable a Cargo feature by default when the target arch is WASM? Part of my Cargo.toml for my crate:
[features]
wasm = ["ed25519-dalek/nightly", "rand/wasm-bindgen", "js-sys"]

This works, when the crate is used in another project, and the "wasm" feature is explicitly chosen.
I want to automatically enable this feature only when the target arch is WASM. I tried adding this:
#[cfg(target_arch = "wasm32")]
default = ["wasm"]

When I compile for a target other than WASM, "wasm" is included as the default, how can I make "wasm" the default only when the target is WASM?

A: You can only have target-specific dependencies, not target-specific features. This is a known bug that is unfortunately opened since 2015.
People expects this syntax to be supported, but right now there is nothing scheduled to make this work:
[target.'cfg(target_arch = "wasm32")'.features]
default = ["ed25519-dalek/nightly", "rand/wasm-bindgen", "js-sys"]

As a ugly workaround, you can create another crate that depends on your crate and let the user use this new crate:
[target.'cfg(target_arch = "wasm32")'.dependencies.your_crate]
version = "1.0.0"
features = ["wasm"]


text:
Q: install ubuntu 12.10 issue I'm installing Ubuntu 12.10 along side windows 7. I have installed windows then Ubuntu 12.10, each on a different partition. while choosing where to install boot loader I left the default, it was my hard disk name in general not a specific sda or something like that. everything was fine and after rebooting again windows start up logo appeared. I tried to add Ubuntu to Windows boot list using easyBCD and it returned success. Now I can see it windows boot menu but after opting Ubuntu a message and grub > prompt appears. I'm totally confused, help please. thanks and happy new year. ;)

A: This exact same thing happened to me, how I fixed it was I booted into ubuntu live cd and used boot repair (information can be found here: https://help.ubuntu.com/community/Boot-Repair) using recommended repair.
Hope that helps.

A: Try booting from your install media again. Open the Disks program and discover the reference toy your hard disk, probably /dev/sda. Then open a terminal and type sudo grub-install /dev/XXX where XXX is the drive name.
Reboot to check if the problem is solved or not.


text:
Q: Postgresql view with many common table expressions is slow This is a huge simplification of my query, but essentially I have a series of common table expressions that build off of each other which I would like to turn into a view. The problem is it's extremely slow when I try to use a view, but very fast when I run the query.
CREATE VIEW user_view AS
WITH cte AS(
  SELECT first,middle,last FROM user
),
cte2 AS(
  SELECT *,first + middle AS first_middle FROM cte
),
cte3 AS(
  SELECT *,first_middle + last AS full_name FROM cte2
)
  SELECT * from cte3;

Fast query
WITH cte AS(
  SELECT first,middle,last FROM user WHERE user_id = 5
),
cte2 AS(
  SELECT *,first + middle AS first_middle FROM cte
),
cte3 AS(
  SELECT *,first_middle + last AS full_name FROM cte2
)
  SELECT * from cte3;

Slow query using the view
SELECT * from user_view WHERE user_id = 5

A: Postgres implements something called an "optimization fence" for CTEs.  That means that Postgres materializes each CTE for subsequent processing.  One nice effect is that a CTE can be referenced multiple times, but the code is only executed once.  The downside is that conveniences such as indexes are "forgotten" after the CTE has been materialized.
For your question, the view is actually immaterial (no pun intended).  In this version:
WITH cte AS (
      SELECT first, middle, last FROM user WHERE user_id = 5
     ),
     cte2 AS (
      SELECT *, first || middle AS first_middle FROM cte
     ),
     cte3 AS (
      SELECT *, first_middle || last AS full_name FROM cte2
    )
SELECT *
FROM cte3;

The first CTE presumably pulls one record out from the table.  Presumably, it uses an index on the id and even that operation is very fast.  That one record is the only record processed by the remaining CTEs.
In this version:
WITH cte AS (
      SELECT first, middle, last FROM user
     ),
     cte2 AS (
      SELECT *, first || middle AS first_middle FROM cte
     ),
     cte3 AS (
      SELECT *, first_middle || last AS full_name FROM cte2
    )
SELECT *
FROM cte3
WHERE user_id = 5;

The CTEs are processing all the data in the user table.  At the end, the row meeting the WHERE condition needs to be found.  The materialized CTE no longer has an index . . . so the data is searched sequentially.
This behavior does not apply to subqueries, so you can try rewriting your logic using subqueries rather than CTEs.
Postgres optimizes CTEs differently from other databases.  For instance, SQL Server never materializes subqueries; the code is always "inserted" into the query and optimized as a whole.  In fact, SQL Server forums have the opposite concern -- to implement an option to materialize the CTEs.   is different from other databases.  Oracle is one database that seems to take both approaches.


text:
Q: Inserting the output of file descriptor 3 inline in bash I've written a program in ruby called citeselect that uses curses to dynamically select a reference from a bibtex bibliogrpahy. I would like to put this program into a pipeline to cite anything easily using the output of this program. Unfortunately, as I found out from
Ncurses and linux pipeline (c),
Curses uses stdout for its display.
Therefore, I've routed the output citation key into file descriptor 3 when it is provided as an output. I've verified that it works:
citeselect 3>output
Is there any way to capture the output sent to fd3 in a one liner in bash? Something like
echo "The citation key is $(citeselect 3>)"
Thanks.

A: Using Victory's answer as a starting point, and after experimenting around with output redirection, I realised that I had the wrong idea about what n>&m did. This guide really helped me:
http://mywiki.wooledge.org/BashFAQ/002
To do this I have to redirect stdout to stderr, and then fd3 to stdout like this:
CITATION=$(citeselect 3>&1 1>&2)
That way curses is still able to use the tty via the stderr stream, while I can still pipe the citation output. In a lot of my earlier attempts, I had the redirection arguments reversed because of a fundamental misunderstanding of what they were doing.

A: Nice question, a much better way to do this is to replace the stdout file descriptor with another number using the exec command:
#!/usr/bin/env bash

exec 3>&1             # 1 is stdout, 3 is the fd to assign stdout to

exec > outputfile.txt # every command executed within this location
                      # to where the fd was closed and replaced back
                      # to it's formal value will be sent to outputfile.txt

citselect

exec 1>&3 3>&-        # the fd of stdout is replaced back to 1 and reset

Put this file in your ${HOME}/bin or /usr/bin/ folder and execute it instead of calling citeselect directly
For more information about this, check the Advanced Bash Guide, but in some cases you should avoid using that Guide for reference.


text:
Q: Do not scroll table headings when scrolling down a html table Richard JP Le Guen kindly provided me help when it comes to creating a scrolling html table. The only problem is that I don't want the table headings to scroll with the table rows. Now it worked in his example using span but if I use it in my table it really messes up my table headings. I have been for the last 2 hours try to get it sorted but I havn't so I have just left the table headings as it was.
So what question is that is there another way to be able to use css to make sure that table headings cannot be scrolled while scrolling down a table?
Below is my html and css code:

    Question No
    Option Type
    Duration
    Weight(%)
    Answer
    Video
    Audio
    Image

    <?php echo $i; ?>

            #qandatbl{
                font-size:12px;
                border-collapse:collapse;
                margin:0px;
                text-align:center;
                margin-left:auto;
                margin-right:auto;
                border:1px solid black;
            }
            .col1{
            background-color:#FCF6CF;
            }
            .col2{
            background-color:#FEFEF2;
            }
                .options{
            overflow:hidden;
            max-width:125px;
            min-width:125px;
            background-color:#FCF6CF;
            border:1px solid black;
                }
            .duration{
            overflow:hidden;
            max-width:125px;
            min-width:125px;
            background-color:#FEFEF2;
            border:1px solid black;
                }
            .weight{
            overflow:hidden;
            max-width:125px;
            min-width:125px;
            background-color:#FCF6CF;
            border:1px solid black;
                }
             .answer{
            overflow:hidden;
            max-width:125px;
            min-width:125px;
            background-color:#FEFEF2;
            border:1px solid black;
                }
            .qid{
            overflow:hidden;
            max-width:125px;
            min-width:125px;
            background-color:#FEFEF2;
            border:1px solid black;
                }
            .video{
            overflow:hidden;
            max-width:350px;
            min-width:350px;
            background-color:#FCF6CF;
            border:1px solid black;
                }
            .audio{
            overflow:hidden;
            max-width:350px;
            min-width:350px;
            background-color:#FEFEF2;
            border:1px solid black;
                }
            .image{
            overflow:hidden;
            max-width:350px;
            min-width:350px;
            background-color:#FCF6CF;
            border:1px solid black;
                }
             #tableWrapper {
  position:relative;
}
#tableScroll {
  height:350px;
  overflow:auto;
  margin-top:20px;
}

A: check out How can I let a table's body scroll but keep its head fixed in place?
using this Pure CSS Scrollable Table with Fixed Header


text:
Q: How to choose different elements within an array of objects in c# I have an Invoice class and a main class. I have an array of objects within my main class and I want to multiply the quantity(7) by the price(57.88). How do you select different elements within an object array. I have shown my main and my invoice classes. I'm looking for an example on how I would go about this pertaining to what I have done with my code.
 static void Main(string[] args)
    {
        var tools = new[]
        {
            new Invoice(83,"Electric Sander", 7, 57.88M),
            new Invoice(24, "Power Saw", 18, 99.99M),
            new Invoice(7, "Sledge Hammer", 11, 21.50M),
            new Invoice(77, "Hammer", 76, 11.99M),
            new Invoice(39, "Lawn Mower", 3, 79.50M),
            new Invoice(68, "Screwdriver", 106, 6.99M),
            new Invoice(56, "Jig Saw", 21, 11.00M),
            new Invoice(3, "Wrench", 34, 7.50M)
        };

        Console.WriteLine("Original Array: ");
        foreach (var tool in tools)
        {
            Console.WriteLine(tool);
        }

        var descriptionSort = from t in tools
            orderby t.PartDescription
            select t;
 }

public class Invoice
  {
    // declare variables for Invoice object
    private int quantityValue;
    private decimal priceValue;

    // auto-implemented property PartNumber
    public int PartNumber { get; set; }

    // auto-implemented property PartDescription
    public string PartDescription { get; set; }

    // four-argument constructor
    public Invoice(int part, string description,
        int count, decimal pricePerItem)
    {
        PartNumber = part;
        PartDescription = description;
        Quantity = count;
        Price = pricePerItem;
    }

    // property for quantityValue; ensures value is positive
    public int Quantity
    {
        get
        {
            return quantityValue;
        }
        set
        {
            if (value > 0) // determine whether quantity is positive
            {
                quantityValue = value; // valid quantity assigned
            }
        }
    }

    // property for pricePerItemValue; ensures value is positive
    public decimal Price
    {
        get
        {
            return priceValue;
        }
        set
        {
            if (value >= 0M) // determine whether price is non-negative
            {
                priceValue = value; // valid price assigned
            }
        }
    }

    // return string containing the fields in the Invoice in a nice format;
    // left justify each field, and give large enough spaces so
    // all the columns line up
    public override string ToString() =>
        $"{PartNumber,-5} {PartDescription,-20} {Quantity,-5} {Price,6:C}";
}

A: You could always just add a getter to your Invoice class
public decimal TotalPrice
{
    get
    {
        return Price * Quantity;
    }
}

tools[0].TotalPrice to get the first element in your array

A: You already "select different objects" here:
foreach (var tool in tools)
{
    Console.WriteLine(tool);

}

You could add to this, and even keep a total:
double total = 0;
foreach (var tool in tools)
{
    Console.WriteLine($"{tool.Quantity} of {tool.Name} (costing {tool.Price} each) totals {tool.Quantity * tool.Price}");

    total += (tool.Quatity * tool.Price);
}

Console.WriteLine("Invoice total " + total);

You can also access arrays etc by index, typical examples being:
for(int x = 0; x < tools.Length; x++)
  Console.WriteLine(tools[x].Price);

for(int x = tools.Length-1; x >= 0; x--)
  Console.WriteLine(tools[x].Price);

This is a common requirement to do that they have a shortcut - you type forTABTABorforr`TABTAB VS will insert skeletons of these for you


text:
Q: Heads/Tails 900 times, find k such that $P(k \leq T \leq 480) = 0.1$ with T the number of Tails Heads/Tails 900 times, find k such that $P(k \leq T \leq 480) = 0.1$ with T the number of Tails.
I will use the CLT because I know that $$P(z_{1} \leq \frac{S_{N} - \mu N}{\sqrt{N} \sigma} \leq z_{2})$$
We have $S_{900}$ a sum of Bernoulli($\frac{1}{2}$) so $\mu = \frac{1}{2}$ and $\sigma = \frac{1}{\sqrt{2}}$.
But here I just don't know what to do.. Do you have any hints ?

A: Here is a start working a similar problem:
$T \sim \mathsf{Binom}(n = 900, p = 1/2),$ so start by showing that $E(T) = 450$ and $SD(T) = 15.$  Then
$$0.1 = P(k \le T \le 450) \approx P\left(\frac{k - 450}{15} \le \frac{T - E(T)}{SD(T)}
\le \frac{450 - 450}{15} \right) = P\left(\frac{k-450}{15} \le Z \le 0\right),$$
where $Z$ is standard normal.
Using standard normal tables (backwards), you should be able to deduce the
value of $(k-450)/15$ and solve for $k.$ It may help to draw a sketch.
Of course, it is too much to expect
the the resulting $k$ will be exactly an integer, so 'round' appropriately.
The normal approximation should work
well enough to get an answer for $k$ that gives a probability very near
to the desired $0.1.$
You will be using standard normal and $\mathsf{Norm}(450, 15)$. Below are
sketches of both. The area for my problem is between the vertical red lines (on both
sketches). You should make one type of sketch for your problem.


text:
Q: Two fair dice are rolled, and the sum is a perfect square and no primes before that. What is the probability that the perfect square is odd?
Two fair dices each with faces numbered $1, 2, \cdots , 6$ are rolled together and the sum of the numbers on the faces are noted. This process is repeated till the sum is either a prime number or a perfect square. Suppose the process stops when the sum turns out to be a perfect square (So, no prime number showed up). Find the probability that the perfect square is odd.

Hello!
The given solution to the problem is $4/7$. The solution is very complex, uses multiple events, and uses conditional probability a lot.
However, I had a solution:

The given number can be $4$ or $9$. The chances of $9$ is $4 / (3 + 4) = 4/7$ because $3$ is the number of times $4$ can show up, and $4$ is the number of times $9$ can show up as sum.

Is my solution correct though (It doesn't seem like it, it uses nothing of what is given in the question)? :/
Thanks


text:
Q: Flutter/Dart: Scan local network to get IP and hostname of connected devices I'm working on a mobile app using Flutter and want to scan the local network for connected devices. I found the ping_discover_network package, which is working fine, but only gets me the IP address, but I also want to show the hostname of the device.
I tried the reverse() method of the InternetAddress class from the dart:io package, but this only gets me the IP address back.
Example:
InternetAddress(ip).reverse().then((value) => print(value));

Is there another package or something I can use, to scan the local network of the app and get the IP address and the hostname back?

A: OK, I got it working and want to share my solution.
I used the network_info_plus package and the dart:io package.
import 'dart:io';
import 'package:network_info_plus/network_info_plus.dart';
Future<void> scanNetwork() async {
  await (NetworkInfo().getWifiIP()).then(
    (ip) async {
      final String subnet = ip!.substring(0, ip.lastIndexOf('.'));
      const port = 22;
      for (var i = 0; i < 256; i++) {
        String ip = '$subnet.$i';
        await Socket.connect(ip, port, timeout: Duration(milliseconds: 50))
          .then((socket) async {
            await InternetAddress(socket.address.address)
              .reverse()
              .then((value) {
                print(value.host);
                print(socket.address.address);
              }).catchError((error) {
                print(socket.address.address);
                print('Error: $error');
              });
            socket.destroy();
          }).catchError((error) => null);
      }
    },
  );
  print('Done');
}

I'm "scanning" the local network by trying to connect to a given ip and port. If that works, I found a device, I'm looking for. In that cause I also try to get the hostname by using the "reverse()" method.
I have tested it on several iOS and Android devices and it works fine with no errors, so I think its a proper solution.

A: This does not work on the desktop as I think it is not implemented.
Only for iOS and Android.


text:
Q: What does this error [NSUnknownKeyException] mean in xcode (objective c)? I am running my app and when I click a navigation button which is supposed to take me to a TableViewController, it crashes, giving me this error:
*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[ setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key index.'
It is also highlighting where the error occurred, pointing to this line in my DataTableViewController class:
CoordinatesCustomCell *cell = [tableView dequeueReusableCellWithIdentifier:@"CoordinatesCustomCell" forIndexPath:indexPath];

I really have no idea what this means and could use some help
github for code: https://github.com/nneeranjun/Maps.git

A: this problem maybe caused in xib or stroryboard. Check the class or any other attributes in it of your cell.

A: Check your cell and subviews custom class and connections with owner.


text:
Q: Calculating test-time perplexity for seq2seq (RNN) language models To compute the perplexity of a language model (LM) on a test sentence $s=w_1,\dots,w_n$ we need to compute all next-word predictions $P(w_1), P(w_2|w_1),\dots,P(w_n|w_1,\dots,w_{n-1})$.
My question is: How are these terms computed for a seq2seq language model (say using LSTMs)?
At training time, we encode $s$ as a vector $\mathbf x_s$, initialize the decoder with $\mathbf x_s$ (usually the last hidden state $\mathbf h_n$), provide it with the ground truth sequence $w_1,\dots,w_n$ as input and obtain a prediction $\hat w_1,\dots,\hat w_n$ which goes into a loss function, e.g. cross-entropy.
At test time, I assume:

*

*Initializing the decoder with $\mathbf x_s$ would be cheating as it encodes information about upcoming words.

*We cannot take an encoder hidden state $\mathbf h_i$ and use it as the decoder hidden state $\hat{\mathbf h}_{i}$ at some time $i>1$ since encoder and decoder weight matrices have learned different dynamics.

So my question boils down to: How can we get a good but fair decoder hidden state $\hat{\mathbf{h}}_i$ to predict word $\hat w_i$? How can it encode as much as possible about the history? One option that I see is:

*

*Run the encoder to obtain $\mathbf h_1,\dots,\mathbf h_n$.

*To obtain $\hat{\mathbf h}_{i-1}$, feed $\mathbf h_{i-1}$ as initial hidden state to the decoder, run it until time step $i-1$ always providing the ground truth as input.

*Compute $\hat{\mathbf h}_i$ using $\hat{\mathbf h}_{i-1}$ and $w_{i-1}$.

*Obtain $P(w_i|w_1,\dots,w_{i-1})$ by feeding $\hat{\mathbf h}_i$ into the softmax.

Can anybody conform that his is the way to do it?
Alternatively, one can of course feed an uninformative, constant/random initial hidden state to the decoder and just provide the ground truth sequence. However, this feels much weaker than the approach described above.
PS: I know that in machine translation the situation is very different as knowing the encoder state when decoding in another language is not cheating. However, there one would not be allowed to get ground truth input at test time.

A:
How can we get a good but fair decoder hidden state $\hat h_i$ to predict word $\hat w_i$? How can it encode as much as possible about the history?

Once the language model has been trained the $\hat h_i$ can be got from the previous words $w_0, w_1, ..., w_{i-1}$ where $w_0$ represents the start of sentence token. The history information is encoded in the cell updated by all the previous words. We do not use the predicted $\hat w_i$ and hence will not affect the results, and the character we input into the model at each time step is the ground truth.
For example, when we calculating the probability of $w_i$(for i >= 1) the input is $h_{i-1}$(which is only affected by $w_0$ to $w_{i-2}$), $w_{i-1}$, and we can get a probability distribution for $w_{i}$ and we just index the probabilty($p(w_i|w_0, ..., w_{i-1})$) using $w_i$ and don't do the others(we don't get the word with max probability $\hat w_i$) and input ground truth $w_i$ for the next time step as the input.
And the probability of each character is indexed by the ground truth character in the softmax output and the mean perplexity is then calculated by this:
\begin{align}
\text{Perplexity}(w_1, ..., w_n) &= \sqrt[n]{\frac{1}{\prod_{i=1}^{n} p(w_{i})}}  \\
               &= 2^{\log_{2}{[\prod_{i=1}^{n} p(w_i|w_0, ..., w_{i-1})]}^{-n}}  \\
               &= 2^{-\frac{1}{n}\log_{2}{[\prod_{i=1}^{n} p(w_i|w_0, ..., w_{i-1})]}}  \\
               &= 2^{-\frac{1}{n}\sum_{i=1}^{n}\log_{2}{p(w_i|w_0, ..., w_{i-1})}}
\end{align}
For the detailed derivation please refer to this article: N-gramLanguage Models.

A: At test time, for decoding, choose the word with highest Softmax probability as the input to the next time step. The perplexity is calculated as
p(sentence)^(-1/N)
where N is number of words in the sentence.


text:
Q: Shift the business month end date by different number of month in pandas I have a dataframe with a Date column in datetime64 and a column Month columns with different integers in float.
Date          Month    New_BDate
2020-06-30    0        2020-06-30
2020-06-30    -1       2020-05-29
2020-06-30    -2       2020-04-30
2020-06-30    -3       2020-03-31
2020-05-29    0        2020-05-29
2020-05-29    -1       2020-04-30

import pandas as pd
df['New_BDate'] = df['Date'] + df['shift'].map(pd.tseries.offsets.BusinessMonthEnd())

Why do I get the below error and how should I solve it? or is there a better alternative?
*** AttributeError: 'float' object has no attribute 'year'
Thanks

A: Here are couple of way's,
import numpy as np
import pandas as pd

df['New_BDate'] = (
    df.assign(Date=pd.to_datetime(df.Date))
        .apply(lambda x: x['Date'] + np.timedelta64(x['Month'], 'M'), axis=1)
)

or
df['New_BDate'] = (
    df.assign(Date=pd.to_datetime(df.Date))
        .apply(lambda x: x['Date'] + pd.tseries.offsets.BusinessMonthEnd(x['Month']), axis=1)
)

A: from dateutil.relativedelta import relativedelta

df['New_BDate'] = df.apply(lambda x: x['Date'] + relativedelta(months=x['Month']), axis=1)


text:
Q: why dig command in cygwin allways return "Segmentation fault"? I was installed cygwin on Windows 7 and when I tried to use dig command, cygwin always return "Segmentation fault ('core' generated). I don't know why.
I've installed cygwin with bind-packets too, but it seems don't work.
Is there anything else to do to make this work? Anything more to install?
Thanks.

A: Segfault could be caused by manual installations and/or corrupted setup.ini files; try removing the whole cygwin package and running the setup again.
I used to run dig on Windows 7 and it worked(*).
(*) note that the current version (9.11.0-2.P3) does not work for me, i.e. returns no output when querying a Windows-based DNS server.
Posted a bug on cygwin mail list, hopefully it will be fixed.


text:
Q: Trying to Fetch Full Table and Email Results Maintaining Proper Form use strict;
use warnings;

# DB Account Parameters

my $driver = "mysql";
my $database = "emegadb";
my $user = "*****";
my $password = "*******";
my $dsn = "DBI:mysql:$database;mysql_local_infile=ON";

use DBI;
my $dbh = DBI->connect($dsn,$user,$password)
  || die "Unable to connect to database. $DBI::errstr.\n";

my $sth = $dbh->prepare("select * from today1")
  || die "cannot prepare select. $DBI::errstr.\n";
$sth->execute || die "cannot execute select. $DBI::errstr.\n";

while(my $row = $sth->fetchrow_hashref){
   my $daily = join (',', values %$row);

   #print "$daily \n";
   push @table1, "$daily";
}
$sth->finish;

$dbh->disconnect();

MAIL:
use Mail::Sendmail qw(sendmail %mailcfg);

#print "Content-type:text/html\n\n";

%mail = (
    To      => 'me@mail.com',
    From    => 'daily_adjust@mail.net',
    Subject => " DAILY ADJUST - DATABASE CAPTURE",
    Message => "DB @table1\n");

$mailcfg{smtp} = [qw(db-ibmv1.mail.net)];

sendmail(%mail) or die $Mail::Sendmail::error;

END:

exit(0);

This provides the following results:
DB 95,1,15476,1016,289.7,288.8,000000,03:00:00,2015-08-29
286.9,15194,1016,287.7,000000,06:00:00,2015-08-29,100,2
3,95,09:00:00,2015-08-29,000000,15476,289.7,1016,289.0
17379,1016,294.8,294.0,000000,12:00:00,2015-08-29,76,4
77,5,294.5,295.2,17569,1.... ETC

What I want is - with column names
+------+------------+----------+----------+------+-------+-------+--------+--------+
| id   | date       | time     | percent  | hpa  | min   | max   | dem    | sumadd |
+------+------------+----------+----------+------+-------+-------+--------+--------+
|    1 | 2015-08-29 | 03:00:00 |       95 | 1016 | 288.8 | 289.7 |  15476 | 000000 |
|    2 | 2015-08-29 | 06:00:00 |      100 | 1016 | 286.9 | 287.7 |  15194 | 000000 |
|    3 | 2015-08-29 | 09:00:00 |       95 | 1016 | 289.0 | 289.7 |  15476 | 000000 |

A: If what you're asking is how to make a tabular layout using ASCII characters, then what you want is something like Text::TabularDisplay.


text:
Q: Присвоить класс блоку, оказавшемуся в центральной части браузера при горизонтальной прокрутке Для упрощения, опишу задачу так. Есть блок, внутри которого прокручиваются горизонтально другие блоки. В каждом из этих блоков абсолютно позиционирован еще один блок в виде цветного квадрата.
Необходимо каждому из этих квадратов присваивать класс .visible в момент, когда этот квадрат докручивается до центра экрана. Центром можно считать область, отстоящую от краёв экрана на 30% слева и справа, вне зависимости от его исходной ширины.
Буду благодарен за подсказку, поскольку в js не силён.

.container{
  max-width: 100%;
  overflow-x: auto;
  white-space: nowrap;
}

.block{
  position:relative;
  width: 800px;
  height: 200px;
  display: inline-block;
  background-color: rgba(0,0,0,0.2);
}
.square1 {
  width:30px;
  height:30px;
  background:red;
  position:absolute;
  right:100px;
  bottom:80px;
}
.square2 {
  width:30px;
  height:30px;
  background:blue;
  position:absolute;
  right:200px;
  bottom:120px;
}
.square3 {
  width:30px;
  height:30px;
  background:green;
  position:absolute;
  right:300px;
  bottom:50px;
}
.square4 {
  width:30px;
  height:30px;
  background:orange;
  position:absolute;
  right:400px;
  bottom:70px;
}

A: Базовый пример, в котором текущему блоку, занимающему большую часть контейнера, добавляется класс active. А дальше уже можете настроить поведение содержимого.
Если цель не в том, чтобы активировать содержимое блока в поле зрения, а нужна более замысловатая механика, значит, я неправильно понял, извините. (Тогда может быть проще слушать событие scroll у контейнера и, выполнять манипуляции с элементами в зависимости от текущего значения scrollLeft)

const slides = document.querySelectorAll('.block');
slides.forEach((i) => {
  if (i) {
    const observer = new IntersectionObserver((entries) => {
      observerCallback(entries, observer, i)
    }, {
      threshold: 0.5
    });
    observer.observe(i);
  }
})

const observerCallback = (entries, observer, header) => {
  entries.forEach((entry, i) => {
    if (entry.isIntersecting) {
      Array.from(document.querySelectorAll('.block')).forEach((el) => el.classList.remove('active'));
      entry.target.classList.add('active');
    }
  });
};
.container {
  max-width: 100%;
  overflow-x: auto;
  white-space: nowrap;
}

.block {
  position: relative;
  width: 800px;
  height: 180px;
  max-width: 80%;
  display: inline-block;
  background-color: rgba(0, 0, 0, 0.2);
  border: solid 2px transparent;
}

.block.active {
  border: solid 2px red;
}

.square1 {
  width: 30px;
  height: 30px;
  background: red;
  position: absolute;
  right: 100px;
  bottom: 80px;
}

.square2 {
  width: 30px;
  height: 30px;
  background: blue;
  position: absolute;
  right: 200px;
  bottom: 120px;
}

.square3 {
  width: 30px;
  height: 30px;
  background: green;
  position: absolute;
  right: 300px;
  bottom: 50px;
}

.square4 {
  width: 30px;
  height: 30px;
  background: orange;
  position: absolute;
  right: 400px;
  bottom: 70px;
}


text:
Q: KSOAP runtime exception in android
Possible Duplicate:
Cannot serialize issue in KSOAP in android

I am calling one web service in my application,in that i am setting the input for that SOAP request as follows:
 PropertyInfo usrid =new PropertyInfo();
            usrid.setName("LoginID");
            usrid.setValue(userid);
            usrid.setType(String.class);
            authentication.addProperty(usrid);

            PropertyInfo pass =new PropertyInfo();
            pass.setName("Password");
            pass.setValue(password);
            pass.setType(String.class);
            authentication.addProperty(pass);

            request.addProperty("authentication", authentication);

            PropertyInfo no =new PropertyInfo();
            no.setName("No");
            no.setValue("28448347");
            no.setType(String.class);
            request.addProperty("Str",no);

But i am receiving the error:
java.lang.RuntimeException: Cannot serialize:no


text:
Q: Analog of TestNG Reporter.getOutput() in Spock I run API tests using Groovy and Spock.
Request/response data, produced by third-party libraries, appear in the system out (I see it in the Jenkins log).
Question:
what is the proper way to start-stop system out recording for each test iteration to some list of strings?
TestNG has Reporter.getOutput(result) which returns all log entries, appeared while test iteration run.
Is it something similar in Spock?
Am I right assuming it should be some implementation of Run listener where I start recording in beforeIteration() and attach it to report in afterIteration()?

A: Solved by using the OutputCapture from
spring-boot-starter-test
The sample of RunListener:
class RunListener extends AbstractRunListener {

    OutputCapture outputCapture

    void beforeSpec(SpecInfo spec) {
        Helper.log "[BEFORE SPEC]: ${spec.name}"
        outputCapture = new OutputCapture()
        outputCapture.captureOutput() //register a copy off system.out, system.err streams
    }

    void beforeFeature(FeatureInfo feature) {
        Helper.log "[BEFORE FEATURE]: ${feature.name}", 2
    }

    void beforeIteration(IterationInfo iteration) {
        outputCapture.reset() //clear the stream copy before each test iteration
    }

    void afterIteration(IterationInfo iteration) {
    }

    void error(ErrorInfo error) {
        //attach the content of copy stream object to the report if  test iteration failed
        Allure.addAttachment("${error.method.iteration.name}_console_out", "text/html", outputCapture.toString(), "txt")

    }

    void afterFeature(FeatureInfo feature) {
    }

    void afterSpec(SpecInfo spec) {
        outputCapture.releaseOutput()
    }
}

Shortly:
CaptureOutput is an implementation of Output Stream which logs in both initial out and  copy stream object. The copy gets cleared in beforeIteration() and is attached to the report in afterIteration() in RunListener, so each test receives its own part of output.


text:
Q: Uppercase random characters in a NSString I'm trying to figure out the best approach to a problem. I have an essentially random alphanumeric string that I'm generating on the fly:
NSString *string = @"e04325ca24cf20ac6bd6ebf73c376b20ac57192dad83b22602264e92dac076611b51142ae12d2d92022eb2c77f";

You can see that there are no special characters, just numbers and letters, and all the letters are lowercase. Changing all the letters in this string to uppercase is easy:
[string capitalizedString];

The hard part is that I want to capitalize random characters in this string, not all of them. For example, this could be the output on one execution:
E04325cA24CF20ac6bD6eBF73C376b20Ac57192DAD83b22602264e92daC076611b51142AE12D2D92022Eb2C77F

This could be the output on another, since it's random:
e04325ca24cf20aC6bd6eBF73C376B20Ac57192DAd83b22602264E92dAC076611B51142AE12D2d92022EB2c77f

In case it makes this easier, let's say I have two variables as well:
int charsToUppercase = 12;//hardcoded value for how many characters to uppercase here
int totalChars = 90;//total string length

In this instance it would mean that 12 random characters out of the 90 in this string would be uppercased. What I've figured out so far is that I can loop through each char in the string relatively easily:
NSUInteger len = [string length];
unichar buffer[len+1];

[string getCharacters:buffer range:NSMakeRange(0, len)];

NSLog(@"loop through each char");
for(int i = 0; i < len; i++) {
    NSLog(@"%C", buffer[i]);
}

Still stuck with selecting random chars in this loop to uppercase, so not all are uppercased. I'm guessing a condition in the for loop could do the trick well, given that it's random enough.

A: Here's one way, not particularly concerned with efficiency, but not silly efficiency-wise either: create an array characters in the original string, building an index of which ones are letters along the way...
NSString *string = @"e04325ca24cf20ac6bd6ebf73c376b20ac57192dad83b22602264e92dac076611b51142ae12d2d92022eb2c77f";
NSMutableArray *chars = [@[] mutableCopy];
NSMutableArray *letterIndexes = [@[] mutableCopy];

for (int i=0; i<string.length; i++) {
    unichar ch = [string characterAtIndex:i];
    // add each char as a string to a chars collection
    [chars addObject:[NSString stringWithFormat:@"%c", ch]];
    // record the index of letters
    if ([[NSCharacterSet letterCharacterSet] characterIsMember:ch]) {
        [letterIndexes addObject:@(i)];
    }
}

Now, select randomly from the letterIndexes (removing them as we go) to determine which letters shall be upper case.  Convert the member of the chars array at that index to uppercase...
int charsToUppercase = 12;

for (int i=0; i<charsToUppercase && letterIndexes.count; i++) {
    NSInteger randomLetterIndex = arc4random_uniform((u_int32_t)(letterIndexes.count));
    NSInteger indexToUpdate = [letterIndexes[randomLetterIndex] intValue];
    [letterIndexes removeObjectAtIndex:randomLetterIndex];

    [chars replaceObjectAtIndex:indexToUpdate withObject:[chars[indexToUpdate] uppercaseString]];
}

Notice the && check on letterIndexes.count.  This guards against the condition where charsToUppercase exceeds the number of chars.  The upper bound of conversions to uppercase is all of the letters in the original string.
Now all that's left is to join the chars array into a string...
NSString *result = [chars componentsJoinedByString:@""];
NSLog(@"%@", result);

EDIT Looking discussion in OP comments, you could, instead of acharsToUppercase input parameter, be given a probability of uppercase change as an input.  That would compress this idea into a single loop with a little less data transformation...
NSString *string = @"e04325ca24cf20ac6bd6ebf73c376b20ac57192dad83b22602264e92dac076611b51142ae12d2d92022eb2c77f";

float upperCaseProbability = 0.5;
NSMutableString *result = [@"" mutableCopy];

for (int i=0; i<string.length; i++) {
    NSString *chString = [string substringWithRange:NSMakeRange(i, 1)];
    BOOL toUppercase = arc4random_uniform(1000) / 1000.0 < upperCaseProbability;

    if (toUppercase) {
        chString = [chString uppercaseString];
    }
    [result appendString:chString];
}
NSLog(@"%@", result);

However this assumes a given uppercase probability for any character, not any letter, so it won't result in a predetermined number of letters changing case.