text:
Q: What is the maximum filename length in Windows 10? Java would try / catch would trough exeption? In old versions of windows I know the max is something around 250 characters for files or folders approximately, does anyone know if they changed it in Windows 10 ?
EDIT:
I'm doing some Java code around given API to extract some content of a application, will be few thousand files, and I'm a bit concern about what could happen as I don't know what the file name and path will look like so I will try to prevent those errors maybe maybe changing the name in Java before save (but ideal keep the original name),
so do you know if there would be some exemption been thrown ? File file = new File(jsonFile); ?  thank I could potentially treat in the catch

A: If you really mean file name, I believe the limit is still "commonly" 255 characters, see the third quoted paragraph ("The Windows API has many...") below.
If you mean file path: You can enable the "Win32 long paths" option. From this Microsoft document:

Maximum Path Length Limitation
In the Windows API (with some exceptions discussed in the following paragraphs), the maximum length for a path is MAX_PATH, which is defined as 260 characters. A local path is structured in the following order: drive letter, colon, backslash, name components separated by backslashes, and a terminating null character. For example, the maximum path on drive D is "D:\some 256-character path string<NUL>" where "<NUL>" represents the invisible terminating null character for the current system codepage. (The characters < > are used here for visual clarity and cannot be part of a valid path string.)

Note
File I/O functions in the Windows API convert "/" to "\" as part of converting the name to an NT-style name, except when using the "\\?\" prefix as detailed in the following sections.

The Windows API has many functions that also have Unicode versions to permit an extended-length path for a maximum total path length of 32,767 characters. This type of path is composed of components separated by backslashes, each up to the value returned in the lpMaximumComponentLength parameter of the GetVolumeInformation function (this value is commonly 255 characters). To specify an extended-length path, use the "\\?\" prefix. For example, "\\?\D:\very long path".

Note
The maximum path of 32,767 characters is approximate, because the "\\?\" prefix may be expanded to a longer string by the system at run time, and this expansion applies to the total length.

The "\\?\" prefix can also be used with paths constructed according to the universal naming convention (UNC). To specify such a path using UNC, use the "\\?\UNC\" prefix. For example, "\\?\UNC\server\share", where "server" is the name of the computer and "share" is the name of the shared folder. These prefixes are not used as part of the path itself. They indicate that the path should be passed to the system with minimal modification, which means that you cannot use forward slashes to represent path separators, or a period to represent the current directory, or double dots to represent the parent directory. Because you cannot use the "\\?\" prefix with a relative path, relative paths are always limited to a total of MAX_PATH characters.
There is no need to perform any Unicode normalization on path and file name strings for use by the Windows file I/O API functions because the file system treats path and file names as an opaque sequence of WCHARs. Any normalization that your application requires should be performed with this in mind, external of any calls to related Windows file I/O API functions.
When using an API to create a directory, the specified path cannot be so long that you cannot append an 8.3 file name (that is, the directory name cannot exceed MAX_PATH minus 12).
The shell and the file system have different requirements. It is possible to create a path with the Windows API that the shell user interface is not able to interpret properly.
Enable Long Paths in Windows 10, Version 1607, and Later
Starting in Windows 10, version 1607, MAX_PATH limitations have been removed from common Win32 file and directory functions. However, you must opt-in to the new behavior.
To enable the new long path behavior, both of the following conditions must be met:

*

*The registry key HKLM\SYSTEM\CurrentControlSet\Control\FileSystem LongPathsEnabled (Type: REG_DWORD) must exist and be set to 1. The key's value will be cached by the system (per process) after the first call to an affected Win32 file or directory function (see below for the list of functions). The registry key will not be reloaded during the lifetime of the process. In order for all apps on the system to recognize the value of the key, a reboot might be required because some processes may have started before the key was set.

Note
This registry key can also be controlled via Group Policy at Computer Configuration > Administrative Templates > System > Filesystem > Enable NTFS long paths.

*

*The application manifest must also include the longPathAware element.
<application xmlns="urn:schemas-microsoft-com:asm.v3">
    <windowsSettings xmlns:ws2="https://schemas.microsoft.com/SMI/2016/WindowsSettings">
        <ws2:longPathAware>true</ws2:longPathAware>
    </windowsSettings>
</application>

These are the directory management functions that no longer have MAX_PATH restrictions if you opt-in to long path behavior: CreateDirectoryW, CreateDirectoryExW GetCurrentDirectoryW RemoveDirectoryW SetCurrentDirectoryW.
These are the file management functions that no longer have MAX_PATH restrictions if you opt-in to long path behavior: CopyFileW, CopyFile2, CopyFileExW, CreateFileW, CreateFile2, CreateHardLinkW, CreateSymbolicLinkW, DeleteFileW, FindFirstFileW, FindFirstFileExW, FindNextFileW, GetFileAttributesW, GetFileAttributesExW, SetFileAttributesW, GetFullPathNameW, GetLongPathNameW, MoveFileW, MoveFileExW, MoveFileWithProgressW, ReplaceFileW, SearchPathW, FindFirstFileNameW, FindNextFileNameW, FindFirstStreamW, FindNextStreamW, GetCompressedFileSizeW, GetFinalPathNameByHandleW.

Note that while that article says the Group Policy editor's setting is "Enable NTFS long paths", that's no longer the case; it's "Enable Win32 long paths" now:

A: The maximum length of a path component (directory or file name) is usually 255 but might be shorter on some file systems on external storage (CD-ROM, FAT-16 floppy etc.). The only way to know for sure is to call GetVolumeInformation. This function reports the maximum component as a DWORD but Windows is currently limited to 255.
The maximum length of a complete path varies:
The limit people often talk about is 260 which comes from the MAX_PATH constant. This is the absolute limit on Windows 95/98/ME.
On Windows NT based systems this limit can be bypassed when calling the Unicode version of the low-level file system functions in kernel32 by using a special prefix. Paths prefixed with \\?\ are passed directly to the NT API. Relative paths are not supported when you do this. These paths are limited to around 32.000 characters and this limit comes from the string format used in the Windows kernel.
Even though this method has been supported for 25 years, most of Windows is still limited to MAX_PATH. The shell/Explorer has this limit in various places and CreateProcess also has this limit.
Windows 10 added support for paths longer than MAX_PATH without the special prefix. This support is only activated if the application has opted in to this behavior in their manifest and the "Enable Win32 long paths" policy has been enabled on the system.
Most of the MAX_PATH limits in the shell/Explorer have been removed in Windows 10.


text:
Q: How to convert live stock market API data into a usable format to calculate technical indicators? I'm trying to automate a trading strategy using python. I already have angelbroking stock market API which fetches open high low close values of a stock.
The problem is, by default the API prints the data. I'm unable to understand how to convert this data to a usable format like DataFrames that will update prices accordingly.
In case of historic data, I can create DataFrames to plot various charts with Matplotlib, Plotly and calculate indicators using TA-lib or math formulas in some cases.
So, how to convert the live stock market API data into a usable format to calculate the technical indicators?
Below is the API:
from smartapi import
SmartWebSocket

# feed_token=092017047
FEED_TOKEN="YOUR_FEED_TOKEN"
CLIENT_CODE="YOUR_CLIENT_CODE"
# token="mcx_fo|224395"
token="EXCHANGE|TOKEN_SYMBOL"
#SAMPLE: nse_cm|2885&nse_cm|1594&nse_cm|11536&nse_cm|3045
task="mw"   # mw|sfi|dp

ss = SmartWebSocket(FEED_TOKEN, CLIENT_CODE)

def on_message(ws, message):
    print("Ticks: {}".format(message))

def on_open(ws):
    print("on open")
    ss.subscribe(task,token)

def on_error(ws, error):
    print(error)

def on_close(ws):
    print("Close")

# Assign the callbacks.
ss._on_open = on_open
ss._on_message = on_message
ss._on_error = on_error
ss._on_close = on_close

ss.connect()

Any suggestion is helpful. Thanks for your valuable time.

A: You have access to the documentation since you have an account. Please read it first and watch some tutorials before asking questions. I do not have access to the documentation since there is an account wall.

redpajama_set_name: RedPajamaStackExchange


text:
Q: C++ usage of template<>
Possible Duplicate:
template<> in c++

I have seen template<> in c++ code.
Is this valid syntax? If it is, what does it mean?

A: It's used whenever you explicitly specialize a template (class or function template) or a member of a class template. The first set of examples use this class template and members:
template<typename T>
struct A {
  void f();

  template<typename U>
  void g();

  struct B {
    void h();
  };

  template<typename U>
  struct C {
    void h();
  };
};

Specializing and defining members
// define A<T>::f() */
template<typename T>
void A<T>::f() {
}

// specialize member A<T>::f() for T = int */
template<>
void A<int>::f() {
}

// specialize member A<T>::g() for T = float
template<>
template<typename T>
void A<float>::g() {
}

// specialize member A<T>::g for T = float and
// U = int
template<>
template<>
void A<float>::g<int>() {
}

// specialize A<T>::B for T = int
template<>
struct A<int>::B {
  /* different members may appear here! */
  void i();
};

/* defining A<int>::B::i. This is not a specialization,
 * hence no template<>! */
void A<int>::B::i() {
}

/* specialize A<T>::C for T = int */
template<>
template<typename U>
struct A<int>::C {
  /* different members may appear here! */
  void i();
};

/* defining A<int>::C<U>::i. This is not a specialization,
 * BUT WE STILL NEED template<>.
 * That's because some of the nested templates are still unspecialized.
 */
template<>
template<typename U>
void A<int>::C<U>::i() {
}

Example with specializing a non-member class template
template<typename T>
struct C {
  void h();
};

/* explicitly specialize 'C' */
template<>
struct C<int> {
  /* different members may appear here */
  void h(int);
};

/* define void C<int>::h(int). Not a specialization, hence no template<>! */
void C<int>::h(int) {
}

/* define void C<T>::h(). */
template<typename T>
void C<T>::h() {
}

A: yes this is valid - it is used for class template specialization... see http://www.cplusplus.com/doc/tutorial/templates/


text:
Q: WP Query to not return values in array I am using WP_Query to return one random post. I would like to use an updated session variable which contains a list of post for WP_Query to not return. How can I add this to the array or function?
This is my code
$args = array(
    'tag' => $_GET['Category'],
    'orderby' => 'rand',
    'posts_per_page'=>1
);
$the_query = new WP_Query( $args);

A: This is the solution: post__not_in where $postid is an array.
$args = array(
    'tag' => $_GET['Category'],
    'orderby' => 'rand',
    'posts_per_page'=>1,
    'post__not_in' =>  $postid
);


text:
Q: Simple PHP form validation? How would I go about validating the input (and not saving to file unless all three fields are filled correctly) of this code?
field1 = Name (first name and last name)
field2 = Text in the format of xxxx#1111
field3 = Email
if(isset($_POST['field1']) && isset($_POST['field2']) && isset($_POST['field3'])) {
  $data = $_POST['field1'] . '-' . $_POST['field2'] . '-' . $_POST['field3'] . "\n";
  $ret = file_put_contents('submissions.txt', $data, FILE_APPEND | LOCK_EX);
if($ret === false) {
  die('There was an error writing this file');
}
  else {
    echo "$ret bytes written to file";
  }
}

Thank you!

A: The PHP function isset() only checks if the variable has been SET or not..
When you fill in the form and post it. Field 1, 2 and 3 will always be true because it containts an empty string.
The first thing you need to do, is to check if the fields are filled or not.. Use !empty() instead.
http://www.php.net/isset

