text:
Q: jQuery Bootstrap works in Firefox but not IE10 I am running jQuery 2.1 and bootstrap 3.2 my code works in firefox but does not work in IE10. I am thinking that it has something to do with compatability mode so I have tried adding
<meta http-equiv="X-UA-Compatible" content="IE=edge"> to the header... which still did not fix anything.
The docs say IE10 should be find that's why I do not understand what is going on and am assuming there is something I can write in the code to make it work. Even the placeholders for ColdFusion will not appear..
<cfinput
  type="text"
  name="firstname_#Add#"
  placeholder="First"
  validateat="onSubmit"
  validate="noblanks" >
<cfinput
  type="text"
  name="middlename_#Add#"
  placeholder="Middle">

Below is an example that works in Firefox but not IE10.
http://jsfiddle.net/hwcu7e05/5/
This is what the top of my page looks like:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test</title>
<script type="text/javascript" src="../../../js/formactions.js"></script>
<link href="../../../stylesTitles.css" rel="stylesheet" type="text/css" />
<link href="../../../js/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="../../../js/jquery-2.1.1.js"></script>
<script src="../../../js/jquery-ui.js"></script>
<script src="../../../js/myjquery.js"></script>
<script src="../../../js/formfeecalculations.js"></script>
<script src="../../../js/Bootstrap/js/bootstrap.min.js"></script>
<link rel="stylesheet" type="text/css" href="../../../js/Bootstrap/css/bootstrap.min.css">
<style type="text/css">
   body { background-image: url("/images/bg_skyblue.jpg"); }
</style>
</head>

A: You only need CFFORM, CFINPUT, etc. if you want to take advantage of CF's built-in client-side validation. Since you're trying to do something modern, get rid of the CFFORM code and just do simple FORM elements. Odds are, some of the ColdFusion generated JavaScript is interfering with jQuery and jQuery Validate in certain situations.


text:
Q: Is it possible to compile flex 3 charts in intellij? I'm aware that mx.charts is part of flex builder professional.
I've downloaded the trial version of flex builder professional and added the datavisualization.swc to my intellij Flex_sdk classpath. The IDE is now aware of the classes, but when I come to compile I still get:

"Type was not found"

Is there a license or something I need to add to the classpath.
Can anyone give a step by step guide to compiling a flex app that uses charts, either in intellij, or from the command line.
Thanks.

A: It seems that just adding all the swc classes from the FB3 lib directory to my existing jdk, based on the Flex SDK installation didn't work. However when I removed the Flex SDK all together and added a new one, with the sdk directory based on that of FB3 it started to work.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Vim: No lines in buffer I recently got started using Vim but I've started to get this whenever I try to open something with vim:
"[No Name]" --No lines in buffer--
Is there a way to get rid of this? Or could someone explain what's going on?
Thanks


text:
Q: Using dllimport in place of dllexport I seem to be able to use __declspec(dllexport) and __declspec(dllimport) interchangeably when building my dll in Visual Studio 2015. I would have thought when making the DLL that the dllexport command would have been required but it seems either dllexport or dllimport is adequate.I have the following header file declaring a simple add() functions:
add.h
#pragma once

#ifdef ADDDLL_EXPORTS
#define ADDDLL_API __declspec(dllexport)
#else
#define ADDDLL_API __declspec(dllimport)
#endif

ADDDLL_API int add(int x, int y);

with the following definition in a cpp file:
add.cpp
#include "add.h"

int add(int x, int y)
{
    return x + y;
}

I seem to be able to use the built DLL whether ADDDLL_EXPORTS is defined or not in Configuration Properties > Preprocessor > Preprocessor Definitions. For example, in a separate project which includes the .lib file as an additional dependency (Configuration Properties > Linker > Input > Additional Dependencies), I have the following code that runs
main.cpp
#include <iostream>
#include "add.h"

int main()
{
    int sum = add(4, 5);
    std::cout << "sum = " << sum << std::endl;
    std::system("pause");
    return 0;
}

Any insight appreciated. Let me know if more information is needed. Thanks in advance!

A: If you look carefully, you will see that your DLL project compiles with warnings, like this:
 c:\yourproject\add.cpp(3,1):warning C4273: 'add': inconsistent dll linkage

The compiler knows that you are up to no good. A dllimport function should not be defined, only declared. So when the compiler sees the definition, it assumes dllexport should be used instead, because that's the most reasonable resolution of the mistake.
It is a good practice to treat compiler warnings as errors.


text:
Q: asp.net call to server fails I'm trying to call a server method from javascript and the call returns the error message "The server method 'IsQueueEmpty' failed." On the server I have:
protected void Page_Load(object sender, EventArgs e)
{
   (this.Master as MainMaster).ScriptManager.EnablePageMethods = true;
}

[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod(UseHttpGet = true, ResponseFormat = System.Web.Script.Services.ResponseFormat.Json)]
public static bool IsQueueEmtpy()
{
   return true;
}

On the client side I have the following:
<script type="text/javascript">
   function onSuccess(complete) {
      if (!complete) {
         watchQueue();
      }
   }

   function onError(result) {
      alert(result);
   }

   var watchQueue = function () {
      setTimeout(function () {
         PageMethods.IsQueueEmpty(onSuccess, onError);
      }, 2000);
   }

   watchQueue();
</script>

Any suggestions would be greatly appreciated.


text:
Q: How do I generate a list of packages added since installation A number of useful pages show how to generate a list of all installed packages, eg
How do I generate a package download list?
Is there a way to restrict the generated list to those I have added since system installation?
That is, excluding all the packages that were installed from the ISO? and excluding any updates to those packages? Diffing the list generated from the link above with the ISO manifest doesn't quite work because some of the packages in the manifest (eg drivers) are dependent on the hardware and the user selections at install time (eg language).
What I'm looking for is a list of what I have added to the base system.

A: See the answer to How to view a list of packages that were manually installed without their dependancies.
You can list the apt-get command-line commands you have typed since installation of Ubuntu with:
cat /var/log/apt/history.log | grep 'apt-get install '


text:
Q: Recommended Bluetooth Receiver for Speakers? I have normal speakers which can be connected via a 3.5mm jack. I want to use those speakers wirelessly with help of bluetooth, so is there any bluetooth receiver device for such type of speakers ?

A: Yes, indeed there are a few bluetooth receivers out there you can buy.
Altough I don't own one, products made by Logitech never disappointed me. So I'd recommend the Logitech Wireless Speaker Adapter for Bluetooth Audio Devices. It also got good customer reviews on amazon.com.

It features the needed 3,5mm Headphone jack and supports many bluetooth devices(including Android phones and iPhones).
But please do your own research before asking these questions and check out this guide. Stackexchange is not the platform for shopping questions. Also see this site for further information.
Sites that I find useful before purchasing hardware are The Wirecutter and the subreddit /r/BuyItForLife. The last one especially is the place to go for such types of questions.


text:
Q: How to create a dataset to use on Google Colab? I've been trying to create a dataset of QR Codes for a project on Google Colab. I've found pretrained datasets of QR codes that I've attempted to use in my project but every time I get the same error, that the location where the dataset is saved (be it Google My Drive or my hard drive) doesn't exist, so I have shifted to trying to create my own, trying to create one in a MNIST format for example, but I keep getting the same error that the directory doesn't exist. Could anyone give me any advice on what I could possibly try?
I've been able to mount my Google My Drive to the Google Colab Notebook but I can't get it to read the images, I've also tried having it read a location in the hard drive, r"C:/...." for example, "r" to read the location and "...." represents where it is in my hard drive but in every case I'm told that the location doesn't exist.


text:
Q: pyDAL - query records newer than a certain date I have the following query working in pure SQL on SQLite but do not know how to convert it to pyDAL:
SELECT * FROM buy WHERE date('now','-2 days') < timestamp;

The buy table schema is:
CREATE TABLE "buy"(
    "id" INTEGER PRIMARY KEY AUTOINCREMENT,
    "order_id" CHAR(512),
    "market" CHAR(512),
    "purchase_price" DOUBLE,
    "selling_price" DOUBLE,
    "amount" DOUBLE
, "timestamp" TIMESTAMP, "config_file" CHAR(512));

A: Instead of using the SQLite date function, you can create the comparison date in Python:
import datetime
cutoff_time = datetime.datetime.now() - datetime.timedelta(2)
rows = db(db.buy.timestamp > cutoff_time).select()

Alternatively, you can also pass a raw SQL string as the query:
rows = db('buy.timestamp > date("now", "-2 days")').select(db.buy.ALL)

Note, in this case, because the query within db() is simply a string, the DAL will not know which table is being selected, so it is necessary to explicitly specify the fields in the .select() (alternatively, you could add a dummy query that selects all records, such as (db.buy.id != None)).


text:
Q: Two Image paths returned in onActivityResult are getting merged into one resulting in java.io.FileNotFoundException I'm using android-image-picker library for picking photos from Gallery.
Here's the code:
tapToUploadLabel.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            ImagePicker.create(MainActivity.this)
                    .returnAfterFirst(false) // set whether pick or camera action should return immediate result or not. For pick image only work on single mode
                    .imageTitle("Tap to select") // image selection title
                    .single() // single mode
                    .multi() // multi mode (default mode)
                    .limit(3) // max images can be selected (99 by default)
                    .showCamera(true) // show camera or not (true by default)
                    .imageDirectory("Camera") // directory name for captured image  ("Camera" folder by default)
                    .enableLog(false) // disabling log
                    .start(REQUEST_CODE_PICKER); // start image picker activity with request code
        }
    });

Here's onActivtyResult():
@Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_CODE_PICKER && resultCode == RESULT_OK && data != null) {
            ArrayList<Image> images = (ArrayList<Image>) ImagePicker.getImages(data);
            printImages(images);
            mViewPager.setAdapter(mCustomPagerAdapter);
        }
    }

Here's printImages():
private void printImages(List<Image> images) {
        if (images == null) return;

        if (imageArray.size() >= 1) {
            imageArray.clear();
        }

        StringBuilder stringBuffer = new StringBuilder();
        for (int i = 0, l = images.size(); i < l; i++) {
            stringBuffer.append(images.get(i).getPath()).append("\n");
            imageArray.add(Uri.parse(stringBuffer.toString().trim()));
        }
}

Now, I'm using this imageArray to set Image in ImageView like this:
ImageView imageView = (ImageView) itemView.findViewById(R.id.imageView);
Log.d("imageArrayContains", imageArray.get(position).toString());
imageView.setImageURI(imageArray.get(position));

The problem is that when I'm choosing just 1 image, it is getting set in the ImageView without any error but when I'm choosing 2 or more images, I'm getting this error:
E/BitmapFactory: Unable to decode stream: java.io.FileNotFoundException: /storage/emulated/0/Pictures/Kwote/1506843168441.jpg
/storage/emulated/0/Pictures/Camera/IMG_20171001_035028145702152.jpg: open failed: ENOENT (No such file or directory)

because 2 filepaths are getting merged into one like this here: /storage/emulated/0/Pictures/Kwote/1506843168441.jpg
/storage/emulated/0/Pictures/Camera/IMG_20171001_035028145702152.jpg
I'm unable to figure out how can I stop this from getting merged so that I can get all the chosen images loaded in my ImageView.
Please help with this.

A: You are appending both paths in a same StringBuilder.
Place it inside the for loop.
I believe you will not need a StringBuilder at all. Just use imageArray.add(Uri.parse
(images.get(i).getPath().trim()));


text:
Q: When do non-trivial solutions exist, and what are they? We want to find a Möbius transformation $f(z) = \frac{az+b}{cz+d}, \; a,b,c,d \in \mathbb C$ such that
$\begin{cases}z_1 \mapsto w_1 \\ z_2 \mapsto w_2 \\ \vdots \\ z_n \mapsto w_n\end{cases}$
Assuming $z \neq \frac{-d}{c}$ we get to solve the matrix equation
$\begin{pmatrix}z_1 & 1 & -w_1 z_1 & - w_1 \\ z_2 & 1 & -w_2 z_2 & - w_2 \\ \vdots & \vdots & \vdots & \vdots \\ z_n & 1 & -w_n z_n & - w_n \end{pmatrix} \mathbf x = \mathbf 0$ where $\mathbf x = \begin{pmatrix}a \\ b \\ c\\ d \end{pmatrix}$
For $f$ to be a function, we need to assume that $\left(z_i \mapsto w_i \right) \land \left(z_i \mapsto w_j \right)$ aren't true whenever $w_i \neq w_j$ (that is, every element in the domain is mapped to exactly one element in the range). Under this assumption, what can we say about the solutions to the matrix equation? When do they exist and what can we say about them?
Note that the trivial solution $\mathbf x = \mathbf 0$ means a Möbius transformation with our constraints cannot exist because $\mathbf x = \mathbf 0 \implies$ "$f(z) = \frac{0}0$".


