Programs & Examples On #System

System may refer to a set of interdependent components; Low level infrastructure like the operating system (from a high language point of view) or an object or function for accessing the previous

A terminal command for a rooted Android to remount /System as read/write

You can try adb remount command also to remount /system as read write

adb remount

How do you run a .bat file from PHP?

You might need to run it via cmd, eg:

system("cmd /c C:[path to file]");

How to run cron once, daily at 10pm

Here is what I look at everytime I am writing a new crontab entry:

To start editing from terminal -type:

 zee$ crontab -e

what you will add to crontab file:

0 22 * * 0  some-user /opt/somescript/to/run.sh

What it means:

[ 
+ user => 'some-user',      
+ minute => ‘0’,             <<= on top of the hour.
+ hour => '22',              <<= at 10 PM. Military time.
+ monthday => '*',           <<= Every day of the month*
+ month => '*',              <<= Every month*
+ weekday => ‘0’,            <<= Everyday (0 thru 6) = sunday thru saturday
] 

Also, check what shell your machine is running and name the the file accordingly OR it wont execute.

Check the shell with either echo $SHELL or echo $0

It can be "Bourne shell (sh) , Bourne again shell (bash),Korn shell (ksh)..etc"

C: Run a System Command and Get Output?

You want the "popen" function. Here's an example of running the command "ls /etc" and outputing to the console.

#include <stdio.h>
#include <stdlib.h>


int main( int argc, char *argv[] )
{

  FILE *fp;
  char path[1035];

  /* Open the command for reading. */
  fp = popen("/bin/ls /etc/", "r");
  if (fp == NULL) {
    printf("Failed to run command\n" );
    exit(1);
  }

  /* Read the output a line at a time - output it. */
  while (fgets(path, sizeof(path), fp) != NULL) {
    printf("%s", path);
  }

  /* close */
  pclose(fp);

  return 0;
}

How can I check the system version of Android?

For checking device version which is greater than or equal to Marshmallow ,use this code.

if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.M){

    }

for ckecking others just change the VERSION_CODES like,
K for kitkat,
L for loolipop N for Nougat and so on...

Difference between subprocess.Popen and os.system

If you check out the subprocess section of the Python docs, you'll notice there is an example of how to replace os.system() with subprocess.Popen():

sts = os.system("mycmd" + " myarg")

...does the same thing as...

sts = Popen("mycmd" + " myarg", shell=True).wait()

The "improved" code looks more complicated, but it's better because once you know subprocess.Popen(), you don't need anything else. subprocess.Popen() replaces several other tools (os.system() is just one of those) that were scattered throughout three other Python modules.

If it helps, think of subprocess.Popen() as a very flexible os.system().

How do I execute a command and get the output of the command within C++ using POSIX?

I couldn't figure out why popen/pclose is missing from Code::Blocks/MinGW. So I worked around the problem by using CreateProcess() and CreatePipe() instead.

Here's the solution that worked for me:

//C++11
#include <cstdio>
#include <iostream>
#include <windows.h>
#include <cstdint>
#include <deque>
#include <string>
#include <thread>

using namespace std;

int SystemCapture(
    string         CmdLine,    //Command Line
    string         CmdRunDir,  //set to '.' for current directory
    string&        ListStdOut, //Return List of StdOut
    string&        ListStdErr, //Return List of StdErr
    uint32_t&      RetCode)    //Return Exit Code
{
    int                  Success;
    SECURITY_ATTRIBUTES  security_attributes;
    HANDLE               stdout_rd = INVALID_HANDLE_VALUE;
    HANDLE               stdout_wr = INVALID_HANDLE_VALUE;
    HANDLE               stderr_rd = INVALID_HANDLE_VALUE;
    HANDLE               stderr_wr = INVALID_HANDLE_VALUE;
    PROCESS_INFORMATION  process_info;
    STARTUPINFO          startup_info;
    thread               stdout_thread;
    thread               stderr_thread;

    security_attributes.nLength              = sizeof(SECURITY_ATTRIBUTES);
    security_attributes.bInheritHandle       = TRUE;
    security_attributes.lpSecurityDescriptor = nullptr;

    if (!CreatePipe(&stdout_rd, &stdout_wr, &security_attributes, 0) ||
            !SetHandleInformation(stdout_rd, HANDLE_FLAG_INHERIT, 0)) {
        return -1;
    }

    if (!CreatePipe(&stderr_rd, &stderr_wr, &security_attributes, 0) ||
            !SetHandleInformation(stderr_rd, HANDLE_FLAG_INHERIT, 0)) {
        if (stdout_rd != INVALID_HANDLE_VALUE) CloseHandle(stdout_rd);
        if (stdout_wr != INVALID_HANDLE_VALUE) CloseHandle(stdout_wr);
        return -2;
    }

    ZeroMemory(&process_info, sizeof(PROCESS_INFORMATION));
    ZeroMemory(&startup_info, sizeof(STARTUPINFO));

    startup_info.cb         = sizeof(STARTUPINFO);
    startup_info.hStdInput  = 0;
    startup_info.hStdOutput = stdout_wr;
    startup_info.hStdError  = stderr_wr;

    if(stdout_rd || stderr_rd)
        startup_info.dwFlags |= STARTF_USESTDHANDLES;

    // Make a copy because CreateProcess needs to modify string buffer
    char      CmdLineStr[MAX_PATH];
    strncpy(CmdLineStr, CmdLine.c_str(), MAX_PATH);
    CmdLineStr[MAX_PATH-1] = 0;

    Success = CreateProcess(
        nullptr,
        CmdLineStr,
        nullptr,
        nullptr,
        TRUE,
        0,
        nullptr,
        CmdRunDir.c_str(),
        &startup_info,
        &process_info
    );
    CloseHandle(stdout_wr);
    CloseHandle(stderr_wr);

    if(!Success) {
        CloseHandle(process_info.hProcess);
        CloseHandle(process_info.hThread);
        CloseHandle(stdout_rd);
        CloseHandle(stderr_rd);
        return -4;
    }
    else {
        CloseHandle(process_info.hThread);
    }

    if(stdout_rd) {
        stdout_thread=thread([&]() {
            DWORD  n;
            const size_t bufsize = 1000;
            char         buffer [bufsize];
            for(;;) {
                n = 0;
                int Success = ReadFile(
                    stdout_rd,
                    buffer,
                    (DWORD)bufsize,
                    &n,
                    nullptr
                );
                printf("STDERR: Success:%d n:%d\n", Success, (int)n);
                if(!Success || n == 0)
                    break;
                string s(buffer, n);
                printf("STDOUT:(%s)\n", s.c_str());
                ListStdOut += s;
            }
            printf("STDOUT:BREAK!\n");
        });
    }

    if(stderr_rd) {
        stderr_thread=thread([&]() {
            DWORD        n;
            const size_t bufsize = 1000;
            char         buffer [bufsize];
            for(;;) {
                n = 0;
                int Success = ReadFile(
                    stderr_rd,
                    buffer,
                    (DWORD)bufsize,
                    &n,
                    nullptr
                );
                printf("STDERR: Success:%d n:%d\n", Success, (int)n);
                if(!Success || n == 0)
                    break;
                string s(buffer, n);
                printf("STDERR:(%s)\n", s.c_str());
                ListStdOut += s;
            }
            printf("STDERR:BREAK!\n");
        });
    }

    WaitForSingleObject(process_info.hProcess,    INFINITE);
    if(!GetExitCodeProcess(process_info.hProcess, (DWORD*) &RetCode))
        RetCode = -1;

    CloseHandle(process_info.hProcess);

    if(stdout_thread.joinable())
        stdout_thread.join();

    if(stderr_thread.joinable())
        stderr_thread.join();

    CloseHandle(stdout_rd);
    CloseHandle(stderr_rd);

    return 0;
}

int main()
{
    int            rc;
    uint32_t       RetCode;
    string         ListStdOut;
    string         ListStdErr;

    cout << "STARTING.\n";

    rc = SystemCapture(
        "C:\\Windows\\System32\\ipconfig.exe",    //Command Line
        ".",                                     //CmdRunDir
        ListStdOut,                              //Return List of StdOut
        ListStdErr,                              //Return List of StdErr
        RetCode                                  //Return Exit Code
    );
    if (rc < 0) {
        cout << "ERROR: SystemCapture\n";
    }

    cout << "STDOUT:\n";
    cout << ListStdOut;

    cout << "STDERR:\n";
    cout << ListStdErr;

    cout << "Finished.\n";

    cout << "Press Enter to Continue";
    cin.ignore();

    return 0;
}

Why doesn't "System.out.println" work in Android?

Recently I noticed the same issue in Android Studio 3.3. I closed the other Android studio projects and Logcat started working. The accepted answer above is not logical at all.

Convert R vector to string vector of 1 element

Use the collapse argument to paste:

paste(a,collapse=" ")
[1] "aa bb cc"

How to print bytes in hexadecimal using System.out.println?

System.out.println(Integer.toHexString(test[0]));

OR (pretty print)

System.out.printf("0x%02X", test[0]);

OR (pretty print)

System.out.println(String.format("0x%02X", test[0]));

How to code a very simple login system with java

Code

import java.util.Scanner;

public class LoginMain {

public static void main(String[] args) {

    String Username;
    String Password;

    Password = "123";
    Username = "wisdom";

    Scanner input1 = new Scanner(System.in);
    System.out.println("Enter Username : ");
    String username = input1.next();

    Scanner input2 = new Scanner(System.in);
    System.out.println("Enter Password : ");
    String password = input2.next();

    if (username.equals(Username) && password.equals(Password)) {

        System.out.println("Access Granted! Welcome!");
    }

    else if (username.equals(Username)) {
        System.out.println("Invalid Password!");
    } else if (password.equals(Password)) {
        System.out.println("Invalid Username!");
    } else {
        System.out.println("Invalid Username & Password!");
    }

}

}

Getting output of system() calls in Ruby

You can use system() or %x[] depending what kind of result you need.

system() returning true if the command was found and ran successfully, false otherwise.

>> s = system 'uptime'
10:56  up 3 days, 23:10, 2 users, load averages: 0.17 0.17 0.14
=> true
>> s.class
=> TrueClass
>> $?.class
=> Process::Status

%x[..] on the other hand saves the results of the command as a string:

>> result = %x[uptime]
=> "13:16  up 4 days,  1:30, 2 users, load averages: 0.39 0.29 0.23\n"
>> p result 
"13:16  up 4 days,  1:30, 2 users, load averages: 0.39 0.29 0.23\n"
>> result.class
=> String

Th blog post by Jay Fields explains in detail the differences between using system, exec and %x[..] .

cannot convert 'std::basic_string<char>' to 'const char*' for argument '1' to 'int system(const char*)'

The system function requires const char *, and your expression is of the type std::string. You should write

string name = "john";
string system_str = " quickscan.exe resolution 300 selectscanner jpg showui showprogress filename '"+name+".jpg'";
system(system_str.c_str ());

How can I store the result of a system command in a Perl variable?

Using backtick or qx helps, thanks everybody for the answers. However, I found that if you use backtick or qx, the output contains trailing newline and I need to remove that. So I used chomp.

chomp($host = `hostname`);
chomp($domain = `domainname`);
$fqdn = $host.".".$domain;

More information here: http://irouble.blogspot.in/2011/04/perl-chomp-backticks.html

Java system properties and environment variables

I think the difference between the two boils down to access. Environment variables are accessible by any process and Java system properties are only accessible by the process they are added to.

Also as Bohemian stated, env variables are set in the OS (however they 'can' be set through Java) and system properties are passed as command line options or set via setProperty().

How to get current CPU and RAM usage in Python?

This aggregate all the goodies: psutil + os to get Unix & Windows compatibility: That allows us to get:

  1. CPU
  2. memory
  3. disk

code:

import os
import psutil  # need: pip install psutil

In [32]: psutil.virtual_memory()
Out[32]: svmem(total=6247907328, available=2502328320, percent=59.9, used=3327135744, free=167067648, active=3671199744, inactive=1662668800,     buffers=844783616, cached=1908920320, shared=123912192, slab=613048320)

In [33]: psutil.virtual_memory().percent
Out[33]: 60.0

In [34]: psutil.cpu_percent()
Out[34]: 5.5

In [35]: os.sep
Out[35]: '/'

In [36]: psutil.disk_usage(os.sep)
Out[36]: sdiskusage(total=50190790656, used=41343860736, free=6467502080, percent=86.5)

In [37]: psutil.disk_usage(os.sep).percent
Out[37]: 86.5

Get OS-level system information

I think the best method out there is to implement the SIGAR API by Hyperic. It works for most of the major operating systems ( darn near anything modern ) and is very easy to work with. The developer(s) are very responsive on their forum and mailing lists. I also like that it is GPL2 Apache licensed. They provide a ton of examples in Java too!

SIGAR == System Information, Gathering And Reporting tool.

get unique machine id

edit: I just saw you meant in c#. Here is a better way with unmanaged code:

ManagementClass oMClass = new ManagementClass ("Win32_NetworkAdapterConfiguration");
ManagementObjectCollection colMObj = oMCLass.GetInstances();
foreach(ManagementObject objMO in colMObj)
    Console.WriteLine(objMO["MacAddress"].ToString());

Adding system header search path to Xcode

We have two options.

  1. Look at Preferences->Locations->"Custom Paths" in Xcode's preference. A path added here will be a variable which you can add to "Header Search Paths" in project build settings as "$cppheaders", if you saved the custom path with that name.

  2. Set HEADER_SEARCH_PATHS parameter in build settings on project info. I added "${SRCROOT}" here without recursion. This setting works well for most projects.

About 2nd option:

Xcode uses Clang which has GCC compatible command set. GCC has an option -Idir which adds system header searching paths. And this option is accessible via HEADER_SEARCH_PATHS in Xcode project build setting.

However, path string added to this setting should not contain any whitespace characters because the option will be passed to shell command as is.

But, some OS X users (like me) may put their projects on path including whitespace which should be escaped. You can escape it like /Users/my/work/a\ project\ with\ space if you input it manually. You also can escape them with quotes to use environment variable like "${SRCROOT}".

Or just use . to indicate current directory. I saw this trick on Webkit's source code, but I am not sure that current directory will be set to project directory when building it.

The ${SRCROOT} is predefined value by Xcode. This means source directory. You can find more values in Reference document.

PS. Actually you don't have to use braces {}. I get same result with $SRCROOT. If you know the difference, please let me know.

How can I alter a primary key constraint using SQL syntax?

Yes. The only way would be to drop the constraint with an Alter table then recreate it.

ALTER TABLE <Table_Name>
DROP CONSTRAINT <constraint_name>

ALTER TABLE <Table_Name>
ADD CONSTRAINT <constraint_name> PRIMARY KEY (<Column1>,<Column2>)