A: $errors = array();
if (isset($_POST)){

if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/",trim($_POST['email'])))
  {
  $errors[] = "Invalid email format";
  }else{
  $email = trim(strip_tags($_POST['email']));
  }

if (strlen(trim($_POST['firstname])) <=0){
   {
  $errors[] = "Invalid firstname format";
  }else{
  $firstname = trim(strip_tags($_POST['firstname']));
  }
}

and so on
in the end
if count($errors)>0){ 'explode errors;}

otherwise process
i hope it helps you


text:
Q: R call to C code faster than c++ function call to C code? for my project I have a R program that calls many times a C function, implemented using #include <R.h> and #include <Rdefines.h>. Since I want to speed as much as possible the whole algorithm, I coded the R program directly in C++, so to remove the layer of translation between C and R.
I called the previously coded C function from C++, as a regular function. I was able to do the translation and to obtain the same output.
Looking at run time I found out that the R execution is faster than the C++ one (2m 10 sec vs 2m 50 sec). To find out where the "problem" was I have used two profilers: gprof and Valgrind, that both report a runtime usage of 99% of the time by the C external function. This gives me no explanation about this difference in run time of 30%, while 99% of the time is spent on executing the same C code. For the integration of C++ and C I have tried both lo link the C object file, and to link all the .o of C creating a single library (libExternal.a). Do you have any suggestion of which could be the reason of this difference?
I have attached a part of the valgrind report. The external C function is underlined.
Thank you!
Here the result of perf stat -d on the C++ program:

Here the result of perf stat -d on the R program:

I want to remind you that 99% of the time is spent in the C function, which is the same for both. In the C++ code I just create the objects before passing to the function, so data should be side by side in the memory. Thank you for your help

A: Clearly, memory layout/memory access might play a decisive role here. Basically, if CPU spend 99% time in function X(), it doesn't mean it is really doing anything. Most likely CPU is waiting for data to be delivered, and one implementation is waiting less (or more) than the other one.
I would advice to check using perf suite, cache hits and misses etc.
Link: http://www.bnikolic.co.uk/blog/hpc-prof-events.html


text:
Q: Read Mutable Array from File / Plist Here is my problem. I show files out of an MutableArray in a UITableView with UISearchBar.
Therefore I made an Array:
allTableData = [[NSMutableArray alloc] initWithObjects:
               [[CRFParts alloc] initWithName:@"ABC" andDescription:@"DEF"],
               [[CRFParts alloc] initWithName:@"GHI" andDescription:@"JKL"],
                nil];

I have round about 2000 lines of this. I build me simple strings out of an excel file but the code inside my .m is huge than. Is there a possibility to read these content out of an file (plist/txt)?
Thanks for helping!

A: Try looking at This Question. It has a lot of good code on how to read a plist and dictionaries vs arrays.
And next time, search before you ask.

A: You can easely use:
NSArray *array = [[NSArray alloc] initWithContentsOfURL:url];
or NSDictionary *dict = [[NSDictionary alloc] initWithContentsOfURL:url];
Check out Apple Documentation on the topic.
Be careful on what structure you are loading as a plist can represent and array or a dictionary at its root. Other thread about it


text:
Q: AsyncStorage.getItem is returning undefined I'm setting a 'session' variable using AsyncStorage in my action file:
axios
...
// Session variable
AsyncStorage.setItem('userID', response.data.toString()).then((user) => {
    this.setState({ user });
});
// Send to next page
NavigationService.navigate('Main');

Then, in my page, I tried to get the value:
...
render() {
    AsyncStorage.getItem('userID')
      .then((value) => {
        const data = JSON.parse(value);
        console.log('userID ', data.name);
      });
...

It is returning 'userID undefined'. Why is it happening?
Thanks

A: The problem with the code you've written is that userId has the value 10 but when you call console.log you're treating it like an object with an attribute name. The correct code would look like:
...
render() {
    AsyncStorage.getItem('userID')
      .then((value) => {
        const userId = JSON.parse(value);
        console.log('userID ', userId);   // This line changed
      });
...


text:
Q: Proof regarding cyclic groups I need to prove the following:
G is cyclic iff for every m s.t m divides |G|, G has an element of order m.
I'm able to convince myself that its true with examples but not sure how to go about proving it formally. Can someone help me with this?

A: It follows from those assumptions that $G$ has an element $g$ of order $\lvert G\rvert$. But then $\langle g\rangle=G$.


text:
Q: Enable pyenv-virtualenv prompt at terminal I just installed pyenv and virtualenv following:
https://realpython.com/intro-to-pyenv/
After completing installation I was prompted with:
pyenv-virtualenv: prompt changing will be removed from future release. configure `export PYENV_VIRTUALENV_DISABLE_PROMPT=1' to simulate the behavior

I added export PYENV_VIRTUALENV_DISABLE_PROMPT=1 to my .bash_aliases just to see what the behavior would be, and sure enough it removed the prompt that used to exist at the beginning of the command prompt indicating the pyenv-virtualenv version. Used to be like:
(myenv) user@foo:~/my_project [main] $
where (myenv) is the active environment, and [main] is the git branch.
I would love to have the environment indicator back! It is very useful. I guess at some possibilities such as:
export PYENV_VIRTUALENV_DISABLE_PROMPT=0
export PYENV_VIRTUALENV_ENABLE_PROMPT=1
But these do not return the previous behavior. I have googled all over and can't figure out how to get this back.
This answer is not useful, as it seems like a hack around the original functionality, and displays the environment always, not just when I enter (or manually activate) an environment.

A: Borrowing a solution from here, the following works (added to .bashrc or .bash_aliases):
export PYENV_VIRTUALENV_DISABLE_PROMPT=1
export BASE_PROMPT=$PS1
function updatePrompt {
    if [[ "$(pyenv virtualenvs)" == *"* $(pyenv version-name) "* ]]; then
        export PS1='($(pyenv version-name)) '$BASE_PROMPT
    else
        export PS1=$BASE_PROMPT
    fi
}
export PROMPT_COMMAND='updatePrompt'


text:
Q: How to write a simple Powershell script to assign a user to an AD group I just getting into writing Powershell scripts to perform repetitive tasks.  I want to write a script that will prompt for an ADgroup, and an AD userID, then add that user to the security group.
It starts like this:
  $SecurityGroup = Read-Host -Prompt 'Input the SecurityGroup name'
  $User = Read-Host -Prompt 'Input the userID'
  Get-ADGroup '$SecurityGroup' | Add-ADGroupMember -Members '$User'
  (GET-ADUSER –Identity '$user' –Properties MemberOf | Select-Object MemberOf).MemberOf
  Write-Host 'The user with userID '$user' has been added to the SecurityGroup '$SecurityGroup'

A: Replace the single quotes surrounding your variables with double quotes " or remove the quotes completely.  The quotes are not necessary for your usage.
$user = "SomeUser"
Write-Host '$user' # Output: $user / variables inside single quotes will be left as-is
Write-Host "$user" # Output: SomeUser / variables inside double-quotes will be expanded
Write-Host $user   # Output: SomeUser

Line
Write-Host 'The user with userID '$user' has been added to the SecurityGroup  $SecurityGroup'

should look something like this (with double quotes surrounding)
Write-Host "The user with userID '$user' has been added to the SecurityGroup '$SecurityGroup'"

About Quoting Rules


text:
Q: Overheating and battery draining About a month ago, I installed Ubuntu 14.10 on Lenovo T430 removing the current OS Windows 7. First two - three weeks everything was working smoothly. After then, my laptop started to overheat and battery life started to drain quicker. It fell down from 2.5 hours to approximately 1 hour. Although I have been using it for more than a month I am still new to Ubuntu. Any help is appreciated.

A: For all supported versions of Ubuntu
You can install TLP, a power management tool, to improve the battery life and reduce overheating.

TLP brings you the benefits of advanced power management for Linux
without the need to understand every technical detail. TLP comes with
a default configuration already optimized for battery life, so you may
just install and forget it. Nevertheless TLP is highly customizable to
fulfil your specific requirements.
You can obtain TLP in one of 2 ways.

Since Wily, TLP is available by enabling the Universe Repository and issuing the commands sudo apt-get update to update the package list
And to install tlp and it's recommended packages
sudo apt install tlp tp-smapi-dkms acpi-call-dkms

If you wish to install from the PPA.
Open a terminal an enter the following commands:
sudo add-apt-repository ppa:linrunner/tlp
sudo apt update
sudo apt install tlp


text:
Q: Unable to build protobuf 2.4.1 on Ubuntu When I was trying to run make command to build protobuf on Ubuntu 20, I faced this error
google/protobuf/compiler/command_line_interface.cc:913:55: error: cannot bind rvalue reference of type 'std::__cxx11::basic_string<char>&&' to lvalue of type 'std::string' {aka 'std::__cxx11::basic_string<char>'}
  913 |       proto_path_.push_back(make_pair<string, string>(virtual_path, disk_path));
      |                                                       ^~~~~~~~~~~~
In file included from /usr/include/c++/9/bits/stl_algobase.h:64,
                 from /usr/include/c++/9/bits/char_traits.h:39,
                 from /usr/include/c++/9/string:40,
                 from ./google/protobuf/stubs/common.h:41,
                 from ./google/protobuf/compiler/command_line_interface.h:41,
                 from google/protobuf/compiler/command_line_interface.cc:35:

Anyone know how to fix it?

A: Three things spring to mind:

*

*You may need to specify a given C++ version e.g. -std=c++11

*It appears you can install multiple versions of gcc on Ubuntu 20 as well: https://linuxize.com/post/how-to-install-gcc-on-ubuntu-20-04/

*If all else fails, you could create a docker image to perform your compilation, base the docker image on an older version of Ubuntu/Debian and/or use an older compiler. Also see this: https://askubuntu.com/questions/1229774/how-to-use-an-older-version-of-gcc


text:
Q: C - array manipulation console app terminated with status 0 My app is supposed to take a double array, find the average of elements of even columns, find the max value, compare average to max / 2 and rotate the matrix 90 degrees if  average > max / 2.
Here is the code:
#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
#include <math.h>

int M = 4, N = 4;

int ** rotateArr(int arr[4][4]) {
    int D[4][4];
    int i, n;
    for(i=0; i <= 4; i++ ){
        for(n =0; n <= 4; n++){
            D[i][n] = arr[n][M - i + 1];
        }
    }
    return D;
}
int getAvg(int arr[4][4]) {
    int sum = 0, num = 0;
    int i, n;
    for(i=0; i <= 4; i += 2){
        for(n=0; n <= 4; n++){
            sum += arr[i][n];
            num += 1;
        }
    }
    return sum/num;
}

int ** getMax(int arr[4][4]) {
    int maxa = arr[0][0];
    int i, n;
    for(i=0; i <= 4; i++){
        for(n=0;  n <= 4; n++){
            if (maxa < arr[i][n]){
                maxa = arr[i][n];
            }
        }
    }
    return maxa;
}

int main()
{

    int S[4][4] = { { 1, 4, 10, 3 }, { 0, 6, 3, 8 }, { 7, 10 ,8, 5 },  { 9, 5, 11, 2}  };
    int maxa = 0;
    float avg = 0;

    avg = getAvg(S);
    maxa = getMax(S);
    int i , n;
    if (avg > maxa/2){
        S[4][4] = rotateArr(S);
        for(i=0; i <= 4; i+=2){
            for(n=0 ; n <= 4; n++){
                    printf("%d", S[i][n]);
            }
            printf("\n");
        }
    }

    getch();

    return 0;
}

The app doesn't output anything and just ends on key press with

Process terminated with status 0 (0 minutes, 2 seconds)

A: There are a lot of problems with your code. For example:

*

*All your loops are of the form for(i=0; i <= 4; i++ ) The condition should be changed to i < 4 because the valid array indices are 0 to 3.

*The rotateArr function returns a pointer to a local variable. You can't do this. One solution is to receive the output array as a parameter and write into it:
void rotateArr(int arr[4][4], int output[4][4]) {
     ....
     output[i][j] = ...;
}

*int** is not the same as int[4][4].

*S[4][4] = ... tries to assign to an invalid element. It looks like you're trying to assign to S itself, which can't be done (you need to assign each element, or memcpy from another array):
int anArray[4][4];
int anotherArray[4][4];
memcpy(anArray, anotherArray, sizeof(anArray));

*In the expression arr[n][M - i + 1], the second index can be out of range. Consider what happens when i==0.

I suggest you pay attention to compiler warnings, as they would catch some of these issues (on GCC compiler use the -Wall option). Also, learn to use a debugger.

A: Analyse your program and you will find that;

*

*You are returning D (of type int (*)[4] from rotateArr whose return type is int **. And similar issue with getMax.

*For n =4 array arr[i][n] will go out of bound!

*sum/num is in fact not calculating the average value (numerator and denominator both are int and you will always get an int value (may be 0 too).
and many more..........


text:
Q: Enable/add scanning to printer from printer server I have a printer that is installed on a Windows Server 2012 R2 machine and being deployed to the Windows clients.
I would like to be able to scan from it, not having to install it locally which is what I've been doing so far.
When it's installed locally, the categories under properties for the printer says "Multi function printer; Scanner", but when it's deployed from the server, it simply says "Printer" and Windows Fax and Scan is unable to detect a scanner without having it locally installed.

How can I enable/add Scanner as a category to the deployed printer so I don't have to install it locally on every machine?

A: According to the User Manual page 55 (page 65 of the PDF), here's how you set up network scanning on the HP LaserJet Pro MFP M225, M226.

*

*Type the printer's IP address in the address line of your browser, to access the printer's embedded web page.

*Click the Scan tab.

*On the left navigation pane, click the Network Folder Setup link.

*On the Network Folder Configuration page, click the New button.
a. In the Network Folder Information section, enter the Display Name and Network Path. If required, enter the network Username and Password.
b. Optional: To secure the folder from unauthorized access, enter a PIN in the Secure the Folder Access with a PIN section. This PIN will be required every time someone uses the scan to network folder feature.
c. In the Scan Settings section, adjust the scan settings.
NOTE: The network folder must be shared for this feature to work. It can be shared for only you or for other users.
Review all the information, then click Save and Test to save the information and test the connection, or Save Only to save the information only.


text:
Q: Conversão de array com json_encode PHP Opa, alguém sabe porque quando eu faço isso:
json_encode(array("0" => 0));

Retorna isso: [0]
Em vez disso: {"0":0}

A: O PHP deteta automáticamente se estás a usar chaves numéricas e converte numa array.
Se quiseres mesmo um objeto podes usar JSON_FORCE_OBJECT no segundo argumento (PHP 5.3+), opcional do json_encode. (exemplo: https://ideone.com/kFftSu)
Repara que se juntares outro elemento a essa array, sem chave numérica, o json_encode já lê como objeto.
Exemplo (https://ideone.com/yyrya4):
echo json_encode(array("0" => 0, "foo" => "bar"));
// dá:
{"0":0,"foo":"bar"}


text:
Q: Can't Assign 64 Bit Number to 64 Bit Min in C++ I'm new to C++, so sorry if this sounds like a dumb question. I'm attempting to assign the 64 bit minimum (-9223372036854775808) to an int64_t (from cstdint), however I'm getting the current error message:
main.cpp:5:27: warning: integer literal is too large to be represented in a signed integer type, interpreting as unsigned [-Wimplicitly-unsigned-literal]
int64_t int_64_min = -9223372036854775808;

The code is as follows:
#include <iostream>
#include <cstdint>

int main() {
    int64_t int_64_min = -9223372036854775808;
    std::cout << int_64_min << std::endl;
    std::cout << INT64_MIN << std::endl;
    return 0;
}

Am I missing something obvious?

A: This is exactly why the INT_MIN family of macros are often defined like -INT_MAX - 1 on a 2's complement platform (virtually ubiquitous and compulsory from C++20).
There is no such thing as a negative literal in C++: just the unary negation of a positive number which produces a compile time evaluable constant expression.
9223372036854775808 is too big to fit into a 64 bit signed integral type, so the behavior of negating this and assigning to a signed 64 bit integral type is implementation defined.
Writing -9223372036854775807 - 1 is probably what your C++ standard library implementation does. If I were you, I'd use INT64_MIN directly or std::numeric_limits<std::int64_t>::min().

A: The problem is that -9223372036854775808 is not a literal. 9223372036854775808 is a literal, and -9223372036854775808 is an expression consisting of that literal with a unary - applied to it.
All unsuffixed decimal literals are of type int, long int, or long long int. Since 9223372036854775808 is 263, it's bigger than the maximum value of long long int (assuming long long int is 64 bits, which it almost certainly is).
The simplest solution is to use the INT64_MIN macro defined in <cstdint>.
Aside from that, the problem is that there are no literals for negative values. Another solution is to replace -9223372036854775808 by -9223372036854775807-1 -- or by (-9223372036854775807-1) to avoid ambiguity. (The <cstdint> header very likely does something similar).


text:
Q: Can other people on an encrypted Wi-Fi AP see what you're doing? If you connect to an open, unencrypted Wi-Fi access point, everything you do can be captured by other people within range.
If you connect to an encrypted point, then people nearby can intercept what you're doing, but can't decrypt it.  The person who runs the access point can intercept what you're doing, though, right?
What about other people who know the key and are connected to the same point?  Can they intercept your wireless transmissions and decrypt them?  Or can they see your packets with a packet sniffer?

A: Yes, with WEP encryption it's super simple. Everything's encrypted with the key you needed to know to get on the network. Everyone on the network can decode everyone else's traffic without even trying.
With WPA-PSK and WPA2-PSK, it's a little trickier, but not too hard. WPA-PSK and WPA2-PSK encrypt everything with per-client, per-session keys, but those keys are derived from the Pre-Shared Key (the PSK; the key you have to know to get on the network) plus some information exchanged in the clear when the client joins or re-joins the network.  So if you know the PSK for the network, and your sniffer catches the "4-way handshake" another client does with the AP as it joins, you can decrypt all of that client's traffic. If you didn't happen to capture that client's 4-way handshake, you can send a spoofed de-authenticate packet to the target client (spoofing it to make it look like it came from the AP's MAC address), forcing the client to fall off the network and get back on, so you can capture its 4-way handshake this time, and decrypt all further traffic to/from that client. The user of the machine receiving the spoofed de-auth probably won't even notice that his laptop was off the network for a split second. Note that NO man-in-the-middle hassle is necessary for this attack. The attacker just has to capture a few specific frames at the time the target client (re-)joins the network.
With WPA-Enterprise and WPA2-Enterprise (that is, with 802.1X authentication instead of using a Pre-Shared Key), all the per-client per-session keys are derived completely independently, so there's no possibility of decoding each others' traffic. An attacker would either have to sniff your traffic on the wired side of the AP, or possibly set up a rogue AP in the hope that you'll ignore the bogus server-side certificate the rogue AP would send, and join the rogue AP anyway.

A: WPA at least has some form of session keys. Assuming (I'm not sure what WPA actually uses) the session keys are established using a protocol like Diffie-Hellman, they are initially secure even when the PSK is not. With the TKIP cypher session keys can be broken quickly, letting someone intercept and inject packets without knowing the pre-shared key.
However, someone who knows the PSK could just set up a rogue access point, do a man in the middle and pick their own session keys, which makes the point moot. An active attacker who knows your PSK can control the link layer, intercepting and modifying packets.
If you replace PSK authentication with IEEE 802.1X, which uses certificates and a PKI, you can trust the AP is initially the right one. A MITM would require the attacker to break clients and access point to get their private certificates, instead of just getting the PSK. The protocol seems to have a weakness that lets an attacker do a man in the middle after the initial authentication; I don't know how applicable this is to the wireless case. But people have a tendency to accept certificates blindly, and not all access points let you configure 802.1X.

A: Unencrypted WAP means all traffic over the wireless link can be read by anyone.
With an encrypted WAP, all traffic is encrypted on the radio link, but anyone with access to the WAP's WAN port can read the traffic even without the encryption key.  With the WAP's key, for WiFi, you can read all the traffic on the radio link.
The secure way to use a shared wireless AP is by using end-to-end encryption; your traffic is encrypted before it is sent over the radio link and is not decrypted until it arrives at the destination.  So, even with the WAP key or access to the WAP's WAN port, end-to-end encrypted traffic is safe.
A common way to gain end-to-end encryption is to use an encrypted VPN.  The traffic using the VPN between your machine and the VPN endpoint is encrypted, and so safe.
One complication.  A VPN can use a technique called split-tunneling, which means that traffic not destined for the network at the VPN's other side doesn't use the VPN.  And traffic that doesn't use the VPN isn't encrypted by the VPN, so if you use split tunneling, traffic not addressed to the other end of the VPN is not protected by the VPN.


text:
Q: A returned Promise with Fetch doesn't respond to .then() I'm a bit confused here, this part of some async code isn't working. Here's the problem:
export async function active() {
    return new Promise(function(resolve,reject){
        fetch("https://api.spotify.com/v1/me", { //omitted headers to keep it clean
        }).then(response => console.log(response)) <-- This code runs, and will log a response
        .then(data => function(){ <-- but this won't
            console.log("This won't run either")
            if (data.status == 200) {
                console.log(true)
                resolve(data)
            } else {
                console.log(false)
                reject(data)
            }
        })
    })
}

Why isn't the second part running? Sorry, I'm a bit new to async/await

A: There are a few problems there

*

*.then(data => function(){ passes a function that returns a function into .then. You want either an arrow function or the function keyword but not both. Since all you're doing is returning a function (which nothing calls), you don't see the contents of that function run. Get rid of the function() part of that.

*There's no reason for new Promise in that code (and no reason for your function to be async), just use the promise chain you have from fetch. (More here.)

*Your first then handler returns undefined, because you're returning the result of console.log.

*Your code uses the name data where you're still dealing with a Response object whose body you haven't yet read. You probably want to read the body, via the .text(), .json(), or other similar body-reading methods.
Instead:
export function active() {
    return fetch("https://api.spotify.com/v1/me", { //omitted headers to keep it clean
    })
    .then(response => {
        if (!repsonse.ok) {
            throw new Error("HTTP status " + response.status);
        }
        return response.text(); // or `.json()` or several others, see #4 above
    });
}

Note I changed the check for success there slightly.


text:
Q: sql query - update fields in existing with record values in the same table Environment: SQL Server 2012
I have a transaction table that contains a group of records with group id column.
In the example illustrated below, group 2 records were copied from group 1 records, Except for the sideId, sideSort, topId and topSort columns. Is there a way to cascade that down from group 1 to group 2 for just topSort and sideSort? The hard part is that topId and sideId aren't the same because of Identity fields in parent tables.
Here is a sqlfiddle of the example

A: You can do it this way. This is based on the assumption that you copy all the records for one group (@copiedFromGroupId) to another (@copiedToGroupId), i.e. that the ID's will be shifted by the number of records in the first group.
declare @copiedFromGroupId int = 1
declare @copiedToGroupId int = 2
declare @shift int

select @shift = (select max(id) from Tracker where GroupId = @copiedToGroupId)
  - (select max(id) from Tracker where GroupId = @copiedFromGroupId)

UPDATE T1
SET
  T1.TopSort = T2.TopSort,
  T1.SideSort = T2.SideSort
FROM Tracker T1
INNER JOIN Tracker T2 ON T1.ID = T2.ID + @shift

Check this SQL Fiddle

A: This is based on the row_number over the ORDER of TopId and SortID columns:
update test
set test.topSort = mix.topSort, test.sideSort = mix.sideSort
from
(select a.groupid aGroupid, b.groupID, b.Id bID, a.topSort, a.sideSort
from (select groupid,
     row_number() over(order by topID, sideId) rn,
     topSort, sideSort,
     id
     from test where groupid=1) a
inner join
     (select groupid,
     row_number() over(order by topID, sideId) rn,
     topSort, sideSort,
     id
     from test where groupid=2) b ON a.rn = b.rn) mix
inner join test on test.id=mix.bId
WHERE test.groupid=2;

SQLFiddle

A: Assuming that Id is an order field in the Group:
WITH C as
(
  select Tracker.*,
    ROW_NUMBER() OVER (PARTITION BY GroupId ORDER BY Id) as RN
  FROM Tracker
)
UPDATE CT
SET CT.topSort=CTU.topSort,
    CT.sideSort=CTU.sideSort

FROM C as CT
JOIN C as CTU ON (CT.rn=CTU.rn)
                  and (CTU.GroupID=1)
WHERE CT.GroupID=2

SQLFiddle demo


text:
Q: I have installed winfonts package as well as the microsoft true type fonts. Pdflatex is unablet find arial.ttf I am using texlive on Ubuntu 17.10. I have installed winfonts package. I have also installed microsoft fonts. However, pdflatex is unable to find arial.ttf. I get the following error message:
!pdfTeX error: /usr/local/bin/pdflatex (file arial.ttf): cannot open
TrueType font file for reading
 ==> Fatal error occurred, no output PDF file produced!

What can be the reason?


text:
Q: Trying to check to see if something exists and if not, assign something different to it with JavaScript Wondering if someone can help, I'll try to explain the best I can. I am looking at a json file for various steam games. Basically what I want to do is check to see if a certain "key(?)" is present and if not then return "None".
e.g. Check to see if body[id].data.metacritic and if it does then assign score to body[id].data.metacritic.score. The same with URL. I cannot figure this out!
I have tried the following:
        if(bulk.metacritic) var { score, url } = bulk.metacritic[0] || "None";

I just can't figure out how to get this right! Basically, body[id].data.metacritic doesn't exist in all json files, along with other parameters so I just want to display some placeholder text if they don't appear.

A: You can check if the body[id].data.metacritic is an array with a non-zero length and if so, use a value from it, otherwise use default values:
let score, url;
let data = body[id].data;
if (data && Array.isArray(data.metacritic) && data.metacritic.length > 0) {
    score = data.metacritic[0].score;
    url = data.metacritic[0].url;
} else {
    score = url = "None";
}

console.log(score, url);


text:
Q: magento 2 downlodable product when upload pdf display pop up "Attention true" in Magento 2 i want to upload a book in pdf in Downloadable Type product.
My pdf size are 11.5 MB. When i upload this pdf a pop up are displayed
like -- "Attention true".

and also when upload smaller size pdf its uploaded normally.
Question:- Why this error are display dose Magento 2 have size limit on uploaded file...?

A: There is no Default setting in Admin:
You have to update your php.ini settings:

/etc/php/  your_php_version directory  /apache2/php.ini

Upload below attributes.
memory_limit = 32M
upload_max_filesize = 24M
post_max_size = 32M

After update:
sudo service apache2 restart


text:
Q: Pressing on "Done" button while playing a YouTube video dismisses the rootViewController I have UINavigationController which needs to be displayed right after my root UINavigationController using storyBoard segue.
[self performSegueWithIdentifier:@"LoginViewController" sender:self];

This storyBoard segue is Modal.
On top of this LoginViewController I embedded YouTube video using the snippet here.
While the video is playing, pressing on the "Done" button will cause my LoginViewController to be dismissed along with the video.
It also happens when the video ends.
Is there any way to handle the "Done" button? is there any notification which Let me know when the video ends?
Thanks in advance

A: Add the UITextfield Delegate to your class, then set the delegate property of your uitextfield to "self".
Handle the "done" (aka "return") key with the following method:
- (BOOL)textFieldShouldReturn:(UITextField *)theTextField {
[textField resignFirstResponder];
    return NO;
}

A: I found a notification which helped me to know when the video end but you will have to use it carefully.
Apparently, When the youTube video plays, it appears on top of the UIWindow, So just before you trigger your video register the UIWindowDidBecomeVisibleNotification notification. Like this:
   [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(windowNowVisible:)
         name:UIWindowDidBecomeVisibleNotification
         object:self.view.window
         ];

When the video ends, The UIWindow comes visible again and and there you should remove the notification.


text:
Q: Protobuf-net and .proto file? I'm going to use protobuf-net library with my WCF services. Clients is Java-Android and I work with proto files on that side.
Should I manually code classes on .NET side or protobuf-net somehow supports .proto files?

A: If you are working from interop, then starting from .proto is the best option. For protobuf-net, there is a command-line tool "protogen", and a VS IDE add-in, that allow you to create protobuf-net compatible classes from .proto, similar to how you generate the code for other platforms. Both are available on the protobuf-net project site. If you already have classes, there is also some support for generating .proto from protobuf-net classes, but this is incomplete (indeed, in terms of v2 I only wrote it last night, so it is not in an official download yet).
If you are using cross-platform, you might also want to consider protobuf-csharp-port. This is a separate and parallel implementation by Jon, which retains a similar API to the Java API. You might find having a similar API between platforms to be be convenient.

A: Since you're interoperating with Java, you shouldn't write .NET classes -- instead, you should generate C# classes from the .proto files.
I haven't used protobuf-net (although I've used the Java protobuf extensively), but supposedly there's a Visual Studio tool to automatically generate C# code from .proto files.  There is also apparently a command line tool, but it seems that may not always be available.


text:
Q: javascript regular expression - getting value after colon, without the colon I have tried the https://www.regex101.com/#javascript tool, as well as a similar stackoverflow question and yet haven't been able to solve/understand this. Hopefully someone here can explain what I am doing wrong. I have created as detailed, step-by-step of an example as I can.
My goal is to be able to parse custom attributes, so for example:
I wrote some jquery code to pull in the attribute and the value, and then wanted to run regex against the result.
Below is the html/js, the output screenshot, and the regular expression screenshot, which says my regex query should match what I am expecting.
Expected result: 'valOne'
Result: ':valOne' <-- why am I getting a ':' character?

        Test custom attr

A: I haven't trudged through all the code, but something you need to understand about regexes is the difference between $0 and $1.
$0 is highlighted in blue. That is the entire part the regex matched.
You want $1. That's where the matches captured by the parenthesis are.
Read more about capture groups here.
var match = myRegexp.exec(myString);
alert(match[1]);  // This accesses $1

A: When you use String#match() with a regex with a global modifier, all the capture groups (those strings in the regex101.com right-hand bottom 'MATCH INFORMATION' pane are the values captured into Groups with ID 1 and higher) defined in the pattern are lost, and you only get an array of matched values.
You need to remove /g from your regexps and fix them as follows:
var regEx_attrVal = /[\w:]+(?=;|$)/;
var regEx_preColon = /\w+(?=:)/;
var regEx_postColon = /:(\w+)(?=;|\b)/;

Then, when getting the regEx_postColon captured value, use
var postColon = customAttrVal_string.match(regEx_postColon);
var postColon_string = postColon !== null ? postColon[1] : "";

First, check if there is a postColon regex match, then access the captured value with postColon[1].
See the whole updated code:

$(document).ready(function() {
  $('[customAttr]').each(function() {

    var attrValues = $(this).attr('customAttr');

    var regEx_attrVal = /[\w:]+(?=;|$)/;
    var regEx_preColon = /\w+(?=:)/;
    var regEx_postColon = /:(\w+)(?=;|\b)/;

    var customAttrVal = attrValues.match(regEx_attrVal);
    var customAttrVal_string = customAttrVal.toString();
    console.log('customAttrVal:');
    console.log(customAttrVal);
    console.log('customAttrVal_string: ' + customAttrVal_string);

    var preColon = customAttrVal_string.match(regEx_preColon);
    preColon_string = preColon.toString();
    console.log('preColon');
    console.log(preColon);
    console.log('preColon_string: ' + preColon_string);

    var postColon = customAttrVal_string.match(regEx_postColon);
    var postColon_string = postColon !== null ? postColon[1] : "";
    console.log('postColon');
    console.log(postColon);
    console.log('postColon_string: ' + postColon_string);

    console.log('pre: ' + preColon_string);
    console.log('post: ' + postColon_string);
  });
});

  Test custom attr

A: use data attributes. you can store json strings in them and access them like objects.
HTML

jQ
$("#div").data("custom").val1; //valOne
$("#div").data("custom").a; //b

A: I guess this is the regex pattern that you're looking for:
(?!(.*?):).*
Explanation

*

*(.*?:) Select all type of values and any number of times and a match that contains (:) simbol

*(?!  :) select inverse values of the first pattern, its kinda negation

*(  ).* Select all type of values after the evaluations

Also you can do the same with Jquery substring which for me the most simple way to do it, just like this:
How to substring in jquery


text:
Q: R - for each observation in a column, find the closest one in another column I'm trying to filter my dataframe to keep only the rows that meet the following condition:
For each day AND each price_1, keep only the row where price_2 is the closest to price_1, and if two rows are at equal distance, take the mean of the 2 prices and volatilies. For example :
 Date              price_2        price_1   Volat
 2011-07-15        215            200.0     5
 2011-07-15        217            200.0     6
 2011-07-15        235            200.0     5.5
 2011-07-15        240            200.0     5.3
 2011-07-15        200            201.5     6.2
 2011-07-16        203            205.0     6.4
 2011-07-16        207            205.0     5.1

Expected output:

 Date              price_2        price_1  Volat
 2011-07-15        215            200.0      5
 2011-07-15        200            201.5     6.2
 2011-07-16        205            205.0     5.75

I started like this, but I don't know how to continue :
group_by(Date)  %>%
which(df,abs(df$price_1-df$price_2)==min(abs(df$price_1-df$price_2)))

Thanks a lot in advance!

A: Base R Solution:
price_summary <-
  data.frame(do.call("rbind", lapply(split(
    df, paste(df$Date, df$price_1, sep = " - ")
  ),
  function(x) {
    data.frame(
      Date = unique(x$Date),
      price_1 = unique(x$price_1),
      price_2 = mean(x$price_2[which.min(abs(x$price_2 - x$price_1))]),
      Volat = mean(x$Volat),
      stringsAsFactors = FALSE
    )
  })),
  row.names = NULL)

Data:
df <- structure(
  list(
    Date = structure(c(
      15170, 15170, 15170, 15170,
      15170, 15171, 15171
    ), class = "Date"),
    price_2 = c(215L, 217L,
                235L, 240L, 200L, 203L, 207L),
    price_1 = c(200, 200, 200, 200,
                201.5, 205, 205),
    Volat = c(5, 6, 5.5, 5.3, 6.2, 6.4, 5.1)
  ),
  row.names = c(NA,-7L),
  class = "data.frame"
)

A: One dplyr option could be:
df %>%
 group_by(Date, price_1) %>%
 mutate(diff = abs(price_2 - price_1)) %>%
 filter(diff == min(diff)) %>%
 summarise_at(vars(price_2, Volat), mean)

  Date       price_1 price_2 Volat
  <chr>        <dbl>   <dbl> <dbl>
1 2011-07-15    200      215  5
2 2011-07-15    202.     200  6.2
3 2011-07-16    205      205  5.75


text:
Q: Can't send form data to wpdb when URL has query string I have a table called wp_invites which contains a list of invitees. This table contains a column called reference, which is added to the URL as a query param in order to customise their invite (i.e. test.com/?ref=1e232ewf2 ).
On my page, I have an RSVP form, and the idea is to submit the form data to another custom table called wp_rsvp.
With my current approach below, whenever I submit the form, I get a 404 error:
This test.test page can't be found
No web page was found for the web address: http://test.test/?ref=1e232ewf2
HTTP ERROR 404

I have tried leaving form action to an empty string (action=""), but no luck.
<form action="<?php get_the_permalink(); ?>" method="post">
  <fieldset class="fieldset">
    <input type="text" name="name" placeholder="Your name*" required />
  </fieldset>
  <fieldset class="fieldset">
    <input type="email" name="email" placeholder="Your email*" required />
  </fieldset>
  <fieldset class="fieldset">
    <textarea name="message"></textarea>
  </fieldset>
</form>

</php

global $wpdb;

/*
* on submit, send form data to DB
*/

if(isset($_POST['submit'])){
  insert_row();
}

/*
* get data from fields
*/

function insert_row(){

  $rsvp_table = $wpdb->prefix . 'invites';

  // get data from fields
  $name = sanitize_text_field( $_POST['name']);
  $email = sanitize_text_field( $_POST['email']);
  $message = sanitize_text_field( $_POST['message']);

  // store data in array
  $data = array(
    'form_completed_by' => $name,
    'email' => $email,
    'notes' => $message
  );

  var_dump($data);

  // set up formats for database SQL injection security
  $formats = array(
    '%s',  // form_completed_by should be an string
    '%s',
    '%s'
  );

  // Debugging: Turn on error reporting for db to see if there's a database error
  $wpdb->show_errors();

  // Actually attempt to insert the data
  $wpdb->insert($rsvp_table, $data, $formats);

}

?>

I am running all this code in one file (rsvp-form.php).
My data dumps (i.e. var_dump($data)) also show nothing. No new results in the wp_rsvp table naturally. Unsure where it's falling apart?
Latest approach
<?php $reference = ( isset( $_GET['ref'] ) ) ? sanitize_text_field( $_GET['ref'] ) : ''; ?>

<form action="<?php echo esc_url( get_the_permalink() ); ?>?<?php echo $reference; ?>" method="post">
  <input type="hidden" name="rsvp_nonce" value="<?php echo wp_create_nonce( 'rsvp_nonce' ); ?>" />
  <fieldset class="fieldset">
    <input type="text" name="name" placeholder="Your name*" required />
  </fieldset>
  <fieldset class="fieldset">
    <input type="email" name="email" placeholder="Your email*" required />
  </fieldset>
  <fieldset class="fieldset">
    <textarea name="message"></textarea>
  </fieldset>
</form>

</php

global $wpdb;

/*
* on submit, send form data to DB
*/

if(isset($_POST['submit'])){
  insert_row();
}

/*
* get data from fields
*/

function insert_row(){

  $rsvp_table = $wpdb->prefix . 'rsvp';

  // get data from fields & sanitize them
  $name = sanitize_text_field( $_POST['name']);
  $email = sanitize_text_field( $_POST['email']);
  $message = sanitize_text_field( $_POST['message']);

  // store data in array
  $data = array(
    'form_completed_by' => $name,
    'email' => $email,
    'notes' => $message
  );

  var_dump($data);

  // set up formats for database SQL injection security
  $formats = array(
    '%s',  // form_completed_by should be an string
    '%s',
    '%s'
  );

  // Debugging: Turn on error reporting for db to see if there's a database error
  $wpdb->show_errors();

  //  attempt to insert the data
  if ( ! wp_verify_nonce( $_POST['rsvp_nonce'], 'rsvp_nonce' ) ) {
    // Nonce verification failed, do not insert data
    return;
  } else {
    $wpdb->insert($rsvp_table, $data, $formats);
  }

  if ( $wpdb->last_error !== '' ) {
    // There was an error
    echo $wpdb->last_error;
  } else {
    // Success
    echo 'Data was inserted successfully';
  }

}

?>

A: I see a few issues with the code:
First, the form action is not set correctly. It should be something like:
<form action="<?php echo esc_url( get_the_permalink() ); ?>" method="post">
In the PHP code, you are using the wrong table name. You are using the table name 'invites' instead of 'rsvp'. You should change this line:
$rsvp_table = $wpdb->prefix . 'invites';
to:
$rsvp_table = $wpdb->prefix . 'rsvp';
You need to sanitize the form input data before inserting it into the database. You should use the sanitize_text_field() function to sanitize the input data. For example:
$name = sanitize_text_field( $_POST['name']);
You should check for errors after inserting data into the database, and display an error message if there are any errors. You can do this by adding this code after the call to $wpdb->insert():
if ( $wpdb->last_error !== '' ) {
    // There was an error
    echo $wpdb->last_error;
} else {
    // Success
    echo 'Data was inserted successfully';
}

You should also consider nonce verification for security purposes. You can add a nonce field to the form and verify it before inserting data into the database. For example:
<input type="hidden" name="my_form_nonce" value="<?php echo wp_create_nonce( 'my_form_nonce' ); ?>" />

And then in the PHP code, you can verify the nonce like this:
if ( ! wp_verify_nonce( $_POST['my_form_nonce'], 'my_form_nonce' ) ) {
    // Nonce verification failed, do not insert data
    return;
}

With these changes, your code should work as expected.


text:
Q: Xamp issue on deploying site I got a php website from my friend  i need to run this on my pc . when i run this the site using xamp it  is not running completely the pictures which are used in it are broken is there any solution to it ?

A: The links are definitely broken just like @chris85 said.
Check all the href attributes and links and make sure your giving them the right path to your images or what not. If your running over Windows it should be C:/Xampp/htdocs/ProjectName/...
You can use a built in function being dirname(FILE)  to get to the root of your project.


text:
Q: Find the point where maximum intervals overlap for certain interval length I'm trying to maximize attendance to a event given a list of busy times for each person. The event can be scheduled anytime between a certain date and hours (Ex. March 1st to March 8th from 9-5) and that attendance is maximized.
So far I've tried using a sliding window approach, and a counting approach described here (https://www.geeksforgeeks.org/find-the-point-where-maximum-intervals-overlap/) however I only managed to get the sliding window approach working with a time complexity of O(n^3) which unfortunately is not good enough for my use case. The counting approach does not work because I can find the maximum interval but not for a certain timeframe.
A worst case scenario use case would be ~500 people and a month timespan.
Any help would be much appreciated.

A: Solved using a Interval Tree (https://en.wikipedia.org/wiki/Interval_tree)


text:
Q: Writing files to a path with name incrementation In a Unity3D script, I have the following that simply writes a file (an image) to a path:
var path = Application.persistentDataPath + "/ocr.jpg";
FileOperations.Create(blah, path);

Of course in a static Utility program elsewhere, I have implemented this helper function as follows:
public static void Create(byte[] bytes, string path)
{
    var file = File.Open(path, FileMode.Create);

    using ( var binary = new BinaryWriter(file) )
    {
        binary.Write(bytes);
        file.Close();
    }
}

I realised my implementation would only create one file; i.e. over-write an existing file with the same name (ocr.jpg) so I wrote the following code:
public static void Create(byte[] bytes, string path)
{
    if ( !File.Exists(path) )
    {
        var file = File.Open(path, FileMode.Create);

        using ( var binary = new BinaryWriter(file) )
        {
            binary.Write(bytes);
            file.Close();
        }
    }
    else
    {
        int counter = 1;
        path = Application.persistentDataPath + "/ocr" + "_" + counter + ".jpg";

        var file = File.Open(path, FileMode.Create);

        using ( var binary = new BinaryWriter(file) )
        {
            binary.Write(bytes);
            file.Close();
        }
    }
}

Then, I realised every time I run the app, the counter is set back to 1, so now my ocr_1.jpg is over-written!
(Never mind that this half-solution is already ugly, because it brings in some Unity-specific stuff. I was hoping not to include the using UnityEngine in my helper utility class.)
Next, I tried to do it recursively, as follows:
public static void Create(byte[] bytes, string path)
{
    if ( !File.Exists(path) )
    {
        var file = File.Open(path, FileMode.Create);

        using ( var binary = new BinaryWriter(file) )
        {
            binary.Write(bytes);
            file.Close();
        }
    }
    else
    {
        int counter = 1;
        path = Application.persistentDataPath + "/ocr" + "_" + counter + ".jpg";

        Create(bytes, path);
    }
}

But I got a StackOverFlow error message. I don't understand why though, because the checking should go on until there is no file with the same name, etc...
Could someone please help me understand what I am doing wrong, and how I can achieve my goal of running the app as many times as I want and getting images created sequentially: ocr.jpg, ocr_1.jpg, ocr_2.jpg, ocr_3.jpg, etc...
Also, it would be great if I find out how to do this in a way that my utility class does not have to include unity-related stuff; i.e. only have using System.IO

A: In case you pass in a path that already exists and
path = Application.persistentDataPath + "/ocr" + "_" + counter + ".jpg";

also exists, you keep on calling Create method without incrementing counter, hence stack overflow. Consider passing counter value to the recursive create method, and updating it in every iteration, until it hits a filename that doesn't exist.

A: The reason why you are getting a StackOverflow is due to the filling of the methods Call Stack. In your code, the counter variable is a local variable to the method and is never incremented. Therefore, every time there is a recursive call to the Create method, an identical call (argument-wise) is made.
As a high-level solution, you should do two things:

*

*Track the value of the counter throughout the recursive calls

*Make sure to increment the value of the counter with every recursive call of Create
You could track the state of the counter variable either by having it as a global variable (which sometimes is not a good idea) or to keep it part of the Create method arguments.

A:
I was hoping not to include the using UnityEngine in my helper utility
  class

You don't have to. You can use its fully qualified name that includes its namespace:
UnityEngine.Application.persistentDataPath

Few things to know:
1.Always catch Exceptions when reading or writing to a file.
2.Don't do something like this: Application.persistentDataPath + "/ocr" + "_" + counter + ".jpg";.
Not a good idea to concatenate file name with "+" since that is not portable across platforms. Use Path.Combine for that.

Here is how I would implement this:
Use PlayerPrefs.SetInt to save the counter. Each time you want to save the image, use PlayerPrefs.GetInt to read the counter then save the image with File.WriteAllBytes. If saving is successful, increment the counter then save it with PlayerPrefs.SetInt.
Roughly something like below:
public static void Create(byte[] dataToSave)
{
    //Load old counter
    int counter = PlayerPrefs.GetInt("_counter_", 0);

    //Concatenate file name
    string tempPath = Path.Combine(UnityEngine.Application.persistentDataPath, "ocr");
    tempPath = Path.Combine(tempPath, "_");
    tempPath = Path.Combine(tempPath, counter.ToString() + ".jpg");

    //Create Directory if it does not exist
    if (!Directory.Exists(Path.GetDirectoryName(tempPath)))
    {
        Directory.CreateDirectory(Path.GetDirectoryName(tempPath));
    }
    //Debug.Log(path);

    try
    {
        File.WriteAllBytes(tempPath, dataToSave);
        Debug.Log("Saved Data to: " + tempPath.Replace("/", "\\"));

        //Increment Counter
        counter++;

        //Save current Counter
        PlayerPrefs.SetInt("_counter_", counter);
        PlayerPrefs.Save();
    }
    catch (Exception e)
    {
        Debug.LogWarning("Failed To PlayerInfo Data to: " + tempPath.Replace("/", "\\"));
        Debug.LogWarning("Error: " + e.Message);
    }
}


text:
Q: EF6 Fluent Api - I need to set Default value in FluentApi in order to Map Child to be used instead of Parent Here's part of the setup. Names are simplified:
I have following classes:

*

*MyClass

*MySubclass1 : MyClass

*MySubClass2 : MyClass

MyClass is part of another class (and table), which I will leave out.
I'm trying to do an EF6 query (using context.Set<MyClass>.Where(...))
I want to return the subclasses instead of the parent class and I want to avoid using the Discriminator. The reason is: there is a property on MyClass that already defines whether it's MySubclass1 or MySubclass2.
The property is called KindId and is an FK to a lookup table (Kinds).
The EF-part is being autogenerated as follows:
public partial class MyClassMap : EntityTypeConfiguration<MyClass>
{
    public MyClassMap ()
    {
        ToTable("MyClasses", "MySchema");
        //...etc (other implementations)

        HasRequired(c=> c.Kind)
            .WithMany(kind => kind.MyClasses)
            .HasForeignKey(c => new { c.KindId });

        Initialize();
    }

    partial void Initialize();
}

This means, I can only update Initialize().
I have done so as follows:
public partial class MyClassMap
{
    partial void Initialize()
    {
        Map<MySubclass1>(c => c.Requires("KindId").HasValue(1));
        Map<MySubclass2>(c => c.Requires("KindId").HasValue(2));
    }
}

When I run the EF query, I'm getting following exception:

error 3023: Problem in mapping fragments starting at lines x:Column
  MyClass.KindId has no default value and is not nullable. A column value
  is required to store entity data.

I tried setting the default value on the DB, but I think it requires the Default to be set within EF.
Question is: how do I do this using the FluentApi?

A: You're probably getting an error because it doesn't know what discriminator value to use for the base class.  So, I think you also need a map for the base class -- for example:
Map<MyClass>(c => c.Requires("KindId").HasValue(0));


text:
Q: How can I avoid an IllegalStateException if I need to add a Fragment in onNewIntent() or after a run-time change? I'm well aware of what an IllegalStateException is and why it happens when you are trying to commit FragmentTransactions after instance state has been saved. I've read through most of the popular Stackoverflow questions on the subject as well as "The Blog Post."
I have a particular scenario in which I've created a Fragment to display a custom progress spinner while the app is waiting for some search results to come in. So my search Activity is running in singleTop mode and relies on onNewIntent() to perform the search and display the spinner. This all works fine, but fails when run-time changes come in (like orientation changes). I'll get an IllegalStateException if I try removing the progress spinner Fragment after an orientation change, or when adding the spinner after a voice search. My setup looks like this:
@Override
protected void onNewIntent(Intent intent) {
    if(intent.getAction().equals(Intent.ACTION_SEARCH)) {
        performSearch(intent.getStringExtra(SearchManager.QUERY));
    }
}

The performSearch() method sends the request to my server and then adds the progress spinner Fragment like this...
private void showProgressSpinner() {
    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction transaction = fragmentManager.beginTransaction();
    transaction.setCustomAnimations(R.anim.fragment_fade_in, R.anim.fragment_fade_out);
    ProgressFragment spinner = ProgressFragment.newInstance();
    transaction.add(R.id.searchContainer, spinner, "spinner");
    transaction.commit();
}

Then when the search results come in through an asynchronous callback, I remove the progress spinner Fragment like this...
private void dismissProgressSpinner() {
    FragmentManager fragmentManager = getSupportFragmentManager();
    FragmentTransaction transaction = fragmentManager.beginTransaction();
    transaction.setCustomAnimations(R.anim.fragment_fade_in, R.anim.fragment_fade_out);
    ProgressFragment spinner = (ProgressFragment) fragmentManager.findFragmentByTag("spinner");
    if(spinner != null) {
        transaction.remove(spinner);
    }
    transaction.commit();
}

If an orientation change comes in while the progress spinner Fragment is being displayed, I get the IllegalStateException when the search results return and I try to remove the spinner Fragment. According to Alex Lockwood, putting the FragmentTransaction in onPostResume() can help, since you are guaranteed to have the state restored by then. This indeed works, but I need to remove the Fragment in my asynchronous callback from the search results, not when the Activity resumes.
So my question is, how can I commit this Fragment transaction after a state change, but within my async callback? I've tried using commitAllowingStateLoss() but I still get the exception because my spinner Fragment is still referencing the old destroyed Activity. What's the best way to handle this?

A:
I've tried using commitAllowingStateLoss() but I still get the exception because my spinner Fragment is still referencing the old destroyed Activity.

your fragment was recreated after config change, ie. after user have rotated screen - your spinner fragment will be destroyed and recreated, and after onAttach it will reference new activity instance. Also all of this process is done by android on UI thread in single message, so there is no chance that your async operation callback (which should execute also on UI thread) gets executed in the middle.
I assume here you are not creating some local reference to activity inside ProgressFragment.
You could write additional logic that would make sure your commit is called in valid moment. ie. in your activity onStart set some static boolean allowCommit to true, and in onPause set it to false. Also add some static variable, searchWasFinished, and in your async callback check if allowCommit is true if so then immediately remove spinner, if not then only set searchWasFinished to true. Inside your Activity.onStart check if searchWasFinished==true and if so then remove fragment with commit. This is just an idea, probably more logic would have to be put in it.


text:
Q: What are the shuffle icons next to function calls in the stack trace view of the Xcode debugger? I am trying to debug an Alamo Fire post request but as soon as the execution makes it to this method the function calls in the stack trace suddenly have shuffle icons next to them and the debugger can't find any of the local variables when using Print description or po <variable name>. Also when I try setting a break point in the calling method instead and stepping into this method, Xcode steps into assembly code and never makes it to getTokens.
func getTokens(from code: String) async throws -> TokenPair {
    let url = self.myUrl
    let request = AF
        .request(url, method: .post, parameters: ["code": code], encoder: .json)
    print(request.data)
    let result = await request.validate()
        .serializingResponse(using: DecodableResponseSerializer<[String: String]>())
        .result

    switch result {
    case .failure(let error):
        throw getError(from: error)
    case .success(let body):
        return try parseTokens(from: body)
    }
}

What are these shuffle icons? And as a bonus, why can't I see variables via the debugger?


text:
Q: Iterating over years for features in public feature collection using GEE? I want to calculate the surfaces deforested every year for every protected area in Democratic Republic of the Congo. I am building from the script provided as answer by Rodrigo Principe in reply to this similar question. But this example used a private shapefile loaded in assets. When I try to reproduce this solution with a public dataset (in-land protected areas in DRC, so my question somehow completes the official GEE tutorial on quantigfying deforestation in DRC), it doesn't work : output "areas" remain desesperatelly empty.
The code bellow is the same as proposed by Rodrigo Principe, except the lines marked with an"// EDIT" comment. Does anyone knows how to fix it?
// Load and filter the Hansen data
// EDIT : The source in following line has been updated to load v1_3
var gfc2014 = ee.Image('UMD/hansen/global_forest_change_2015_v1_3')
              // END EDIT
              .select(['treecover2000','loss','gain','lossyear']);

// list for filter iteration
var years = ee.List.sequence(1, 14)

// turn your scale into a var in case you want to change it
var scale = 100

//add country districts as a feature collection
// EDIT: loads public source+filters inland protected areas in DRC
var distr = ee.FeatureCollection('WCMC/WDPA/current/polygons');
// Filter to keep only inland PA in 2 countries
var distr = distr.filter(ee.Filter.and(
    ee.Filter.eq("ISO3", "COD"),
    ee.Filter.eq("MARINE", "0")));
// END EDIT

//look at tree cover, find the area
var treeCover = gfc2014.select(['treecover2000']);
var areaCover = treeCover.multiply(ee.Image.pixelArea())
                .divide(10000).select([0],["areacover"])

// total loss area
var loss = gfc2014.select(['loss']);
var areaLoss = loss.gt(0).multiply(ee.Image.pixelArea())
               .divide(10000).select([0],["arealoss"]);

// total gain area
var gain = gfc2014.select(['gain'])
var areaGain = gain.gt(0).multiply(ee.Image.pixelArea())
               .divide(10000).select([0],["areagain"]);

// final image
var total = gfc2014.addBands(areaCover)
            .addBands(areaLoss)
            .addBands(areaGain)

Map.addLayer(total,{},"total")

// Map cover area per feature
var districtSums = areaCover.reduceRegions({
  collection: distr,
  reducer: ee.Reducer.sum(),
  scale: scale,
});

var addVar = function(feature) {

  // function to iterate over the sequence of years
  var addVarYear = function(year, feat) {
    // cast var
    year = ee.Number(year).toInt()
    feat = ee.Feature(feat)

    // actual year to write as property
    var actual_year = ee.Number(2000).add(year)

    // filter year:
    // 1st: get mask
    var filtered = total.select("lossyear").eq(year)
    // 2nd: apply mask
    filtered = total.updateMask(filtered)

    // reduce variables over the feature
    var reduc = filtered.reduceRegion({
      geometry: feature.geometry(),
      reducer: ee.Reducer.sum(),
      scale: scale,
      maxPixels: 1e9 // EDIT : added to allow large areas
    })

    // get results
    var loss = ee.Number(reduc.get("arealoss"))
    var gain = ee.Number(reduc.get("areagain"))

    // set names
    var nameloss = ee.String("loss_").cat(actual_year)
    var namegain = ee.String("gain_").cat(actual_year)

    // alternative 1: set property only if change greater than 0
    var cond = loss.gt(0).or(gain.gt(0))
    return ee.Algorithms.If(cond,
                            feat.set(nameloss, loss, namegain, gain),
                            feat)

    // alternative 2: always set property
    // set properties to the feature
    // return feat.set(nameloss, loss, namegain, gain)
  }

  // iterate over the sequence
  var newfeat = ee.Feature(years.iterate(addVarYear, feature))

  // return feature with new properties
  return newfeat
}

// Map over the FeatureCollection
var areas = districtSums.map(addVar);

Map.addLayer(areas, {}, "areas")

print(areas)

A: It does work, to prove it, I modified a little bit the code to show a chart. Just click on one feature and it shows 2 charts: loss and gain. If there are 2 overlapping features, it just plots for the first.
Code link: https://code.earthengine.google.com/7405deb2901a53729745cea43986e708
Code:
// Load and filter the Hansen data
// EDIT : The source in following line has been updated to load v1_3
var gfc2014 = ee.Image('UMD/hansen/global_forest_change_2015_v1_3')
              // END EDIT
              .select(['treecover2000','loss','gain','lossyear']);

// list for filter iteration
var years = ee.List.sequence(1, 14)

// turn your scale into a var in case you want to change it
var scale = 100

//add country districts as a feature collection
// EDIT: loads public source+filters inland protected areas in DRC
var distr = ee.FeatureCollection('WCMC/WDPA/current/polygons');
// Filter to keep only inland PA in 2 countries
var distr = distr.filter(ee.Filter.and(
    ee.Filter.eq("ISO3", "COD"),
    ee.Filter.eq("MARINE", "0")));
// END EDIT

//look at tree cover, find the area
var treeCover = gfc2014.select(['treecover2000']);
var areaCover = treeCover.multiply(ee.Image.pixelArea())
                .divide(10000).select([0],["areacover"])

// total loss area
var loss = gfc2014.select(['loss']);
var areaLoss = loss.gt(0).multiply(ee.Image.pixelArea())
               .divide(10000).select([0],["arealoss"]);

// total gain area
var gain = gfc2014.select(['gain'])
var areaGain = gain.gt(0).multiply(ee.Image.pixelArea())
               .divide(10000).select([0],["areagain"]);

// final image
var total = gfc2014.addBands(areaCover)
            .addBands(areaLoss)
            .addBands(areaGain)

// Map cover area per feature
var districtSums = areaCover.reduceRegions({
  collection: distr,
  reducer: ee.Reducer.sum(),
  scale: scale,
});

var addVar = function(feature) {

  var nfeat = ee.Feature(ee.Feature(feature).geometry(), {})

  // function to iterate over the sequence of years
  var addVarYear = function(year, feat) {
    // cast var
    year = ee.Number(year).toInt()
    feat = ee.Feature(feat)
    //var nfeat = ee.Feature(feat.geometry(), {})

    // actual year to write as property
    var actual_year = ee.Number(2000).add(year)

    // filter year:
    // 1st: get mask
    var filtered = total.select("lossyear").eq(year)
    // 2nd: apply mask
    filtered = total.updateMask(filtered)

    // reduce variables over the feature
    var reduc = filtered.reduceRegion({
      geometry: feature.geometry(),
      reducer: ee.Reducer.sum(),
      scale: scale,
      maxPixels: 1e9 // EDIT : added to allow large areas
    })

    // get results
    var loss = ee.Number(reduc.get("arealoss"))
    var gain = ee.Number(reduc.get("areagain"))

    // set names
    var nameloss = ee.String("loss_").cat(actual_year)
    var namegain = ee.String("gain_").cat(actual_year)

    // alternative 1: set property only if change greater than 0
    var cond = loss.gt(0).or(gain.gt(0))
    //return ee.Algorithms.If(cond,
    //                        feat.set(nameloss, loss, namegain, gain),
    //                        feat)

    // alternative 2: always set property
    // set properties to the feature
    //return ee.Feature(feat.geometry(), {nemeloss:loss, namegain: gain})
    return feat.set(nameloss, loss, namegain, gain)
  }

  // iterate over the sequence
  var newfeat = ee.Feature(years.iterate(addVarYear, nfeat))

  // return feature with new properties
  return newfeat
}

// Map over the FeatureCollection
var areas = districtSums.map(addVar);

Map.addLayer(areas, {}, "areas")

var allY = ee.List.sequence(2001, 2014)
var allN = ee.List(['gain', 'loss'])
var allG = allY.map(function(item) {return ee.String('gain_').cat(ee.Number(item).int().format())})
var allL = allY.map(function(item) {return ee.String('loss_').cat(ee.Number(item).int().format())})

var onclick = function(coord) {
  var filt = areas.filterBounds(ee.Geometry.Point(coord.lon, coord.lat))
  var feat = ee.Feature(filt.first())
  var char_gain = ui.Chart.feature.byProperty({'features': feat,
                                               'xProperties': allG.getInfo()})
  print(char_gain.setOptions({'title':'GAIN'}))
  var char_loss = ui.Chart.feature.byProperty({'features': feat,
                                               'xProperties': allL.getInfo()})
  print(char_loss.setOptions({'title':'LOSS'}))
}
Map.onClick(onclick)


text:
Q: Catching NSException in Swift The following code in Swift raises NSInvalidArgumentException exception:
task = NSTask()
task.launchPath = "/SomeWrongPath"
task.launch()

How can I catch the exception? As I understand, try/catch in Swift is for errors thrown within Swift, not for NSExceptions raised from objects like NSTask (which I guess is written in ObjC). I'm new to Swift so may be I'm missing something obvious...
Edit: here's a radar for the bug (specifically for NSTask): openradar.appspot.com/22837476

A: TL;DR: Use Carthage to include https://github.com/eggheadgames/SwiftTryCatch or CocoaPods to include https://github.com/williamFalcon/SwiftTryCatch.
Then you can use code like this without fear it will crash your app:
import Foundation
import SwiftTryCatch

class SafeArchiver {

    class func unarchiveObjectWithFile(filename: String) -> AnyObject? {

        var data : AnyObject? = nil

        if NSFileManager.defaultManager().fileExistsAtPath(filename) {
            SwiftTryCatch.tryBlock({
                data = NSKeyedUnarchiver.unarchiveObjectWithFile(filename)
                }, catchBlock: { (error) in
                    Logger.logException("SafeArchiver.unarchiveObjectWithFile")
                }, finallyBlock: {
            })
        }
        return data
    }

    class func archiveRootObject(data: AnyObject, toFile : String) -> Bool {
        var result: Bool = false

        SwiftTryCatch.tryBlock({
            result =  NSKeyedArchiver.archiveRootObject(data, toFile: toFile)
            }, catchBlock: { (error) in
                Logger.logException("SafeArchiver.archiveRootObject")
            }, finallyBlock: {
        })
        return result
    }
}

The accepted answer by @BPCorp works as intended, but as we discovered, things get a little interesting if you try to incorporate this Objective C code into a majority Swift framework and then run tests. We had problems with the class function not being found (Error: Use of unresolved identifier). So, for that reason, and just general ease of use, we packaged it up as a Carthage library for general use.
Strangely, we could use the Swift + ObjC framework elsewhere with no problems, it was just the unit tests for the framework that were struggling.
PRs requested!  (It would be nice to have it a combo CocoaPod & Carthage build, as well as have some tests).

A: As noted in comments, that this API throws exceptions for otherwise-recoverable failure conditions is a bug. File it, and request an NSError-based alternative. Mostly the current state of affairs is an anachronism, as NSTask dates to back before Apple standardized on having exceptions be for programmer errors only.
In the meantime, while you could use one of the mechanisms from other answers to catch exceptions in ObjC and pass them to Swift, be aware that doing so isn't very safe. The stack-unwinding mechanism behind ObjC (and C++) exceptions is fragile and fundamentally incompatible with ARC. This is part of why Apple uses exceptions only for programmer errors — the idea being that you can (theoretically, at least) sort out all the exception cases in your app during development, and have no exceptions occurring in your production code. (Swift errors or NSErrors, on the other hand, can indicate recoverable situational or user errors.)
The safer solution is to foresee the likely conditions that could cause an API to throw exceptions and handle them before calling the API. If you're indexing into an NSArray, check its count first. If you're setting the launchPath on an NSTask to something that might not exist or might not be executable, use NSFileManager to check that before you launch the task.

A: The version improves the answer above to return the actual detailed exception message.
@implementation ObjC

+ (BOOL)tryExecute:(nonnull void(NS_NOESCAPE^)(void))tryBlock error:(__autoreleasing NSError * _Nullable * _Nullable)error {
   @try {
      tryBlock();
      return YES;
   }
   @catch (NSException *exception) {
      NSMutableDictionary *userInfo = [[NSMutableDictionary alloc] init];
      if (exception.userInfo != NULL) {
         userInfo = [[NSMutableDictionary alloc] initWithDictionary:exception.userInfo];
      }
      if (exception.reason != nil) {
         if (![userInfo.allKeys containsObject:NSLocalizedFailureReasonErrorKey]) {
            [userInfo setObject:exception.reason forKey:NSLocalizedFailureReasonErrorKey];
         }
      }
      *error = [[NSError alloc] initWithDomain:exception.name code:0 userInfo:userInfo];
      return NO;
   }
}

@end

Example usage:
      let c = NSColor(calibratedWhite: 0.5, alpha: 1)
      var r: CGFloat = 0
      var g: CGFloat = 0
      var b: CGFloat = 0
      var a: CGFloat = 0
      do {
         try ObjC.tryExecute {
            c.getRed(&r, green: &g, blue: &b, alpha: &a)
         }
      } catch {
         print(error)
      }

Before:
Error Domain=NSInvalidArgumentException Code=0 "(null)"

After:
Error Domain=NSInvalidArgumentException Code=0
"*** -getRed:green:blue:alpha: not valid for the NSColor NSCalibratedWhiteColorSpace 0.5 1; need to first convert colorspace."
UserInfo={NSLocalizedFailureReason=*** -getRed:green:blue:alpha: not valid for the NSColor NSCalibratedWhiteColorSpace 0.5 1; need to first convert colorspace.}

A: You cannot catch an Objective-C exception in Swift. However, you can work around that by making an Objective-C wrapper that you then import into Swift. I have done that work and made it a reusable Swift Package Manager package. Just add this package in Xcode and then use it like this:
import Foundation
import ExceptionCatcher

final class Foo: NSObject {}

do {
    let value = try ExceptionCatcher.catch {
        return Foo().value(forKey: "nope")
    }

    print("Value:", value)
} catch {
    print("Error:", error.localizedDescription)
    //=> Error: [valueForUndefinedKey:]: this class is not key value coding-compliant for the key nope.
}

A: Here is some code, that converts NSExceptions to Swift 2 errors.
Now you can use
do {
    try ObjC.catchException {

       /* calls that might throw an NSException */
    }
}
catch {
    print("An error ocurred: \(error)")
}

ObjC.h:
#import <Foundation/Foundation.h>

@interface ObjC : NSObject

+ (BOOL)catchException:(void(^)(void))tryBlock error:(__autoreleasing NSError **)error;

@end

ObjC.m
#import "ObjC.h"

@implementation ObjC

+ (BOOL)catchException:(void(^)(void))tryBlock error:(__autoreleasing NSError **)error {
    @try {
        tryBlock();
        return YES;
    }
    @catch (NSException *exception) {
        *error = [[NSError alloc] initWithDomain:exception.name code:0 userInfo:exception.userInfo];
        return NO;
    }
}

@end

Don't forget to add this to your "*-Bridging-Header.h":
#import "ObjC.h"

A: What I suggest is to make an C function that will catch the exception and return a NSError instead. And then, use this function.
The function could look like this:
NSError *tryCatch(void(^tryBlock)(), NSError *(^convertNSException)(NSException *))
{
    NSError *error = nil;
    @try {
        tryBlock();
    }
    @catch (NSException *exception) {
        error = convertNSException(exception);
    }
    @finally {
        return error;
    }
}

And with a little bridging help, you'll just have to call:
if let error = tryCatch(task.launch, myConvertFunction) {
    print("An exception happened!", error.localizedDescription)
    // Do stuff
}
// Continue task

Note: I didn't really test it, I couldn't find a quick and easy way to have Objective-C and Swift in a Playground.


text:
Q: Solving a recurrence for a random walk revisited I previously asked about the following recurrence which I get when trying to solve a random walk problem given a positive integer $x$.
$p_i = \dfrac{p_{i-1}}{2} + \dfrac{p_{i+2}}{2}$ if $0< i < x$
$p_i = 1$ if $i \geq x$
$p_0 = \dfrac{p_{2}}{2}$

Numerically it appears that $p_0$ tends to the ratio between every second term in the Fibonacci sequence as $x \to \infty$. Why is this?

We previously showed that the generating function for the recurrence is $U(z) = \frac{zp_1 + p_0}{z^3-2z^2+1}$.  @Did also showed that
$$p_i=As^i+B(-s)^{-i}+C$$
where  $s=\frac12(\sqrt5-1)$ . The boundary conditions $p_2=2p_0$ and $p_x=p_{x+1}=1$ indicate that
$$
(2-s^2)A+(2-s^{-2})B+C=0,
$$
and
$$
As^x+B(-s)^{-x}+C=As^{x+1}+B(-s)^{-x-1}+C=1.
$$
This enables us in principle to determine $A,B,$ and $C$.  However the solution I get using Maple looks really horrible. As I only want to get $p_0$ and $p_1$ in this question is there some way of getting a good large $x$ estimate that is easier to interpret?

It also seems numerically that as $x\to \infty$, $p_1$ tends to $s$ (that is the ratio between consecutive terms in the Fibonacci sequence).
  Why is this?

A: Consider a random walk on the integer line making $+2/-1$ steps with equal probabilities. The usual one-step recursion shows that each $p_i$ in the question is the probability to hit the negative halfline $H=\{n\in\mathbb Z\mid n\leqslant-1\}$ after the halfline $\{n\in\mathbb Z\mid n\geqslant x\}$ above $x$, starting from $i$.
When $x\to\infty$, the situation becomes simpler since $p_i\to q_i$ the probability to never hit $H$, starting from $i$. The drift of the random walk is positive hence $q_i\gt0$ for every $i\geqslant0$ and $q_i\to1$ when $i\to\infty$. To reach $H$ starting from $i\geqslant1$, one must first hit $i-1$ starting from $i$, then hit $i-2$ starting from $i-1$, and so on until one hits $-1$ starting from $0$. By the Markov property and the space invariance of the walk, this implies that $$1-q_i=(1-q_0)^{i+1},$$ for every $i\geqslant0$. Since $q_2=2q_0$ one gets $q_i=1-r^{i+1}$ for every $i\geqslant0$, where $r$ solves $$r^3-2r+1=0,$$ and $0\lt r\lt1$. Since $x^3-2x+1=(x-1)(x^2+x-1)$, one gets $$r^2+r-1=0.$$ The roots of $x^2+x-1$ are $x=\frac12(\pm\sqrt5-1)$, hence
$$r=\tfrac12(\sqrt5-1),$$
which implies
$$q_0=1-r=r^2=\tfrac12(3-\sqrt5),\quad q_1=1-r^2=r=\tfrac12(\sqrt5-1).$$


text:
Q: Web3j ECKeyPair to KeyPair I'm trying to make an ECC with the generated key using web3j. I have the ECKeyPair object, but cipher.init() requires 2nd parameter to be Key object. ECKeyPair returns BigInteger of private key and public key, how can I convert them to KeyPair which holds PrivateKey and PublicKey object?
I've tried (reference: CryptoUtil.java):
private fun decodeKeyPair(ecKeyPair: ECKeyPair): KeyPair {
        val xp = getNamedCurveByName("secp256k1")
        val p = ECNamedCurveSpec("secp256k1", xp.curve, xp.g, xp.n, xp.h, null)
        val curve = convertCurve(p.curve)
        val g = EC5Util.convertPoint(curve, p.generator, false)
        val n = p.order
        val h = BigInteger.valueOf(p.cofactor.toLong())
        val dp = ECDomainParameters(curve, g, n, h)

        val bytes = Numeric.toBytesPadded(ecKeyPair.publicKey, 64)
        val x = Numeric.toBigInt(Arrays.copyOfRange(bytes, 0, 32))
        val y = Numeric.toBigInt(Arrays.copyOfRange(bytes, 32, 64))
        val q = curve.createPoint(x, y)
        val publicKey = BCECPublicKey(
           "EC",
            ECPublicKeyParameters(q, dp),
            BouncyCastleProvider.CONFIGURATION
        )
        val privateKey = BCECPrivateKey(
            "EC",
            ECPrivateKeyParameters(ecKeyPair.privateKey, dp),
            publicKey,
            p,
            BouncyCastleProvider.CONFIGURATION
        )
        return KeyPair(publicKey, privateKey)
    }

but this returns an error:
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'org.bouncycastle.math.ec.ECCurve org.bouncycastle.jce.spec.ECParameterSpec.getCurve()' on a null object reference
Is there any other way to convert Web3j ECKeyPair to KeyPair?

A: I finally got it after exploring around https://www.programcreek.com. Main thing here was "how to generate ECPoint using the public key string".
Here's how I did it, instead of transforming the whole EcKeyPair object, I convert the keys separately.
Public Key String to ECPublicKey:
private fun toEcPublicKey(publicKey: String): ECPublicKey {
        val params = ECNamedCurveTable.getParameterSpec("secp256k1")
        val curveSpec = ECNamedCurveSpec("secp256k1", params.curve, params.g, params.n)

        //This is the part how to generate ECPoint manually from public key string.
        val pubKeyX = publicKey.substring(0, publicKey.length / 2)
        val pubKeyY = publicKey.substring(publicKey.length / 2)
        val ecPoint = ECPoint(BigInteger(pubKeyX, 16), BigInteger(pubKeyY, 16))

        val params2 = EC5Util.convertSpec(curveSpec.curve, params)

        val keySpec = java.security.spec.ECPublicKeySpec(ecPoint, params2)
        val factory = KeyFactory.getInstance("ECDSA")
        return factory.generatePublic(keySpec) as ECPublicKey
}

Private Key String to ECPrivateKey:
private fun toEcPrivateKey(privateKey: String): ECPrivateKey {
        val ecKeyPair = ECKeyPair.create(Numeric.hexStringToByteArray(privateKey))

        val params = ECNamedCurveTable.getParameterSpec("secp256k1")
        val curveSpec = ECNamedCurveSpec("secp256k1", params.curve, params.g, params.n)

        val keySpec = java.security.spec.ECPrivateKeySpec(
            ecKeyPair.privateKey,
            curveSpec)

        val factory = KeyFactory.getInstance("ECDSA")
        return factory.generatePrivate(keySpec) as ECPrivateKey
}

String key inputs are generated from Web3j library.


text:
Q: FD_SET causing seg fault I am running into an issue where FD_SET is crashing my program.  I am running the example code from a boost Boost ASIO sample HTTP Server.  In the request handler, I put a third party api the eventually makes the following calls:
fd_set fds;
FD_ZERO(&fds);
FD_SET(sockfd, &fds);

My program seems to be crashing on the FD_SET. Is there a situation where calling FD_SET from different threads would cause a segfault? I am not sure exactly how FD_SET works, my gut feeling would be that I am calling FD_SET on a fd that is already in use.  Would this cause a problem at all?
sockfd is a class member, which is created each time a request comes in, so I should not be sharing a sockfd variable between threads.

A: At 1000 requests/second you are very likely eclipsing the FD_SETSIZE limit (typically 1024 on Linux), which results in undefined behavior:

An fd_set is a fixed size buffer. Executing FD_CLR() or FD_SET() with
  a value of fd that is negative or is equal to or larger than
  FD_SETSIZE will result in undefined behavior. Moreover, POSIX requires
  fd to be a valid file descriptor.

You should look at using poll, epoll, or a higher level library like Boost Asio. Any of those choices will not have the limitation of select.


text:
Q: Linking 64bit app with 32bit lib in centos 5.6 64bit I want to build an application on Centos 5.6 64bit as a 64bit application and link it with a 32bit library.
How can i do this and what is the switches i need to pass to the gcc to compile and link.
Thanks.

A: You cannot.  A 64 bit application must link to 64 bit libraries.  If the library you must use is 32 bit, you must compile your application 32 bit as well.


text:
Q: Sequelize Op.like and Op.or failing i have this issue with Sequelize:
I'm trying to have a 3 parameter research and if one of those parameter is empty it should not consider that parameter.
const users = await User.findAll({
  where: {
    category: { [Op.like]: `%${req.query.category}%` },
    location: { [Op.like]: `%${req.query.location}%` },
    [Op.or]: [
      { job: { [Op.like]: `%${req.query.job}%` } },
      { bio: { [Op.like]: `%${req.query.job}%` } },
      { skills: { [Op.like]: `%${req.query.job}%` } },
    ],
  },
  attributes: { exclude: ['password', 'createdAt', 'updatedAt'] },
})

I've found out that the [Op.like] is not working anywhere.
It only works if a parameter is empty (blocks that parameter from filtering the users and that's something i like).
When i do a research with the example payload {category:'Information Technology', job:'frontend web dev', location:'Sydn'} this is logged in the process log:
Executing (default): SELECT `id`, `email`, `firstName`, `lastName`, `image`, `location`, `phone`,
`website`, `availability`, `category`, `job`, `skills`, `bio` FROM `Users` AS `User`
WHERE (`User`.`job` LIKE '%frontend web dev%' OR `User`.`bio` LIKE '%frontend web dev%' OR
`User`.`skills` LIKE '%frontend web dev%') AND `User`.`category` LIKE '%Information Technology%'
AND `User`.`location` LIKE '%Sydn%';

but no user is found. (yes, in the database  I have users with similar parameters)

A: I think it should looks more like this:
category: { [Op.like]: '%`${req.query.category}%`' },

What I did here is add single quote mark '. Reference to the documentation

A: In my opinion your code and your logged SQL are same. I don't see any errors. Maybe you should try to copy that SQL and paste it in MySQL Workbench (if you're using MySQL) then try to run it.


text:
Q: Create an INSERT SQL query based on other queries I need to perform an INSERT query like this:
INSERT INTO Clients (ClientName, CountryID) VALUES ("STYLUS", 4)

But:

*

*Only insert if ClientName (STYLUS for the example here) does not already exists

*The CountryID (4 for the example here) must be retrieved from another query: SELECT CountryID FROM Countries WHERE CountryUK = 'FRANCE'
Is it possible to build a single SQL Query for all of this ?
Thanks.

A: For the first condition, you need a unique index/constraint on the table:
create unique index unq_clients_clientname;

Then, you can insert the value doing:
insert into clients(clientname, countryId)
    select 'STYLUS', countryid
    from countries
    where countryuk = 'FRANCE';

This will return an error if you attempt to insert a duplicate value.  If you don't want an error, then a database-independent method is:
insert into clients(clientname, countryId)
    select 'STYLUS', countryid
    from countries
    where countryuk = 'FRANCE' and
          not exists (select 1 from clients c2 where c2.clientname = 'STYLUS');

A: Being Simple,
if not exists(select * from Clients  where Cientname='Stylus') begin insert into Clients select 'Stylus',Countryid from Countries  where countryname='France' end

will do the work.Hope It helps.