text:
Q: Bash iterate through every file but start from 2nd file and get names of 1st and 2nd files I have files all named following the convention:
xxx_yyy_zzz_ooo_date_ppp.tif
I have a python functions that needs 3 inputs: the date of two consecutive files in my folder, and an output name generated from those two dates.
I created a loop that:

*

*goes through every file in the folder

*grabs the date of the file and assigns it to a variable ("file2", 5th place in the file name)

*runs a python function that takes as inputs: date file 1, date file 2, output name

How could I make my loop start at the 2nd file in my folder, and grab the name of the previous file to assign it to a variable "file1" (so far it only grabs the date of 1 file at a time) ?
#!/bin/bash

output_path=path # Folder in which my output will be saved

for file2 in *; do

        f1=$( "$file1" | awk -F'[_.]' '{print $5}' )   # File before the one over which the loop is running
        f2=$( "$file2" | awk -F'[_.]' '{print $5}' )   # File 2 over which the loop is running
        outfile=$output_path+$f1+$f2
        function_python -$f1 -$f2 -$outfile
done

A: You could make it work like this:
#!/bin/bash

output_path="<path>"

readarray -t files < <(find . -maxdepth 1 -type f | sort)     # replaces '*'

for ((i=1; i < ${#files[@]}; i++)); do
    f1=$( echo "${files[i-1]}" | awk -F'[_.]' '{print $5}' )  # previous file
    f2=$( echo "${files[i]}" | awk -F'[_.]' '{print $5}' )    # current file
    outfile="${output_path}/${f1}${f2}"
    function_python -"$f1" -"$f2" -"$outfile"
done

Not exactly sure about the call to function_python though, I have never seen that tool before (can't ask since I can't comment yet).

A: Read the files into an array and then iterate from index 1 instead of over the whole array.
#!/bin/bash
set -euo pipefail

declare -r output_path='/some/path/'
declare -a files fsegments
for file in *; do files+=("$file"); done
declare -ar files  # optional

declare -r file1="${files[0]}"
IFS=_. read -ra fsegments <<< "$file1"
declare -r f1="${fsegments[4]}"

for file2 in "${files[@]:1}"; do  # from 1
  IFS=_. read -ra fsegments <<< "$file2"
  f2="${fsegments[4]}"
  outfile="${output_path}${f1}${f2}"
  function_python -"$f1" -"$f2" -"$outfile"  # weird format!
done


text:
Q: Why signtool.exe very slow with self signed code certificate? I try to generate certificate from
How do I create a self-signed certificate for code signing on Windows?
When using signtool wnd tested it with a list of available timestamp here:
https://gist.github.com/Manouchehri/fd754e402d98430243455713efada710
It took (5 - 10) minutes for sign.
a DLL have few classes only.
Should I use timestamp with non-official self-signed code certificates?
Or ignore timestamp for generated self-signed certificates? I know that purchased certificates must use timestamp.
Edit:
I still have problem. Anyone can help please :(


text:
Q: Java/Arduino - Read data from the Serial Port I've got a program in Java where I have to read the information that an Arduino is sending.
I took the Java code from here. Now, I didn't really understand how it works, but I tried to modify it and I got this:
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.util.Enumeration;

public class Serial implements SerialPortEventListener {
    SerialPort serialPort;

    private static final String PORT_NAMES[] = {
            "/dev/tty.usbserial-A9007UX1", // Mac OS X
            "/dev/ttyUSB0", // Linux
            "COM3", // Windows
    };

    private BufferedReader input;
    private static OutputStream output;
    private static final int TIME_OUT = 2000;
    private static final int DATA_RATE = 115200;

    public void initialize() {
        CommPortIdentifier portId = null;
        Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();

        while (portEnum.hasMoreElements()) {
            CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
            for (String portName : PORT_NAMES) {
                if (currPortId.getName().equals(portName)) {
                    portId = currPortId;
                    break;
                }
            }
        }
        if (portId == null) {
            System.out.println("Could not find COM port.");
            return;
        }

        try {
            serialPort = (SerialPort) portId.open(this.getClass().getName(),TIME_OUT);

            serialPort.setSerialPortParams(DATA_RATE, SerialPort.DATABITS_8, SerialPort.STOPBITS_1,    SerialPort.PARITY_NONE);

            input = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));
            output = serialPort.getOutputStream();

            serialPort.addEventListener(this);
            serialPort.notifyOnDataAvailable(true);
        }
        catch (Exception e) {
            System.err.println(e.toString());
        }
    }

    public synchronized void serialEvent(SerialPortEvent oEvent) {
        if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
            try {
                String inputLine=input.readLine();
                System.out.println(inputLine);
            } catch (Exception e) {
                System.err.println(e.toString());
            }
        }
    }

    public synchronized void close() {
        if (serialPort != null) {
            serialPort.removeEventListener();
            serialPort.close();
        }
    }

    public Serial(String ncom){
        if(Integer.parseInt(ncom)>=3 && Integer.parseInt(ncom)<=9)
            PORT_NAMES[2] = "COM" + ncom;
        initialize();
        Thread t=new Thread() {
            public void run() {
                try {Thread.sleep(1000000);} catch (InterruptedException ie) {}
            }
        };
        t.start();
        System.out.println("Serial Comms Started");
    }

    public synchronized void send(int b){
        try{
            output.write(b);
        }
        catch (Exception e) {
            System.err.println(e.toString());
        }
    }

    public synchronized int read(){
        int b = 0;

        try{
            b = (int)input.read();
        }
        catch (Exception e) {
            System.err.println(e.toString());
        }
        return b;
    }
}

I create the object Serial with the COM port I need in the main program, then I use Serial.read and Serial.write when I need it.
Serial.write works great, Arduino gets the data and show it in a LCD Display. The problem is Serial.read. When the program is running, it keep read from serial port (around every 40 ms), but that doesn't mean Arduino sent something. Arduino sends a byte only when a button is pushed. So, when the Java code is running, it throws "n" Exception before read something, and this couses so much lag.
I know I need something like Serial.available(), I tried input.available(), but it doesn't work. I don't know how to solve this problem.
If you have a code that working, I'd be so much grateful if you could give it to me. I just need two methods, read and write, I don't care how the code works :D
EDIT:
I changed the Serial class, now it has again this method as apremalal said
public synchronized void serialEvent(SerialPortEvent oEvent) {

        if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
            try {

                String inputLine=null;
                if (input.ready()) {
                    inputLine = input.readLine();
                    panel.read(inputLine);
                }

            } catch (Exception e) {
                System.err.println(e.toString());
            }
        }
    }

and in the other class (Panel in this case) I've got this:
public void read(String data){
    System.out.println(data);
    System.out.println(data == "255");
    if(data == "255")
        //code here
}

It print the values correctly but data == "255" is always false, even if I really get a 255
....I tried to do Integer.parseInt but nothing changed. Why the hell?
EDIT 2: Ok solved :\
public void read(String data){

    serialRead = Integer.parseInt(data);

    if(serialRead == 255)
        //code here
}

Now it's work..don't know why I had to do this... meh whatever :)

A: You don't want to specifically write a read function it's already there in the sample code.As TheMerovingian pointed out you can check the input Buffer before reading.Here is the working code which I have used in one of my projects.
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import gnu.io.CommPortIdentifier;
import gnu.io.SerialPort;
import gnu.io.SerialPortEvent;
import gnu.io.SerialPortEventListener;
import java.util.Enumeration;

public class SerialTest implements SerialPortEventListener {
SerialPort serialPort;
    /** The port we're normally going to use. */
private static final String PORT_NAMES[] = {                  "/dev/tty.usbserial-A9007UX1", // Mac OS X
        "/dev/ttyUSB0", // Linux
        "COM35", // Windows
};
private BufferedReader input;
private OutputStream output;
private static final int TIME_OUT = 2000;
private static final int DATA_RATE = 9600;

public void initialize() {
    CommPortIdentifier portId = null;
    Enumeration portEnum = CommPortIdentifier.getPortIdentifiers();

    //First, Find an instance of serial port as set in PORT_NAMES.
    while (portEnum.hasMoreElements()) {
        CommPortIdentifier currPortId = (CommPortIdentifier) portEnum.nextElement();
        for (String portName : PORT_NAMES) {
            if (currPortId.getName().equals(portName)) {
                portId = currPortId;
                break;
            }
        }
    }
    if (portId == null) {
        System.out.println("Could not find COM port.");
        return;
    }

    try {
        serialPort = (SerialPort) portId.open(this.getClass().getName(),
                TIME_OUT);
        serialPort.setSerialPortParams(DATA_RATE,
                SerialPort.DATABITS_8,
                SerialPort.STOPBITS_1,
                SerialPort.PARITY_NONE);

        // open the streams
        input = new BufferedReader(new InputStreamReader(serialPort.getInputStream()));
        output = serialPort.getOutputStream();

        serialPort.addEventListener(this);
        serialPort.notifyOnDataAvailable(true);
    } catch (Exception e) {
        System.err.println(e.toString());
    }
}

public synchronized void close() {
    if (serialPort != null) {
        serialPort.removeEventListener();
        serialPort.close();
    }
}

public synchronized void serialEvent(SerialPortEvent oEvent) {
    if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
        try {
            String inputLine=null;
            if (input.ready()) {
                inputLine = input.readLine();
                            System.out.println(inputLine);
            }

        } catch (Exception e) {
            System.err.println(e.toString());
        }
    }
    // Ignore all the other eventTypes, but you should consider the other ones.
}

public static void main(String[] args) throws Exception {
    SerialTest main = new SerialTest();
    main.initialize();
    Thread t=new Thread() {
        public void run() {
            //the following line will keep this app alive for 1000    seconds,
            //waiting for events to occur and responding to them    (printing incoming messages to console).
            try {Thread.sleep(1000000);} catch (InterruptedException    ie) {}
        }
    };
    t.start();
    System.out.println("Started");
}
}

EDIT : serialEvent function is responsible for reading the buffer.
public synchronized void serialEvent(SerialPortEvent oEvent) {
 if (oEvent.getEventType() == SerialPortEvent.DATA_AVAILABLE) {
    try {
        String inputLine=null;
        if (input.ready()) {
            inputLine = input.readLine();
            System.out.println(inputLine);
        }

    } catch (Exception e) {
        System.err.println(e.toString());
    }
 }
// Ignore all the other eventTypes, but you should consider the other ones.
}

A: The BufferedReader class has a ready() method that returns True if "the buffer is not empty, or if the underlying character stream is ready." and False otherwise. So you could add a check in the read() method to make sure there is data to be read before trying to read.
public synchronized int read(){

    int b = 0;

    try{
        if (input.ready()) {
            b = (int)input.read();
        }
    }catch (Exception e) {
        System.err.println(e.toString());
    }
    return b;
}

It looks like the code has a try-catch in place to handle if those things fail, which is possibly what causes your lag because try-catch are quite expensive. So the input.ready() check should result in fewer exceptions.


text:
Q: How I can add unique words to array from simple long (big) text with minimum loss time? I want get all unique words to array from my long text. You can see my example code here but I thik what it not performance:
$text = $_REQUEST['text'];

$text = mb_strtolower($text);

$text = $this->TimesNewRoman($text);

$text = $this->Tajikan($text);

$text = $this->DSRL($text);

$text = preg_replace("/[^а-яёқӣғҷҳӯў ]/iu", ' ', $text);

$text = array_filter(array_unique(explode(" ", $text)));

$uncorrect_words = $this->WWOSTL($text);

$correct_words = $this->WWSTL($text);

/* Used methods(functions) from my class here */