Node.js - Maximum call stack size exceeded

Regarding increasing the max stack size, on 32 bit and 64 bit machines V8's memory allocation defaults are, respectively, 700 MB and 1400 MB. In newer versions of V8, memory limits on 64 bit systems are no longer set by V8, theoretically indicating no limit. However, the OS (Operating System) on which Node is running can always limit the amount of memory V8 can take, so the true limit of any given process cannot be generally stated.

Though V8 makes available the --max_old_space_size option, which allows control over the amount of memory available to a process, accepting a value in MB. Should you need to increase memory allocation, simply pass this option the desired value when spawning a Node process.

It is often an excellent strategy to reduce the available memory allocation for a given Node instance, especially when running many instances. As with stack limits, consider whether massive memory needs are better delegated to a dedicated storage layer, such as an in-memory database or similar.

What is the first character in the sort order used by Windows Explorer?

Although the answer with "!" was chosen as the correct answer, this is NOT true. I´m not sure about Windows Explorer in Windows 10/8.1/8, but I am certain concerning Windows 7 and XP.

The character that moves your filename to the very top is "'" (alt+39), and second best is "-" (the minus sign).

But sorting order in Windows Explorer is more complicated - it depends on the filename-lenght also, and numbers are treated very special.

The second character (and the following) is treated different. Here you often go best with a " " (spacebar), followed by the characters mentioned above, but you´ll have to try out, because it´s not so easy to find out the exact algorithm:

Here is an example for the correct sorting order for your understanding:

  1. file: "'"
  2. file: "''" (longer filename)
  3. file: "'''" (and so on)
  4. file: "-"
  5. file: "--"
  6. file: "---" (and so on)
  7. file: "- -" (spacebar used)
  8. file: "' '" (spacebar two times, therefore longer filename)
  9. file: "' ' '" (most top character, but longer filename!)
  10. file: "'' 0" (shorter filename, but chars like numbers came in)

Another example:

  1. "'' aaaa" ("'" is better than spacebar and spacebar is better than "a")
  2. "'' aaaaa"
  3. "' aaaaaa"

Same filelenght:

  1. "-- aa" (spacebar comes before "-" in this case!)
  2. "---aa"
  3. "--aaa"

Finally the very special logic when it comes to numbers:

  1. "0000000"
  2. "0"
  3. "00001"

But nevertheless: Renaming folders or files this way, you can quickly find what you are searching for.

Generating UML from C++ code?

Whoever wants UML deserves Rational Rose :)

Scheduling recurring task in Android

Quoting the Scheduling Repeating Alarms - Understand the Trade-offs docs:

A common scenario for triggering an operation outside the lifetime of your app is syncing data with a server. This is a case where you might be tempted to use a repeating alarm. But if you own the server that is hosting your app's data, using Google Cloud Messaging (GCM) in conjunction with sync adapter is a better solution than AlarmManager. A sync adapter gives you all the same scheduling options as AlarmManager, but it offers you significantly more flexibility.

So, based on this, the best way to schedule a server call is using Google Cloud Messaging (GCM) in conjunction with sync adapter.

Python: Find in list

Another alternative: you can check if an item is in a list with if item in list:, but this is order O(n). If you are dealing with big lists of items and all you need to know is whether something is a member of your list, you can convert the list to a set first and take advantage of constant time set lookup:

my_set = set(my_list)
if item in my_set:  # much faster on average than using a list
    # do something

Not going to be the correct solution in every case, but for some cases this might give you better performance.

Note that creating the set with set(my_list) is also O(n), so if you only need to do this once then it isn't any faster to do it this way. If you need to repeatedly check membership though, then this will be O(1) for every lookup after that initial set creation.

MySQL default datetime through phpmyadmin

You're getting that error because the default value current_time is not valid for the type DATETIME. That's what it says, and that's whats going on.

The only field you can use current_time on is a timestamp.

PHP display current server path

  • To get your current working directory: getcwd() (documentation)
  • To get the document root directory: $_SERVER['DOCUMENT_ROOT']
  • To get the filename of the current script: $_SERVER['SCRIPT_FILENAME']

Setting the default ssh key location

If you are only looking to point to a different location for you identity file, the you can modify your ~/.ssh/config file with the following entry:

IdentityFile ~/.foo/identity

man ssh_config to find other config options.

Can HTML checkboxes be set to readonly?

When posting an HTML checkbox to the server, it has a string value of 'on' or ''.

Readonly does not stop the user editing the checkbox, and disabled stops the value being posted back.
One way around this is to have a hidden element to store the actual value and the displayed checkbox is a dummy which is disabled. This way the checkbox state is persisted between posts.

Here is a function to do this. It uses a string of 'T' or 'F' and you can change this any way you like. This has been used in an ASP page using server side VB script.

public function MakeDummyReadonlyCheckbox(i_strName, i_strChecked_TorF)

    dim strThisCheckedValue

    if (i_strChecked_TorF = "T") then
        strThisCheckedValue = " checked "
        i_strChecked_TorF = "on"
    else
        strThisCheckedValue = ""
        i_strChecked_TorF = ""
    end if

    MakeDummyReadonlyCheckbox = "<input type='hidden' id='" & i_strName & "' name='" & i_strName & "' " & _
        "value='" & i_strChecked_TorF & "'>" & _
    "<input type='checkbox' disabled id='" & i_strName & "Dummy' name='" & i_strName & "Dummy' " & _
        strThisCheckedValue & ">"   
end function

public function GetCheckbox(i_objCheckbox)

    select case trim(i_objCheckbox)

        case ""
            GetCheckbox = "F"

        case else
            GetCheckbox = "T"

    end select

end function

At the top of an ASP page you can pickup the persisted value...

strDataValue = GetCheckbox(Request.Form("chkTest"))

and when you want to output your checkbox you can do this...

response.write MakeDummyReadonlyCheckbox("chkTest", strDataValue)

I have tested this and it works just fine. It also does not rely upon JavaScript.

Unresolved external symbol on static class members

Since this is the first SO thread that seemed to come up for me when searching for "unresolved externals with static const members" in general, I'll leave another hint to solve one problem with unresolved externals here:

For me, the thing that I forgot was to mark my class definition __declspec(dllexport), and when called from another class (outside that class's dll's boundaries), I of course got the my unresolved external error.
Still, easy to forget when you're changing an internal helper class to a one accessible from elsewhere, so if you're working in a dynamically linked project, you might as well check that, too.

Remove xticks in a matplotlib plot?

Modify the following rc parameters by adding the commands to the script:

plt.rcParams['xtick.bottom'] = False
plt.rcParams['xtick.labelbottom'] = False

A sample matplotlibrc file is depicted in this section of the matplotlib documentation, which lists many other parameters like changing figure size, color of figure, animation settings, etc.

Displaying Image in Java

If you want to load/process/display images I suggest you use an image processing framework. Using Marvin, for instance, you can do that easily with just a few lines of source code.

Source code:

public class Example extends JFrame{

    MarvinImagePlugin prewitt           = MarvinPluginLoader.loadImagePlugin("org.marvinproject.image.edge.prewitt");
    MarvinImagePlugin errorDiffusion    = MarvinPluginLoader.loadImagePlugin("org.marvinproject.image.halftone.errorDiffusion");
    MarvinImagePlugin emboss            = MarvinPluginLoader.loadImagePlugin("org.marvinproject.image.color.emboss");

    public Example(){
        super("Example");

        // Layout
        setLayout(new GridLayout(2,2));

        // Load images
        MarvinImage img1 = MarvinImageIO.loadImage("./res/car.jpg");
        MarvinImage img2 = new MarvinImage(img1.getWidth(), img1.getHeight());
        MarvinImage img3 = new MarvinImage(img1.getWidth(), img1.getHeight());
        MarvinImage img4 = new MarvinImage(img1.getWidth(), img1.getHeight());

        // Image Processing plug-ins
        errorDiffusion.process(img1, img2);
        prewitt.process(img1, img3);
        emboss.process(img1, img4);

        // Set panels
        addPanel(img1);
        addPanel(img2);
        addPanel(img3);
        addPanel(img4);

        setSize(560,380);
        setVisible(true);
    }

    public void addPanel(MarvinImage image){
        MarvinImagePanel imagePanel = new MarvinImagePanel();
        imagePanel.setImage(image);
        add(imagePanel);
    }

    public static void main(String[] args) {
        new Example().setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

Output:

enter image description here

Can the jQuery UI Datepicker be made to disable Saturdays and Sundays (and holidays)?

If you don't want the weekends to appear at all, simply:

CSS

th.ui-datepicker-week-end,
td.ui-datepicker-week-end {
    display: none;
}

Rails Root directory path?

In addition to all the other correct answers, since Rails.root is a Pathname object, this won't work:

Rails.root + '/app/assets/...'

You could use something like join

Rails.root.join('app', 'assets')

If you want a string use this:

Rails.root.join('app', 'assets').to_s

capture div into image using html2canvas

window.open didn't work for me... just a blank page rendered... but I was able to make the png appear on the page by replacing the src attribute of a pre-existing img element created as the target.

_x000D_
_x000D_
$("#btn_screenshot").click(function(){_x000D_
     element_to_png("container", "testhtmltocanvasimg");_x000D_
});_x000D_
_x000D_
_x000D_
function element_to_png(srcElementID, targetIMGid){_x000D_
    console.log("element_to_png called for element id " + srcElementID);_x000D_
    html2canvas($("#"+srcElementID)[0]).then( function (canvas) {_x000D_
        var myImage = canvas.toDataURL("image/png");_x000D_
        $("#"+targetIMGid).attr("src", myImage);_x000D_
  console.log("html2canvas completed.  png rendered to " + targetIMGid);_x000D_
    });_x000D_
}
_x000D_
<div id="testhtmltocanvasdiv" class="mt-3">_x000D_
   <img src="" id="testhtmltocanvasimg">_x000D_
</div>
_x000D_
_x000D_
_x000D_

I can then right-click on the rendered png and "save as". May be just as easy to use the "snipping tool" to capture the element, but html2canvas is an certainly an interesting bit of code!

Load dimension value from res/values/dimension.xml from source code

You can use getDimensionPixelOffset() instead of getDimension, so you didn't have to cast to int.

int valueInPixels = getResources().getDimensionPixelOffset(R.dimen.test)

Singular matrix issue with Numpy

The matrix you pasted

[[   1,    8,   50],
 [   8,   64,  400],
 [  50,  400, 2500]]

Has a determinant of zero. This is the definition of a Singular matrix (one for which an inverse does not exist)

http://en.wikipedia.org/wiki/Invertible_matrix

C++ error 'Undefined reference to Class::Function()'

In the definition of your Card class, a declaration for a default construction appears:

class Card
{
    // ...

    Card(); // <== Declaration of default constructor!

    // ...
};

But no corresponding definition is given. In fact, this function definition (from card.cpp):

void Card() {
//nothing
}

Does not define a constructor, but rather a global function called Card that returns void. You probably meant to write this instead:

Card::Card() {
//nothing
}

Unless you do that, since the default constructor is declared but not defined, the linker will produce error about undefined references when a call to the default constructor is found.


The same applies to your constructor accepting two arguments. This:

void Card(Card::Rank rank, Card::Suit suit) {
    cardRank = rank;
    cardSuit = suit;
}

Should be rewritten into this:

Card::Card(Card::Rank rank, Card::Suit suit) {
    cardRank = rank;
    cardSuit = suit;
}

And the same also applies for other member functions: it seems you did not add the Card:: qualifier before the member function names in their definitions. Without it, those functions are global functions rather than definitions of member functions.


Your destructor, on the other hand, is declared but never defined. Just provide a definition for it in card.cpp:

Card::~Card() { }

SQL - using alias in Group By

SQL Server doesn't allow you to reference the alias in the GROUP BY clause because of the logical order of processing. The GROUP BY clause is processed before the SELECT clause, so the alias is not known when the GROUP BY clause is evaluated. This also explains why you can use the alias in the ORDER BY clause.

Here is one source for information on the SQL Server logical processing phases.

Check if a string is a valid Windows directory (folder) path

I actually disagree with SLaks. That solution did not work for me. Exception did not happen as expected. But this code worked for me:

if(System.IO.Directory.Exists(path))
{
    ...
}

Python list / sublist selection -1 weirdness

It seems pretty consistent to me; positive indices are also non-inclusive. I think you're doing it wrong. Remembering that range() is also non-inclusive, and that Python arrays are 0-indexed, here's a sample python session to illustrate:

>>> d = range(10)
>>> d
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> d[9]
9
>>> d[-1]
9
>>> d[0:9]
[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>> d[0:-1]
[0, 1, 2, 3, 4, 5, 6, 7, 8]
>>> len(d)
10

What is the HTML tabindex attribute?

tabindex is a global attribute responsible for two things:

  1. it sets the order of "focusable" elements and
  2. it makes elements "focusable".

In my mind the second thing is even more important than the first one. There are very few elements that are focusable by default (e.g. <a> and form controls). Developers very often add some JavaScript event handlers (like 'onclick') on not focusable elements (<div>, <span> and so on), and the way to make your interface be responsive not only to mouse events but also to keyboard events (e.g. 'onkeypress') is to make such elements focusable. Lastly, if you don't want to set the order but just make your element focusable use tabindex="0" on all such elements:

<div tabindex="0"></div>

Also, if you don't want it to be focusable via the tab key then use tabindex="-1". For example, the below link will not be focused while using tab keys to traverse.

<a href="#" tabindex="-1">Tab key cannot reach here!</a>

executing shell command in background from script

For example you have a start program named run.sh to start it working at background do the following command line. ./run.sh &>/dev/null &

Detect whether Office is 32bit or 64bit via the registry

Open Outlook 2013 > File > Office account > About Outlook > click large "? About Outlook" button > read popup description

Docker for Windows error: "Hardware assisted virtualization and data execution protection must be enabled in the BIOS"

Besides the original answer, I have done the following:

  • Disable Hyper-V in Windows Features
  • Turning virtualization off and on in BIOS
  • Log back in windows, enabled Hyper-V. I was prompted there are updates for Hyper-V and I did the update. Restart when prompted.
  • It worked!

Storing an object in state of a React component?

this.setState({abc: {xyz: 'new value'}}); will NOT work, as state.abc will be entirely overwritten, not merged.

This works for me:

this.setState((previousState) => {
  previousState.abc.xyz = 'blurg';
  return previousState;
});

Unless I'm reading the docs wrong, Facebook recommends the above format. https://facebook.github.io/react/docs/component-api.html

Additionally, I guess the most direct way without mutating state is to directly copy by using the ES6 spread/rest operator:

const newState = { ...this.state.abc }; // deconstruct state.abc into a new object-- effectively making a copy
newState.xyz = 'blurg';
this.setState(newState);

How do I restrict my EditText input to numerical (possibly decimal and signed) input?

Try having this in your xml of Edit Text:

android:inputType="numberDecimal"

Transform DateTime into simple Date in Ruby on Rails

In Ruby 1.9.2 and above they added a .to_date function to DateTime:

http://ruby-doc.org/stdlib-1.9.2/libdoc/date/rdoc/DateTime.html#method-i-to_date

This instance method doesn't appear to be present in earlier versions like 1.8.7.

how to avoid extra blank page at end while printing?

Strangely setting a transparent border solved this for me:

@media print {
  div {
    border: 1px solid rgba(0,0,0,0)
  }
}

Maybe it will suffice to set the border on the container element. <- Untestet.

Best Java obfuscator?

Check out my article Protect Your Java Code - Through Obfuscators And Beyond [Archived] for a discussion of obfuscation vs three other ways to make the reverse engineering of your apps more expensive, and a collection of links to tools and further reading materials.

JSP : JSTL's <c:out> tag

As said Will Wagner, in old version of jsp you should always use c:out to output dynamic text.

Moreover, using this syntax:

<c:out value="${person.name}">No name</c:out>

you can display the text "No name" when name is null.

Validate form field only on submit or user input

If you want to show error messages on form submission, you can use condition form.$submitted to check if an attempt was made to submit the form. Check following example.

<form name="myForm" novalidate ng-submit="myForm.$valid && createUser()">
  <input type="text" name="name" ng-model="user.name" placeholder="Enter name of user" required>
  <div ng-messages="myForm.name.$error" ng-if="myForm.$submitted">
    <div ng-message="required">Please enter user name.</div>
  </div>

  <input type="text" name="address" ng-model="user.address" placeholder="Enter Address" required ng-maxlength="30">
  <div ng-messages="myForm.name.$error" ng-if="myForm.$submitted">
    <div ng-message="required">Please enter user address.</div>
    <div ng-message="maxlength">Should be less than 30 chars</div>
  </div>

  <button type="submit">
    Create user
  </button>
</form>

How to find the size of a table in SQL?

SQL Server provides a built-in stored procedure that you can run to easily show the size of a table, including the size of the indexes… which might surprise you.

Syntax:

 sp_spaceused 'Tablename'

see in :

http://www.howtogeek.com/howto/database/determine-size-of-a-table-in-sql-server/

Automatic vertical scroll bar in WPF TextBlock?

Wrap it in a scroll viewer:

<ScrollViewer>
    <TextBlock />
</ScrollViewer>

NOTE this answer applies to a TextBlock (a read-only text element) as asked for in the original question.

If you want to show scroll bars in a TextBox (an editable text element) then use the ScrollViewer attached properties:

<TextBox ScrollViewer.HorizontalScrollBarVisibility="Disabled"
         ScrollViewer.VerticalScrollBarVisibility="Auto" />

Valid values for these two properties are Disabled, Auto, Hidden and Visible.

Hide element by class in pure Javascript

var appBanners = document.getElementsByClassName('appBanner');

for (var i = 0; i < appBanners.length; i ++) {
    appBanners[i].style.display = 'none';
}

JSFiddle.

Is there any way to show a countdown on the lockscreen of iphone?

A today extension would be the most fitting solution.

Also you could do something on the lock screen with local notifications queued up to fire at regular intervals showing the latest countdown value.

How can I get the actual video URL of a YouTube live stream?

Yes this is possible Since the question is update, this solution can only gives you the embed url not the HLS url, check @JAL answer. with the ressource search.list and the parameters:

* part: id
* channelId: UCURGpU4lj3dat246rysrWsw
* eventType: live
* type: video

Request :

GET https://www.googleapis.com/youtube/v3/search?part=snippet&channelId=UCURGpU4lj3dat246rysrWsw&eventType=live&type=video&key={YOUR_API_KEY}

Result:

 "items": [
  {
   "kind": "youtube#searchResult",
   "etag": "\"DsOZ7qVJA4mxdTxZeNzis6uE6ck/enc3-yCp8APGcoiU_KH-mSKr4Yo\"",
   "id": {
    "kind": "youtube#video",
    "videoId": "WVZpCdHq3Qg"
   }
  },

Then get the videoID value WVZpCdHq3Qg for example and add the value to this url:

https://www.youtube.com/embed/ + videoID
https://www.youtube.com/watch?v= + videoID

Popup Message boxes

Ok, SO Basically I think I have a simple and effective solution.

package AnotherPopUpMessage;
import javax.swing.JOptionPane;
public class AnotherPopUp {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        JOptionPane.showMessageDialog(null, "Again? Where do all these come from?", 
            "PopUp4", JOptionPane.CLOSED_OPTION);
    }
}

Div with horizontal scrolling only

The solution is fairly straight forward. To ensure that we don't impact the width of the cells in the table, we'll turn off white-space. To ensure we get a horizontal scroll bar, we'll turn on overflow-x. And that's pretty much it:

.container {
    width: 30em;
    overflow-x: auto;
    white-space: nowrap;
}

You can see the end-result here, or in the animation below. If the table determines the height of your container, you should not need to explicitly set overflow-y to hidden. But understand that is also an option.

enter image description here

re.sub erroring with "Expected string or bytes-like object"

As you stated in the comments, some of the values appeared to be floats, not strings. You will need to change it to strings before passing it to re.sub. The simplest way is to change location to str(location) when using re.sub. It wouldn't hurt to do it anyways even if it's already a str.

letters_only = re.sub("[^a-zA-Z]",  # Search for all non-letters
                          " ",          # Replace all non-letters with spaces
                          str(location))

How to create Temp table with SELECT * INTO tempTable FROM CTE Query

Here's one slight alteration to the answers of a query that creates the table upon execution (i.e. you don't have to create the table first):

SELECT * INTO #Temp
FROM (
select OptionNo, OptionName from Options where OptionActive = 1
) as X

SQL Server: Difference between PARTITION BY and GROUP BY

partition by doesn't actually roll up the data. It allows you to reset something on a per group basis. For example, you can get an ordinal column within a group by partitioning on the grouping field and using rownum() over the rows within that group. This gives you something that behaves a bit like an identity column that resets at the beginning of each group.

How can I convince IE to simply display application/json rather than offer to download it?

I found the answer.

You can configure IE8 to display application/json in the browser window by updating the registry. There's no need for an external tool. I haven't tested this broadly, but it works with IE8 on Vista.

To use this, remember, all the usual caveats about updating the registry apply. Stop IE. Then, cut and paste the following into a file, by the name of json-ie.reg.

Windows Registry Editor Version 5.00
;
; Tell IE to open JSON documents in the browser.  
; 25336920-03F9-11cf-8FD0-00AA00686F13 is the CLSID for the "Browse in place" .
;  

[HKEY_CLASSES_ROOT\MIME\Database\Content Type\application/json]
"CLSID"="{25336920-03F9-11cf-8FD0-00AA00686F13}"
"Encoding"=hex:08,00,00,00

[HKEY_CLASSES_ROOT\MIME\Database\Content Type\text/json]
"CLSID"="{25336920-03F9-11cf-8FD0-00AA00686F13}"
"Encoding"=hex:08,00,00,00

Then double-click the .reg file. Restart IE. The new behavior you get when tickling a URL that returns a doc with Content-Type: application/json or Content-Type: text/json is like this:

alt text

What it does, why it works:

The 25336920-03F9-11cf-8FD0-00AA00686F13 is the CLSID for the "Browse in place" action. Basically this registry entry is telling IE that for docs that have a mime type of application/json, just view it in place. This won't affect any application/json documents downloaded via <script> tags, or via XHR, and so on.

The CLSID and Encoding keys get the same values used for image/gif, image/jpeg, and text/html.

This hint came from this site, and from Microsoft's article Handling MIME Types in Internet Explorer .


In FF, you don't need an external add-on either. You can just use the view-source: pseudo-protocol. Enter a URL like this into the address bar:

view-source:http://myserver/MyUrl/That/emits/Application/json

This pseudo-protocol used to be supported in IE, also, until WinXP-sp2, when Microsoft disabled it for security reasons.

plot legends without border and with white background

As documented in ?legend you do this like so:

plot(1:10,type = "n")
abline(v=seq(1,10,1), col='grey', lty='dotted')
legend(1, 5, "This legend text should not be disturbed by the dotted grey lines,\nbut the plotted dots should still be visible",box.lwd = 0,box.col = "white",bg = "white")
points(1:10,1:10)

enter image description here

Line breaks are achieved with the new line character \n. Making the points still visible is done simply by changing the order of plotting. Remember that plotting in R is like drawing on a piece of paper: each thing you plot will be placed on top of whatever's currently there.

Note that the legend text is cut off because I made the plot dimensions smaller (windows.options does not exist on all R platforms).

Select all from table with Laravel and Eloquent

You simply call

Blog::all();

//example usage.
$posts = Blog::all();

$posts->each(function($post) // foreach($posts as $post) { }
{
    //do something
}

from anywhere in your application.

Reading the documentation will help a lot.

Using intents to pass data between activities

Simple.

Assuming that in your Activity-1, you did this:

String stringExtra = "Some string you want to pass";

Intent intent = new Intent(this, AndroidTabRestaurantDescSearchListView.class);

//include the string in your intent
intent.putExtra("string", stringExtra);

startActivity(intent);

And in your AndroidTabRestaurantDescSearchListView class, do this:

//fetch the string  from the intent
String extraFromAct1 = getIntent().getStringExtra("string");

Intent intent = new Intent(this, RatingDescriptionSearchActivity.class);

//attach same string and send it with the intent
intent.putExtra("string", extraFromAct1);
startActivity(intent);

Then in your RatingDescriptionSearchActivity class, do this:

String extraFromAct1 = getIntent().getStringExtra("string");

Impact of Xcode build options "Enable bitcode" Yes/No

@vj9 thx. I update to xcode 7 . It show me the same error. Build well after set "NO"

enter image description here

set "NO" it works well.

enter image description here

Android SDK Manager Not Installing Components

I had a similar issue - very slow xml downloads followed by an empty package list. The SDK, it seems, was trying to use legacy Java installation. Setting the JAVA_HOME to the 1.6 jdk did the trick.

How can I declare and define multiple variables in one line using C++?

I wouldn't recommend this, but if you're really into it being one line and only writing 0 once, you can also do this:

int row, column, index = row = column = 0;

How to URL encode a string in Ruby

Code:

str = "http://localhost/with spaces and spaces"
encoded = URI::encode(str)
puts encoded

Result:

http://localhost/with%20spaces%20and%20spaces

Download large file in python with requests

use wget module of python instead. Here is a snippet

import wget
wget.download(url)

Get index of array element faster than O(n)

If it's a sorted array you could use a Binary search algorithm (O(log n)). For example, extending the Array-class with this functionality:

class Array
  def b_search(e, l = 0, u = length - 1)
    return if lower_index > upper_index

    midpoint_index = (lower_index + upper_index) / 2
    return midpoint_index if self[midpoint_index] == value

    if value < self[midpoint_index]
      b_search(value, lower_index, upper_index - 1)
    else
      b_search(value, lower_index + 1, upper_index)
    end
  end
end

PHP how to get value from array if key is in a variable

Your code seems to be fine, make sure that key you specify really exists in the array or such key has a value in your array eg:

$array = array(4 => 'Hello There');
print_r(array_keys($array));
// or better
print_r($array);

Output:

Array
(
    [0] => 4
)

Now:

$key = 4;
$value = $array[$key];
print $value;

Output:

Hello There

Convert a string to a datetime

Try to see if the following code helps you:

Dim iDate As String = "05/05/2005"
Dim oDate As DateTime = Convert.ToDateTime(iDate)

How to tell which disk Windows Used to Boot

Try HKEY_LOCAL_MACHINE\SYSTEM\Setup\SystemPartition

Add class to an element in Angular 4

Here is a plunker showing how you can use it with the ngClass directive.

I'm demonstrating with divs instead of imgs though.

Template:

<ul>
      <li><div [ngClass]="{'this-is-a-class': selectedIndex == 1}" (click)="setSelected(1)"> </div></li>
      <li><div [ngClass]="{'this-is-a-class': selectedIndex == 2}" (click)="setSelected(2)"> </div></li>
      <li><div [ngClass]="{'this-is-a-class': selectedIndex == 3}" (click)="setSelected(3)"> </div></li>
</ul>

TS:

export class App {
  selectedIndex = -1;

  setSelected(id: number) {
    this.selectedIndex = id;
  }
}

mysql error 2005 - Unknown MySQL server host 'localhost'(11001)

The case is like :

 mysql connects will localhost when network is not up.
 mysql cannot connect when network is up.

You can try the following steps to diagnose and resolve the issue (my guess is that some other service is blocking port on which mysql is hosted):

  1. Disconnect the network.
  2. Stop mysql service (if windows, try from services.msc window)
  3. Connect to network.
  4. Try to start the mysql and see if it starts correctly.
  5. Check for system logs anyways to be sure that there is no error in starting mysql service.
  6. If all goes well try connecting.
  7. If fails, try to do a telnet localhost 3306 and see what output it shows.
  8. Try changing the port on which mysql is hosted, default 3306, you can change to some other port which is ununsed.

This should ideally resolve the issue you are facing.

How to add new column to an dataframe (to the front not end)?

df <- data.frame(b = c(1, 1, 1), c = c(2, 2, 2), d = c(3, 3, 3))
df
##   b c d
## 1 1 2 3
## 2 1 2 3
## 3 1 2 3

df <- data.frame(a = c(0, 0, 0), df)
df
##   a b c d
## 1 0 1 2 3
## 2 0 1 2 3
## 3 0 1 2 3

Is there shorthand for returning a default value if None in Python?

You could use the or operator:

return x or "default"

Note that this also returns "default" if x is any falsy value, including an empty list, 0, empty string, or even datetime.time(0) (midnight).

Get first element from a dictionary

Dictionary does not define order of items. If you just need an item use Keys or Values properties of dictionary to pick one.

R color scatter plot points based on values

Here is a method using a lookup table of thresholds and associated colours to map the colours to the variable of interest.

 # make a grid 'Grd' of points and number points for side of square 'GrdD'
Grd <- expand.grid(seq(0.5,400.5,10),seq(0.5,400.5,10))
GrdD <- length(unique(Grd$Var1))

# Add z-values to the grid points
Grd$z <- rnorm(length(Grd$Var1), mean = 10, sd =2)

# Make a vector of thresholds 'Brks' to colour code z 
Brks <- c(seq(0,18,3),Inf)

# Make a vector of labels 'Lbls' for the colour threhsolds
Lbls <- Lbls <- c('0-3','3-6','6-9','9-12','12-15','15-18','>18')

# Make a vector of colours 'Clrs' for to match each range
Clrs <- c("grey50","dodgerblue","forestgreen","orange","red","purple","magenta")

# Make up lookup dataframe 'LkUp' of the lables and colours 
LkUp <- data.frame(cbind(Lbls,Clrs),stringsAsFactors = FALSE)

# Add a new variable 'Lbls' the grid dataframe mapping the labels based on z-value
Grd$Lbls <- as.character(cut(Grd$z, breaks = Brks, labels = Lbls))

# Add a new variable 'Clrs' to the grid dataframe based on the Lbls field in the grid and lookup table
Grd <- merge(Grd,LkUp, by.x = 'Lbls')

# Plot the grid using the 'Clrs' field for the colour of each point
plot(Grd$Var1,
     Grd$Var2,
     xlim = c(0,400),
     ylim = c(0,400),
     cex = 1.0,
     col = Grd$Clrs,
     pch = 20,
     xlab = 'mX',
     ylab = 'mY',
     main = 'My Grid',
     axes = FALSE,
     labels = FALSE,
     las = 1
)

axis(1,seq(0,400,100))
axis(2,seq(0,400,100),las = 1)
box(col = 'black')

legend("topleft", legend = Lbls, fill = Clrs, title = 'Z')

How to return only the Date from a SQL Server DateTime datatype

SQLServer 2008 now has a 'date' data type which contains only a date with no time component. Anyone using SQLServer 2008 and beyond can do the following:

SELECT CONVERT(date, GETDATE())

disable editing default value of text input

I don't think all the other answerers understood the question correctly. The question requires disabling editing part of the text. One solution I can think of is simulating a textbox with a fixed prefix which is not part of the textarea or input.

An example of this approach is:

<div style="border:1px solid gray; color:#999999; font-family:arial; font-size:10pt; width:200px; white-space:nowrap;">Default Notes<br/>
<textarea style="border:0px solid black;" cols="39" rows="5"></textarea></div>

The other approach, which I end up using is using JS and JQuery to simulate "Disable" feature. Example with pseudo-code (cannot be specific cause of legal issue):

  // disable existing notes by preventing keystroke
  document.getElementById("txtNotes").addEventListener('keydown', function (e) {
    if (cursorLocation < defaultNoteLength ) {
            e.preventDefault();
  });

    // disable existing notes by preventing right click
    document.addEventListener('contextmenu', function (e) {
        if (cursorLocation < defaultNoteLength )
            e.preventDefault();
    });

Thanks, Carsten, for mentioning that this question is old, but I found that the solution might help other people in the future.

How to copy part of an array to another array in C#?

In case if you want to implement your own Array.Copy method.

Static method which is of generic type.

 static void MyCopy<T>(T[] sourceArray, long sourceIndex, T[] destinationArray, long destinationIndex, long copyNoOfElements)
 {
  long totaltraversal = sourceIndex + copyNoOfElements;
  long sourceArrayLength = sourceArray.Length;

  //to check all array's length and its indices properties before copying
  CheckBoundaries(sourceArray, sourceIndex, destinationArray, copyNoOfElements, sourceArrayLength);
   for (long i = sourceIndex; i < totaltraversal; i++)
     {
      destinationArray[destinationIndex++] = sourceArray[i]; 
     } 
  }

Boundary method implementation.

private static void CheckBoundaries<T>(T[] sourceArray, long sourceIndex, T[] destinationArray, long copyNoOfElements, long sourceArrayLength)
        {
            if (sourceIndex >= sourceArray.Length)
            {
                throw new IndexOutOfRangeException();
            }
            if (copyNoOfElements > sourceArrayLength)
            {
                throw new IndexOutOfRangeException();
            }
            if (destinationArray.Length < copyNoOfElements)
            {
                throw new IndexOutOfRangeException();
            }
        }

How to use Servlets and Ajax?

$.ajax({
type: "POST",
url: "url to hit on servelet",
data:   JSON.stringify(json),
dataType: "json",
success: function(response){
    // we have the response
    if(response.status == "SUCCESS"){
        $('#info').html("Info  has been added to the list successfully.<br>"+
        "The  Details are as follws : <br> Name : ");

    }else{
        $('#info').html("Sorry, there is some thing wrong with the data provided.");
    }
},
 error: function(e){
   alert('Error: ' + e);
 }
});

Counting repeated elements in an integer array

public class FindRepeatedNumbers 
{
 public static void main(String[] args) 
    {
     int num[]={1,3,2,4,1,2,4,6,7,5};
           Arrays.sort(num);

  for(int j=1;j<num.length;j++)
      {
       if(num[j]==num[j-1])
    {
            System.out.println(num[j]);

       }
   }

       }
     }

Printing out a number in assembly language?

You might have some luck calling the Win32 API's MessageBoxA, although whether Win16 supports that particular method is for someone else to answer.

Oracle REPLACE() function isn't handling carriage-returns & line-feeds

Just wanted to drop a note. I was having trouble formatting a text 4000 field that had a mind of its own and the text would seeming wrap (or not wrap) randomly on the report. When I updated the column using the replace chr(10) noted above. My report finally formatted as I wanted. Many Thanx!

Java ElasticSearch None of the configured nodes are available

Elasticsearch settings are in $ES_HOME/config/elasticsearch.yml. There, if the cluster.name setting is commented out, it means ES would take just about any cluster name. So, in your code, the cluster.name as "elastictest" might be the problem. Try this:

Client client = new TransportClient()
                .addTransportAddress(new InetSocketTransportAddress(
                        "143.79.236.xxx",
                        9300));

JavaScript get window X/Y position for scroll

The method jQuery (v1.10) uses to find this is:

var doc = document.documentElement;
var left = (window.pageXOffset || doc.scrollLeft) - (doc.clientLeft || 0);
var top = (window.pageYOffset || doc.scrollTop)  - (doc.clientTop || 0);

That is:

  • It tests for window.pageXOffset first and uses that if it exists.
  • Otherwise, it uses document.documentElement.scrollLeft.
  • It then subtracts document.documentElement.clientLeft if it exists.

The subtraction of document.documentElement.clientLeft / Top only appears to be required to correct for situations where you have applied a border (not padding or margin, but actual border) to the root element, and at that, possibly only in certain browsers.

Move existing, uncommitted work to a new branch in Git

I used @Robin answer & listing all that I did,

git status                               <-- review/list uncommitted changes
git stash                                <-- stash uncommitted changes
git stash branch <new-branch> stash@{1}  <-- create a branch from stash
git add .                                <-- add local changes
git status                               <-- review the status; ready to commit
git commit -m "local changes ..."        <-- commit the changes
git branch --list                        <-- see list of branches incl the one created above
git status                               <-- nothing to commit, working tree (new-branch) is clean
git checkout <old-branch>                <-- switch back

! If the repo has more than one stash, see which one to apply to the new-branch:

git stash list  
  stash@{0}: WIP on ...  
  stash@{1}: WIP on ...

and inspect the individual stash by,

git stash show stash@{1}

Or inspect all stashes at once:

git stash list -p

Regex - Does not contain certain Characters

Here you go:

^[^<>]*$

This will test for string that has no < and no >

If you want to test for a string that may have < and >, but must also have something other you should use just

[^<>] (or ^.*[^<>].*$)

Where [<>] means any of < or > and [^<>] means any that is not of < or >.

And of course the mandatory link.

Test for non-zero length string in Bash: [ -n "$var" ] or [ "$var" ]

Use case/esac to test:

case "$var" in
  "") echo "zero length";;
esac

C# Passing Function as Argument

public static T Runner<T>(Func<T> funcToRun)
{
    //Do stuff before running function as normal
    return funcToRun();
}

Usage:

var ReturnValue = Runner(() => GetUser(99));

How to convert color code into media.brush?

In code, you need to explicitly create a Brush instance:

Fill = new SolidColorBrush(Color.FromArgb(0xff, 0xff, 0x90))

Testing for empty or nil-value string

If you're in Rails, .blank? should be the method you are looking for:

a = nil
b = []
c = ""

a.blank? #=> true
b.blank? #=> true
c.blank? #=> true

d = "1"
e = ["1"]

d.blank? #=> false
e.blank? #=> false

So the answer would be:

variable = id if variable.blank?

Is there a way for non-root processes to bind to "privileged" ports on Linux?

Or patch your kernel and remove the check.

(Option of last resort, not recommended).

In net/ipv4/af_inet.c, remove the two lines that read

      if (snum && snum < PROT_SOCK && !capable(CAP_NET_BIND_SERVICE))
              goto out;

and the kernel won't check privileged ports anymore.

Where Is Machine.Config?

C:\Windows\Microsoft.NET\Framework\v2.0.50727\CONFIG

Signed versus Unsigned Integers

  1. Yes, unsigned integer can store large value.
  2. No, there are different ways to show positive and negative values.
  3. Yes, signed integer can contain both positive and negative values.

Regex Match all characters between two strings

Lazy Quantifier Needed

Resurrecting this question because the regex in the accepted answer doesn't seem quite correct to me. Why? Because

(?<=This is)(.*)(?=sentence)

will match my first sentence. This is my second in This is my first sentence. This is my second sentence.

See demo.

You need a lazy quantifier between the two lookarounds. Adding a ? makes the star lazy.

This matches what you want:

(?<=This is).*?(?=sentence)

See demo. I removed the capture group, which was not needed.

DOTALL Mode to Match Across Line Breaks

Note that in the demo the "dot matches line breaks mode" (a.k.a.) dot-all is set (see how to turn on DOTALL in various languages). In many regex flavors, you can set it with the online modifier (?s), turning the expression into:

(?s)(?<=This is).*?(?=sentence)

Reference

How to create composite primary key in SQL Server 2008

create table my_table (
     column_a integer not null,
     column_b integer not null,
     column_c varchar(50),
     primary key (column_a, column_b)
);

Matplotlib scatter plot legend

Other answers seem a bit complex, you can just add a parameter 'label' in scatter function and that will be the legend for your plot.

import matplotlib.pyplot as plt
from numpy.random import random

colors = ['b', 'c', 'y', 'm', 'r']

lo = plt.scatter(random(10), random(10), marker='x', color=colors[0],label='Low Outlier')
ll = plt.scatter(random(10), random(10), marker='o', color=colors[0],label='LoLo')
l  = plt.scatter(random(10), random(10), marker='o', color=colors[1],label='Lo')
a  = plt.scatter(random(10), random(10), marker='o', color=colors[2],label='Average')
h  = plt.scatter(random(10), random(10), marker='o', color=colors[3],label='Hi')
hh = plt.scatter(random(10), random(10), marker='o', color=colors[4],label='HiHi')
ho = plt.scatter(random(10), random(10), marker='x', color=colors[4],label='High Outlier')

plt.legend(loc='upper center', bbox_to_anchor=(0.5, -0.05),
          fancybox=True, shadow=True, ncol=4)

plt.show()

This is your output:

img

Using array map to filter results with if conditional

You could use flatMap. It can filter and map in one.

$scope.appIds = $scope.applicationsHere.flatMap(obj => obj.selected ? obj.id : [])

SQL how to check that two tables has exactly the same data?

Source: Use NATURAL FULL JOIN to compare two tables in SQL by Lukas Eder

Clever approach of using NATURAL FULL JOIN to detect the same/different rows between two tables.

Example 1 - status flag:

SELECT t1.*, t2.*, CASE WHEN t1 IS NULL OR t2 IS NULL THEN 'Not equal' ELSE 'Equal' END
FROM t1
NATURAL FULL JOIN t2;

Example 2 - filtering rows

SELECT *
FROM (SELECT 't1' AS t1, t1.* FROM t1) t1 
NATURAL FULL JOIN (SELECT 't2' AS t2, t2.* FROM t2) t2 
WHERE t1 IS NULL OR t2 IS NULL -- show differences
--WHERE  t1 IS NOT NULL AND t2 IS NOT NULL    -- show the same

db<>fiddle demo

Instantiating a generic class in Java

And this is the Factory implementation, as Jon Skeet suggested:

interface Factory<T> {
    T factory();
}

class Araba {
    //static inner class for Factory<T> implementation
    public static class ArabaFactory implements Factory<Araba> {
        public Araba factory() {
            return new Araba();
        }
    }
    public String toString() { return "Abubeee"; }
}

class Generic<T> {
    private T var;

    Generic(Factory<T> fact) {
        System.out.println("Constructor with Factory<T> parameter");
        var = fact.factory();
    }
    Generic(T var) {
        System.out.println("Constructor with T parameter");
        this.var = var;
    }
    T get() { return var; }
}

public class Main {
    public static void main(String[] string) {
        Generic<Araba> gen = new Generic<Araba>(new Araba.ArabaFactory());
        System.out.print(gen.get());
    }
}

Output:

Constructor with Factory<T> parameter
Abubeee

What is the Maximum Size that an Array can hold?

I think it is linked with your RAM (or probably virtual memory) space and for the absolute maximum constrained to your OS version (e.g. 32 bit or 64 bit)

Some dates recognized as dates, some dates not recognized. Why?

This is caused by the regional settings of your computer.

When you paste data into excel it is only a bunch of strings (not dates).

Excel has some logic in it to recognize your current data formats as well as a few similar date formats or obvious date formats where it can assume it is a date. When it is able to match your pasted in data to a valid date then it will format it as a date in the cell it is in.

Your specific example is due to your list of dates is formatted as "m/d/yy" which is US format. it pastes correctly in my excel because I have my regional setting set to "US English" (even though I'm Canadian :) )

If you system is set to Canadian English/French format then it will expect "d/m/yy" format and not recognize any date where the month is > 13.

The best way to import data, that contains dates, into excel is to copy it in this format.

2011-04-22
2011-12-19
2011-11-04
2011-12-08
2011-09-27
2011-09-27
2011-04-01

Which is "yyyy-MM-dd", this format is recognized the same way on every computer I have ever seen (is often refered to as ODBC format or Standard format) where the units are always from greatest to least weight ("yyyy-MM-dd HH:mm:ss.fff") another side effect is it will sort correctly as a string.

To avoid swaping your regional settings back and forth you may consider writting a macro in excel to paste the data in. a simple popup format and some basic logic to reformat the dates would not be too difficult.

Installing PHP Zip Extension

The best way to install the Zip extension in php7.2 on CentOS would be as below:

  1. Find the available extention by searching with yum command

    yum search zip

  2. This will list all the zip packages. We need to look for the php7.2 zip package enter image description here

  1. Then if your php version is 7.2 then run the command

    yum install ea-php72-php-zip

This will definetly resolve your issue.

Cheers !!

Change DIV content using ajax, php and jQuery

This works for me and you don't need the inline script:

Javascript:

    $(document).ready(function() {
    $('.showme').bind('click', function() {

        var id=$(this).attr("id");
        var num=$(this).attr("class");
        var poststr="request="+num+"&moreinfo="+id;
        $.ajax({
              url:"testme.php",
              cache:0,
              data:poststr,
              success:function(result){
                     document.getElementById("stuff").innerHTML=result;
               }
        }); 
    });
 });

HTML:

    <div class='request_1 showme' id='rating_1'>More stuff 1</div>
    <div class='request_2 showme' id='rating_2'>More stuff 2</div>
    <div class='request_3 showme' id='rating_3'>More stuff 3</div>

    <div id="stuff">Here is some stuff that will update when the links above are clicked</div>

The request is sent to testme.php:

    header("Cache-Control: no-cache");
    header("Pragma: nocache");

    $request_id = preg_replace("/[^0-9]/","",$_REQUEST['request']);
    $request_moreinfo = preg_replace("/[^0-9]/","",$_REQUEST['moreinfo']);

    if($request_id=="1")
    {
        echo "show 1";
    }
    elseif($request_id=="2")
    {
        echo "show 2";
    }
    else
    {
        echo "show 3";
    }

Django Admin - change header 'Django administration' text

In urls.py you can override the 3 most important variables:

from django.contrib import admin

admin.site.site_header = 'My project'                    # default: "Django Administration"
admin.site.index_title = 'Features area'                 # default: "Site administration"
admin.site.site_title = 'HTML title from adminsitration' # default: "Django site admin"

Reference: Django documentation on these attributes.

Java collections convert a string to a list of characters

List<String> result = Arrays.asList("abc".split(""));

Marquee text in Android

I found a Problem with marquee that it can't be used for short strings(As its function is only to Show Long strings).

I suggest Use Webview If you want to move short strings horizontally. Main_Activity.java Code:`

        WebView webView;

        webView = (WebView)findViewById(R.id.web);


        String summary = "<html><FONT color='#fdb728' FACE='courier'><marquee behavior='scroll' direction='left' scrollamount=10>"
                + "Hello Droid" + "</marquee></FONT></html>";

        webView.loadData(summary, "text/html", "utf-8"); // Set focus to the textview
`

main_activity.xml code:

<WebView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/web"
        ></WebView>

Is there a vr (vertical rule) in html?

How about:

writing-mode:tb-rl

Where top->bottom, right->left?

We will need vertical rule for this.

How to select between brackets (or quotes or ...) in Vim?

Use arrows or hjkl to get to one of the bracketing expressions, then v to select visual (i.e. selecting) mode, then % to jump to the other bracket.

How to use private Github repo as npm dependency

If someone is looking for another option for Git Lab and the options above do not work, then we have another option. For a local installation of Git Lab server, we have found that the approach, below, allows us to include the package dependency. We generated and use an access token to do so.

$ npm install --save-dev https://git.yourdomain.com/userOrGroup/gitLabProjectName/repository/archive.tar.gz?private_token=InsertYourAccessTokenHere

Of course, if one is using an access key this way, it should have a limited set of permissions.

Good luck!

Cannot authenticate into mongo, "auth fails"

This is kind of a specific case, but in case anyone gets here with my problem:

In MongoHQ, it'll show you a field called "password", but it's actually just the hash of the password. You'll have to add a new user and store the password elsewhere (because MongoHQ won't show it to you).

How to rebuild docker container in docker-compose.yml?

Maybe these steps are not quite correct, but I do like this:

stop docker compose: $ docker-compose down

remove the container: $ docker system prune -a

start docker compose: $ docker-compose up -d

cleanup php session files

cd to sessions directory and then:

1) View sessions older than 40 min: find . -amin +40 -exec stat -c "%n %y" {} \;

2) Remove sessions older than 40 min: find . -amin +40 -exec rm {} \;

Octave/Matlab: Adding new elements to a vector

x(end+1) = newElem is a bit more robust.

x = [x newElem] will only work if x is a row-vector, if it is a column vector x = [x; newElem] should be used. x(end+1) = newElem, however, works for both row- and column-vectors.

In general though, growing vectors should be avoided. If you do this a lot, it might bring your code down to a crawl. Think about it: growing an array involves allocating new space, copying everything over, adding the new element, and cleaning up the old mess...Quite a waste of time if you knew the correct size beforehand :)