public function TimesNewRoman($text)
{
    // Correcting Times New Roman Tj Symbols
    $search  = array("ѓ","ї","љ","њ","ќ","ў");
    $replace = array("ғ","ӣ","ҷ","ҳ","қ","ӯ");

    $result  = str_replace($search, $replace, $text);

    return $result;
}

public function Tajikan($text)
{
    // Correcting Tajikan Symbols
    $search  = array("щ","ц","ж","ь","ы","=");
    $replace = array("ғ","ӣ","ҷ","ҳ","қ","ӯ");

    $result  = str_replace($search, $replace, $text);

    return $result;
}

public function DSRL($text) // DELETE SPECIAL RUSSIAN WORDS WITH LETTERS ("ц", "щ", "ы", "ь")
{
    $text = mb_strtolower($text);

    $letters = array("ц", "щ", "ы", "ь");

    $pattern = '/\p{L}*[' . implode("", $letters) . ']\p{L}*/u';

    $text = preg_replace($pattern, '', $text);

    return $text;
}

public function WWSTL($array_words) // GET Words With Special Tajik Letters ("қ", "ҳ", "ҷ", "ӯ", "ғ", "ӣ", "ў")
{
    $letters = array("қ", "ҳ", "ҷ", "ӯ", "ғ", "ӣ", "ў");

    $pattern = '/[' . implode("", $letters) . ']/u';

    $result = preg_grep($pattern, $array_words);

    return $result;
}

public function WWOSTL($array_words) // GET Words Without Special Tajik Letters ("қ", "ҳ", "ҷ", "ӯ", "ғ", "ӣ", "ў")
{
    $letters = array("қ", "ҳ", "ҷ", "ӯ", "ғ", "ӣ", "ў");

    $pattern = '/[' . implode("", $letters) . ']/u';

    $result = preg_grep($pattern, $array_words, PREG_GREP_INVERT);

    return $result;
}

Please tell us your opinion about the reduction, optimization and acceleration of the process and code. Maybe where it is superfluous codes, I can do something wrong. It should be noted that my text will be very large and I need to optimize my code to work with such a large amount of text. Help if you have any of your options for optimizing and speeding up the process of text processing. Thank you all in advance.
Example my small text:
$text = "Русия ва вазъи сиёсию иқтисодӣ  ва фарҳангии   Осиёи Миёна,
бахусус аморати Бухоро мегардад. Маорифпарвар яке аз
роҳҳои дигаргунсозии   ҷомеаро дар маърифатнокшавии
амиру ҳокимон, нест кардани зулм ва ислоҳоти ислом
медонист. Ислоҳоте, ки ў пешниҳод мекард, хислати
гуманистӣ  – инсонпарварӣ  дошт. Масъалаи инсон дар
маркази фалсафаи иҷтимоию сиёсии   ў меистод ва ин
таълимоти ў нисбат ба анъанаҳои классикӣ  бештар хислати
прогрессивию навин доштанд. Андешаҳои маорифпарварии
мутафаккир дар асарҳояш «Наводир –ул-вақоеъ» ва дар
«Васоёти фарзандон ва баёни ҳақиқати касбҳову пешаҳо»
баён шудаанд. Дар ин асарҳо А. Дониш роҳҳои азнавсозии
ҷамъиятро ба воситаи идеалҳои озодӣ , баробарӣ , бародарӣ ,
муттаҳидӣ  ва идеалҳое, ки ҳанўз дар асрҳои ХVII- ХVIII дар
Аврупо пайдо шуда буданд (ҳимояи адолати иҷтимоӣ , рушди
илму маориф, қадру қимати инсонӣ ) тарғиб менамояд.
3. Анъанаҳои фалсафаи рус
Давраи нисбатан озоди анъанаи фалсафаи рус аз
ташкилёбии   Донишгоҳи Москав (1755) оғоз меёбад.
Профессори аввалини факултаи фалсафаи ин донишгоҳ Н.И.
Поповский аз анъанаи курси фалсафии   лотинӣ  ба забони
русии   фалсафа гузаштанро даъват намуд. Вале сарфи назар
аз ин ташаббус афкори фалсафӣ  аз фишори сензураи
давлатӣ -калисоӣ  озод набуд.
Табиати эҳёгароии   фарҳангу фалсафаи рус дар эҷодиёти
мутафаккирон М.В.Ломоносов ва А.Н.Радишев бо низоми
нисбатан озоду равшан инъикос меёбад. Онҳо ба андозае
синтези фарҳанги атиқӣ  ва насрониро ба даст оварда бештар
майли маорифпарварӣ  доштанд.
Ломоносов ҳамчун табиатшиноси барҷаста (асосгузори
қонуни нигаҳдории   масса ва энергия)- поягузори анъанаи
материалистӣ  дар фалсафаи рус, Радишев аввалин шуда дар
ҷаҳонбинии   рус масъалаи инсонро ҳамчун арзиши муҳим
муайян намуд ва ба анъанаи маорифпарварии   инқилобӣ  ибтидо
гузошт. Чунин тарзи гузориши масъала дар ақидаҳои
45
декабристон ва демократҳои инқилобӣ  (Белинский, Герсен,
Чернишевский ва диг.) ифода ёфт. Хусусияти фалсафаи рус
робитаи ақоидии   васеъ ҳам бо Ғарбу ва ҳам бо Шарқ мебошад.
Ҳамчун натиҷаи бўҳрони материализми механикӣ  ва
метафизикӣ  дар солҳои 30-юми асри ХIХ дар фалсафаи
Русия тағйири тамоил ба диалектикаи идеалистӣ  ба амал
меояд ва ингуна тамоил ба гузариши ақидаҳои
натурфалсафаи мутафаккирони рус ба мавқеи идеализм ва
дин таъсир мерасонад (Чаадаев).
Ҷустуҷўи хусусияти инкишофи иҷтимоии   Русия дар
маркази фалсафаи рус дарки вазифаҳои миллиро мегузорад.
Инқилобчиён-демократҳои рус – Белинский, Герсен,
Чернишевский консепсияи сотсиализми деҳқонӣ ,
общинагиро пешниҳод намуданд.
Файласуфони динӣ  – славянофилҳо (Киреевский,
Хомяков, Данилевский)- роҳи славянии   инкишофи ҷомеаро
аз диди таълимоти дини насронӣ  азнавсозии   навъи олмонии
тафаккури фалсафиро тарғиб менамуданд. Дар ин ҷараён
фалсафаи В.С.Соловьев низоми хосро ташкил мекард.
Чунончи, аз ҷониби ў таҳлил намудани ягонагии   олам, инсон
ва соҳаи ғайриҳастӣ  (Худо); назарияи маърифатии   ў – бо
роҳи интуитивӣ , инъикоси рамзӣ  - символикӣ  ба ҳақиқат
ноил гардидан.
В.С.Соловьев мақоми хосро дар ҷараёни славянофилҳо
ишғол мекунад. Фалсафаи аз ҳама пурарзиш ба ақидаи
В.С.Соловьев фалсафаи тасаввуф мебошад, ки на бо тарғиби
берунии   ҳодисаҳо, балки бо тартиби ботинии   мавҷудот ва
ҳаёти онҳо машғул аст ва ҳаёти ин мавҷудотро муносибати
онҳо ба ҳастии   нахустибтидо муайян менамояд.
Моҳияти империяи Русияро В.Соловьев дар умумияти
аз миллат волотари Шарқу Ғарб мебинад. Русия, - мегўяд ў, -
натанҳо халқи рус, балки «оилаи халқҳо», ки на бо зўрӣ ,
ихтиёрӣ  муттаҳид шудаанд. Мутафаккир умуман муқобили
ҳамагуна ғуломӣ  ва системаи ҷомеаи ба ғуломӣ  асос ёфта
46
буд. Тафаккури асили фалсафа ба ақидаи ў ҷустуҷўи
мунтазами ҳақиқати боэтимод мебошад.
Фалсафаи рус дар ин давра бо фарҳанги ватанашон, ба
хусус ба адабиёти он робитаи зич дошт.
Фалсафаи рус, ки дар ду даҳсолаи аввали асри ХХ таҳти
таъсири фалсафаи марксизм қарор надошт, мебоист роҳи
ояндаашро интихоб намояд. Аз Ғарб ба Русия неокантчигӣ ,
неогогелчигӣ , фалсафаи ҳаёт таъсир доштанд. Вале
файласуфони рус мекушиданд, то ҷабҳаи инсонгароии   ин
ҷараёнҳои фалсафиро инкишоф диҳанд.
Равияи дигаре, ки дар таҳти таъсири табиатшиносӣ
ташаккул ёфта аст, космизми рус мебошад (Н.Ф.Федоров,
Ф.С.Соловьев, Н.А.Умов, К.Э.Циолковский ,
В.И.Вернадский ва дигарон). Масъалаи ягонагии   инсону
коинот ва табиати коинотии   инсон мавриди таҳлили ин
ҷараён қарор мегирад.
4. Фалсафа дар СССР
Тафаккури фалсафӣ  дар СССР бо хусусиятҳои миллӣ -
минтақавии   давлати сермиллат роҳи басо мураккабу
зиддиятнокро дар давоми 70 соли сохти Шўравӣ  тай
карда аст. Бурду бохтҳои фалсафа дар ин давра бо вазифаҳои
табаддулотҳои инқилобӣ  дар мамлакат, идеологияи
ҳукмрони коммунистӣ , мақоми роҳбарикунандагии   ҳизби
коммунистӣ  дар ҳамаи соҳаҳои иқтисодию иҷтимоӣ  ва
фарҳангию сиёсӣ  робитаи зич дошт. Дигар ҷиҳати инкишофи
фалсафа самти аз байн рафтани гуфтугўи файласуфони
марксистӣ  бо намояндагони дигар ҷараёнҳои фалсафӣ  буд.
Мубоҳисаҳои (дискуссияҳои) солҳои 20-ум, 30-юм, 40-
ум ба раванди рушди фалсафа дигаргуниҳо меандохтанд ва
баъзан файласуфонро ба ҷараёнҳои мухталиф ҷудо
мекарданд.
Муноқишаҳои аввалин (солҳои 20-ум) дар доираи
масъалаи мақоми фалсафаи марксистӣ , муносибати ў ба
илмҳои табиатшиносӣ  буд.
47
Тибқи ақидаҳои файласуфони ба ном «механистон»
фалсафа чун илми мустақил шуда наметавонад, ў бояд бо
хулосаҳои илми табиатшиносӣ  якҷоя бошад. Барои
«диалектикҳо» фалсафаи марксистӣ  дорои мазмуни хос ва
мустақил буда, вазифаи методологию маърифатиро иҷро
менамояд.
Хулосаи мубоҳисаҳои солҳои 30-юм сиёсигардонии
пурраи назария ва принсипи ҳизбиятии   илми фалсафа ва
тамоми соҳаи ҷамъиятшиносӣ  гардид. Ҳамзамон барномаи аз
ҷониби Ленин муайян кардашудаи тадқиқотҳои таърихи
фалсафа ба роҳ монда шуда буд. Файласуфони шўравӣ  дар
ин давра диққати ҷиддӣ  ба тадқиқот ва нашри таърихи
материализм, таърихи диалектика, инкишофи сотсиализми
хаёлӣ  равона карда буданд. Тарҷумаи асарҳои файласуфони
материалисти фаронсавӣ , англисӣ , олмонӣ  ва бисёр дигар
асарҳои таърихӣ  нашр мешаванд.
Дискуссияи соли 1947 ба муҳокимаи асари таълимии
Г.Ф.Александров «Таърихи фалсафаи Аврупои Ғарбӣ »
бахшида шуда буд. Аз муҳокимаҳо хулоса бармеояд, ки ин
асар ғайримарксистӣ  буда нақши инқилобии   марксизмро дар
фалсафа аз эътибор дур карда аст.
Танқиди шахсиятпарастии   Сталин дар съезди ХХ-уми
ҳизби коммунистӣ , баъдан азнавсозии   Горбачёв ба тамоюли
аз чорчўбаи догматизм озод шудани фалсафа, ба танзими
ақоидҳои гуногун ва гуфтугўи тамаддунҳо имконият
фароҳам оварданд.
Соли 1971 дар назди АУ СССР Ҷамъияти фалсафӣ
ташкил меёбад, ки 8000 аъзоёни шахсӣ  ва 200 аъзоёни
коллективиро муттаҳид намуд. Дар солҳои фаъолияташ ин
ҷамъияти ихтиёрӣ  барои рушди эҷодии   тафаккури фалсафӣ
дар мамлакат, ҷумҳуриҳои алоҳида ва рушди робитаҳои
илмии   файласуфони шўравӣ  бо файласуфони хориҷӣ  саҳми
арзанда гузошт. Худи Ҷамъияти фалсафии   СССР аъзои
баробарҳуқуқи Федератсияи байналмилалии   ҷамъиятҳои
фалсафӣ  буд.
48
Бешубҳа, ҷараёни инкишофи илм, фалсафа ҳам дар ин
ҷумла, бе бархурии   низомҳои гуногуни арзишҳо намешавад.
Муҳимтаринаш дар ин ҷараён донистани волоияти арзишҳои
умумибашарӣ , ҳамдигарро ғанӣ  гардонида ва дар замони
ҷаҳонишавӣ  нигоҳ дошта тавонистани анъанаҳои миллӣ
мебошад. Ҳамин буд, ки дар СССР як зумра арбобони илми
фалсафа – Б.М. Кедров, В.Ф. Асмус, А.Ф. Лосев, Э.В.
Илъекков, М.М. Розентал, П.К. Анохин, Т.И. Ойзерман, М.Ф.
Овсяников ва дар ҳар як ҷумҳурият файласуфони номдор
тарбия ёфта ба хазинаи афкори фалсафӣ  саҳмгузор
гардиданд.
5. Мактабҳои фалсафии   Ғарб
Кўшиши тасвири нави олам
Фалсафаи асри ХХ кўшиш менамояд, то манзараи
оламро дар тағйирот ифода намояд, танқиди ратсионализму
илм, ки аз ҷониби ба ном «фалсафаи ҳаёт» ва дигар ҷараёнҳо
қарор гирифта буд, маҳдудияти усули хиради ақлиро дар
маърифат нишон медиҳад. Вале инкишофу фаҳмиши
идеяҳои умедбахш басо мушкил буданд, зеро онҳо бо
омезиши тасаввуротҳо, далелҳо ва хулосаҳои идеалистӣ
пешниҳод мешуданд.
Кўшиши аз нав сохтани манзараи олам аз тарафи
файласуфи Фаронса Бергсон мушоҳида карда мешуд. Дар
таълимоти пайравони «фалсафаи ҳаёт» Бергсон, Нитсше,
Шпенглер чунин манзараи оламро мегузоранд, ки дар асоси
он фаҳмиши нави эволютсияи табиат, инкишофи инсон ва
ягонагии   онҳо истода бошад. Ба ақидаи онҳо материя тобеи
ҳаёт, эволютсияи олам ҳам ба туфайли ҳаёт тағйир меёбад.
Тасаввуроти субъективӣ -идеалистӣ  доир ба тасвири
нави олам дар фалсафаи эмпериокритисизм дида мешавад.
Мах, Авенариус, Богданов, Базаров кулли ҳастиро моҳиятан ";