SCP Permission denied (publickey). on EC2 only when using -r flag on directories

The -i flag specifies the private key (.pem file) to use. If you don't specify that flag (as in your first command) it will use your default ssh key (usually under ~/.ssh/).

So in your first command, you are actually asking scp to upload the .pem file itself using your default ssh key. I don't think that is what you want.

Try instead with:

scp -r -i /Applications/XAMPP/htdocs/keypairfile.pem uploads/* ec2-user@publicdns:/var/www/html/uploads

How can you tell if a value is not numeric in Oracle?

You can use the following regular expression which will match integers (e.g., 123), floating-point numbers (12.3), and numbers with exponents (1.2e3):

^-?\d*\.?\d+([eE]-?\d+)?$

If you want to accept + signs as well as - signs (as Oracle does with TO_NUMBER()), you can change each occurrence of - above to [+-]. So you might rewrite your block of code above as follows:

IF (option_id = 0021) THEN 
    IF NOT REGEXP_LIKE(value, '^[+-]?\d*\.?\d+([eE][+-]?\d+)?$') OR TO_NUMBER(value) < 10000 OR TO_NUMBER(value) > 7200000 THEN
        ip_msg(6214,option_name);
        RETURN;
    END IF;
END IF;

I am not altogether certain that would handle all values so you may want to add an EXCEPTION block or write a custom to_number() function as @JustinCave suggests.

How to parse XML in Bash?

Well, you can use xpath utility. I guess perl's XML::Xpath contains it.

set dropdown value by text using jquery

Here is an simple example:

$("#country_id").change(function(){
    if(this.value.toString() == ""){
        return;
    }
    alert("You just changed country to: " + $("#country_id option:selected").text() + " which carried the value for country_id as: " + this.value.toString());
});

How to extract the nth word and count word occurrences in a MySQL string?

As others have said, mysql does not provide regex tools for extracting sub-strings. That's not to say you can't have them though if you're prepared to extend mysql with user-defined functions:

https://github.com/mysqludf/lib_mysqludf_preg

That may not be much help if you want to distribute your software, being an impediment to installing your software, but for an in-house solution it may be appropriate.

__FILE__ macro shows full path

#include <algorithm>
#include <string>
using namespace std;
string f( __FILE__ );
f = string( (find(f.rbegin(), f.rend(), '/')+1).base() + 1, f.end() );

// searches for the '/' from the back, transfers the reverse iterator 
// into a forward iterator and constructs a new sting with both

How to map atan2() to degrees 0-360

double degree = fmodf((atan2(x, y) * (180.0 / M_PI)) + 360, 360);

This will return degree from 0°-360° counter-clockwise, 0° is at 3 o'clock.

Effects of the extern keyword on C functions

Inline functions have special rules about what extern means. (Note that inline functions are a C99 or GNU extension; they weren't in original C.

For non-inline functions, extern is not needed as it is on by default.

Note that the rules for C++ are different. For example, extern "C" is needed on the C++ declaration of C functions that you are going to call from C++, and there are different rules about inline.

Testing if value is a function

form.onsubmit will always be a function when defined as an attribute of HTML the form element. It's some sort of anonymous function attached to an HTML element, which has the this pointer bound to that FORM element and also has a parameter named event which will contain data about the submit event.

Under these circumstances I don't understand how you got a string as a result of a typeof operation. You should give more details, better some code.

Edit (as a response to your second edit):

I believe the handler attached to the HTML attribute will execute regardless of the above code. Further more, you could try to stop it somehow, but, it appears that FF 3, IE 8, Chrome 2 and Opera 9 are executing the HTML attribute handler in the first place and then the one attached (I didn't tested with jQuery though, but with addEventListener and attachEvent). So... what are you trying to accomplish exactly?

By the way, your code isn't working because your regular expression will extract the string "valid();", which is definitely not a function.

jQuery: find element by text

Yes, use the jQuery contains selector.

When do you use map vs flatMap in RxJava?

The question is When do you use map vs flatMap in RxJava?. And I think a simple demo is more specific.

When you want to convert item emitted to another type , in your case converting file to String, map and flatMap can both work. But I prefer map operator because it's more clearly.

However in some place, flatMap can do magic work but map can't. For example, I want to get a user's info but I have to first get his id when user login in. Obviously I need two requests and they are in order.

Let's begin.

Observable<LoginResponse> login(String email, String password);

Observable<UserInfo> fetchUserInfo(String userId);

Here are two methods, one for login returned Response, and another for fetching user info.

login(email, password)
        .flatMap(response ->
                fetchUserInfo(response.id))
        .subscribe(userInfo -> {
            // get user info and you update ui now
        });

As you see, in function flatMap applies, at first I get user id from Response then fetch user info. When two requests are finished, we can do our job such as updating UI or save data into database.

However if you use map you can't write such nice code. In a word, flatMap can help us serialize requests.

Performance of Arrays vs. Lists

Since List<> uses arrays internally, the basic performance should be the same. Two reasons, why the List might be slightly slower:

  • To look up a element in the list, a method of List is called, which does the look up in the underlying array. So you need an additional method call there. On the other hand the compiler might recognize this and optimize the "unnecessary" call away.
  • The compiler might do some special optimizations if it knows the size of the array, that it can't do for a list of unknown length. This might bring some performance improvement if you only have a few elements in your list.

To check if it makes any difference for you, it's probably best adjust the posted timing functions to a list of the size you're planning to use and see how the results for your special case are.

Using If else in SQL Select statement

SELECT CASE WHEN IDParent < 1 
            THEN ID 
            ELSE IDParent 
       END AS colname 
FROM yourtable

Way to get all alphabetic chars in an array in PHP?

range for A-Z but if you want to go for example from A to DU then:

 function generateAlphabet($na) {
        $sa = "";
        while ($na >= 0) {
            $sa = chr($na % 26 + 65) . $sa;
            $na = floor($na / 26) - 1;
        }
        return $sa;
    }

    $alphabet = Array();
    for ($na = 0; $na < 125; $na++) {
        $alphabet[]=generateAlphabet($na);
    }

    print_r($alphabet);

your answer will look like:

Array ( [0] => A [1] => B [2] => C [3] => D [4] => E [5] => F [6] => G [7] => H [8] => I [9] => J [10] => K [11] => L [12] => M [13] => N [14] => O [15] => P [16] => Q [17] => R [18] => S [19] => T [20] => U [21] => V [22] => W [23] => X [24] => Y [25] => Z [26] => AA [27] => AB [28] => AC [29] => AD [30] => AE [31] => AF [32] => AG [33] => AH [34] => AI [35] => AJ [36] => AK [37] => AL [38] => AM [39] => AN [40] => AO [41] => AP [42] => AQ [43] => AR [44] => AS [45] => AT [46] => AU [47] => AV [48] => AW [49] => AX [50] => AY [51] => AZ [52] => BA [53] => BB [54] => BC [55] => BD [56] => BE [57] => BF [58] => BG [59] => BH [60] => BI [61] => BJ [62] => BK [63] => BL [64] => BM [65] => BN [66] => BO [67] => BP [68] => BQ [69] => BR [70] => BS [71] => BT [72] => BU [73] => BV [74] => BW [75] => BX [76] => BY [77] => BZ [78] => CA [79] => CB [80] => CC [81] => CD [82] => CE [83] => CF [84] => CG [85] => CH [86] => CI [87] => CJ [88] => CK [89] => CL [90] => CM [91] => CN [92] => CO [93] => CP [94] => CQ [95] => CR [96] => CS [97] => CT [98] => CU [99] => CV [100] => CW [101] => CX [102] => CY [103] => CZ [104] => DA [105] => DB [106] => DC [107] => DD [108] => DE [109] => DF [110] => DG [111] => DH [112] => DI [113] => DJ [114] => DK [115] => DL [116] => DM [117] => DN [118] => DO [119] => DP [120] => DQ [121] => DR [122] => DS [123] => DT [124] => DU ) 

How to force a component's re-rendering in Angular 2?

Rendering happens after change detection. To force change detection, so that component property values that have changed get propagated to the DOM (and then the browser will render those changes in the view), here are some options:

  • ApplicationRef.tick() - similar to Angular 1's $rootScope.$digest() -- i.e., check the full component tree
  • NgZone.run(callback) - similar to $rootScope.$apply(callback) -- i.e., evaluate the callback function inside the Angular 2 zone. I think, but I'm not sure, that this ends up checking the full component tree after executing the callback function.
  • ChangeDetectorRef.detectChanges() - similar to $scope.$digest() -- i.e., check only this component and its children

You will need to import and then inject ApplicationRef, NgZone, or ChangeDetectorRef into your component.

For your particular scenario, I would recommend the last option if only a single component has changed.

How do I make this file.sh executable via double click?

you can change the file executable by using chmod like this

chmod 755 file.sh

and use this command for execute

./file.sh

ldconfig error: is not a symbolic link

I ran into this issue with the Oracle 11R2 client. Not sure if the Oracle installer did this or someone did it here before i arrived. It was not 64-bit vs 32-bit, all was 64-bit.

The error was that libexpat.so.1 was not a symbolic link.

It turned out that there were two identical files, libexpat.so.1.5.2 and libexpat.so.1. Removing the offending file and making it a symlink to the 1.5.2 version caused the error to go away.

Makes sense that you'd want the well-known name to be a symlink to the current version. If you do this, it's less likely that you'll end up with a stale library.

How to commit to remote git repository

just type "git push" if this doesn't give you a positive replay, then check if you are connected with your repository correctly.

How do you make Git work with IntelliJ?

On unix systems, you can use the following command to determine where git is installed:

whereis git

If you are using MacOS and did a recent update, it is possible you have to agree to the licence terms again. Try typing 'git' in a terminal, and see if you get the following message:

Agreeing to the Xcode/iOS license requires admin privileges, please re-run as root via sudo.

How to get current value of RxJS Subject or Observable?

I had similar situation where late subscribers subscribe to the Subject after its value arrived.

I found ReplaySubject which is similar to BehaviorSubject works like a charm in this case. And here is a link to better explanation: http://reactivex.io/rxjs/manual/overview.html#replaysubject

Has an event handler already been added?

From outside the defining class, as @Telos mentions, you can only use EventHandler on the left-hand side of a += or a -=. So, if you have the ability to modify the defining class, you could provide a method to perform the check by checking if the event handler is null - if so, then no event handler has been added. If not, then maybe and you can loop through the values in Delegate.GetInvocationList. If one is equal to the delegate that you want to add as event handler, then you know it's there.

public bool IsEventHandlerRegistered(Delegate prospectiveHandler)
{   
    if ( this.EventHandler != null )
    {
        foreach ( Delegate existingHandler in this.EventHandler.GetInvocationList() )
        {
            if ( existingHandler == prospectiveHandler )
            {
                return true;
            }
        }
    }
    return false;
}

And this could easily be modified to become "add the handler if it's not there". If you don't have access to the innards of the class that's exposing the event, you may need to explore -= and +=, as suggested by @Lou Franco.

However, you may be better off reexamining the way you're commissioning and decommissioning these objects, to see if you can't find a way to track this information yourself.

Tower of Hanoi: Recursive Algorithm

Here is my solution code to Towers of Hanoi problem using recursion with golang. `package main

import "fmt"

func main() {
    toi(4, "src", "dest", "swap")
}

func toi(n int, from, to, swap string) {
    if n == 0 {
        return
    }
    if n == 1 {
        fmt.Printf("mov %v %v -> %v\n", n, from, to)
        return
    }
    toi(n-1, from, swap, to)
    fmt.Printf("mov %v %v -> %v\n", n, from, to)
    toi(n-1, swap, to, from)
}`

Facebook share button and custom text

You can customize Facebook share dialog box by using asynchronous JavaScript SDK provided by Facebook and setting up its parameter values

Have a look at the following code:

<script type="text/javascript">
  $(document).ready(function(){
    $('#share_button').click(function(e){
      e.preventDefault();
      FB.ui(
        {
          method: 'feed',
          name: 'This is the content of the "name" field.',
          link: 'URL which you would like to share ',
          picture: ‘URL of the image which is going to appear as thumbnail image in share dialogbox’,
          caption: 'Caption like which appear as title of the dialog box',
          description: 'Small description of the post',
          message: ''
        }
      );
    });
  });
</script>

Before copying and pasting the below code you must first initialize the SDK and set up jQuery library. Please click here to know a step by step how to set information on the same.

ASP.NET Core Identity - get current user

For context, I created a project using the ASP.NET Core 2 Web Application template. Then, select the Web Application (MVC) then hit the Change Authentication button and select Individual User accounts.

There is a lot of infrastructure built up for you from this template. Find the ManageController in the Controllers folder.

This ManageController class constructor requires this UserManager variable to populated:

private readonly UserManager<ApplicationUser> _userManager;

Then, take a look at the the [HttpPost] Index method in this class. They get the current user in this fashion:

var user = await _userManager.GetUserAsync(User);

As a bonus note, this is where you want to update any custom fields to the user Profile you've added to the AspNetUsers table. Add the fields to the view, then submit those values to the IndexViewModel which is then submitted to this Post method. I added this code after the default logic to set the email address and phone number:

user.FirstName = model.FirstName;
user.LastName = model.LastName;
user.Address1 = model.Address1;
user.Address2 = model.Address2;
user.City = model.City;
user.State = model.State;
user.Zip = model.Zip;
user.Company = model.Company;
user.Country = model.Country;
user.SetDisplayName();
user.SetProfileID();

_dbContext.Attach(user).State = EntityState.Modified;
_dbContext.SaveChanges();

How to use custom packages

First, be sure to read and understand the "How to write Go code" document.

The actual answer depends on the nature of your "custom package".

If it's intended to be of general use, consider employing the so-called "Github code layout". Basically, you make your library a separate go get-table project.

If your library is for internal use, you could go like this:

  1. Place the directory with library files under the directory of your project.
  2. In the rest of your project, refer to the library using its path relative to the root of your workspace containing the project.

To demonstrate:

src/
  myproject/
    mylib/
      mylib.go
      ...
    main.go

Now, in the top-level main.go, you could import "myproject/mylib" and it would work OK.

selecting unique values from a column

DISTINCT is always a right choice to get unique values. Also you can do it alternatively without using it. That's GROUP BY. Which has simply add at the end of the query and followed by the column name.

SELECT * FROM buy GROUP BY date,description

What methods of ‘clearfix’ can I use?

It is so simple clearfix clears the issue by when we using the float properties inside the div element.If we use two div elements one as float:left; and other one as float:right; we can use clearfix for the parent of the two div element. If we refuse to use clearfix unnecessary spaces fill with contents below and site structure will be broken.

How to use php serialize() and unserialize()

From http://php.net/manual/en/function.serialize.php :

Generates a storable representation of a value. This is useful for storing or passing PHP values around without losing their type and structure.

Essentially, it takes a php array or object and converts it to a string (which you can then transmit or store as you see fit).

Unserialize is used to convert the string back to an object.

error: unknown type name ‘bool’

C99 does, if you have

#include <stdbool.h> 

If the compiler does not support C99, you can define it yourself:

// file : myboolean.h
#ifndef MYBOOLEAN_H
#define MYBOOLEAN_H

#define false 0
#define true 1
typedef int bool; // or #define bool int

#endif

(but note that this definition changes ABI for bool type so linking against external libraries which were compiled with properly defined bool may cause hard-to-diagnose runtime errors).

Does a TCP socket connection have a "keep alive"?

Here is some supplemental literature on keepalive which explains it in much finer detail.

http://www.tldp.org/HOWTO/html_single/TCP-Keepalive-HOWTO

Since Java does not allow you to control the actual keepalive times, you can use the examples to change them if you're using a Linux kernel (or proc based OS).

Sort a list of lists with a custom compare function

>>> l = [list(range(i, i+4)) for i in range(10,1,-1)]
>>> l
[[10, 11, 12, 13], [9, 10, 11, 12], [8, 9, 10, 11], [7, 8, 9, 10], [6, 7, 8, 9], [5, 6, 7, 8], [4, 5, 6, 7], [3, 4, 5, 6], [2, 3, 4, 5]]
>>> sorted(l, key=sum)
[[2, 3, 4, 5], [3, 4, 5, 6], [4, 5, 6, 7], [5, 6, 7, 8], [6, 7, 8, 9], [7, 8, 9, 10], [8, 9, 10, 11], [9, 10, 11, 12], [10, 11, 12, 13]]

The above works. Are you doing something different?

Notice that your key function is just sum; there's no need to write it explicitly.

XML element with attribute and content using JAXB

Annotate type and gender properties with @XmlAttribute and the description property with @XmlValue:

package org.example.sport;

import javax.xml.bind.annotation.*;

@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement
public class Sport {

    @XmlAttribute
    protected String type;

    @XmlAttribute
    protected String gender;

    @XmlValue;
    protected String description;

}

For More Information

SQL Server 2008 R2 Express permissions -- cannot create database or modify users

I followed the steps in killthrush's answer and to my surprise it did not work. Logging in as sa I could see my Windows domain user and had made them a sysadmin, but when I tried logging in with Windows auth I couldn't see my login under logins, couldn't create databases, etc. Then it hit me. That login was probably tied to another domain account with the same name (with some sort of internal/hidden ID that wasn't right). I had left this organization a while back and then came back months later. Instead of re-activating my old account (which they might have deleted) they created a new account with the same domain\username and a new internal ID. Using sa I deleted my old login, re-added it with the same name and added sysadmin. I logged back in with Windows Auth and everything looks as it should. I can now see my logins (and others) and can do whatever I need to do as a sysadmin using my Windows auth login.

Get fragment (value after hash '#') from a URL in php

I've been searching for a workaround for this for a bit - and the only thing I have found is to use URL rewrites to read the "anchor". I found in the apache docs here http://httpd.apache.org/docs/2.2/rewrite/advanced.html the following...

By default, redirecting to an HTML anchor doesn't work, because mod_rewrite escapes the # character, turning it into %23. This, in turn, breaks the redirection.

Solution: Use the [NE] flag on the RewriteRule. NE stands for No Escape.

Discussion: This technique will of course also work with other special characters that mod_rewrite, by default, URL-encodes.

It may have other caveats and what not ... but I think that at least doing something with the # on the server is possible.

Select last row in MySQL

Keep in mind that tables in relational databases are just sets of rows. And sets in mathematics are unordered collections. There is no first or last row; no previous row or next row.

You'll have to sort your set of unordered rows by some field first, and then you are free the iterate through the resultset in the order you defined.

Since you have an auto incrementing field, I assume you want that to be the sorting field. In that case, you may want to do the following:

SELECT    *
FROM      your_table
ORDER BY  your_auto_increment_field DESC
LIMIT     1;

See how we're first sorting the set of unordered rows by the your_auto_increment_field (or whatever you have it called) in descending order. Then we limit the resultset to just the first row with LIMIT 1.

ASP.NET strange compilation error

I resolved this by deleting the contents of the bin and obj folders for the project, and the contents of the bin folder on the remote server, then redeploying.

add new element in laravel collection object

If you want to add a product into the array you can use:

$item['product'] = $product;

No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?

I tried all of the above, however, still getting the same error message.

In my case an actual JRE was incorrectly used as JRE System Library in the project-specific build path which was obviously overriding all those other settings discussed here.

If that is so in your case try the following:

  1. Open the project-specific libraries of the Java Build Path: Right-click "Project > Build Path > Configure Build Path..." and select "Libraries" tab.
  2. Select the "JRE System Library" entry and hit "Remove".
  3. Hit "Add Library...".
  4. A wizard pops up. Select "JRE System Library" and hit "Next >".
  5. Now select the correct JDK (in my case "Workspace default JRE", which I configured using a JDK).
  6. Close wizard by hitting "Finish".
  7. Close "Properties" dialog by hitting "OK".

Bootstrap 3 grid with no gap

The grid system in Bootstrap 3 requires a bit of a lateral shift in your thinking from Bootstrap 2. A column in BS2 (col-*) is NOT synonymous with a column in BS3 (col-sm-*, etc), but there is a way to achieve the same result.

Check out this update to your fiddle: http://jsfiddle.net/pjBzY/22/ (code copied below).

First of all, you don't need to specify a col for each screen size if you want 50/50 columns at all sizes. col-sm-6 applies not only to small screens, but also medium and large, meaning class="col-sm-6 col-md-6" is redundant (the benefit comes in if you want to change the column widths at different size screens, such as col-sm-6 col-md-8).

As for the margins issue, the negative margins provide a way to align blocks of text in a more flexible way than was possible in BS2. You'll notice in the jsfiddle, the text in the first column aligns visually with the text in the paragraph outside the row -- except at "xs" window sizes, where the columns aren't applied.

If you need behavior closer to what you had in BS2, where there is padding between each column and there are no visual negative margins, you will need to add an inner-div to each column. See the inner-content in my jsfiddle. Put something like this in each column, and they will behave the way old col-* elements did in BS2.


jsfiddle HTML

<div class="container">
    <p class="other-content">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Suspendisse aliquam sed sem nec viverra. Phasellus fringilla metus vitae libero posuere mattis. Integer sit amet tincidunt felis. Maecenas et pharetra leo. Etiam venenatis purus et nibh laoreet blandit.</p>
    <div class="row">
        <div class="col-sm-6 my-column">
            Col 1
            <p class="inner-content">Inner content - THIS element is more synonymous with a Bootstrap 2 col-*.</p>
        </div>
        <div class="col-sm-6 my-column">
            Col 2
        </div>
    </div>
</div>

and the CSS

.row {
    border: blue 1px solid;
}
.my-column {
    background-color: green;
    padding-top: 10px;
    padding-bottom: 10px;
}
.my-column:first-child {
    background-color: red;
}

.inner-content {
    background: #eee;
    border: #999;
    border-radius: 5px;
    padding: 15px;
}

passing 2 $index values within nested ng-repeat

When you are dealing with objects, you want to ignore simple id's as much as convenient.

If you change the click line to this, I think you will be well on your way:

<li class="tutorial_title {{tutorial.active}}" ng-click="loadFromMenu(tutorial)" ng-repeat="tutorial in section.tutorials">

Also, I think you may need to change

class="tutorial_title {{tutorial.active}}"

to something like

ng-class="tutorial_title {{tutorial.active}}"

See http://docs.angularjs.org/misc/faq and look for ng-class.

Differences between Microsoft .NET 4.0 full Framework and Client Profile

A list of assemblies is available at Assemblies in the .NET Framework Client Profile on MSDN (the list is too long to include here).

If you're more interested in features, .NET Framework Client Profile on MSDN lists the following as being included:

  • common language runtime (CLR)
  • ClickOnce
  • Windows Forms
  • Windows Presentation Foundation (WPF)
  • Windows Communication Foundation (WCF)
  • Entity Framework
  • Windows Workflow Foundation
  • Speech
  • XSLT support
  • LINQ to SQL
  • Runtime design libraries for Entity Framework and WCF Data Services
  • Managed Extensibility Framework (MEF)
  • Dynamic types
  • Parallel-programming features, such as Task Parallel Library (TPL), Parallel LINQ (PLINQ), and Coordination Data Structures (CDS)
  • Debugging client applications

And the following as not being included:

  • ASP.NET
  • Advanced Windows Communication Foundation (WCF) functionality
  • .NET Framework Data Provider for Oracle
  • MSBuild for compiling

Oracle DateTime in Where Clause?

You can also use the following to include the TIME portion in your query:

SELECT EMP_NAME
     , DEPT
  FROM EMPLOYEE 
 WHERE TIME_CREATED >= TO_DATE('26/JAN/2011 00:00:00', 'dd/mon/yyyy HH24:MI:SS');

spring autowiring with unique beans: Spring expected single matching bean but found 2

If I'm not mistaken, the default bean name of a bean declared with @Component is the name of its class its first letter in lower-case. This means that

@Component
public class SuggestionService {

declares a bean of type SuggestionService, and of name suggestionService. It's equivalent to

@Component("suggestionService")
public class SuggestionService {

or to

<bean id="suggestionService" .../>

You're redefining another bean of the same type, but with a different name, in the XML:

<bean id="SuggestionService" class="com.hp.it.km.search.web.suggestion.SuggestionService">
    ...
</bean>

So, either specify the name of the bean in the annotation to be SuggestionService, or use the ID suggestionService in the XML (don't forget to also modify the <ref> element, or to remove it, since it isn't needed). In this case, the XML definition will override the annotation definition.

How can I convert a long to int in Java?

Updated, in Java 8:

Math.toIntExact(value);

Original Answer:

Simple type casting should do it:

long l = 100000;
int i = (int) l;

Note, however, that large numbers (usually larger than 2147483647 and smaller than -2147483648) will lose some of the bits and would be represented incorrectly.

For instance, 2147483648 would be represented as -2147483648.

Join/Where with LINQ and Lambda

I've done something like this;

var certificationClass = _db.INDIVIDUALLICENSEs
    .Join(_db.INDLICENSECLAsses,
        IL => IL.LICENSE_CLASS,
        ILC => ILC.NAME,
        (IL, ILC) => new { INDIVIDUALLICENSE = IL, INDLICENSECLAsse = ILC })
    .Where(o => 
        o.INDIVIDUALLICENSE.GLOBALENTITYID == "ABC" &&
        o.INDIVIDUALLICENSE.LICENSE_TYPE == "ABC")
    .Select(t => new
        {
            value = t.PSP_INDLICENSECLAsse.ID,
            name = t.PSP_INDIVIDUALLICENSE.LICENSE_CLASS,                
        })
    .OrderBy(x => x.name);

Haskell: Converting Int to String

An example based on Chuck's answer:

myIntToStr :: Int -> String
myIntToStr x
    | x < 3     = show x ++ " is less than three"
    | otherwise = "normal"

Note that without the show the third line will not compile.

Java 8 stream reverse order

ArrayDeque are faster in the stack than a Stack or LinkedList. "push()" inserts elements at the front of the Deque

 protected <T> Stream<T> reverse(Stream<T> stream) {
    ArrayDeque<T> stack = new ArrayDeque<>();
    stream.forEach(stack::push);
    return stack.stream();
}

Why are C++ inline functions in the header?

There are two ways to look at it:

  1. Inline functions are defined in the header because, in order to inline a function call, the compiler must be able to see the function body. For a naive compiler to do that, the function body must be in the same translation unit as the call. (A modern compiler can optimize across translation units, and so a function call may be inlined even though the function definition is in a separate translation unit, but these optimizations are expensive, aren't always enabled, and weren't always supported by the compiler)

  2. functions defined in the header must be marked inline because otherwise, every translation unit which includes the header will contain a definition of the function, and the linker will complain about multiple definitions (a violation of the One Definition Rule). The inline keyword suppresses this, allowing multiple translation units to contain (identical) definitions.

The two explanations really boil down to the fact that the inline keyword doesn't exactly do what you'd expect.

A C++ compiler is free to apply the inlining optimization (replace a function call with the body of the called function, saving the call overhead) any time it likes, as long as it doesn't alter the observable behavior of the program.

The inline keyword makes it easier for the compiler to apply this optimization, by allowing the function definition to be visible in multiple translation units, but using the keyword doesn't mean the compiler has to inline the function, and not using the keyword doesn't forbid the compiler from inlining the function.

What is the best way to conditionally apply a class?

I am new to Angular but have found this to solve my issue:

<i class="icon-download" ng-click="showDetails = ! showDetails" ng-class="{'icon-upload': showDetails}"></i>

This will conditionally apply a class based on a var. It starts off with a icon-download as a default, the using ng-class, I check the status of showDetails if true/false and apply class icon-upload. Its working great.

Hope it helps.

How can I get href links from HTML using Python?

You can use the HTMLParser module.

The code would probably look something like this:

from HTMLParser import HTMLParser

class MyHTMLParser(HTMLParser):

    def handle_starttag(self, tag, attrs):
        # Only parse the 'anchor' tag.
        if tag == "a":
           # Check the list of defined attributes.
           for name, value in attrs:
               # If href is defined, print it.
               if name == "href":
                   print name, "=", value


parser = MyHTMLParser()
parser.feed(your_html_string)

Note: The HTMLParser module has been renamed to html.parser in Python 3.0. The 2to3 tool will automatically adapt imports when converting your sources to 3.0.

how do I insert a column at a specific column index in pandas?

You could try to extract columns as list, massage this as you want, and reindex your dataframe:

>>> cols = df.columns.tolist()
>>> cols = [cols[-1]]+cols[:-1] # or whatever change you need
>>> df.reindex(columns=cols)

   n  l  v
0  0  a  1
1  0  b  2
2  0  c  1
3  0  d  2

EDIT: this can be done in one line ; however, this looks a bit ugly. Maybe some cleaner proposal may come...

>>> df.reindex(columns=['n']+df.columns[:-1].tolist())

   n  l  v
0  0  a  1
1  0  b  2
2  0  c  1
3  0  d  2

jQuery duplicate DIV into another DIV

Put this on an event

$(function(){
    $('.package').click(function(){
       var content = $('.container').html();
       $(this).html(content);
    });
});

Generate a random number in a certain range in MATLAB

if you are looking to generate all the number within a specific rang randomly then you can try

r = randi([a b],1,d)

a = start point

b = end point

d = how many number you want to generate but keep in mind that d should be less than or equal to b-a

How to copy a directory structure but only include certain files (using windows batch files)

You don't mention if it has to be batch only, but if you can use ROBOCOPY, try this:

ROBOCOPY C:\Source C:\Destination data.zip info.txt /E

EDIT: Changed the /S parameter to /E to include empty folders.

Converting .NET DateTime to JSON

I have been using this method for a while:

using System;

public static class ExtensionMethods {
  // returns the number of milliseconds since Jan 1, 1970 (useful for converting C# dates to JS dates)
  public static double UnixTicks(this DateTime dt)
  {
    DateTime d1 = new DateTime(1970, 1, 1);
    DateTime d2 = dt.ToUniversalTime();
    TimeSpan ts = new TimeSpan(d2.Ticks - d1.Ticks);
    return ts.TotalMilliseconds;
  }
}

Assuming you are developing against .NET 3.5, it's a straight copy/paste. You can otherwise port it.

You can encapsulate this in a JSON object, or simply write it to the response stream.

On the Javascript/JSON side, you convert this to a date by simply passing the ticks into a new Date object:

jQuery.ajax({
  ...
  success: function(msg) {
    var d = new Date(msg);
  }
}

Are arrays passed by value or passed by reference in Java?

Everything in Java is passed by value. In case of an array (which is nothing but an Object), the array reference is passed by value (just like an object reference is passed by value).

When you pass an array to other method, actually the reference to that array is copied.

  • Any changes in the content of array through that reference will affect the original array.
  • But changing the reference to point to a new array will not change the existing reference in original method.

See this post: Is Java "pass-by-reference" or "pass-by-value"?

See this working example:

public static void changeContent(int[] arr) {

   // If we change the content of arr.
   arr[0] = 10;  // Will change the content of array in main()
}

public static void changeRef(int[] arr) {
   // If we change the reference
   arr = new int[2];  // Will not change the array in main()
   arr[0] = 15;
}

public static void main(String[] args) {
    int [] arr = new int[2];
    arr[0] = 4;
    arr[1] = 5;

    changeContent(arr);

    System.out.println(arr[0]);  // Will print 10.. 
  
    changeRef(arr);

    System.out.println(arr[0]);  // Will still print 10.. 
                                 // Change the reference doesn't reflect change here..
}

How to install Python packages from the tar.gz file without using pip install

Install it by running

python setup.py install

Better yet, you can download from github. Install git via apt-get install git and then follow this steps:

git clone https://github.com/mwaskom/seaborn.git
cd seaborn
python setup.py install

What are unit tests, integration tests, smoke tests, and regression tests?

  • Integration testing: Integration testing is the integrate another element
  • Smoke testing: Smoke testing is also known as build version testing. Smoke testing is the initial testing process exercised to check whether the software under test is ready/stable for further testing.
  • Regression testing: Regression testing is repeated testing. Whether new software is effected in another module or not.
  • Unit testing: It is a white box testing. Only developers involve in it

Best way to format integer as string with leading zeros?

This is my Python function:

def add_nulls(num, cnt=2):
  cnt = cnt - len(str(num))
  nulls = '0' * cnt
  return '%s%s' % (nulls, num)

Compiler error: memset was not declared in this scope

You should include <string.h> (or its C++ equivalent, <cstring>).

How to check that a string is parseable to a double?

Apache, as usual, has a good answer from Apache Commons-Lang in the form of NumberUtils.isCreatable(String).

Handles nulls, no try/catch block required.

How to use JavaScript to change the form action

I wanted to use JavaScript to change a form's action, so I could have different submit inputs within the same form linking to different pages.

I also had the added complication of using Apache rewrite to change example.com/page-name into example.com/index.pl?page=page-name. I found that changing the form's action caused example.com/index.pl (with no page parameter) to be rendered, even though the expected URL (example.com/page-name) was displayed in the address bar.

To get around this, I used JavaScript to insert a hidden field to set the page parameter. I still changed the form's action, just so the address bar displayed the correct URL.

function setAction (element, page)
{
  if(checkCondition(page))
  {
    /* Insert a hidden input into the form to set the page as a parameter.
     */
    var input = document.createElement("input");
    input.setAttribute("type","hidden");
    input.setAttribute("name","page");
    input.setAttribute("value",page);
    element.form.appendChild(input);

    /* Change the form's action. This doesn't chage which page is displayed,
     * it just make the URL look right.
     */
    element.form.action = '/' + page;
    element.form.submit();
  }
}

In the form:

<input type="submit" onclick='setAction(this,"my-page")' value="Click Me!" />

Here are my Apache rewrite rules:

RewriteCond %{DOCUMENT_ROOT}%{REQUEST_URI} !-f
RewriteRule ^/(.*)$ %{DOCUMENT_ROOT}/index.pl?page=$1&%{QUERY_STRING}

I'd be interested in any explanation as to why just setting the action didn't work.

Adding options to a <select> using jQuery?

Not mentioned in any answer but useful is the case where you want that option to be also selected, you can add:

var o = new Option("option text", "value");
o.selected=true;
$("#mySelect").append(o);

Convert java.util.date default format to Timestamp in Java

You can use DateFormat(java.text.*) to parse the date:

DateFormat df = new SimpleDateFormat("EEE MMM dd kk:mm:ss z yyyy", Locale.ENGLISH);
Date d = df.parse("Mon May 27 11:46:15 IST 2013")

You will have to change the locale to match your own (with this you will get 10:46:15). Then you can use the same code you have to convert it to a timestamp.

Change label text using JavaScript

Because a label element is not loaded when a script is executed. Swap the label and script elements, and it will work:

<label id="lbltipAddedComment"></label>
<script>
    document.getElementById('lbltipAddedComment').innerHTML = 'Your tip has been submitted!';