A: The efficient way of doing this is first sorting the words alphabetically and then scanning through the array while keeping only the first occurrence of each word. This gives you O(n*log(n)) complexity. And this is exactly what happens internally inside array_unique().

A: like matey said
    array_unique
is the fastest
but you can try to use explode and then foreach:
foreach($words as $word){
   if(!isset($uniqueWords[$word])){
    $uniqueWords[$word] = 1;
   }
}

maybe it fits more your intention because you can make more things in the if block with the words


text:
Q: JDFPrintProcessor ERROR: Could not put job on SSQ When trying to run the Adobe PDF Print Engine (APPE) with a command like:
.\JDFPrintProcessor.exe -injdf "C:\Temp\PrintMyPDF.jdf" -outdir "C:\Temp\output"

I get the following error:
_________________
JDFPrintProcessor ERROR: Could not put job on SSQ.

Terminating JDF Print Processor

A: The required format for -injdf absolute file paths is 'file:///...' (but not for other parameters).  E.g.
.\JDFPrintProcessor.exe -injdf "file:///c:/Temp/PrintMyPDF.jdf" -outdir "C:\Temp\output"

Correct output is:
>>>> Submitting J O B  0 to JDF Player <<<<<
>>>> Job 0 was received on command line
>>>> Job 0 URL is file:///c:/Temp/PrintMyPDF.jdf
[TiffFile: PrintMyPDF001_p00.tif,1,0,Cyan,5100x6600]
[TiffFile: PrintMyPDF001_p01.tif,1,1,Magenta,5100x6600]
[TiffFile: PrintMyPDF001_p02.tif,1,2,Yellow,5100x6600]
[TiffFile: PrintMyPDF001_p03.tif,1,3,Black,5100x6600]
[JobTime Job 0: PrintMyPDF, 0.652 sec.]

<<<<< Job 0 processing completed: Successful >>>>>

Terminating JDF Print Processor

Hope this saves someone some time (including my future self)


text:
Q: what does the flag VM_IOREMAP in vmalloc.c in mean? http://lxr.free-electrons.com/source/include/linux/vmalloc.h?v=3.4;a=arm#L11
There are bunch of flags for vm_struct in vmalloc.c. I can understand VM_ALLOC, which means the vm_struct is constructed by the vmalloc() call.
But what do the other flags mean? Particularly the VM_IOREMAP. It is used in Android binder driver.
http://lxr.free-electrons.com/source/drivers/staging/android/binder.c?v=3.4;a=arm#L2819

A: define VM_IOREMAP      0x00000001  /* ioremap() and friends */
VM_IOREMAP means this virtual memory region is created by ioremap(), * ususally * ( but * not limited to *) to map a I/O memory region ( featured by its physical address ) of a hardware device ( like a PCI device) into kernel virtual address range, so we can access the I/O memory by simple read / write.
Not go into driver detail much, But in Android binder driver you mentioned, it seems the driver is using it to implement mmap() system call, which is to share a set of RAM pages ( not device I/O memory region) between driver and user-space code.  So after user-space code mmap() the driver char device file, it could direct access those RAM pages directly from user-level without do a kernel-user-level transition.  The common usage of this coding trick (as far as I remember for other driver cases ) is, driver produce data content into those RAM pages in kernel-level,  user-level code read data content of those RAM pages directly from user-level.


text:
Q: Page display error after changing base url I am setting up a new Magento 2 store on AWS.
After installed M2 on my server (13.210.72.64), the site'base url was 13.210.72.64/magento2 and then I changed it to 13.210.72.64 in the admin panel(configuration->web). The site now is not working correctly.
I am pretty new to Magento 2.
Please help me out.Any help is greatly appreciated.

A: Please check your base URL in database you can find it on core_config_data table, If its not correct then please change it. If its correct (I mean which you want) then there should be cache issue, please try to execute below magento 2 commands,
php bin/magento cache:flush

php bin/magento s:s:d

php bin/magento setup:di:compile

A: you should copy all your website file to the web folder of your server like this :
in magento2/  folder run :

*

*cp -r * ../

*sudo chmod -R 777 ../

*cd ..

*php bin/magento setup:di:compile
-php bin/magento setup:static-content:deploy

*chmod -R 777 *


text:
Q: Enable FlipView only when specific UI element is touched I have a FlipView control which is used to navigate between two pages. I would like to have the FlipView control only animating to the second page when a specific UI element on the first page is dragged.
I managed to disable the FlipView by setting
ManipulationMode = "None";

On the first FlipViewItem.
I then tried to re-enable the FlipView when the UI element inside the first FlipViewItem was touched (ManipulationStarted event). The problem I'm facing, is that the ManipulationStarted event is not getting triggered, and therefor have no way of enabling the FlipView when needed... Is there an easy way to fix this?


text:
Q: MySQL Query Question to finde value in string i have a simple (i hope its simple) question.
In my database, i have an entry like this:

Now, i need a response with true or a count if the '514' in 'error_code' is in the string 'count_alarm'. In this example it returns zero because 514 isnt in count_alarm.
I beginns the query, but i dont know how i can solve this query:

select count(*) from table where sID='56df32a1463d4387' and [if
error_code in count_alarm then True]

Somebody an idea?

A: find_in_set can parse comma separated fields:
select count(*)
from your_table
where sID = '56df32a1463d4387'
and find_in_set(error_code, replace(count_alarm, '|', ',')) > 0

or use instr
where sID = '56df32a1463d4387'
and instr(count_alarm, concat('|', error_code, '|')) > 0

A: Perhaps you can just use REGEXP here:
SELECT COUNT(*) AS cnt
FROM yourTable
WHERE sID = '56df32a1463d4387' AND
      count_alarm REGEXP CONCAT('[[:<:]]', error_code, '[[:>:]]');

A: select count(sID) as n514 from table where sID='56df32a1463d4387'
and count_alarm like '%|514|%'

The LIKE operator searches for the pattern |514| anywhere in the value under count_alarm.
The assumption is that the first and last character of that value is this character | else 514 would not be found if it is the first or last pattern within that value.


text:
Q: Found nil while unwrapping optional value You might think: "another post about this error".
Yes, i've been looking into this forum before writing this question and unfortunately i couldn't find something that could help, or atleast i know that this error gets on when there is a var that is not bound.
However since im quite new into this, i'd like some help.
I'm following a guide to make a simple infinite side scroller game.
So far everything went good but then i encountered this "nill" error.
The guide itself does not have this error.
So i tought maybe it could be that i use a newer version of xCode or iphone simulation. But im pretty sure its not about that.
My codings so far:
import Foundation

class MainScene: CCNode {
    weak var hero: CCSprite!

    func didLoadFromCCB() {
       userInteractionEnabled = true
    }

    override func touchesBegan(touch: CCTouch!, withEvent event: CCTouchEvent!) {
       // This is the error line. I think it is caused by (applyImpulse(ccp(0, 400)) )
        hero.physicsBody.applyImpulse(ccp(0, 400))
    }
}

How can i simply fix this?
should i make a variable with applyImpulse?
I also tried to switch between CGPoint (ccp) and CCPackage, both didn't worked.

A:   weak var hero: CCSprite!

This is incredibly dangerous and likely the cause of your problem. Besides using !, which is almost always to be avoided, this mixes it with weak. That means that if something else stops pointing to hero, this variable becomes an implicitly unwrapped nil. The next time you access it, you crash.
First, get rid of the !. If it needs to be weak, use ?. Beyond that, decide if it should really be strong. nothing you've shown here suggests that it should be weak.

A: I think the error code above can cause much confusion for new people because we don't know what is "optional" in swift 2.0 vs older versions of swift.  For example I was getting the same error and could not tell where the problem was.  What I found out is that I was making a call to a method using parenthesis () and in the same function I called the method without the parenthesis.  This caused the error above.  The () are an optional component that became optional with Swift 2.0 the way I understand it.  You have to be consistent when calling the methods otherwise the compiler will throw the "Found nil error while unwrapping an optional value".  Here is my code: The method I called inconsistently was NSDirectoryEnnumerationOptions().  This is corrected in the example I am sharing:
      func listFilesWithFilter() -> [String]
{
NSFileManager().URLForDirectory(.DocumentDirectory, inDomain: .UserDomainMask, appropriateForURL: nil, create: true)
    let musicUrl = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).first!
    do{
        let fileList = try NSFileManager.defaultManager().contentsOfDirectoryAtURL(musicUrl,includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions())
        print(fileList)
    } catch let error as NSError {
        print(error.localizedDescription)
    }
    // filter for wav files
    do {
        let directoryUrls = try NSFileManager.defaultManager().contentsOfDirectoryAtURL(musicUrl, includingPropertiesForKeys: nil, options: NSDirectoryEnumerationOptions())
        print(directoryUrls)
        let wavFiles = directoryUrls.filter(){ $0.pathExtension == "wav"}.map{ $0.lastPathComponent}
        print ("WavFiles:\n" + wavFiles.description)
    } catch let error as NSError {
        print(error.localizedDescription)
    }
    return wavFiles
    }


text:
Q: How can I enable Worker in an existing Nextjs project? I realised that I would like to make use of a Worker in my Nextjs project but since it's already created, how can I enable this?
At the time of creating the project I could have used npx create-next-app --example with-web-worker but how can I add this option once the project has been created?
Running the following command in my existing project isn't working
npx create-next-app . --with-web-worker