</script>

How to permanently export a variable in Linux?

add the line to your .bashrc or .profile. The variables set in $HOME/.profile are active for the current user, the ones in /etc/profile are global. The .bashrc is pulled on each bash session start.

Dynamically select data frame columns using $ and a character value

Had similar problem due to some CSV files that had various names for the same column.
This was the solution:

I wrote a function to return the first valid column name in a list, then used that...

# Return the string name of the first name in names that is a column name in tbl
# else null
ChooseCorrectColumnName <- function(tbl, names) {
for(n in names) {
    if (n %in% colnames(tbl)) {
        return(n)
    }
}
return(null)
}

then...

cptcodefieldname = ChooseCorrectColumnName(file, c("CPT", "CPT.Code"))
icdcodefieldname = ChooseCorrectColumnName(file, c("ICD.10.CM.Code", "ICD10.Code"))

if (is.null(cptcodefieldname) || is.null(icdcodefieldname)) {
        print("Bad file column name")
}

# Here we use the hash table implementation where 
# we have a string key and list value so we need actual strings,
# not Factors
file[cptcodefieldname] = as.character(file[cptcodefieldname])
file[icdcodefieldname] = as.character(file[icdcodefieldname])
for (i in 1:length(file[cptcodefieldname])) {
    cpt_valid_icds[file[cptcodefieldname][i]] <<- unique(c(cpt_valid_icds[[file[cptcodefieldname][i]]], file[icdcodefieldname][i]))
}

HTML select drop-down with an input field

You can use input text with "list" attribute, which refers to the datalist of values.

_x000D_
_x000D_
<input type="text" name="city" list="cityname">_x000D_
    <datalist id="cityname">_x000D_
      <option value="Boston">_x000D_
      <option value="Cambridge">_x000D_
    </datalist>
_x000D_
_x000D_
_x000D_

This creates a free text input field that also has a drop-down to select predefined choices. Attribution for example and more information: https://www.w3.org/wiki/HTML/Elements/datalist

Mailto on submit button

What you need to do is use the onchange event listener in the form and change the href attribute of the send button according to the context of the mail:

<form id="form" onchange="mail(this)">
  <label>Name</label>
  <div class="row margin-bottom-20">
    <div class="col-md-6 col-md-offset-0">
      <input class="form-control" name="name" type="text">
    </div>
  </div>

  <label>Email <span class="color-red">*</span></label>
  <div class="row margin-bottom-20">
    <div class="col-md-6 col-md-offset-0">
      <input class="form-control" name="email" type="text">
    </div>
  </div>

  <label>Date of visit/departure </label>
  <div class="row margin-bottom-20">
    <div class="col-md-3 col-md-offset-0">
      <input class="form-control w8em" name="adate" type="text">
      <script>
        datePickerController.createDatePicker({
          // Associate the text input to a DD/MM/YYYY date format
          formElements: {
            "adate": "%d/%m/%Y"
          }
        });
      </script>
    </div>
    <div class="col-md-3 col-md-offset-0">
      <input class="form-control" name="ddate" type="date">
    </div>
  </div>

  <label>No. of people travelling with</label>
  <div class="row margin-bottom-20">
    <div class="col-md-3 col-md-offset-0">
      <input class="form-control" placeholder="Adults" min=1 name="adult" type="number">
    </div>
    <div class="col-md-3 col-md-offset-0">
      <input class="form-control" placeholder="Children" min=0 name="childeren" type="number">
    </div>
  </div>

  <label>Cities you want to visit</label><br />
  <div class="checkbox-inline">
    <label><input type="checkbox" name="city" value="Cassablanca">Cassablanca</label>
  </div>
  <div class="checkbox-inline">
    <label><input type="checkbox" name="city" value="Fez">Fez</label>
  </div>
  <div class="checkbox-inline">
    <label><input type="checkbox" name="city" value="Tangier">Tangier</label>
  </div>
  <div class="checkbox-inline">
    <label><input type="checkbox" name="city" value="Marrakech">Marrakech</label>
  </div>
  <div class="checkbox-inline">
    <label><input type="checkbox" name="city" value="Rabat">Rabat</label>
  </div>

  <div class="row margin-bottom-20">
    <div class="col-md-8 col-md-offset-0">
      <textarea rows="4" placeholder="Activities Intersted in" name="activities" class="form-control"></textarea>
    </div>
  </div>


  <div class="row margin-bottom-20">
    <div class="col-md-8 col-md-offset-0">
      <textarea rows="6" class="form-control" name="comment" placeholder="Comment"></textarea>
    </div>
  </div>

  <p><a id="send" class="btn btn-primary">Create Message</a></p>
</form>

JavaScript

function mail(form) {
    var name = form.name.value;
    var city = "";
    var adate = form.adate.value;
    var ddate = form.ddate.value;
    var activities = form.activities.value;
    var adult = form.adult.value;
    var child = form.childeren.value;
    var comment = form.comment.value;
    var warning = ""
    for (i = 0; i < form.city.length; i++) {
        if (form.city[i].checked)
            city += " " + form.city[i].value;
    }
    var str = "mailto:[email protected]?subject=travel to morocco&body=";
    if (name.length > 0) {
        str += "Hi my name is " + name + ", ";
    } else {
        warning += "Name is required"
    }
    if (city.length > 0) {
        str += "I am Intersted in visiting the following citis: " + city + ", ";
    }
    if (activities.length > 0) {
        str += "I am Intersted in following activities: " + activities + ". "
    }
    if (adate.length > 0) {
        str += "I will be ariving on " + adate;
    }
    if (ddate.length > 0) {
        str += " And departing on " + ddate;
    }
    if (adult.length > 0) {
        if (adult == 1 && child == null) {
            str += ". I will be travelling alone"
        } else if (adult > 1) {
            str += ".We will have a group of " + adult + " adults ";
        }
        if (child == null) {
            str += ".";
        } else if (child > 1) {
            str += "along with " + child + " children.";
        } else if (child == 1) {
            str += "along with a child.";
        }
    }

    if (comment.length > 0) {
        str += "%0D%0A" + comment + "."
    }

    if (warning.length > 0) {
        alert(warning)
    } else {
        str += "%0D%0ARegards,%0D%0A" + name;
        document.getElementById('send').href = str;
    }
}