Output:
npx: installed 1 in 3.02s
The directory src contains files that could conflict:

  .env.local
  .eslintrc.json
  .next/
  .prettierignore
  .prettierrc.json
  Dockerfile
  README.md
  my-app/
  next.config.js
  node_modules/
  package-lock.json
  package.json
  pages/
  public/
  styles/
  with-web-worker/
  workers/

Either try using a new directory name, or remove the files listed above.

Trying to use create-next-app but in a different directory as suggested, below is what I experienced.
Success! Created with-web-worker-app at /src/test/with-web-worker-app
Inside that directory, you can run several commands:

  npm run dev
    Starts the development server.

  npm run build
    Builds the app for production.

  npm start
    Runs the built app in production mode.

We suggest that you begin by typing:

  cd with-web-worker-app
  npm run dev

Now running: npm run dev
> @ dev /src/test/with-web-worker-app
> next dev

ready - started server on 0.0.0.0:3000, url: http://localhost:3000
error - Failed to load next.config.js, see more info here https://nextjs.org/docs/messages/next-config-error
Error: Not supported
    at Object.loadConfig [as default] (/src/test/with-web-worker-app/node_modules/next/dist/server/config.js:399:74)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! @ dev: `next dev`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the @ dev script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2021-10-28T11_40_34_433Z-debug.log
root@70c71730b6de:/src/test/with-web-worker-app# cat /root/.npm/_logs/2021-10-28T11_40_34_433Z-debug.log

So I copied the next.config.js file from the parent folder and reran npm run dev
Same output
> @ dev /src/test/with-web-worker-app
> next dev

ready - started server on 0.0.0.0:3000, url: http://localhost:3000
error - Failed to load next.config.js, see more info here https://nextjs.org/docs/messages/next-config-error
Error: Not supported
    at Object.loadConfig [as default] (/src/test/with-web-worker-app/node_modules/next/dist/server/config.js:399:74)
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! @ dev: `next dev`
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the @ dev script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.

npm ERR! A complete log of this run can be found in:
npm ERR!     /root/.npm/_logs/2021-10-28T11_43_50_236Z-debug.log

Update
I created /test outside the /src folder and ran /test# npx create-next-app --example with-web-worker webworkerapp
And I got
Success! Created webworkerapp at /test/webworkerapp
Inside that directory, you can run several commands:

  npm run dev
    Starts the development server.

  npm run build
    Builds the app for production.

  npm start
    Runs the built app in production mode.

We suggest that you begin by typing:

  cd webworkerapp
  npm run dev

Now /test/webworkerapp# npm run dev
Output:
> @ dev /test/webworkerapp
> next dev

ready - started server on 0.0.0.0:3000, url: http://localhost:3000
event - compiled successfully in 10.2s (159 modules)
Attention: Next.js now collects completely anonymous telemetry regarding usage.
This information is used to shape Next.js' roadmap and prioritize features.
You can learn more, including how to opt-out if you'd not like to participate in this anonymous program, by visiting the following URL:
https://nextjs.org/telemetry

wait  - compiling /_error...
event - compiled successfully in 918 ms (160 modules)
Error [ERR_METHOD_NOT_IMPLEMENTED]: The _write() method is not implemented
    at Writable._write (_stream_writable.js:566:6)
    at doWrite (_stream_writable.js:415:12)
    at clearBuffer (_stream_writable.js:545:7)
    at Writable.uncork (_stream_writable.js:319:7)
    at /test/webworkerapp/node_modules/next/dist/server/render.js:976:17
    at /test/webworkerapp/node_modules/next/dist/server/render.js:960:13
    at rhs (/test/webworkerapp/node_modules/next/dist/server/render.js:960:47)
    at /test/webworkerapp/node_modules/next/dist/server/render.js:978:9
    at /test/webworkerapp/node_modules/next/dist/server/render.js:960:13
    at Promise (/test/webworkerapp/node_modules/next/dist/server/render.js:991:9)
wait  - compiling /...
event - compiled successfully in 1867 ms (193 modules)
Error [ERR_METHOD_NOT_IMPLEMENTED]: The _write() method is not implemented
    at Writable._write (_stream_writable.js:566:6)
    at doWrite (_stream_writable.js:415:12)
    at clearBuffer (_stream_writable.js:545:7)
    at Writable.uncork (_stream_writable.js:319:7)
    at /test/webworkerapp/node_modules/next/dist/server/render.js:976:17
    at /test/webworkerapp/node_modules/next/dist/server/render.js:960:13
    at rhs (/test/webworkerapp/node_modules/next/dist/server/render.js:960:47)
    at /test/webworkerapp/node_modules/next/dist/server/render.js:978:9
    at /test/webworkerapp/node_modules/next/dist/server/render.js:960:13
    at Promise (/test/webworkerapp/node_modules/next/dist/server/render.js:991:9)
error - Error [ERR_METHOD_NOT_IMPLEMENTED]: The _write() method is not implemented
Error [ERR_METHOD_NOT_IMPLEMENTED]: The _write() method is not implemented
    at Writable._write (_stream_writable.js:566:6)
    at doWrite (_stream_writable.js:415:12)
    at clearBuffer (_stream_writable.js:545:7)
    at Writable.uncork (_stream_writable.js:319:7)
    at /test/webworkerapp/node_modules/next/dist/server/render.js:976:17
    at /test/webworkerapp/node_modules/next/dist/server/render.js:960:13
    at rhs (/test/webworkerapp/node_modules/next/dist/server/render.js:960:47)
    at /test/webworkerapp/node_modules/next/dist/server/render.js:978:9
    at /test/webworkerapp/node_modules/next/dist/server/render.js:960:13
    at Promise (/test/webworkerapp/node_modules/next/dist/server/render.js:991:9)
Error [ERR_METHOD_NOT_IMPLEMENTED]: The _write() method is not implemented
    at Writable._write (_stream_writable.js:566:6)
    at doWrite (_stream_writable.js:415:12)
    at clearBuffer (_stream_writable.js:545:7)
    at Writable.uncork (_stream_writable.js:319:7)
    at /test/webworkerapp/node_modules/next/dist/server/render.js:976:17
    at /test/webworkerapp/node_modules/next/dist/server/render.js:960:13
    at rhs (/test/webworkerapp/node_modules/next/dist/server/render.js:960:47)
    at /test/webworkerapp/node_modules/next/dist/server/render.js:978:9
    at /test/webworkerapp/node_modules/next/dist/server/render.js:960:13
    at Promise (/test/webworkerapp/node_modules/next/dist/server/render.js:991:9)
error - Error [ERR_METHOD_NOT_IMPLEMENTED]: The _write() method is not implemented
Error [ERR_METHOD_NOT_IMPLEMENTED]: The _write() method is not implemented
    at Writable._write (_stream_writable.js:566:6)
    at doWrite (_stream_writable.js:415:12)
    at clearBuffer (_stream_writable.js:545:7)
    at Writable.uncork (_stream_writable.js:319:7)
    at /test/webworkerapp/node_modules/next/dist/server/render.js:976:17
    at /test/webworkerapp/node_modules/next/dist/server/render.js:960:13
    at rhs (/test/webworkerapp/node_modules/next/dist/server/render.js:960:47)
    at /test/webworkerapp/node_modules/next/dist/server/render.js:978:9
    at /test/webworkerapp/node_modules/next/dist/server/render.js:960:13
    at Promise (/test/webworkerapp/node_modules/next/dist/server/render.js:991:9)
Error [ERR_METHOD_NOT_IMPLEMENTED]: The _write() method is not implemented
    at Writable._write (_stream_writable.js:566:6)
    at doWrite (_stream_writable.js:415:12)
    at clearBuffer (_stream_writable.js:545:7)
    at Writable.uncork (_stream_writable.js:319:7)
    at /test/webworkerapp/node_modules/next/dist/server/render.js:976:17
    at /test/webworkerapp/node_modules/next/dist/server/render.js:960:13
    at rhs (/test/webworkerapp/node_modules/next/dist/server/render.js:960:47)
    at /test/webworkerapp/node_modules/next/dist/server/render.js:978:9
    at /test/webworkerapp/node_modules/next/dist/server/render.js:960:13
    at Promise (/test/webworkerapp/node_modules/next/dist/server/render.js:991:9)
Error [ERR_METHOD_NOT_IMPLEMENTED]: The _write() method is not implemented
    at Writable._write (_stream_writable.js:566:6)
    at doWrite (_stream_writable.js:415:12)
    at clearBuffer (_stream_writable.js:545:7)
    at Writable.uncork (_stream_writable.js:319:7)
    at /test/webworkerapp/node_modules/next/dist/server/render.js:976:17
    at /test/webworkerapp/node_modules/next/dist/server/render.js:960:13
    at rhs (/test/webworkerapp/node_modules/next/dist/server/render.js:960:47)
    at /test/webworkerapp/node_modules/next/dist/server/render.js:978:9
    at /test/webworkerapp/node_modules/next/dist/server/render.js:960:13
    at Promise (/test/webworkerapp/node_modules/next/dist/server/render.js:991:9)
error - Error [ERR_METHOD_NOT_IMPLEMENTED]: The _write() method is not implemented
Error [ERR_METHOD_NOT_IMPLEMENTED]: The _write() method is not implemented
    at Writable._write (_stream_writable.js:566:6)
    at doWrite (_stream_writable.js:415:12)
    at clearBuffer (_stream_writable.js:545:7)
    at Writable.uncork (_stream_writable.js:319:7)
    at /test/webworkerapp/node_modules/next/dist/server/render.js:976:17
    at /test/webworkerapp/node_modules/next/dist/server/render.js:960:13
    at rhs (/test/webworkerapp/node_modules/next/dist/server/render.js:960:47)
    at /test/webworkerapp/node_modules/next/dist/server/render.js:978:9
    at /test/webworkerapp/node_modules/next/dist/server/render.js:960:13
    at Promise (/test/webworkerapp/node_modules/next/dist/server/render.js:991:9)
Error [ERR_METHOD_NOT_IMPLEMENTED]: The _write() method is not implemented
    at Writable._write (_stream_writable.js:566:6)
    at doWrite (_stream_writable.js:415:12)
    at clearBuffer (_stream_writable.js:545:7)
    at Writable.uncork (_stream_writable.js:319:7)
    at /test/webworkerapp/node_modules/next/dist/server/render.js:976:17
    at /test/webworkerapp/node_modules/next/dist/server/render.js:960:13
    at rhs (/test/webworkerapp/node_modules/next/dist/server/render.js:960:47)
    at /test/webworkerapp/node_modules/next/dist/server/render.js:978:9
    at /test/webworkerapp/node_modules/next/dist/server/render.js:960:13
    at Promise (/test/webworkerapp/node_modules/next/dist/server/render.js:991:9)
Error [ERR_METHOD_NOT_IMPLEMENTED]: The _write() method is not implemented
    at Writable._write (_stream_writable.js:566:6)
    at doWrite (_stream_writable.js:415:12)
    at clearBuffer (_stream_writable.js:545:7)
    at Writable.uncork (_stream_writable.js:319:7)
    at /test/webworkerapp/node_modules/next/dist/server/render.js:976:17
    at /test/webworkerapp/node_modules/next/dist/server/render.js:960:13
    at rhs (/test/webworkerapp/node_modules/next/dist/server/render.js:960:47)
    at /test/webworkerapp/node_modules/next/dist/server/render.js:978:9
    at /test/webworkerapp/node_modules/next/dist/server/render.js:960:13
    at Promise (/test/webworkerapp/node_modules/next/dist/server/render.js:991:9)
error - Error [ERR_METHOD_NOT_IMPLEMENTED]: The _write() method is not implemented
Error [ERR_METHOD_NOT_IMPLEMENTED]: The _write() method is not implemented
    at Writable._write (_stream_writable.js:566:6)
    at doWrite (_stream_writable.js:415:12)
    at clearBuffer (_stream_writable.js:545:7)
    at Writable.uncork (_stream_writable.js:319:7)
    at /test/webworkerapp/node_modules/next/dist/server/render.js:976:17
    at /test/webworkerapp/node_modules/next/dist/server/render.js:960:13
    at rhs (/test/webworkerapp/node_modules/next/dist/server/render.js:960:47)
    at /test/webworkerapp/node_modules/next/dist/server/render.js:978:9
    at /test/webworkerapp/node_modules/next/dist/server/render.js:960:13
    at Promise (/test/webworkerapp/node_modules/next/dist/server/render.js:991:9)