How to secure phpMyAdmin

One of my concerns with phpMyAdmin was that by default, all MySQL users can access the db. If DB's root password is compromised, someone can wreck havoc on the db. I wanted to find a way to avoid that by restricting which MySQL user can login to phpMyAdmin.

I have found using AllowDeny configuration in PhpMyAdmin to be very useful. http://wiki.phpmyadmin.net/pma/Config#AllowDeny_.28rules.29

AllowDeny lets you configure access to phpMyAdmin in a similar way to Apache. If you set the 'order' to explicit, it will only grant access to users defined in 'rules' section. In the rules, section you restrict MySql users who can access use the phpMyAdmin.

$cfg['Servers'][$i]['AllowDeny']['order'] = 'explicit'
$cfg['Servers'][$i]['AllowDeny']['rules'] = array('pma-user from all')

Now you have limited access to the user named pma-user in MySQL, you can grant limited privilege to that user.

grant select on db_name.some_table to 'pma-user'@'app-server'

How to convert an Object {} to an Array [] of key-value pairs in JavaScript

With lodash, in addition to the answer provided above, you can also have the key in the output array.

Without the object keys in the output array

for:

const array = _.values(obj);

If obj is the following:

{ “art”: { id: 1,  title: “aaaa” }, “fiction”: { id: 22,  title: “7777”} }

Then array will be:

[ { id: 1, title: “aaaa” }, { id: 22, title: “7777” } ]

With the object keys in the output array

If you write instead ('genre' is a string that you choose):

const array= _.map(obj, (val, id) => {
    return { ...val, genre: key };
  });

You will get:

[ 
  { id: 1, title: “aaaa” , genre: “art”}, 
  { id: 22, title: “7777”, genre: “fiction” }
]

How can I check if a View exists in a Database?

To expand on Kevin's answer.

    private bool CustomViewExists(string viewName)
    {
        using (SalesPad.Data.DataConnection dc = yourconnection)
        {
            System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(String.Format(@"IF EXISTS(select * FROM sys.views where name = '{0}')
                Select 1
            else
                Select 0", viewName));
            cmd.CommandType = CommandType.Text;
            return Convert.ToBoolean(dc.ExecuteScalar(cmd));
        }
    }

LINQ to SQL - How to select specific columns and return strongly typed list

The issue was in fact that one of the properties was a relation to another table. I changed my LINQ query so that it could get the same data from a different method without needing to load the entire table.

Thank you all for your help!

How to fix java.net.SocketException: Broken pipe?

In our case we experienced this while performing a load test on our app server. The issue turned out that we need to add additional memory to our JVM because it was running out. This resolved the issue.

Try increasing the memory available to the JVM and or monitor the memory usage when you get those errors.

Carry Flag, Auxiliary Flag and Overflow Flag in Assembly

Carry Flag is a flag set when:

a) two unsigned numbers were added and the result is larger than "capacity" of register where it is saved. Ex: we wanna add two 8 bit numbers and save result in 8 bit register. In your example: 255 + 9 = 264 which is more that 8 bit register can store. So the value "8" will be saved there (264 & 255 = 8) and CF flag will be set.

b) two unsigned numbers were subtracted and we subtracted the bigger one from the smaller one. Ex: 1-2 will give you 255 in result and CF flag will be set.

Auxiliary Flag is used as CF but when working with BCD. So AF will be set when we have overflow or underflow on in BCD calculations. For example: considering 8 bit ALU unit, Auxiliary flag is set when there is carry from 3rd bit to 4th bit i.e. carry from lower nibble to higher nibble. (Wiki link)

Overflow Flag is used as CF but when we work on signed numbers. Ex we wanna add two 8 bit signed numbers: 127 + 2. the result is 129 but it is too much for 8bit signed number, so OF will be set. Similar when the result is too small like -128 - 1 = -129 which is out of scope for 8 bit signed numbers.

You can read more about flags on wikipedia

org.hibernate.exception.ConstraintViolationException: Could not execute JDBC batch update

You can find your sample code completely here: http://www.java2s.com/Code/Java/Hibernate/OneToManyMappingbasedonSet.htm

Have a look and check the differences. specially the even_id in :

<set name="attendees" cascade="all">
    <key column="event_id"/>
    <one-to-many class="Attendee"/>
</set> 

How do you get the current project directory from C# code when creating a custom MSBuild task?

This solution works well for me, on Develop and also on TEST and PROD servers with ASP.NET MVC5 via C#:

var projectDir = Path.GetDirectoryName(AppDomain.CurrentDomain.BaseDirectory);

If you need project directory in project configuration file use:

$(ProjectDir)

How to delete last character from a string using jQuery?

You can do it with plain JavaScript:

alert('123-4-'.substr(0, 4)); // outputs "123-"

This returns the first four characters of your string (adjust 4 to suit your needs).

How to pass parameters in GET requests with jQuery

Here is the syntax using jQuery $.get

$.get(url, data, successCallback, datatype)

So in your case, that would equate to,

var url = 'ajax.asp';
var data = { ajaxid: 4, UserID: UserID, EmailAddress: EmailAddress };
var datatype = 'jsonp';

function success(response) {
// do something here 
}

$.get('ajax.aspx', data, success, datatype)

Note $.get does not give you the opportunity to set an error handler. But there are several ways to do it either using $.ajaxSetup(), $.ajaxError() or chaining a .fail on your $.get like below

$.get(url, data, success, datatype)
 .fail(function(){
})

The reason for setting the datatype as 'jsonp' is due to browser same origin policy issues, but if you are making the request on the same domain where your javascript is hosted, you should be fine with datatype set to json.

If you don't want to use the jquery $.get then see the docs for $.ajax which allows room for more flexibility

How to use and style new AlertDialog from appCompat 22.1 and above

Follow @reVerse answer but in my case, I already had some property in my AppTheme like

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    ...
    <item name="android:textColor">#111</item>
    <item name="android:textSize">13sp</item>
</style>

So my dialog will look like
enter image description here

I solved it by

1) Change the import from android.app.AlertDialog to android.support.v7.app.AlertDialog
2) I override 2 property in AppTheme with null value

<style name="MyAlertDialogStyle" parent="Theme.AppCompat.Light.Dialog.Alert">
    <!-- Used for the buttons -->
    <item name="colorAccent">#FFC107</item>
    <!-- Used for the title and text -->
    <item name="android:textColorPrimary">#FFFFFF</item>
    <!-- Used for the background -->
    <item name="android:background">#4CAF50</item>


    <item name="android:textColor">@null</item>
    <item name="android:textSize">@null</item>
</style>

.

AlertDialog.Builder builder = new AlertDialog.Builder(mContext, R.style.MyAlertDialogStyle);

Hope it help another people

enter image description here

How to execute an action before close metro app WinJS

If I am not mistaken, it will be onunload event.

"Occurs when the application is about to be unloaded." - MSDN

Local variable referenced before assignment?

As the Python interpreter reads the definition of a function (or, I think, even a block of indented code), all variables that are assigned to inside the function are added to the locals for that function. If a local does not have a definition before an assignment, the Python interpreter does not know what to do, so it throws this error.

The solution here is to add

global feed

to your function (usually near the top) to indicate to the interpreter that the feed variable is not local to this function.

How can I combine multiple rows into a comma-delimited list in Oracle?

Here is a simple way without stragg or creating a function.

create table countries ( country_name varchar2 (100));

insert into countries values ('Albania');

insert into countries values ('Andorra');

insert into countries values ('Antigua');


SELECT SUBSTR (SYS_CONNECT_BY_PATH (country_name , ','), 2) csv
      FROM (SELECT country_name , ROW_NUMBER () OVER (ORDER BY country_name ) rn,
                   COUNT (*) OVER () cnt
              FROM countries)
     WHERE rn = cnt
START WITH rn = 1
CONNECT BY rn = PRIOR rn + 1;

CSV                                                                             
--------------------------
Albania,Andorra,Antigua                                                         

1 row selected.

As others have mentioned, if you are on 11g R2 or greater, you can now use listagg which is much simpler.

select listagg(country_name,', ') within group(order by country_name) csv
  from countries;

CSV                                                                             
--------------------------
Albania, Andorra, Antigua

1 row selected.

Shell command to sum integers, one per line?

You can do it with Alacon - command-line utility for Alasql database.

It works with Node.js, so you need to install Node.js and then Alasql package:

To calculate sum from stdin you can use the following command:

> cat data.txt | node alacon "SELECT VALUE SUM([0]) FROM TXT()" >b.txt

Open Bootstrap Modal from code-behind

How about doing it like this:

1) show popup with form

2) submit form using AJAX

3) in AJAX server side code, render response that will either:

  • show popup with form with validations or just a message
  • close the popup (and maybe redirect you to new page)

Looking for simple Java in-memory cache

Try @Cacheable from jcabi-aspects. With a single annotation you make the entire method result cacheable in memory:

public class Resource {
  @Cacheable(lifetime = 5, unit = TimeUnit.SECONDS)
  public String load(URL url) {
    return url.openConnection().getContent();
  }
}

Also, read this article: http://www.yegor256.com/2014/08/03/cacheable-java-annotation.html

How to perform runtime type checking in Dart?

Dart Object type has a runtimeType instance member (source is from dart-sdk v1.14, don't know if it was available earlier)

class Object {
  //...
  external Type get runtimeType;
}

Usage:

Object o = 'foo';
assert(o.runtimeType == String);

A potentially dangerous Request.Form value was detected from the client

As long as these are only "<" and ">" (and not the double quote itself) characters and you're using them in context like <input value="this" />, you're safe (while for <textarea>this one</textarea> you would be vulnerable of course). That may simplify your situation, but for anything more use one of other posted solutions.

Could not install Gradle distribution from 'https://services.gradle.org/distributions/gradle-2.1-all.zip'

If all above solutions is not working and In case of your project was working fine and now getting this issue, then try this,

  • go to android studio setting.
  • select gradle under build,execution.
  • then again just set path of gradle user home (C:/Users/%user_name%/.gradle/wrapper/dists/gradle-6.5-bin)
  • just rebuild again, this helps me.

Import Excel to Datagridview

try this following snippet, its working fine.

private void button1_Click(object sender, EventArgs e)
{
     try
     {
             OpenFileDialog openfile1 = new OpenFileDialog();
             if (openfile1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
             {
                   this.textBox1.Text = openfile1.FileName;
             }
             {
                   string pathconn = "Provider = Microsoft.jet.OLEDB.4.0; Data source=" + textBox1.Text + ";Extended Properties=\"Excel 8.0;HDR= yes;\";";
                   OleDbConnection conn = new OleDbConnection(pathconn);
                   OleDbDataAdapter MyDataAdapter = new OleDbDataAdapter("Select * from [" + textBox2.Text + "$]", conn);
                   DataTable dt = new DataTable();
                   MyDataAdapter.Fill(dt);
                   dataGridView1.DataSource = dt;
             }
      }
      catch { }
}

Mocking static methods with Mockito

Observation : When you call static method within a static entity, you need to change the class in @PrepareForTest.

For e.g. :

securityAlgo = MessageDigest.getInstance(SECURITY_ALGORITHM);

For the above code if you need to mock MessageDigest class, use

@PrepareForTest(MessageDigest.class)

While if you have something like below :

public class CustomObjectRule {

    object = DatatypeConverter.printHexBinary(MessageDigest.getInstance(SECURITY_ALGORITHM)
             .digest(message.getBytes(ENCODING)));

}

then, you'd need to prepare the class this code resides in.

@PrepareForTest(CustomObjectRule.class)

And then mock the method :

PowerMockito.mockStatic(MessageDigest.class);
PowerMockito.when(MessageDigest.getInstance(Mockito.anyString()))
      .thenThrow(new RuntimeException());

What's Mongoose error Cast to ObjectId failed for value XXX at path "_id"?

Mongoose's findById method casts the id parameter to the type of the model's _id field so that it can properly query for the matching doc. This is an ObjectId but "foo" is not a valid ObjectId so the cast fails.

This doesn't happen with 41224d776a326fb40f000001 because that string is a valid ObjectId.

One way to resolve this is to add a check prior to your findById call to see if id is a valid ObjectId or not like so:

if (id.match(/^[0-9a-fA-F]{24}$/)) {
  // Yes, it's a valid ObjectId, proceed with `findById` call.
}

Block direct access to a file over http but allow php script access

The safest way is to put the files you want kept to yourself outside of the web root directory, like Damien suggested. This works because the web server follows local file system privileges, not its own privileges.

However, there are a lot of hosting companies that only give you access to the web root. To still prevent HTTP requests to the files, put them into a directory by themselves with a .htaccess file that blocks all communication. For example,

Order deny,allow
Deny from all

Your web server, and therefore your server side language, will still be able to read them because the directory's local permissions allow the web server to read and execute the files.

How do I use jQuery to redirect?

Via Jquery:

$(location).attr('href','http://example.com/Registration/Success/');

PHP Function with Optional Parameters

Make the function take one parameter: an array. Pass in the actual parameters as values in the array.


Edit: the link in Pekka's comment just about sums it up.

Regular expression to match a dot

In javascript you have to use \. to match a dot.

Example

"blah.tests.zibri.org".match('test\\..*')
null

and

"blah.test.zibri.org".match('test\\..*')
["test.zibri.org", index: 5, input: "blah.test.zibri.org", groups: undefined]

How do I return multiple values from a function?

Named tuples were added in 2.6 for this purpose. Also see os.stat for a similar builtin example.

>>> import collections
>>> Point = collections.namedtuple('Point', ['x', 'y'])
>>> p = Point(1, y=2)
>>> p.x, p.y
1 2
>>> p[0], p[1]
1 2

In recent versions of Python 3 (3.6+, I think), the new typing library got the NamedTuple class to make named tuples easier to create and more powerful. Inheriting from typing.NamedTuple lets you use docstrings, default values, and type annotations.

Example (From the docs):

class Employee(NamedTuple):  # inherit from typing.NamedTuple
    name: str
    id: int = 3  # default value

employee = Employee('Guido')
assert employee.id == 3