Error [ERR_METHOD_NOT_IMPLEMENTED]: The _write() method is not implemented
    at Writable._write (_stream_writable.js:566:6)
    at doWrite (_stream_writable.js:415:12)
    at clearBuffer (_stream_writable.js:545:7)
    at Writable.uncork (_stream_writable.js:319:7)
    at /test/webworkerapp/node_modules/next/dist/server/render.js:976:17
    at /test/webworkerapp/node_modules/next/dist/server/render.js:960:13
    at rhs (/test/webworkerapp/node_modules/next/dist/server/render.js:960:47)
    at /test/webworkerapp/node_modules/next/dist/server/render.js:978:9
    at /test/webworkerapp/node_modules/next/dist/server/render.js:960:13
    at Promise (/test/webworkerapp/node_modules/next/dist/server/render.js:991:9)
Error [ERR_METHOD_NOT_IMPLEMENTED]: The _write() method is not implemented
    at Writable._write (_stream_writable.js:566:6)
    at doWrite (_stream_writable.js:415:12)
    at clearBuffer (_stream_writable.js:545:7)
    at Writable.uncork (_stream_writable.js:319:7)
    at /test/webworkerapp/node_modules/next/dist/server/render.js:976:17
    at /test/webworkerapp/node_modules/next/dist/server/render.js:960:13
    at rhs (/test/webworkerapp/node_modules/next/dist/server/render.js:960:47)
    at /test/webworkerapp/node_modules/next/dist/server/render.js:978:9
    at /test/webworkerapp/node_modules/next/dist/server/render.js:960:13
    at Promise (/test/webworkerapp/node_modules/next/dist/server/render.js:991:9)
error - Error [ERR_METHOD_NOT_IMPLEMENTED]: The _write() method is not implemented
Error [ERR_METHOD_NOT_IMPLEMENTED]: The _write() method is not implemented
    at Writable._write (_stream_writable.js:566:6)
    at doWrite (_stream_writable.js:415:12)
    at clearBuffer (_stream_writable.js:545:7)
    at Writable.uncork (_stream_writable.js:319:7)
    at /test/webworkerapp/node_modules/next/dist/server/render.js:976:17
    at /test/webworkerapp/node_modules/next/dist/server/render.js:960:13
    at rhs (/test/webworkerapp/node_modules/next/dist/server/render.js:960:47)
    at /test/webworkerapp/node_modules/next/dist/server/render.js:978:9
    at /test/webworkerapp/node_modules/next/dist/server/render.js:960:13
    at Promise (/test/webworkerapp/node_modules/next/dist/server/render.js:991:9)
Error [ERR_METHOD_NOT_IMPLEMENTED]: The _write() method is not implemented
    at Writable._write (_stream_writable.js:566:6)
    at doWrite (_stream_writable.js:415:12)
    at clearBuffer (_stream_writable.js:545:7)
    at Writable.uncork (_stream_writable.js:319:7)
    at /test/webworkerapp/node_modules/next/dist/server/render.js:976:17
    at /test/webworkerapp/node_modules/next/dist/server/render.js:960:13
    at rhs (/test/webworkerapp/node_modules/next/dist/server/render.js:960:47)
    at /test/webworkerapp/node_modules/next/dist/server/render.js:978:9
    at /test/webworkerapp/node_modules/next/dist/server/render.js:960:13
    at Promise (/test/webworkerapp/node_modules/next/dist/server/render.js:991:9)

This could be a Docker problem.


text:
Q: How to get City and Country using HTML5 Geolocation without relying on Google API? This may seem unorthodox, but what I want to do is get a persons entire city, state(or province) and country based on his or her input. I want to do this without using Google API as this project I am working on is a commercial project and as per Google's TOS I need to pay $10,000 to use it for commercial purposes (which is a pretty steep price for how often I would be using it i.e. 1-5 times a week).
Sample Input: Toronto
Return: Toronto, Ontario, Canada
Sample Input2: Vancouver
Return: Vancouver, British Columbia, Canada
Sample Input3: Otawwa (notice the typo)
Return: Ottawa, Ontario, Canada
Thanks for your assistance.

A: The only location info you can get from geolocation api is longitude and latitude. However, you could use this info to query a database and return the info you need. There are many free geo location databases on the internet. Google "free geolocation database" and just use any that you see fit. They usually come in a big data file that you need to import to your own database. After that, you just can just call your own ajax service to get results fast and free.
Alternatively, you can find the location by using their IP, if you need to code this on the server and not the client, again, there are free IP databases for this, too. I've used http://www.ipligence.com/ to query IP locations and it worked fine. They have free version.

A: My friend and I put this together, we use standard government data, and tie it to google maps.
http://nwstartups.com/api/geo/country.php
Will


text:
Q: PHP Page name variable + jQuery I'm having a problem, after implementing a jQuery in-page tab navigation system, with how to redefine my page names, so that they can be styled as "active" in my main navigation.
I use:
<?php $var_page_name = 'example.php'; ?>

to define each page name on my web site, with example replaced with the correct page name.
I then use the following to style the "active" page in the navigation, with the active class defined using CSS:
<?php global $var_page_name; ?>

<a<? if($var_page_name == 'index.php') print ' class="active"'; ?> href="index.php">web design

Works great. I've added an in-page jQuery tabbing solution for navigation. Which also works.
However, after clicking on one of the tabs and going to the new content div, its seems that the page name changes, so the correct main navigation item is no longer considered active. The url reads as http://www.example.com/index.php#, but if I modify my active page navigation variable to read:
<a<? if($var_page_name == 'index.php' || $var_page_name == 'index.php#' ) print ' class="active"'; ?>

or try the div id that is being used by the tabs:
<a<? if($var_page_name == 'index.php' || $var_page_name == 'index.php#content_2' ) print ' class="active"'; ?>

it doesn't fix the problem. Any suggestions?

A: It's a bug in your tabs script.
When you click a tab it removes the "active" class from your  in your top nav even though that  is not a tab.
Change the line:
// switch all tabs off
$(".active").removeClass("active");

to:
$(".tabs .active").removeClass("active");

or something similar to that which only removes the class 'active' from your tabs instead of all elements in your page.

A: <?php $var_page_name = 'example.php'; ?>
that's wrong. Use something like
<?php
$exploded = explode($_SERVER['REQUEST_URI']);
<a href="/page/" class="<?php echo ($exploded[1] == "page") ? "active" : ""; ?>">Page

Keep in mind that hash isn't being sent to the server by default

A: Well, I think the problem is more related with the jquery code in the page, than the PHP code. Checking the js header code, I found this:
// When a link is clicked
$("a.tab").click(function () {
  // switch all tabs off
  $(".active").removeClass("active");
  ...
});

The click binding on the selector "a.tab" is clearing all ".active" classes in the whole page, including the ones in the "nav" section (wich is above the tab).
Try changin this line:
$(".active").removeClass("active");

To this:
$("#tabbed_box_1").find(".active").removeClass("active");

That should do it.


text:
Q: Extend a view or use a mixin in Ember.js I would like to include standard functionality in several views within an Ember app. The functionality includes things like setting the tagName and classNames of the views to be the same and keeping track of a property for each view.
The question in a nutshell: Should I use a mixin or extend a base view?
The expanded question...
Should one extend a base view to do this? For example:
App.BaseView = Em.View.extend({
    tagName: 'section',
    classNames: ['page_section', 'blue'],
    willInsertElement: function() {
        // Some functions called here that set properties
    },
});

App.PageOneView = App.BaseView.extend({
    // View specific stuff here
});

App.PageTwoView = App.BaseView.extend({
    // View specific stuff here
});

... Or, should one use a Mixin to extend the functionality? For example:
App.BaseMixin = Em.Mixin.create({
    tagName: 'section',
    classNames: ['page_section', 'blue'],
    willInsertElement: function() {
        // Some functions called here that set properties
    },
});

App.PageOneView = Em.View.extend(App.BaseMixin, {
    // View specific stuff here
});

App.PageTwoView = Em.View.extend(App.BaseMixin, {
    // View specific stuff here
});

I understand that views and mixins are both Ember objects, but does using either of them to extend standard functionality to other objects (e.g. views) affects how the objects and prototypes/instances (if they differ from the object) interact and whether properties get set on the instance of the view or the view object?
If the two examples above differ, would setting the properties on the mixin's init function change anything? For example:
App.BaseMixin = Em.Mixin.create({
    tagName: null,
    classNames: null,
    init: function() {
        this.set('tagName', 'section');
        // And so forth...
    },
});

However, if using a mixin and extending a view have the same affect on the views I am trying to add the standard functionality to (that is, they affect the views' objects and prototypes/instances in the same way), do you see an advantage to using one over the other (whether in terms of efficiency, maintainability, etc)?

A: Great question,
Short and simple, extend the view.

*

*The hooks/bindings are view specific, so the mixin can't be applied to a controller, route etc, and depending on your team makeup, you don't want to give someone an opportunity to mix in code that doesn't belong.

*Extending a class in Ember just makes the base class into a mixin and applies it to your class.  https://github.com/emberjs/ember.js/blob/v1.2.0/packages/ember-runtime/lib/system/core_object.js#L488
So it's almost the exact same thing, only your base view makes more sense since it only really applies to views.


text:
Q: (javascript) how to do a reverse regex replace sentence start with tab? I want to keep all sentences start with one Tab [key \t] and delete the rest
input
This is aciton
        Two tab
    One tabdialog
This is aciton
        Two tab
    Second tabdialog

output
One tabdialog

Second tabdialog

A: You can simply do this as
^\t[\w ]+

DEMO

const str = `
This is aciton
        Two tab
    One tabdialog
This is aciton
        Two tab
    Second tabdialog
`;

const regex = /^\t[\w ]+/gm;
const result = str
  .match(regex)
  .flatMap((s) => s.split(/\t/))
  .filter(Boolean);

console.log(result);

A: Using match we can try the following approach:

var input = "This is aciton\n\t\tTwo tab\n\tOne tabdialog\nThis is aciton\n\t\tTwo tab\n\tSecond tabdialog";
console.log(input);

var matches = input.match(/(?:^|\n)\t([^\t]+?)(?:\r?\n|$)/g);
for (var i=0; i < matches.length; ++i) {
    matches[i] = matches[i].trim();
}
console.log(matches);

A: You may use this simple regex for this:
^\t\S.*

Where we match \t (tab) after line start followed by a non-whitespace character which is followed by 0 or more of any characters.
RegEx Demo
Code:

const str = `
This is aciton
        Two tab
    One tabdialog
This is aciton
        Two tab
    Second tabdialog
`;

var arr = str.match(/^\t\S.*/gm);

console.log(arr);


text:
Q: Standard error in Poisson process with sensitivity analysis and extrapolation Imagine, we have a population of size $N$ and a random sample of size $n$, comprising both women and men. We want to estimate the prevalence of some phenomenon in the population using our sample data, let's say smoking. Each person either smokes or does not smoke (denoted $x_i=1$ if they smoke). We ask the people in the sample if they smoke or not and get some number of people $s$ in the sample who say they smoke. This gives us a share of the sample $s/n$ who report smoking. Let's call the share of women (men) who report smoking $s_w$ ($s_m$).
The mean in a Poisson distribution will simply be the sample mean:
$ \mu   =   \frac{1}{n}\sum{x_i} = \frac{s}{n}$
Assuming the sample is iid, I understand that the standard error of the mean of a Poisson distribution would be
$SE = \sqrt{\frac{\mu}{n}}$
Imagine that we suspect that men (but not women) under-report smoking and want to see how much our estimates change if the actual share of men who smoke is 2 times higher than reported, 3 times higher than reported, 4 times higher than reported, etc. A series of estimates of the share of smokers in the sample under these varied rates of male underreporting would be:

*

*$\frac{1}{n}  \left( s_w + 2s_m \right)$

*$\frac{1}{n}  \left( s_w + 3s_m \right)$

*Etc.

First, how would one calculate a SE for simulated estimates of this sort? Is it still $\sqrt{\frac{\mu}{n}}$, where $\mu$ is redefined according to the simulated prevalence rate?
Second, how would one calculate a SE that incorporates the uncertainty of extrapolating from our sample of size $n$ to the population of size $N$?
I'd be thrilled to get either a definitive answer or a reference to one.


text:
Q: Why does JSON_QUERY within CASE statement fail to remove escape characters? It would seem that json_query fails to remove escape characters for the double quote character (") if the function is being applied within a case statement.
Example code below.
declare @data nvarchar(max);
declare @debug int = 0;

set @data = '{"id":10}';

set @debug = 0;
select
    isjson(@data) as 'validateData',
    @data as 'unprocessedSourceData',
    json_query(@data) as 'processedSourceData',
    case when @debug = 1 then json_query(@data) else null end as 'conditionallyProcessedSourceData'
    for json path, without_array_wrapper ;

set @debug = 1;
select
    isjson(@data) as 'validateData',
    @data as 'unprocessedSourceData',
    json_query(@data) as 'processedSourceData',
    case when @debug = 1 then json_query(@data) else null end as 'conditionallyProcessedSourceData'
    for json path, without_array_wrapper ;

Result from the first query:
{"validateData":1,"unprocessedSourceData":"{\"id\":10}","processedSourceData":{"id":10}}

Result from the second query:
{"validateData":1,"unprocessedSourceData":"{\"id\":10}","processedSourceData":{"id":10},"conditionallyProcessedSourceData":"{\"id\":10}"}

Note the escape characters toward the end: "{\"id\":10}"
1) Why would this be so?
2) How do I rework this query so that if @debug = 1 then the conditionallyProcessedSourceData element contains valid JSON, and if @debug = 0 then the element is null?

A: From JSON_QUERY (Transact-SQL)

Returns a JSON fragment of type nvarchar(max).

and

JSON_QUERY returns a valid JSON fragment. As a result, FOR JSON
  doesn't escape special characters in the JSON_QUERY return value.

So for json path escapes nvarchar(max) data unless the nvarchar(max) data comes from json_query().
In your query the data comes from the case statement not directly from json_query.
The workaround you can do is to put json_query outside of the case.
json_query(case when @debug = 1 then @data else null end)

Incorporating this into your full script, so you can compare the different approaches, gives:
declare @data nvarchar(max);
declare @debug int = 0;

set @data = '{"id":10}';

set @debug = 0;
select
    isjson(@data) as 'validateData',
    @data as 'unprocessedSourceData',
    json_query(@data) as 'processedSourceData',
    case when @debug = 1 then json_query(@data) else null end as 'conditionallyProcessedSourceData',
    json_query(case when @debug = 1 then @data else null end) as 'caseResultProcessed'
    for json path, without_array_wrapper ;

set @debug = 1;
select
    isjson(@data) as 'validateData',
    @data as 'unprocessedSourceData',
    json_query(@data) as 'processedSourceData',
    case when @debug = 1 then json_query(@data) else null end as 'conditionallyProcessedSourceData', -- This was the issue
    json_query(case when @debug = 1 then @data else null end) as 'caseResultProcessed' -- This is the solution
    for json path, without_array_wrapper ;


text:
Q: Let $X,Y$ be sets , $\phi: X\to Y$ is a bijection. Find a isomorphism $\rho : Sym(X) \to Sym(Y)$. Let $X,Y$ be sets , $\phi: X\to Y$ is a bijection.
Find a isomorphism $\rho : Sym(X) \to Sym(Y)$.
My attempt:
$\rho(\sigma)=\sigma^{-1}\phi\sigma$.
$\rho$ injective:
I show that $\rho(\sigma_1)=\rho(\sigma_2)\implies \sigma_1=\sigma_2$.
Suppose $\rho(\sigma_1)=\rho(\sigma_2)$ such that $ \sigma_1\neq\sigma_2$.
$\rho(\sigma_1)=\rho(\sigma_2)\implies \sigma_1^{-1}\phi\sigma_1=\sigma_2^{-1}\phi\sigma_2\implies \phi=\sigma_1\sigma_2^{-1}\phi\sigma_2\sigma_1^{-1} \underset{(*)}{\implies} \sigma_2\sigma_1^{-1}=\{Id\}\implies \sigma_2=\sigma_1$.
I have a problem how to show surjective and well-defined.
For showing well-defined I have to prove that $\sigma_1=\sigma_2 \implies \rho(\sigma_1)=\rho(\sigma_2)$, it looks very trivial to me and I am not sure how to prove it.
Any help is welcome thanks !


text:
Q: Python selenium rc create_cookie I can't seem to figure out how set cookies with Square brackets [ ] with python for Selenium. This is what i'm trying:
selenium.create_cookie("test[country]=nl", "path=/, max_age=6000")

Results in:
Traceback (most recent call last):
  File "test.py", line 55, in test
    sel.create_cookie('test[country]=nl', "path=/, max_age=6000")
  File "C:\Python27\lib\site-packages\selenium\selenium.py", line 1813, in create_cookie
    self.do_command("createCookie", [nameValuePair,optionsString,])
  File "C:\Python27\lib\site-packages\selenium\selenium.py", line 225, in do_command
    raise Exception(data)
Exception: ERROR: Invalid parameter.

How can I fix this?
EDIT:
This is some of the code. It is based on the code exported by IDE.
from selenium.selenium import selenium
import unittest, time, re
from selenium import webdriver

class country(unittest.TestCase):
    def setUp(self):
        self.verificationErrors = []
        self.selenium = selenium("localhost", 4444, "*chrome", "http://example.com/")
        self.selenium.start()

    def test_country_cookie_redirect(self):
        sel = self.selenium
        sel.create_cookie('test[country]=nl', "path=/, max_age=6000")
        sel.open("http://example.com")
        self.assertEqual("http://example.com/nl/nld", sel.get_location())

    def tearDown(self):
        self.selenium.stop()
        self.assertEqual([], self.verificationErrors)

if __name__ == "__main__":
    unittest.main()

A: Use add_cookie(). For example:
from selenium import webdriver

browser = webdriver.Firefox()
browser.get("http://stackoverflow.com")

browser.add_cookie({"name": "test[country]",
                    "value": "nl",
                    "path": "/",
                    "max_age": 6000})

browser.close()

UPD (modified test case using webdriver):
import unittest
from selenium import webdriver

class country(unittest.TestCase):
    def setUp(self):
        self.verificationErrors = []
        self.driver = webdriver.Remote("http://127.0.0.1:4444/wd/hub", {'browserName': 'chrome'})

    def test_country_cookie_redirect(self):
        self.driver.add_cookie({"name": "test[country]",
                                "value": "nl",
                                "path": "/",
                                "max_age": 6000})
        self.driver.get("http://example.com")
        self.assertEqual("http://example.com", self.driver.current_url)

    def tearDown(self):
        self.driver.quit()
        self.assertEqual([], self.verificationErrors)

if __name__ == "__main__":
    unittest.main()


text:
Q: Clojure PN (java.lang.ClassCastException) I'm using Clojure for a code golf challenge, in which the aim is to write a function that evaluates and returns the value from a Polish Notation expression. Below is my code.
(require '[clojure.string :as s])
(defn p[e](
    (load-string (reduce (fn[x c]
        (s/replace x #"([\+\-\*\/] (\(.*\) \d+|\d+ \d+))" "($0)")
    ) e (subvec (s/split e #"\d") 1)))))

Remember this is golfed code (not meant to be readable).
In short, the function takes a string, the string is then split into a vector. Reduce iterates over the vector and applies the expression for the n-1 elements in the vector. What comes out is a string that Clojure should be able to evaluate with load-string.
If I declare a var called e with the value "+ 3 5" then run just the reduce from the function, "(+ 3 5)" is expected as returned. But when I call the function as (p "+ 3 5") I get the following error.
java.lang.ClassCastException: java.lang.String cannot be cast to clojure.lang.IFn (NO_SOURCE_FILE:0)

No idea what's going on here.

A: You are using extra parentheses after defn args vector. It should be:
(defn r[e]
  (load-string
    (reduce
      (fn[x c]
        (s/replace x #"([\+\-\*\/] (\(.*\) \d+|\d+ \d+))" "($0)"))
      e
      (subvec (s/split e #"\d") 1))))

user=> (r "+ 3 5")
8


text:
Q: Why does C++ use pointers? Why does C++ need and use pointers? I know they add power to the language but they make it a lot harder to understand for beginners. Languages like F#, Java, Ruby, Python, Lua, etc. get by just fine without them, and they're quite powerful.

A: All other languages you mention (and you forgot, at least, Java!!!), while each very useful and usable, don't let you get anywhere as close to the machine as C++ (and C) allow: simply put, all of those languages impose on you a higher level of abstraction... which may mostly be fine but will occasionally get in your way.
C++ is a bigger and more complicated language because it allows programming at really low levels of abstraction (very close to the machine) AND at pretty high levels (close to many of the languages you mention) within the same language, indeed within the same source files.
Beginners are well advised to stay FAR away from this amount of power and (inevitably) complication -- but not every programmer is a beginner, and not every bit of code needs (or, actually, can at all stand!-) being within an environment that has "let's protect the poor shmucks from themselves" as a major design goal!-)

A: In short, because C++ targets systems programming.
What this means is that C++ is oriented around implementing pretty much everything, from top to bottom.
This includes Operating Systems, where you need to have a level of control of what's happening down to the machine address, not just the VM mapped logical addresses.
This also includes compilers for C++ or any other language, which requires actually implementing the abstractions used by those languages.
This also includes performance constrained settings such as embedded devices programming, or high performance computing, where it's necessary to program in a way that makes very careful use of memory, of instructions, of code size, and any other constrained resource.
Not very many languages target this broad range of tasks.  Calling other languages powerful by this standard is rather misleading, because those languages are simply not suited to those tasks.

A:
Why does C++ need and use pointers?

C++ doesn't need anything. Programmers need them and there are programmers who really need them. Like programmers who are building device drivers.

So, there must be some languages that allow raw memory access. C++ happens to be one of those languages.

A: Maybe C++ isn't for beginners.
Pointers have been around for a long time. They were in Pascal and C. When C++ came out, it would have lost out of the gate without pointers.

A: One reason I've haven't read yet here:
C++ was designed with compatibility to C as a goal, so simply put C++ is a superset to C (which is not 100% true, but almost). As C does have pointers (and, due to its low level nature needs them) C++ also needs to support them.

A: C# has pointers, and I couldn't get by just fine without them. It completely depends on what you are doing, and learning pointers is extremely good for you as a developer. The question isn't why, it is when to use them.

A: Lots of good answers here, but there aren't very many good examples of why it's needed. ... Or why C is sometimes called "Portable Assembly Language."
On the lowest level of abstraction on the machine, there are a large number of hardware functions that are accessed through memory ranges. These memory addresses are often quite standardized with various types of hardware.
For example, when an x86 computer first starts up and BIOS has loaded and started the boot sector, the CPU is in a mode called "16-bit Real Mode" for memory addressing. To access hardware peripherals, there are a few methods, including memory regions and the IN and OUT assembly instructions. Video is accessible at the memory address range 0xA0000-0xBFFFF. Writing to this memory location will draw characters to the screen. Writing to certain regions above 0xC0000 manipulates video BIOS registers, which can, for example, change video modes.
C was initially created to port UNIX to the PDP-11, which uses a memory-mapped I/O scheme similar to the x86 today. UNIX would have never run on the PDP-11 without pointers.
Languages like F#, C#, Ruby, Python, Lua, etc. can't do that without modifying the core language. C and C++ can:
/* Assuming 16-bit DOS environment, 80x25 character video mode. */
char* video = 0xA0000;
video[1] = 'H';
video[3] = 'e';
video[5] = 'l';
video[7] = 'l';
video[9] = 'o'; /* prints "Hello" in the top-left corner of the screen.

A: You're mixing up pointer arithmetic with immutable pointers, AKA, references. All of these languages, including Java, which you didn't mention, do have references.  References are slightly less powerful than pointers, but you won't notice this until you get to the stage where you need pointer arithmetic or double or triple pointers.  But, under the hood, references are really the same thing as pointers, just that the language won't let you do whatever you want to them (i.e., they're not first-class objects).
Consider this python code:
class X: z=13

y=X()
def f(aa): aa.z = aa.z+1

print(y.z)
f(y)
print(y.z)

f() changes the value of y.z, and this is exactly what would happen in the corresponding C or C++ code written with pointers.

A: Pointers provide a means to pass by reference, which is crucial in some programs that pass large data structures. Instead of passing 100mb, you just pass a small pointer. Languages without "pointers" usually have a mechanism to pass by reference.

A: Most higher level languages don't have pointers per se, but they do use similar constructs.  Here's an example.  In C++, if you have something like:
Foo myObject();

you've declared an instance of a Foo, which is always going to be of type Foo.  You can't declare a Foo and instantiate another type without using a pointer.  However, in C#, you can do it easily:
Foo myObject = new Bar(); // assuming Bar derives from class Foo

The only way to do this in C++ is with a pointer (and thanks to polymorphism).  C# is using a pointer of sorts, but abstracting out the messy stuff that makes pointers so "hard" to use.

A: You can do a lot in C++ without using pointers. Stick with references and higher level things like the STL. Read Accelerated C++ for a good beginner (albeit someone who has programmed in another language) book. C++ can be programmed in a much higher way than C. Stay away from stuff like multiple inheritance, writing your own templates, and pointers at the beginning and you'll be fine. Do learn about virtual functions and object oriented programming from the get go if you are just beginning. Stay away from overloading. Get the first 50% of the language and the hard to learn extra 50% will seem a lot less disconcerting.

A: This question can start a serious flame war.
I asked myself the same thing over and over while trying to get my head around pointers and all the related stuff in c++
On reason languages like ruby, python and others are on another level of coding. They are more abstract farther away from the machine language. But maybe slower.
Another reason is that c++ is a very old language. Many concepts are from times people didn't know any better and I think that is a serious problem. C++ has its advantages it lets you write very fast code and take great shortcuts. But the tradeoff is a language that is hard to understand and programs that look like art but puzzle the persons working with it later.

A: Garbage collection (GC) is assumed to be too much overhead for some of the environments where C++ will be used, e.g. embedded systems, operating systems. With high-level references, there is no way for an object to be deleted if it is still accessible. That safety guarantee is made possible by the assumption that GC is there. Without adopting GC as a basic assumption, C++ will always need raw pointers.
Unsurprisingly, one of the most popular C++ questions on this site is "How can I solve the dangling-pointer problem in a general way?", and the most popular answer is to use a reference-counting smart pointer, which is like a poor man's GC. Another answer is to use the right tool for the job - if you aren't doing low-level or embedded systems programming, C++ is probably the wrong tool. C++ is used far more widely in high-level application programming than it probably should be. A lot of people are wasting time debugging memory leaks, memory corruption, etc. just because they're using the wrong tool for the job.
Another reason for using pointers is that they allow the author of a device driver to address a specific region of memory, which is often useful when communicating with devices because certain areas of memory are "mapped" to the hardware device. But again, this is very much a low-level systems programming concern.


text:
Q: Adding an ASP.Net button in code-behind I've got a pretty tight form with an AJAX Accordion pane.  I'm using a Master page, but the ASPX child page looks like this:
<asp:Content ID="Content1" ContentPlaceHolderID="HeadContent" runat="server">
  <link rel="stylesheet" href="Content/themes/base/jquery-ui.css">

</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="FeaturedContent" runat="server">
</asp:Content>
<asp:Content ID="Content4" ContentPlaceHolderID="MainContent" runat="server">

    <asp:UpdatePanel ID="MyUpdatePanel" runat="server">
        <ContentTemplate>
            <asp:panel ID="MyContent" runat="server">

                    <ajaxtoolkit:modalpopupextender id="MdlCommentsExtender" runat="server"
                        targetcontrolid="MyContent" popupcontrolid="pnlComments"
                        popupdraghandlecontrolid="PopupHeader" drag="True"
                        backgroundcssclass="ModalPopupBG" Enabled="False"  >
                    </ajaxtoolkit:modalpopupextender>

                    <asp:panel id="pnlComments" style="display: none" runat="server" BackColor="White" CssClass="modalPopup">

Pend Comment

                                            <asp:Label ID="lblCommentBox" runat="server" Text="Comment:"></asp:Label>

                                                <asp:TextBox ID="txtCommentBox" TextMode="MultiLine" CssClass="textbox" Wrap="True" Height="70px" Width="270px" Font-Size="Small" Rows="3" runat="server"  onkeyup="textCounter(this, this.form.remLen, 50);" onkeydown="textCounter(this, this.form.remLen, 50);" onpaste="textCounter(this, this.form.remLen, 50);" />

                                                <input readonly="readonly" type="text" id="remLen" name="remLen" size="2" maxlength="3" value="50" /> characters left

                                            <asp:Button ID="mdlCmntsOk_Click" runat="server" Text="OK" CssClass="textbox" Height="28px" Width="75px" OnClick="mdlCommentsOk_Click" />

                    </asp:panel>
            </asp:panel>
        </ContentTemplate>
    </asp:UpdatePanel>

</asp:Content>

This form contains a modalpopupextender which I would like to call from an "Edit" button.  The Accordion is being added dynamically via code-behind.  My entire code-behind looks like this:
public partial class frmBenefitSummaryList : System.Web.UI.Page
{
    string ConnStr = System.Configuration.ConfigurationManager.ConnectionStrings["ConnCST"].ConnectionString;

    protected void Page_Load(object sender, EventArgs e)
    {

        BindAccordions();
        if (Page.IsPostBack)
        {
            MdlCommentsExtender.Show();
        }
    }

    private void BindAccordions()
    {
        #region Get the value from the database

         DataTable dt = new DataTable();
         try
         {

             using (SqlConnection connection = new SqlConnection())
             {
                 connection.ConnectionString = ConfigurationManager.ConnectionStrings["ConnCST"].ToString();
                 connection.Open();
                 SqlCommand cmd = new SqlCommand();
                 cmd.Connection = connection;
                 string CmdTxt = "Select CBL.ID, CBL.[Category], CBL.[Provision], CTL.MarkForReview, CTL.IssueType, CTL.Resolution, CTL.Feedback, CTL.TemplateID";
                 CmdTxt = CmdTxt + " from [tblCSTBenefitList] CBL";
                 CmdTxt = CmdTxt + " LEFT JOIN tblCSTTemplateList CTL";
                 CmdTxt = CmdTxt + " ON CBL.ID = CTL.BenefitID";
                 CmdTxt = CmdTxt + " where CBL.ID > '0'";
                 CmdTxt = CmdTxt + " ORDER BY CBL.[Category], CBL.[Provision] ASC";

                 cmd.CommandText = CmdTxt;
                 cmd.CommandType = CommandType.Text;
                 SqlDataAdapter da = new SqlDataAdapter(cmd);

                 da.Fill(dt);
                 cmd.Dispose();
                 connection.Close();
             }
         }
         catch (Exception ex) { Response.Write(ex.Message); }

        #endregion

        #region Create accordion with properties

        Accordion acrDynamic = new Accordion();
        acrDynamic.ID = "MyAccordion";
        acrDynamic.SelectedIndex = -1;//No default selection
        acrDynamic.RequireOpenedPane = false;//no open pane
        acrDynamic.HeaderCssClass = "accordionHeader";//Header class
        acrDynamic.HeaderSelectedCssClass = "accordionHeaderSelected";//Selected herder class
        acrDynamic.ContentCssClass = "accordionContent";//Content class

        #endregion

        #region Create the panes

        Label lbTitle;
        Label lbContent;
        AccordionPane pane;
        string Content = "";

        for (int i = 0; i < dt.Rows.Count; i++)
        {
            if (Content == "")
                Content += "

Provision	Mark For Review	Issue Type	Resolution	Feedback	Edit
";

            string BranchName = dt.Rows[i]["Category"].ToString();
            string Next_Branch = "";

            if (i != dt.Rows.Count - 1)
                Next_Branch = dt.Rows[i + 1]["Category"].ToString();

            Content += "
";
            Content += "" + dt.Rows[i]["Provision"].ToString() + "	";
            Content += "" + dt.Rows[i]["MarkForReview"].ToString() + "	";
            Content += "" + dt.Rows[i]["IssueType"].ToString() + "	";
            Content += "" + dt.Rows[i]["Resolution"].ToString() + "	";
            Content += "" + dt.Rows[i]["Feedback"].ToString() + "	";
            Content += "<input type=\"submit\" ID=\"btnEdit\" name=\"ctl00$MainContent$btnEdit_OnClick\" onserverclick=\"btnEdit_OnClick()\" UseSubmitBehavior=\"False\" value=\"Edit\" />	";
            Content += "
";

            if (BranchName != Next_Branch) //if last row of branch
            {
                Content += "
";
                pane = new AccordionPane();
                lbTitle = new Label();
                lbContent = new Label();
                pane.ID = "Pane_" + BranchName.ToString();
                lbTitle.Text = BranchName;
                pane.HeaderContainer.Controls.Add(lbTitle);
                lbContent.Text = Content;
                pane.ContentContainer.Controls.Add(lbContent);
                acrDynamic.Panes.Add(pane);
                Content = "";
            }
        }

        #endregion

        #region Add the accordion to the page

        MyContent.Controls.Add(acrDynamic);

        #endregion

    }

    protected void btnEdit_OnClick(object sender, EventArgs e)
    {
        MdlCommentsExtender.Enabled = true;
        MdlCommentsExtender.Show();
        ScriptManager.GetCurrent(this).SetFocus(this.txtCommentBox);
    }

    protected void mdlCommentsOk_Click(object sender, EventArgs e)
    {
        MdlCommentsExtender.Hide();
    }
}

That's it.  That's all my code.  And it runs like a champ.  Except one thing: the current Edit button is created by this line in the in the #region Create the panes section:
Content += "<input type=\"submit\" ID=\"btnEdit\" name=\"ctl00$MainContent$btnEdit_OnClick\" onserverclick=\"btnEdit_OnClick()\" UseSubmitBehavior=\"False\" value=\"Edit\" />	";

This causes a postback, and that negates my modal form.  So, what I need to do is change that to an asp:Button button so I can call my modal window.
Can anyone tell me how to do this?  Assume I'm an idiot (because I kind of am) and be explicit in your explanation, please.

A: I would always try to prevent creating html markup in the code-behind, specially if you still plan on leveraging the ASP.NET pipeline. If you can make sure your controltree is regenerated on page load, your changed code would look like this:
Table table = null;

string BranchName = null;

for (int i = 0; i < dt.Rows.Count; i++)
{
    TableRow tr;
    if (BranchName != dt.Rows[i]["Category"].ToString())
    {
        BranchName = dt.Rows[i]["Category"].ToString();
        // setup pane
        pane = new AccordionPane();
        // add pane to accordion
        acrDynamic.Panes.Add(pane);

        // pane content
        lbTitle = new Label();
        pane.ID = "Pane_" + BranchName;
        lbTitle.Text = BranchName;
        pane.HeaderContainer.Controls.Add(lbTitle);

        // pane container will have the table
        table = new Table();
        // set properties like class, height .. etc
        table.CssClass = "hoverTable";
        // add it to a container
        pane.ContentContainer.Controls.Add(table);

        // top row
        tr = new TableRow();
        // cells
        TableHeaderCell th = new TableHeaderCell();
        th.Width = 440;
        th.Text = "Provision";
        // set other properties
        tr.Controls.Add(th);
        // create next control
        th = new TableHeaderCell();
        th.Width = 120;
        th.Text = "Mark for Review";
        // set other properties
        tr.Controls.Add(th);
        // etc for other columns
        table.Controls.Add(tr);

    }

    tr = new TableRow();
    TableCell tc = new TableCell();
    tc.Text = dt.Rows[i]["Provision"].ToString();
    tr.Controls.Add(tc);
    tc = new TableCell();
    tc.Text = dt.Rows[i]["MarkForReview"].ToString();
    tr.Controls.Add(tc);
    // etc for other columns
    // add the button
    tc = new TableCell();
    Button button = new Button();
    button.Text = "Edit";
    button.UseSubmitBehavior = false;
    button.Click += new EventHandler(btnEdit_OnClick);
    tc.Controls.Add(button);
    tr.Controls.Add(tc);

    table.Controls.Add(tr);
}

I wasn't sure about the Name and ID. I expect the control will get a proper name and id in the Render method of the Button control.