Programs & Examples On #Adoconnection

#1146 - Table 'phpmyadmin.pma_recent' doesn't exist

Edit:

$cfg['Servers'][$i]['userconfig'] = 'pma__userconfig'; 

Change into:

$Cfg ['Servers'] [$ i] ['table_uiprefs'] = ‘pma_table_uiprefs’;

Then https://kamalkaur188.wordpress.com/category/removing-error-1146-table-phpmyadmin-pma_recent-doesnt-exist/ work for me.

Auto Generate Database Diagram MySQL

Here is a tool that generates relational diagrams from MySQL (on Windows at the moment). I have used it on a database with 400 tables. If the diagram is too big for a single diagram, it gets broken down into smaller ones. So you will probably end up with multiple diagrams and you can navigate between them by right clicking. It is all explained in the link below. The tool is free (as in free beer), the author uses it himself on consulting assignments, and lets other people use it. http://www.scmlite.com/Quick%20overview

CodeIgniter Disallowed Key Characters

i saw this error when i was trying to send a form, and in one of the fields' names, i let the word "endereço".

echo form_input(array('class' => 'form-control', 'name' => 'endereco', 'placeholder' => 'Endereço', 'value' => set_value('endereco')));

When i changed 'ç' for 'c', the error was gone.

How can I find out if an .EXE has Command-Line Options?

Sysinternals has another tool you could use, Strings.exe

Example:

strings.exe c:\windows\system32\wuauclt.exe > %temp%\wuauclt_strings.txt && %temp%\wuauclt_strings.txt

how to save DOMPDF generated content to file?

I did test your code and the only problem I could see was the lack of permission given to the directory you try to write the file in to.

Give "write" permission to the directory you need to put the file. In your case it is the current directory.

Use "chmod" in linux.

Add "Everyone" with "write" enabled to the security tab of the directory if you are in Windows.

How to get rid of `deprecated conversion from string constant to ‘char*’` warnings in GCC?

I had a similar problem, I solved it like this:

#include <string.h>

extern void foo(char* m);

int main() {
    // warning: deprecated conversion from string constant to ‘char*’
    //foo("Hello");

    // no more warning
    char msg[] = "Hello";
    foo(msg);
}

Is this an appropriate way of solving this? I do not have access to foo to adapt it to accept const char*, although that would be a better solution (because foo does not change m).

How to replace plain URLs with links?

I searched on google for anything newer and ran across this one:

$('p').each(function(){
   $(this).html( $(this).html().replace(/((http|https|ftp):\/\/[\w?=&.\/-;#~%-]+(?![\w\s?&.\/;#~%"=-]*>))/g, '<a href="$1">$1</a> ') );
});

demo: http://jsfiddle.net/kachibito/hEgvc/1/

Works really well for normal links.

When to use window.opener / window.parent / window.top

  • window.opener refers to the window that called window.open( ... ) to open the window from which it's called
  • window.parent refers to the parent of a window in a <frame> or <iframe>
  • window.top refers to the top-most window from a window nested in one or more layers of <iframe> sub-windows

Those will be null (or maybe undefined) when they're not relevant to the referring window's situation. ("Referring window" means the window in whose context the JavaScript code is run.)

C++ create string of text and variables

See also boost::format:

#include <boost/format.hpp>

std::string var = (boost::format("somtext %s sometext %s") % somevar % somevar).str();

How to import XML file into MySQL database table using XML_LOAD(); function

Since ID is auto increment, you can also specify ID=NULL as,

LOAD XML LOCAL INFILE '/pathtofile/file.xml' INTO TABLE my_tablename SET ID=NULL;

Expand a random range from 1–5 to 1–7

I don't like ranges starting from 1, so I'll start from 0 :-)

unsigned rand5()
{
    return rand() % 5;
}

unsigned rand7()
{
    int r;

    do
    {
        r =         rand5();
        r = r * 5 + rand5();
        r = r * 5 + rand5();
        r = r * 5 + rand5();
        r = r * 5 + rand5();
        r = r * 5 + rand5();
    } while (r > 15623);

    return r / 2232;
}

What does body-parser do with express?

These are all a matter of convenience.

Basically, if the question were 'Do we need to use body-parser?' The answer is 'No'. We can come up with the same information from the client-post-request using a more circuitous route that will generally be less flexible and will increase the amount of code we have to write to get the same information.

This is kind of the same as asking 'Do we need to use express to begin with?' Again, the answer there is no, and again, really it all comes down to saving us the hassle of writing more code to do the basic things that express comes with 'built-in'.

On the surface - body-parser makes it easier to get at the information contained in client requests in a variety of formats instead of making you capture the raw data streams and figuring out what format the information is in, much less manually parsing that information into useable data.

Connect to SQL Server database from Node.js

//start the program
var express = require('express');
var app = express();

app.get('/', function (req, res) {

    var sql = require("mssql");

    // config for your database
    var config = {
        user: 'datapullman',
        password: 'system',
        server: 'localhost', 
        database: 'chat6' 
    };

    // connect to your database
    sql.connect(config, function (err) {

        if (err) console.log(err);

        // create Request object
        var request = new sql.Request();

        // query to the database and get the records

        request.query("select * From emp", function (err, recordset) {            
            if  (err) console.log(err)

            // send records as a response
            res.send(recordset);

        });
    });
});

var server = app.listen(5000, function () {
    console.log('Server is running..');
});

//create a table as emp in a database (i have created as chat6)

// programs ends here

//save it as app.js and run as node app.js //open in you browser as localhost:5000

how to change color of TextinputLayout's label and edittext underline android

Add this attribute in Edittext tag and enjoy:

 android:backgroundTint="@color/colorWhite"

SQL Error: ORA-12899: value too large for column

This answer still comes up high in the list for ORA-12899 and lot of non helpful comments above, even if they are old. The most helpful comment was #4 for any professional trying to find out why they are getting this when loading data.

Some characters are more than 1 byte in length, especially true on SQL Server. And what might fit in a varchar(20) in SQLServer won't fit into a similar varchar2(20) in Oracle.

I ran across this error yesterday with SSIS loading an Oracle database with the Attunity drivers and thought I would save folks some time.

Provide password to ssh command inside bash script, Without the usage of public keys and Expect

Install sshpass, then launch the command:

sshpass -p "yourpassword" ssh -o StrictHostKeyChecking=no yourusername@hostname

Twitter Bootstrap and ASP.NET GridView

There are 2 steps to resolve this:

  1. Add UseAccessibleHeader="true" to Gridview tag:

    <asp:GridView ID="MyGridView" runat="server" UseAccessibleHeader="true">
    
  2. Add the following Code to the PreRender event:


Protected Sub MyGridView_PreRender(sender As Object, e As EventArgs) Handles MyGridView.PreRender
    Try
        MyGridView.HeaderRow.TableSection = TableRowSection.TableHeader
    Catch ex As Exception
    End Try
End Sub

Note setting Header Row in DataBound() works only when the object is databound, any other postback that doesn't databind the gridview will result in the gridview header row style reverting to a standard row again. PreRender works everytime, just make sure you have an error catch for when the gridview is empty.

How do I get next month date from today's date and insert it in my database?

01-Feb-2014

$date = mktime( 0, 0, 0, 2, 1, 2014 );

echo strftime( '%d %B %Y', strtotime( '+1 month', $date ) );

The model item passed into the dictionary is of type .. but this dictionary requires a model item of type

This question already has a great answer, but I ran into the same error, in a different scenario: displaying a List in an EditorTemplate.

I have a model like this:

public class Foo
{
    public string FooName { get; set; }
    public List<Bar> Bars { get; set; }
}

public class Bar
{
    public string BarName { get; set; }
}

And this is my main view:

@model Foo

@Html.TextBoxFor(m => m.Name, new { @class = "form-control" })  
@Html.EditorFor(m => m.Bars)

And this is my Bar EditorTemplate (Bar.cshtml)

@model List<Bar>

<div class="some-style">
    @foreach (var item in Model)
    {
        <label>@item.BarName</label>
    }
</div>

And I got this error:

The model item passed into the dictionary is of type 'Bar', but this dictionary requires a model item of type 'System.Collections.Generic.List`1[Bar]


The reason for this error is that EditorFor already iterates the List for you, so if you pass a collection to it, it would display the editor template once for each item in the collection.

This is how I fixed this problem:

Brought the styles outside of the editor template, and into the main view:

@model Foo

@Html.TextBoxFor(m => m.Name, new { @class = "form-control" })  
<div class="some-style">
    @Html.EditorFor(m => m.Bars)
</div>

And changed the EditorTemplate (Bar.cshtml) to this:

@model Bar

<label>@Model.BarName</label>

jQuery click event not working after adding class

You should use the following:

$('#gentab').on('click', 'a.tabclick', function(event) {
    event.preventDefault();
    var liId = $(this).closest("li").attr("id");
    alert(liId);  
});

This will attach your event to any anchors within the #gentab element, reducing the scope of having to check the whole document element tree and increasing efficiency.

How to switch to new window in Selenium for Python?

for eg. you may take

driver.get('https://www.naukri.com/')

since, it is a current window ,we can name it

main_page = driver.current_window_handle

if there are atleast 1 window popup except the current window,you may try this method and put if condition in break statement by hit n trial for the index

for handle in driver.window_handles:
    if handle != main_page:
        print(handle)
        login_page = handle
        break

driver.switch_to.window(login_page)

Now ,whatever the credentials you have to apply,provide after it is loggen in. Window will disappear, but you have to come to main page window and you are done

driver.switch_to.window(main_page)
sleep(10)

How to get the android Path string to a file on Assets folder?

AFAIK the files in the assets directory don't get unpacked. Instead, they are read directly from the APK (ZIP) file.

So, you really can't make stuff that expects a file accept an asset 'file'.

Instead, you'll have to extract the asset and write it to a seperate file, like Dumitru suggests:

  File f = new File(getCacheDir()+"/m1.map");
  if (!f.exists()) try {

    InputStream is = getAssets().open("m1.map");
    int size = is.available();
    byte[] buffer = new byte[size];
    is.read(buffer);
    is.close();


    FileOutputStream fos = new FileOutputStream(f);
    fos.write(buffer);
    fos.close();
  } catch (Exception e) { throw new RuntimeException(e); }

  mapView.setMapFile(f.getPath());

How to update primary key

Don't update the primary key. It could cause a lot of problems for you keeping your data intact, if you have any other tables referencing it.

Ideally, if you want a unique field that is updateable, create a new field.

Nginx location "not equal to" regex

i was looking for the same. and found this solution.

Use negative regex assertion:

location ~ ^/(?!(favicon\.ico|resources|robots\.txt)) { 
.... # your stuff 
} 

Source Negated Regular Expressions in location

Explanation of Regex :

If URL does not match any of the following path

example.com/favicon.ico
example.com/resources
example.com/robots.txt

Then it will go inside that location block and will process it.

SyntaxError: unexpected EOF while parsing

elec_and_weather['DEMAND_t-%i'% k] = np.zeros(len(elec_and_weather['DEMAND']))'

The error comes at the end of the line where you have the (') sign; this error always means that you have a syntax error.

Finding smallest value in an array most efficiently

                //smalest number in the array//
    double small = x[0];
    for(t=0;t<x[t];t++)
    {
         if(x[t]<small)
             {
                small=x[t];
            }
    }
    printf("\nThe smallest number is  %0.2lf  \n",small);

How does Java resolve a relative path in new File()?

Relative paths can be best understood if you know how Java runs the program.

There is a concept of working directory when running programs in Java. Assuming you have a class, say, FileHelper that does the IO under /User/home/Desktop/projectRoot/src/topLevelPackage/.

Depending on the case where you invoke java to run the program, you will have different working directory. If you run your program from within and IDE, it will most probably be projectRoot.

  • In this case $ projectRoot/src : java topLevelPackage.FileHelper it will be src.

  • In this case $ projectRoot : java -cp src topLevelPackage.FileHelper it will be projectRoot.

  • In this case $ /User/home/Desktop : java -cp ./projectRoot/src topLevelPackage.FileHelper it will be Desktop.

(Assuming $ is your command prompt with standard Unix-like FileSystem. Similar correspondence/parallels with Windows system)

So, your relative path root (.) resolves to your working directory. Thus to be better sure of where to write files, it's said to consider below approach.

package topLevelPackage

import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;

public class FileHelper {

    // Not full implementation, just barebone stub for path
    public void createLocalFile() {

        // Explicitly get hold of working directory
        String workingDir = System.getProperty("user.dir");

        Path filePath = Paths.get(workingDir+File.separator+"sampleFile.txt");

        // In case we need specific path, traverse that path, rather using . or .. 
        Path pathToProjectRoot = Paths.get(System.getProperty("user.home"), "Desktop", "projectRoot");

        System.out.println(filePath);
        System.out.println(pathToProjectRoot);

    }
}

Hope this helps.

How can I parse a String to BigDecimal?

Try this

// Create a DecimalFormat that fits your requirements
DecimalFormatSymbols symbols = new DecimalFormatSymbols();
symbols.setGroupingSeparator(',');
symbols.setDecimalSeparator('.');
String pattern = "#,##0.0#";
DecimalFormat decimalFormat = new DecimalFormat(pattern, symbols);
decimalFormat.setParseBigDecimal(true);

// parse the string
BigDecimal bigDecimal = (BigDecimal) decimalFormat.parse("10,692,467,440,017.120");
System.out.println(bigDecimal);

If you are building an application with I18N support you should use DecimalFormatSymbols(Locale)

Also keep in mind that decimalFormat.parse can throw a ParseException so you need to handle it (with try/catch) or throw it and let another part of your program handle it

C++ vector of char array

In fact technically you can store C++ arrays in a vector, and it makes a lot of sense. Not directly, but by a simple workaround, wrapping in a class, will meet exactly all the requirements of a multidimensional array. As the question is already answered by anon. Some explanations steel needed. STL already provides std::array for these purposes.
Is an unpleasant surprise to fall in the trap of not understanding clearly the difference between arrays and pointers, between multidimensional arrays and arrays of arrays, and so on and so on. Vectors of vectors contains vectors as elements. Each element containing a copy of size, capacity and maybe other things, meanwhile the vector datas for elements will be placed in different random places in memory. But a vector of arrays will contain a contiguous segment of memory with all data, which is identical to multidimensional array. Also there is no good reason to keep the size of each array element while it is known to be the same for all elements. So, making a vector of array, you can't do it directly. But you can workaround it easily by wrapping the array in a class, and in this sample the memory will be identical to the memory of a bidimensional array. This approach is already widely used by many libraries. At low level it will be easily interoperable with APIs that are not C++ vector aware. So without using std::array it will look like this:

int main()
{
    struct ss
    {
        int a[5];
        int& operator[] (const int& i) { return a[i]; }
    } a{ 1,2,3,4,5 }, b{ 9,8,7,6,5 };

    vector<ss> v;
    v.resize(10);
    v[0] = a;
    v[1] = b;
    v.push_back(a); // will push to index 10, with reallocation
    v.push_back(b); // will push to index 11, with reallocation

    auto d = v.data();
    // cin >> v[1][3]; //input any element from stdin
    cout << "show two element: "<< v[1][2] <<":"<< v[1][3] << endl;
    return 0;
}

Since C++11 STL contains std::array for these purposes, so no need to reinvent it:

....
#include<array>
....
int main()
{
    vector<array<int, 5>> v;
    v.reserve(10);
    v.resize(2);
    v[0] = array<int, 5> {1, 2, 3, 4, 5};
    v[1] = array<int, 5> {9, 8, 7, 6, 5};
    v.emplace_back(array<int, 5>{ 7, 2, 53, 4, 5 });
    ///cin >> v[1][1];
    auto d = v.data();

Now look how looks in memory


Now, this is why vectors of vectors is not the answer. Supposing following code

int main()
{
    vector<vector<int>> vv = { { 1,2,3,4,5 }, { 9,8,7,6,5 } };
    auto dd = vv.data();
    return 0;
}

Guess what it looks like in the memory now

How to make program go back to the top of the code instead of closing

Python, like most modern programming languages, does not support "goto". Instead, you must use control functions. There are essentially two ways to do this.

1. Loops

An example of how you could do exactly what your SmallBasic example does is as follows:

while True :
    print "Poo"

It's that simple.

2. Recursion

def the_func() :
   print "Poo"
   the_func()

the_func()

Note on Recursion: Only do this if you have a specific number of times you want to go back to the beginning (in which case add a case when the recursion should stop). It is a bad idea to do an infinite recursion like I define above, because you will eventually run out of memory!

Edited to Answer Question More Specifically

#Alan's Toolkit for conversions

invalid_input = True
def start() :
    print ("Welcome to the converter toolkit made by Alan.")
    op = input ("Please input what operation you wish to perform. 1 for Fahrenheit to Celsius, 2 for meters to centimetres and 3 for megabytes to gigabytes")
    if op == "1":
        #stuff
        invalid_input = False # Set to False because input was valid


    elif op == "2":
        #stuff
        invalid_input = False # Set to False because input was valid
    elif op == "3": # you still have this as "if"; I would recommend keeping it as elif
        #stuff
        invalid_input = False # Set to False because input was valid
    else:
        print ("Sorry, that was an invalid command!")

while invalid_input : # this will loop until invalid_input is set to be True
    start()

Use grep to report back only line numbers

If you're open to using AWK:

awk '/textstring/ {print FNR}' textfile

In this case, FNR is the line number. AWK is a great tool when you're looking at grep|cut, or any time you're looking to take grep output and manipulate it.

The target principal name is incorrect. Cannot generate SSPI context

I had this problem when accessing the web application. It might be due to i have changed a windows password recently.

This issue got resolved when i have updated the password for the app pool where i have hosted the web application.

Add vertical scroll bar to panel

Add to your panel's style code something like this:

<asp:Panel ID="myPanel" runat="Server" CssClass="myPanelCSS" style="overflow-y:auto; overflow-x:hidden"></asp:Panel>

Python and JSON - TypeError list indices must be integers not str

I solved changing

readable_json['firstName']

by

readable_json[0]['firstName']

SSL handshake alert: unrecognized_name error since upgrade to Java 1.7.0

My VirtualHost's ServerName was commented out by default. It worked after uncommenting.

How to remove a virtualenv created by "pipenv run"

You can run the pipenv command with the --rm option as in:

pipenv --rm

This will remove the virtualenv created for you under ~/.virtualenvs

See https://pipenv.kennethreitz.org/en/latest/cli/#cmdoption-pipenv-rm

Retrofit 2 - Dynamic URL

You can use this :

@GET("group/{id}/users")

Call<List<User>> groupList(@Path("id") int groupId, @Query("sort") String sort);

For more information see documentation https://square.github.io/retrofit/

R Plotting confidence bands with ggplot

require(ggplot2)
require(nlme)

set.seed(101)
mp <-data.frame(year=1990:2010)
N <- nrow(mp)

mp <- within(mp,
         {
             wav <- rnorm(N)*cos(2*pi*year)+rnorm(N)*sin(2*pi*year)+5
             wow <- rnorm(N)*wav+rnorm(N)*wav^3
         })

m01 <- gls(wow~poly(wav,3), data=mp, correlation = corARMA(p=1))

Get fitted values (the same as m01$fitted)

fit <- predict(m01)

Normally we could use something like predict(...,se.fit=TRUE) to get the confidence intervals on the prediction, but gls doesn't provide this capability. We use a recipe similar to the one shown at http://glmm.wikidot.com/faq :

V <- vcov(m01)
X <- model.matrix(~poly(wav,3),data=mp)
se.fit <- sqrt(diag(X %*% V %*% t(X)))

Put together a "prediction frame":

predframe <- with(mp,data.frame(year,wav,
                                wow=fit,lwr=fit-1.96*se.fit,upr=fit+1.96*se.fit))

Now plot with geom_ribbon

(p1 <- ggplot(mp, aes(year, wow))+
    geom_point()+
    geom_line(data=predframe)+
    geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))

year vs wow

It's easier to see that we got the right answer if we plot against wav rather than year:

(p2 <- ggplot(mp, aes(wav, wow))+
    geom_point()+
    geom_line(data=predframe)+
    geom_ribbon(data=predframe,aes(ymin=lwr,ymax=upr),alpha=0.3))

wav vs wow

It would be nice to do the predictions with more resolution, but it's a little tricky to do this with the results of poly() fits -- see ?makepredictcall.

How can I iterate over an enum?

In Bjarne Stroustrup's C++ programming language book, you can read that he's proposing to overload the operator++ for your specific enum. enum are user-defined types and overloading operator exists in the language for these specific situations.

You'll be able to code the following:

#include <iostream>
enum class Colors{red, green, blue};
Colors& operator++(Colors &c, int)
{
     switch(c)
     {
           case Colors::red:
               return c=Colors::green;
           case Colors::green:
               return c=Colors::blue;
           case Colors::blue:
               return c=Colors::red; // managing overflow
           default:
               throw std::exception(); // or do anything else to manage the error...
     }
}

int main()
{
    Colors c = Colors::red;
    // casting in int just for convenience of output. 
    std::cout << (int)c++ << std::endl;
    std::cout << (int)c++ << std::endl;
    std::cout << (int)c++ << std::endl;
    std::cout << (int)c++ << std::endl;
    std::cout << (int)c++ << std::endl;
    return 0;
}

test code: http://cpp.sh/357gb

Mind that I'm using enum class. Code works fine with enum also. But I prefer enum class since they are strong typed and can prevent us to make mistake at compile time.

How to split data into training/testing sets using sample function

Beware of sample for splitting if you look for reproducible results. If your data changes even slightly, the split will vary even if you use set.seed. For example, imagine the sorted list of IDs in you data is all the numbers between 1 and 10. If you just dropped one observation, say 4, sampling by location would yield a different results because now 5 to 10 all moved places.

An alternative method is to use a hash function to map IDs into some pseudo random numbers and then sample on the mod of these numbers. This sample is more stable because assignment is now determined by the hash of each observation, and not by its relative position.

For example:

require(openssl)  # for md5
require(data.table)  # for the demo data

set.seed(1)  # this won't help `sample`

population <- as.character(1e5:(1e6-1))  # some made up ID names

N <- 1e4  # sample size

sample1 <- data.table(id = sort(sample(population, N)))  # randomly sample N ids
sample2 <- sample1[-sample(N, 1)]  # randomly drop one observation from sample1

# samples are all but identical
sample1
sample2
nrow(merge(sample1, sample2))

[1] 9999

# row splitting yields very different test sets, even though we've set the seed
test <- sample(N-1, N/2, replace = F)

test1 <- sample1[test, .(id)]
test2 <- sample2[test, .(id)]
nrow(test1)

[1] 5000

nrow(merge(test1, test2))

[1] 2653

# to fix that, we can use some hash function to sample on the last digit

md5_bit_mod <- function(x, m = 2L) {
  # Inputs: 
  #  x: a character vector of ids
  #  m: the modulo divisor (modify for split proportions other than 50:50)
  # Output: remainders from dividing the first digit of the md5 hash of x by m
  as.integer(as.hexmode(substr(openssl::md5(x), 1, 1)) %% m)
}

# hash splitting preserves the similarity, because the assignment of test/train 
# is determined by the hash of each obs., and not by its relative location in the data
# which may change 
test1a <- sample1[md5_bit_mod(id) == 0L, .(id)]
test2a <- sample2[md5_bit_mod(id) == 0L, .(id)]
nrow(merge(test1a, test2a))

[1] 5057

nrow(test1a)

[1] 5057

sample size is not exactly 5000 because assignment is probabilistic, but it shouldn't be a problem in large samples thanks to the law of large numbers.

See also: http://blog.richardweiss.org/2016/12/25/hash-splits.html and https://crypto.stackexchange.com/questions/20742/statistical-properties-of-hash-functions-when-calculating-modulo

How to get JavaScript caller function line number? How to get JavaScript caller source URL?

This is how I have done it, I have tested it in both Firefox and Chrome. This makes it possible to check the filename and line number of the place where the function is called from.

logFileAndLineNumber(new Error());

function logFileAndLineNumber(newErr)
{
   if(navigator.userAgent.indexOf("Firefox") != -1)
   {
      var originPath = newErr.stack.split('\n')[0].split("/");
      var fileNameAndLineNumber = originPath[originPath.length - 1].split(">")[0];
      console.log(fileNameAndLineNumber);
   }else if(navigator.userAgent.indexOf("Chrome") != -1)
   {
      var originFile = newErr.stack.split('\n')[1].split('/');
      var fileName = originFile[originFile.length - 1].split(':')[0];
      var lineNumber = originFile[originFile.length - 1].split(':')[1];
      console.log(fileName+" line "+lineNumber);
    }
}

Angular + Material - How to refresh a data source (mat-table)

I did some more research and found this place to give me what I needed - feels clean and relates to update data when refreshed from server: https://blog.angular-university.io/angular-material-data-table/

Most credits to the page above. Below is a sample of how a mat-selector can be used to update a mat-table bound to a datasource on change of selection. I am using Angular 7. Sorry for being extensive, trying to be complete but concise - I have ripped out as many non-needed parts as possible. With this hoping to help someone else getting forward faster!

organization.model.ts:

export class Organization {
    id: number;
    name: String;
}

organization.service.ts:

import { Observable, empty } from 'rxjs';
import { of } from 'rxjs';

import { Organization } from './organization.model';

export class OrganizationService {
  getConstantOrganizations(filter: String): Observable<Organization[]> {
    if (filter === "All") {
      let Organizations: Organization[] = [
        { id: 1234, name: 'Some data' }
      ];
      return of(Organizations);
     } else {
       let Organizations: Organization[] = [
         { id: 5678, name: 'Some other data' }
       ];
     return of(Organizations);
  }

  // ...just a sample, other filterings would go here - and of course data instead fetched from server.
}

organizationdatasource.model.ts:

import { CollectionViewer, DataSource } from '@angular/cdk/collections';
import { Observable, BehaviorSubject, of } from 'rxjs';
import { catchError, finalize } from "rxjs/operators";

import { OrganizationService } from './organization.service';
import { Organization } from './organization.model';

export class OrganizationDataSource extends DataSource<Organization> {
  private organizationsSubject = new BehaviorSubject<Organization[]>([]);

  private loadingSubject = new BehaviorSubject<boolean>(false);

  public loading$ = this.loadingSubject.asObservable();

  constructor(private organizationService: OrganizationService, ) {
    super();
  }

  loadOrganizations(filter: String) {
    this.loadingSubject.next(true);

    return this.organizationService.getOrganizations(filter).pipe(
      catchError(() => of([])),
      finalize(() => this.loadingSubject.next(false))
    ).subscribe(organization => this.organizationsSubject.next(organization));
  }

  connect(collectionViewer: CollectionViewer): Observable<Organization[]> {
    return this.organizationsSubject.asObservable();
  }

  disconnect(collectionViewer: CollectionViewer): void {
    this.organizationsSubject.complete();
    this.loadingSubject.complete();
  }
}

organizations.component.html:

<div class="spinner-container" *ngIf="organizationDataSource.loading$ | async">
    <mat-spinner></mat-spinner>
</div>

<div>
  <form [formGroup]="formGroup">
    <mat-form-field fxAuto>
      <div fxLayout="row">
        <mat-select formControlName="organizationSelectionControl" (selectionChange)="updateOrganizationSelection()">
          <mat-option *ngFor="let organizationSelectionAlternative of organizationSelectionAlternatives"
            [value]="organizationSelectionAlternative">
            {{organizationSelectionAlternative.name}}
          </mat-option>
        </mat-select>
      </div>
    </mat-form-field>
  </form>
</div>

<mat-table fxLayout="column" [dataSource]="organizationDataSource">
  <ng-container matColumnDef="name">
    <mat-header-cell *matHeaderCellDef>Name</mat-header-cell>
    <mat-cell *matCellDef="let organization">{{organization.name}}</mat-cell>
  </ng-container>

  <ng-container matColumnDef="number">
    <mat-header-cell *matHeaderCellDef>Number</mat-header-cell>
    <mat-cell *matCellDef="let organization">{{organization.number}}</mat-cell>
  </ng-container>

  <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>
  <mat-row *matRowDef="let row; columns: displayedColumns"></mat-row>
</mat-table>

organizations.component.scss:

.spinner-container {
    height: 360px;
    width: 390px;
    position: fixed;
}

organization.component.ts:

import { Component, OnInit } from '@angular/core';
import { FormGroup, FormBuilder } from '@angular/forms';
import { Observable } from 'rxjs';

import { OrganizationService } from './organization.service';
import { Organization } from './organization.model';
import { OrganizationDataSource } from './organizationdatasource.model';

@Component({
  selector: 'organizations',
  templateUrl: './organizations.component.html',
  styleUrls: ['./organizations.component.scss']
})
export class OrganizationsComponent implements OnInit {
  public displayedColumns: string[];
  public organizationDataSource: OrganizationDataSource;
  public formGroup: FormGroup;

  public organizationSelectionAlternatives = [{
    id: 1,
    name: 'All'
  }, {
    id: 2,
    name: 'With organization update requests'
  }, {
    id: 3,
    name: 'With contact update requests'
  }, {
    id: 4,
    name: 'With order requests'
  }]

  constructor(
    private formBuilder: FormBuilder,
    private organizationService: OrganizationService) { }

  ngOnInit() {
    this.formGroup = this.formBuilder.group({
      'organizationSelectionControl': []
    })

    const toSelect = this.organizationSelectionAlternatives.find(c => c.id == 1);
    this.formGroup.get('organizationSelectionControl').setValue(toSelect);

    this.organizationDataSource = new OrganizationDataSource(this.organizationService);
    this.displayedColumns = ['name', 'number' ];
    this.updateOrganizationSelection();
  }

  updateOrganizationSelection() {
    this.organizationDataSource.loadOrganizations(this.formGroup.get('organizationSelectionControl').value.name);
  }
}

Should I return EXIT_SUCCESS or 0 from main()?

It does not matter. Both are the same.

C++ Standard Quotes:

If the value of status is zero or EXIT_SUCCESS, an implementation-defined form of the status successful termination is returned.

How to load external webpage in WebView

Add WebView Client

mWebView.setWebViewClient(new WebViewClient());

Merging multiple PDFs using iTextSharp in c#.net

Using iTextSharp.dll

protected void Page_Load(object sender, EventArgs e)
{
    String[] files = @"C:\ENROLLDOCS\A1.pdf,C:\ENROLLDOCS\A2.pdf".Split(',');
    MergeFiles(@"C:\ENROLLDOCS\New1.pdf", files);
}
public void MergeFiles(string destinationFile, string[] sourceFiles)
{
    if (System.IO.File.Exists(destinationFile))
        System.IO.File.Delete(destinationFile);

    string[] sSrcFile;
    sSrcFile = new string[2];

    string[] arr = new string[2];
    for (int i = 0; i <= sourceFiles.Length - 1; i++)
    {
        if (sourceFiles[i] != null)
        {
            if (sourceFiles[i].Trim() != "")
                arr[i] = sourceFiles[i].ToString();
        }
    }

    if (arr != null)
    {
        sSrcFile = new string[2];

        for (int ic = 0; ic <= arr.Length - 1; ic++)
        {
            sSrcFile[ic] = arr[ic].ToString();
        }
    }
    try
    {
        int f = 0;

        PdfReader reader = new PdfReader(sSrcFile[f]);
        int n = reader.NumberOfPages;
        Response.Write("There are " + n + " pages in the original file.");
        Document document = new Document(PageSize.A4);

        PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(destinationFile, FileMode.Create));

        document.Open();
        PdfContentByte cb = writer.DirectContent;
        PdfImportedPage page;

        int rotation;
        while (f < sSrcFile.Length)
        {
            int i = 0;
            while (i < n)
            {
                i++;

                document.SetPageSize(PageSize.A4);
                document.NewPage();
                page = writer.GetImportedPage(reader, i);

                rotation = reader.GetPageRotation(i);
                if (rotation == 90 || rotation == 270)
                {
                    cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height);
                }
                else
                {
                    cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
                }
                Response.Write("\n Processed page " + i);
            }

            f++;
            if (f < sSrcFile.Length)
            {
                reader = new PdfReader(sSrcFile[f]);
                n = reader.NumberOfPages;
                Response.Write("There are " + n + " pages in the original file.");
            }
        }
        Response.Write("Success");
        document.Close();
    }
    catch (Exception e)
    {
        Response.Write(e.Message);
    }


}

Writing an Excel file in EPPlus

It's best if you worked with DataSets and/or DataTables. Once you have that, ideally straight from your stored procedure with proper column names for headers, you can use the following method:

ws.Cells.LoadFromDataTable(<DATATABLE HERE>, true, OfficeOpenXml.Table.TableStyles.Light8);

.. which will produce a beautiful excelsheet with a nice table!

Now to serve your file, assuming you have an ExcelPackage object as in your code above called pck..

Response.Clear();

Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("Content-Disposition", "attachment;filename=" + sFilename);

Response.BinaryWrite(pck.GetAsByteArray());
Response.End();

Get the size of a 2D array

In Java, 2D arrays are really arrays of arrays with possibly different lengths (there are no guarantees that in 2D arrays that the 2nd dimension arrays all be the same length)

You can get the length of any 2nd dimension array as z[n].length where 0 <= n < z.length.

If you're treating your 2D array as a matrix, you can simply get z.length and z[0].length, but note that you might be making an assumption that for each array in the 2nd dimension that the length is the same (for some programs this might be a reasonable assumption).

Update R using RStudio

I found that for me the best permanent solution to stay up-to-date under Linux was to install the R-patched project. This will keep your R installation up-to-date, and you needn't even move your packages between installations (which is described in RyanStochastic's answer).

For openSUSE, see the instructions here.

How to use router.navigateByUrl and router.navigate in Angular

navigateByUrl

routerLink directive as used like this:

<a [routerLink]="/inbox/33/messages/44">Open Message 44</a>

is just a wrapper around imperative navigation using router and its navigateByUrl method:

router.navigateByUrl('/inbox/33/messages/44')

as can be seen from the sources:

export class RouterLink {
  ...

  @HostListener('click')
  onClick(): boolean {
    ...
    this.router.navigateByUrl(this.urlTree, extras);
    return true;
  }

So wherever you need to navigate a user to another route, just inject the router and use navigateByUrl method:

class MyComponent {
   constructor(router: Router) {
      this.router.navigateByUrl(...);
   }
}

navigate

There's another method on the router that you can use - navigate:

router.navigate(['/inbox/33/messages/44'])

difference between the two

Using router.navigateByUrl is similar to changing the location bar directly–we are providing the “whole” new URL. Whereas router.navigate creates a new URL by applying an array of passed-in commands, a patch, to the current URL.

To see the difference clearly, imagine that the current URL is '/inbox/11/messages/22(popup:compose)'.

With this URL, calling router.navigateByUrl('/inbox/33/messages/44') will result in '/inbox/33/messages/44'. But calling it with router.navigate(['/inbox/33/messages/44']) will result in '/inbox/33/messages/44(popup:compose)'.

Read more in the official docs.

How to set -source 1.7 in Android Studio and Gradle

Java 7 support was added at build tools 19. You can now use features like the diamond operator, multi-catch, try-with-resources, strings in switches, etc. Add the following to your build.gradle.

android {
    compileSdkVersion 19
    buildToolsVersion "19.0.0"

    defaultConfig {
        minSdkVersion 7
        targetSdkVersion 19
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_7
        targetCompatibility JavaVersion.VERSION_1_7
    }
}

Gradle 1.7+, Android gradle plugin 0.6.+ are required.

Note, that only try with resources require minSdkVersion 19. Other features works on previous platforms.

Link to android gradle plugin user guide

Link to see how source vs target are different

Upload DOC or PDF using PHP

You can use

$_FILES['filename']['error'];

If any type of error occurs then it returns 'error' else 1,2,3,4 or 1 if done

1 : if file size is over limit .... You can find other options by googling

How to post JSON to a server using C#?

I recently came up with a much simpler way to post a JSON, with the additional step of converting from a model in my app. Note that you have to make the model [JsonObject] for your controller to get the values and do the conversion.

Request:

 var model = new MyModel(); 

 using (var client = new HttpClient())
 {
     var uri = new Uri("XXXXXXXXX"); 
     var json = new JavaScriptSerializer().Serialize(model);
     var stringContent = new StringContent(json, Encoding.UTF8, "application/json");
     var response = await Client.PutAsync(uri,stringContent).Result;
     ...
     ...
  }

Model:

[JsonObject]
[Serializable]
public class MyModel
{
    public Decimal Value { get; set; }
    public string Project { get; set; }
    public string FilePath { get; set; }
    public string FileName { get; set; }
}

Server side:

[HttpPut]     
public async Task<HttpResponseMessage> PutApi([FromBody]MyModel model)
{
    ...
    ... 
}

Is it possible to create a temporary table in a View and drop it after select?

Try creating another SQL view instead of a temporary table and then referencing it in the main SQL view. In other words, a view within a view. You can then drop the first view once you are done creating the main view.

Example: Communication between Activity and Service using Messaging

Great tutorial, fantastic presentation. Neat, simple, short and very explanatory. Although, notification.setLatestEventInfo(this, getText(R.string.service_label), text, contentIntent); method is no more. As trante stated here, good approach would be:

private static final int NOTIFICATION_ID = 45349;

private void showNotification() {
    NotificationCompat.Builder builder =
            new NotificationCompat.Builder(this)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle("My Notification Title")
                    .setContentText("Something interesting happened");

    Intent targetIntent = new Intent(this, MainActivity.class);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, targetIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setContentIntent(contentIntent);
    _nManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    _nManager.notify(NOTIFICATION_ID, builder.build());
}

@Override
public void onDestroy() {
    super.onDestroy();
    if (_timer != null) {_timer.cancel();}
    _counter=0;
    _nManager.cancel(NOTIFICATION_ID); // Cancel the persistent notification.
    Log.i("PlaybackService", "Service Stopped.");
    _isRunning = false;
}

Checked myself, everything works like a charm (activity and service names may differ from original).

How to extract numbers from a string and get an array of ints?

Pattern p = Pattern.compile("-?\\d+");
Matcher m = p.matcher("There are more than -2 and less than 12 numbers here");
while (m.find()) {
  System.out.println(m.group());
}

... prints -2 and 12.


-? matches a leading negative sign -- optionally. \d matches a digit, and we need to write \ as \\ in a Java String though. So, \d+ matches 1 or more digits.

Reset git proxy to default configuration

git config --global --unset http.proxy

Clone contents of a GitHub repository (without the folder itself)

You can specify the destination directory as second parameter of the git clone command, so you can do:

git clone <remote> .

This will clone the repository directly in the current local directory.

Using subprocess to run Python script on Windows

Just found sys.executable - the full path to the current Python executable, which can be used to run the script (instead of relying on the shbang, which obviously doesn't work on Windows)

import sys
import subprocess

theproc = subprocess.Popen([sys.executable, "myscript.py"])
theproc.communicate()

How can I Insert data into SQL Server using VBNet

It means that the number of values specified in your VALUES clause on the INSERT statement is not equal to the total number of columns in the table. You must specify the columnname if you only try to insert on selected columns.

Another one, since you are using ADO.Net , always parameterized your query to avoid SQL Injection. What you are doing right now is you are defeating the use of sqlCommand.

ex

Dim query as String = String.Empty
query &= "INSERT INTO student (colName, colID, colPhone, "
query &= "                     colBranch, colCourse, coldblFee)  "
query &= "VALUES (@colName,@colID, @colPhone, @colBranch,@colCourse, @coldblFee)"

Using conn as New SqlConnection("connectionStringHere")
    Using comm As New SqlCommand()
        With comm
            .Connection = conn
            .CommandType = CommandType.Text
            .CommandText = query
            .Parameters.AddWithValue("@colName", strName)
            .Parameters.AddWithValue("@colID", strId)
            .Parameters.AddWithValue("@colPhone", strPhone)
            .Parameters.AddWithValue("@colBranch", strBranch)
            .Parameters.AddWithValue("@colCourse", strCourse)
            .Parameters.AddWithValue("@coldblFee", dblFee)
        End With
        Try
            conn.open()
            comm.ExecuteNonQuery()
        Catch(ex as SqlException)
            MessageBox.Show(ex.Message.ToString(), "Error Message")
        End Try
    End Using
End USing 

PS: Please change the column names specified in the query to the original column found in your table.

Which version of CodeIgniter am I currently using?

Yes, the constant CI_VERSION will give you the current CodeIgniter version number. It's defined in: /system/codeigniter/CodeIgniter.php As of CodeIgniter 2, it's defined in /system/core/CodeIgniter.php

For example,

echo CI_VERSION; // echoes something like 1.7.1

Changing PowerShell's default output encoding to UTF-8

Note: The following applies to Windows PowerShell.
See the next section for the cross-platform PowerShell Core (v6+) edition.

  • On PSv5.1 or higher, where > and >> are effectively aliases of Out-File, you can set the default encoding for > / >> / Out-File via the $PSDefaultParameterValues preference variable:

    • $PSDefaultParameterValues['Out-File:Encoding'] = 'utf8'
  • On PSv5.0 or below, you cannot change the encoding for > / >>, but, on PSv3 or higher, the above technique does work for explicit calls to Out-File.
    (The $PSDefaultParameterValues preference variable was introduced in PSv3.0).

  • On PSv3.0 or higher, if you want to set the default encoding for all cmdlets that support
    an -Encoding parameter
    (which in PSv5.1+ includes > and >>), use:

    • $PSDefaultParameterValues['*:Encoding'] = 'utf8'

If you place this command in your $PROFILE, cmdlets such as Out-File and Set-Content will use UTF-8 encoding by default, but note that this makes it a session-global setting that will affect all commands / scripts that do not explicitly specify an encoding via their -Encoding parameter.

Similarly, be sure to include such commands in your scripts or modules that you want to behave the same way, so that they indeed behave the same even when run by another user or a different machine; however, to avoid a session-global change, use the following form to create a local copy of $PSDefaultParameterValues:

  • $PSDefaultParameterValues = @{ '*:Encoding' = 'utf8' }

Caveat: PowerShell, as of v5.1, invariably creates UTF-8 files _with a (pseudo) BOM_, which is customary only in the Windows world - Unix-based utilities do not recognize this BOM (see bottom); see this post for workarounds that create BOM-less UTF-8 files.

For a summary of the wildly inconsistent default character encoding behavior across many of the Windows PowerShell standard cmdlets, see the bottom section.


The automatic $OutputEncoding variable is unrelated, and only applies to how PowerShell communicates with external programs (what encoding PowerShell uses when sending strings to them) - it has nothing to do with the encoding that the output redirection operators and PowerShell cmdlets use to save to files.


Optional reading: The cross-platform perspective: PowerShell Core:

PowerShell is now cross-platform, via its PowerShell Core edition, whose encoding - sensibly - defaults to BOM-less UTF-8, in line with Unix-like platforms.

  • This means that source-code files without a BOM are assumed to be UTF-8, and using > / Out-File / Set-Content defaults to BOM-less UTF-8; explicit use of the utf8 -Encoding argument too creates BOM-less UTF-8, but you can opt to create files with the pseudo-BOM with the utf8bom value.

  • If you create PowerShell scripts with an editor on a Unix-like platform and nowadays even on Windows with cross-platform editors such as Visual Studio Code and Sublime Text, the resulting *.ps1 file will typically not have a UTF-8 pseudo-BOM:

    • This works fine on PowerShell Core.
    • It may break on Windows PowerShell, if the file contains non-ASCII characters; if you do need to use non-ASCII characters in your scripts, save them as UTF-8 with BOM.
      Without the BOM, Windows PowerShell (mis)interprets your script as being encoded in the legacy "ANSI" codepage (determined by the system locale for pre-Unicode applications; e.g., Windows-1252 on US-English systems).
  • Conversely, files that do have the UTF-8 pseudo-BOM can be problematic on Unix-like platforms, as they cause Unix utilities such as cat, sed, and awk - and even some editors such as gedit - to pass the pseudo-BOM through, i.e., to treat it as data.

    • This may not always be a problem, but definitely can be, such as when you try to read a file into a string in bash with, say, text=$(cat file) or text=$(<file) - the resulting variable will contain the pseudo-BOM as the first 3 bytes.

Inconsistent default encoding behavior in Windows PowerShell:

Regrettably, the default character encoding used in Windows PowerShell is wildly inconsistent; the cross-platform PowerShell Core edition, as discussed in the previous section, has commendably put and end to this.

Note:

  • The following doesn't aspire to cover all standard cmdlets.

  • Googling cmdlet names to find their help topics now shows you the PowerShell Core version of the topics by default; use the version drop-down list above the list of topics on the left to switch to a Windows PowerShell version.

  • As of this writing, the documentation frequently incorrectly claims that ASCII is the default encoding in Windows PowerShell - see this GitHub docs issue.


Cmdlets that write:

Out-File and > / >> create "Unicode" - UTF-16LE - files by default - in which every ASCII-range character (too) is represented by 2 bytes - which notably differs from Set-Content / Add-Content (see next point); New-ModuleManifest and Export-CliXml also create UTF-16LE files.

Set-Content (and Add-Content if the file doesn't yet exist / is empty) uses ANSI encoding (the encoding specified by the active system locale's ANSI legacy code page, which PowerShell calls Default).

Export-Csv indeed creates ASCII files, as documented, but see the notes re -Append below.

Export-PSSession creates UTF-8 files with BOM by default.

New-Item -Type File -Value currently creates BOM-less(!) UTF-8.

The Send-MailMessage help topic also claims that ASCII encoding is the default - I have not personally verified that claim.

Start-Transcript invariably creates UTF-8 files with BOM, but see the notes re -Append below.

Re commands that append to an existing file:

>> / Out-File -Append make no attempt to match the encoding of a file's existing content. That is, they blindly apply their default encoding, unless instructed otherwise with -Encoding, which is not an option with >> (except indirectly in PSv5.1+, via $PSDefaultParameterValues, as shown above). In short: you must know the encoding of an existing file's content and append using that same encoding.

Add-Content is the laudable exception: in the absence of an explicit -Encoding argument, it detects the existing encoding and automatically applies it to the new content.Thanks, js2010. Note that in Windows PowerShell this means that it is ANSI encoding that is applied if the existing content has no BOM, whereas it is UTF-8 in PowerShell Core.

This inconsistency between Out-File -Append / >> and Add-Content, which also affects PowerShell Core, is discussed in this GitHub issue.

Export-Csv -Append partially matches the existing encoding: it blindly appends UTF-8 if the existing file's encoding is any of ASCII/UTF-8/ANSI, but correctly matches UTF-16LE and UTF-16BE.
To put it differently: in the absence of a BOM, Export-Csv -Append assumes UTF-8 is, whereas Add-Content assumes ANSI.

Start-Transcript -Append partially matches the existing encoding: It correctly matches encodings with BOM, but defaults to potentially lossy ASCII encoding in the absence of one.


Cmdlets that read (that is, the encoding used in the absence of a BOM):

Get-Content and Import-PowerShellDataFile default to ANSI (Default), which is consistent with Set-Content.
ANSI is also what the PowerShell engine itself defaults to when it reads source code from files.

By contrast, Import-Csv, Import-CliXml and Select-String assume UTF-8 in the absence of a BOM.

How to sort a Pandas DataFrame by index?

Dataframes have a sort_index method which returns a copy by default. Pass inplace=True to operate in place.

import pandas as pd
df = pd.DataFrame([1, 2, 3, 4, 5], index=[100, 29, 234, 1, 150], columns=['A'])
df.sort_index(inplace=True)
print(df.to_string())

Gives me:

     A
1    4
29   2
100  1
150  5
234  3

Node.js: what is ENOSPC error and how to solve?

On Ubuntu 18.04 , I tried a trick that I used to reactivate the file watching by ionic/node, and it works also here. This could be useful for those who don't have access to system conf files.

CHOKIDAR_USEPOLLING=1 npm start

How to validate domain name in PHP?

With this you will not only be checking if the domain has a valid format, but also if it is active / has an IP address assigned to it.

$domain = "stackoverflow.com";

if(filter_var(gethostbyname($domain), FILTER_VALIDATE_IP))
{
    return TRUE;
}

Note that this method requires the DNS entries to be active so if you require a domain string to be validated without being in the DNS use the regular expression method given by velcrow above.

Also this function is not intended to validate a URL string use FILTER_VALIDATE_URL for that. We do not use FILTER_VALIDATE_URL for a domain because a domain string is not a valid URL.

How can I show current location on a Google Map on Android Marshmallow?

Firstly make sure your API Key is valid and add this into your manifest <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

Here's my maps activity.. there might be some redundant information in it since it's from a larger project I created.

import android.content.Intent;
import android.content.IntentSender;
import android.location.Location;
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.api.GoogleApiClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.Marker;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends FragmentActivity implements
        GoogleApiClient.ConnectionCallbacks,
        GoogleApiClient.OnConnectionFailedListener,
        LocationListener {


    //These variable are initalized here as they need to be used in more than one methid
    private double currentLatitude; //lat of user
    private double currentLongitude; //long of user

    private double latitudeVillageApartmets= 53.385952001750184;
    private double longitudeVillageApartments= -6.599087119102478;


    public static final String TAG = MapsActivity.class.getSimpleName();

    private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST = 9000;

    private GoogleMap mMap; // Might be null if Google Play services APK is not available.

    private GoogleApiClient mGoogleApiClient;
    private LocationRequest mLocationRequest;

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

        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();

        // Create the LocationRequest object
        mLocationRequest = LocationRequest.create()
                .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                .setInterval(10 * 1000)        // 10 seconds, in milliseconds
                .setFastestInterval(1 * 1000); // 1 second, in milliseconds
 }
    /*These methods all have to do with the map and wht happens if the activity is paused etc*/
    //contains lat and lon of another marker
    private void setUpMap() {

            MarkerOptions marker = new MarkerOptions().position(new LatLng(latitudeVillageApartmets, longitudeVillageApartments)).title("1"); //create marker
            mMap.addMarker(marker); // adding marker
    }

    //contains your lat and lon
    private void handleNewLocation(Location location) {
        Log.d(TAG, location.toString());

        currentLatitude = location.getLatitude();
        currentLongitude = location.getLongitude();

        LatLng latLng = new LatLng(currentLatitude, currentLongitude);

        MarkerOptions options = new MarkerOptions()
                .position(latLng)
                .title("You are here");
        mMap.addMarker(options);
        mMap.moveCamera(CameraUpdateFactory.newLatLngZoom((latLng), 11.0F));
    }

    @Override
    protected void onResume() {
        super.onResume();
        setUpMapIfNeeded();
        mGoogleApiClient.connect();
    }

    @Override
    protected void onPause() {
        super.onPause();

        if (mGoogleApiClient.isConnected()) {
            LocationServices.FusedLocationApi.removeLocationUpdates(mGoogleApiClient, this);
            mGoogleApiClient.disconnect();
        }
    }

    private void setUpMapIfNeeded() {
        // Do a null check to confirm that we have not already instantiated the map.
        if (mMap == null) {
            // Try to obtain the map from the SupportMapFragment.
            mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                    .getMap();
            // Check if we were successful in obtaining the map.
            if (mMap != null) {
                setUpMap();
            }

        }
    }

    @Override
    public void onConnected(Bundle bundle) {
        Location location = LocationServices.FusedLocationApi.getLastLocation(mGoogleApiClient);
        if (location == null) {
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
        }
        else {
            handleNewLocation(location);
        }
    }

    @Override
    public void onConnectionSuspended(int i) {
    }

    @Override
    public void onConnectionFailed(ConnectionResult connectionResult) {
        if (connectionResult.hasResolution()) {
            try {
                // Start an Activity that tries to resolve the error
                connectionResult.startResolutionForResult(this, CONNECTION_FAILURE_RESOLUTION_REQUEST);
                /*
                 * Thrown if Google Play services canceled the original
                 * PendingIntent
                 */
            } catch (IntentSender.SendIntentException e) {
                // Log the error
                e.printStackTrace();
            }
        } else {
            /*
             * If no resolution is available, display a dialog to the
             * user with the error.
             */
            Log.i(TAG, "Location services connection failed with code " + connectionResult.getErrorCode());
        }
    }

    @Override
    public void onLocationChanged(Location location) {
        handleNewLocation(location);
    }

}

There's a lot of methods here that are hard to understand but basically all update the map when it's paused etc. There are also connection timeouts etc. Sorry for just posting this, I tried to fix your code but I couldn't figure out what was wrong.

C# DateTime to "YYYYMMDDHHMMSS" format

Get the date as a DateTime object instead of a String. Then you can format it as you want.

  • MM/dd/yyyy 08/22/2006
  • dddd, dd MMMM yyyy Tuesday, 22 August 2006
  • dddd, dd MMMM yyyy HH:mm Tuesday, 22 August 2006 06:30
  • dddd, dd MMMM yyyy hh:mm tt Tuesday, 22 August 2006 06:30 AM
  • dddd, dd MMMM yyyy H:mm Tuesday, 22 August 2006 6:30
  • dddd, dd MMMM yyyy h:mm tt Tuesday, 22 August 2006 6:30 AM
  • dddd, dd MMMM yyyy HH:mm:ss Tuesday, 22 August 2006 06:30:07
  • MM/dd/yyyy HH:mm 08/22/2006 06:30
  • MM/dd/yyyy hh:mm tt 08/22/2006 06:30 AM
  • MM/dd/yyyy H:mm 08/22/2006 6:30
  • MM/dd/yyyy h:mm tt 08/22/2006 6:30 AM
  • MM/dd/yyyy HH:mm:ss 08/22/2006 06:30:07

Click here for more patterns

How do I fix a merge conflict due to removal of a file in a branch?

If you are using Git Gui on windows,

  1. Abort the merge
  2. Make sure you are on your target branch
  3. Delete the conflicting file from explorer
  4. Rescan for changes in Git Gui (F5)
  5. Notice that conflicting file is deleted
  6. Select Stage Changed Files To Commit (Ctrl-I) from Commit menu
  7. Enter a commit comment like "deleted conflicting file"
  8. Commit (ctrl-enter)
  9. Now if you restart the merge it will (hopefully) work.

Multiple Java versions running concurrently under Windows

We can install multiple versions of Java Development kits on the same machine using SDKMan.

Some points about SDKMan are as following:

  1. SDKMan is free to use and it is developed by the open source community.
  2. SDKMan is written in bash and it only requires curl and zip/unzip programs to be present on your system.
  3. SDKMan can install around 29 Software Development Kits for the JVM such as Java, Groovy, Scala, Kotlin and Ceylon. Ant, Gradle, Grails, Maven, SBT, Spark, Spring Boot, Vert.x.
  4. We do not need to worry about setting the _HOME and PATH environment variables because SDKMan handles it automatically.

SDKMan can run on any UNIX based platforms such as Mac OSX, Linux, Cygwin, Solaris and FreeBSD and we can install it using following commands:

$ curl -s "https://get.sdkman.io" | bash  
$ source "$HOME/.sdkman/bin/sdkman-init.sh" 

Because SDKMan is written in bash and only requires curl and zip/unzip to be present on your system. You can install SDKMan on windows as well either by first installing Cygwin or Git Bash for Windows environment and then running above commands.

Command sdk list java will give us a list of java versions which we can install using SDKMan.

Installing Java 8

$ sdk install java 8.0.201-oracle

Installing Java 9

$ sdk install java 9.0.4-open 

Installing Java 11

$ sdk install java 11.0.2-open

Uninstalling a Java version

In case you want to uninstall any JDK version e.g., 11.0.2-open you can do that as follows:

$ sdk uninstall java 11.0.2-open

Switching current Java version

If you want to activate one version of JDK for all terminals and applications, you can use the command

sdk default java <your-java_version>

Above commands will also update the PATH and JAVA_HOME variables automatically. You can read more on my article How to Install Multiple Versions of Java on the Same Machine.

How to add hamburger menu in bootstrap

CSS only (no icon sets) Codepen

_x000D_
_x000D_
.nav-link #navBars {_x000D_
margin-top: -3px;_x000D_
padding: 8px 15px 3px;_x000D_
border: 1px solid rgba(0,0,0,.125);_x000D_
border-radius: .25rem;_x000D_
}_x000D_
_x000D_
.nav-link #navBars input {_x000D_
display: none;_x000D_
}_x000D_
_x000D_
.nav-link #navBars span {_x000D_
position: relative;_x000D_
z-index: 1;_x000D_
display: block;_x000D_
margin-bottom: 6px;_x000D_
width: 24px;_x000D_
height: 2px;_x000D_
background-color: rgba(125, 125, 126, 1);_x000D_
border-radius: .25rem;_x000D_
}
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<nav class="navbar navbar-expand-lg navbar-light bg-light">_x000D_
   <!-- <a class="navbar-brand" href="#">_x000D_
      <img src="https://getbootstrap.com/docs/4.0/assets/brand/bootstrap-solid.svg" width="30" height="30" class="d-inline-block align-top" alt="">_x000D_
      Bootstrap_x000D_
      </a> -->_x000D_
   <!-- https://stackoverflow.com/questions/26317679 -->_x000D_
   <a class="nav-link" href="#">_x000D_
      <div id="navBars">_x000D_
         <input type="checkbox" /><span></span>_x000D_
         <span></span>_x000D_
         <span></span>_x000D_
      </div>_x000D_
   </a>_x000D_
   <!-- /26317679 -->_x000D_
   <div class="collapse navbar-collapse" id="navbarNav">_x000D_
      <ul class="navbar-nav">_x000D_
         <li class="nav-item active"><a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a></li>_x000D_
         <li class="nav-item"><a class="nav-link" href="#">Features</a></li>_x000D_
         <li class="nav-item"><a class="nav-link" href="#">Pricing</a></li>_x000D_
         <li class="nav-item"><a class="nav-link disabled" href="#">Disabled</a></li>_x000D_
      </ul>_x000D_
   </div>_x000D_
</nav>
_x000D_
_x000D_
_x000D_

postgresql port confusion 5433 or 5432?

I ran into this problem as well, it ended up that I had two postgres servers running at the same time. I uninstalled one of them and changed the port back to 5432 and works fine now.

How do I open workbook programmatically as read-only?

Check out the language reference:

http://msdn.microsoft.com/en-us/library/aa195811(office.11).aspx

expression.Open(FileName, UpdateLinks, ReadOnly, Format, Password, WriteResPassword, IgnoreReadOnlyRecommended, Origin, Delimiter, Editable, Notify, Converter, AddToMru, Local, CorruptLoad)

How can I trigger the click event of another element in ng-click using angularjs?

I just came across this problem and have written a solution for those of you who are using Angular. You can write a custom directive composed of a container, a button, and an input element with type file. With CSS you then place the input over the custom button but with opacity 0. You set the containers height and width to exactly the offset width and height of the button and the input's height and width to 100% of the container.

the directive

angular.module('myCoolApp')
  .directive('fileButton', function () {
    return {
      templateUrl: 'components/directives/fileButton/fileButton.html',
      restrict: 'E',
      link: function (scope, element, attributes) {

        var container = angular.element('.file-upload-container');
        var button = angular.element('.file-upload-button');

        container.css({
            position: 'relative',
            overflow: 'hidden',
            width: button.offsetWidth,
            height: button.offsetHeight
        })

      }

    };
  });

a jade template if you are using jade

div(class="file-upload-container") 
    button(class="file-upload-button") +
    input#file-upload(class="file-upload-input", type='file', onchange="doSomethingWhenFileIsSelected()")  

the same template in html if you are using html

<div class="file-upload-container">
   <button class="file-upload-button"></button>
   <input class="file-upload-input" id="file-upload" type="file" onchange="doSomethingWhenFileIsSelected()" /> 
</div>

the css

.file-upload-button {
    margin-top: 40px;
    padding: 30px;
    border: 1px solid black;
    height: 100px;
    width: 100px;
    background: transparent;
    font-size: 66px;
    padding-top: 0px;
    border-radius: 5px;
    border: 2px solid rgb(255, 228, 0); 
    color: rgb(255, 228, 0);
}
.file-upload-input {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 2;
    width: 100%;
    height: 100%;
    opacity: 0;
    cursor: pointer;
}

How to set selected value from Combobox?

To set value in the ComboBox

cmbEmployeeStatus.Text="Something";

How can I make SMTP authenticated in C#

Set the Credentials property before sending the message.

Downloading Java JDK on Linux via wget is shown license page instead

Here's how to get the command yourself. This works for any version:

  1. Access packages page here: https://www.oracle.com/java/technologies/javase-jdk11-downloads.html
  2. Click the download link for your desired package
  3. Check the box indicating that you have "reviewed and accept..."
  4. Right-click & Copy the link address from the button
  5. Paste into a text editor and then copy everything AFTER 'nexturl=', beginning with 'https://'
  6. Update the download URL in this command and you should be good to go:

    wget --no-check-certificate -c --header "Cookie: oraclelicense=accept-securebackup-cookie" https://download.oracle.com/otn/java/jdk/11.0.6+8/90eb79fb590d45c8971362673c5ab495/jdk-11.0.6_linux-x64_bin.tar.gz

To further explain the wget, the --no-check-certificate should be clear enough, but the header content (for any call) is discoverable by using the Developer Tools Network Tab in your browser. The developer tools are powerful and are well worth the time to learn. Enjoy.

Retrieving data from a POST method in ASP.NET

You need to examine (put a breakpoint on / Quick Watch) the Request object in the Page_Load method of your Test.aspx.cs file.

C# Dictionary get item by index

Your key is a string and your value is an int. Your code won't work because it cannot look up the random int you pass. Also, please provide full code

How to override !important?

This can help too

td[style] {height: 50px !important;}

This will override any inline style

Disable HTTP OPTIONS, TRACE, HEAD, COPY and UNLOCK methods in IIS

This worked for me but only after forcing the specific verbs to be handled by the default handler.

<system.web>
...
  <httpHandlers>
  ... 
    <add path="*" verb="OPTIONS" type="System.Web.DefaultHttpHandler" validate="true"/>
    <add path="*" verb="TRACE" type="System.Web.DefaultHttpHandler" validate="true"/>
    <add path="*" verb="HEAD" type="System.Web.DefaultHttpHandler" validate="true"/>

You still use the same configuration as you have above, but also force the verbs to be handled with the default handler and validated. Source: http://forums.asp.net/t/1311323.aspx

An easy way to test is just to deny GET and see if your site loads.

Int to Char in C#

int i = 65;
char c = Convert.ToChar(i);

Remove characters from NSString?

You could use:

NSString *stringWithoutSpaces = [myString 
   stringByReplacingOccurrencesOfString:@" " withString:@""];

Get cookie by name

I wrote something that might be easy to use, If anyone has some things to add, feel free to do so.

function getcookie(name = '') {
    let cookies = document.cookie;
    let cookiestore = {};
    
    cookies = cookies.split(";");
    
    if (cookies[0] == "" && cookies[0][0] == undefined) {
        return undefined;
    }
    
    cookies.forEach(function(cookie) {
        cookie = cookie.split(/=(.+)/);
        if (cookie[0].substr(0, 1) == ' ') {
            cookie[0] = cookie[0].substr(1);
        }
        cookiestore[cookie[0]] = cookie[1];
    });
    
    return (name !== '' ? cookiestore[name] : cookiestore);
}

Usage

getcookie() - returns an object with all cookies on the web page.

getcookie('myCookie') - returns the value of the cookie myCookie from the cookie object, otherwise returns undefined if the cookie is empty or not set.


Example

// Have some cookies :-)
document.cookie = "myCookies=delicious";
document.cookie = "myComputer=good";
document.cookie = "myBrowser=RAM hungry";

// Read them
console.log( "My cookies are " + getcookie('myCookie') );
// Outputs: My cookies are delicious

console.log( "My computer is " + getcookie('myComputer') );
// Outputs: My computer is good

console.log( "My browser is " + getcookie('myBrowser') );
// Outputs: My browser is RAM hungry

console.log( getcookie() );
// Outputs: {myCookie: "delicious", myComputer: "good", myBrowser: "RAM hungry"}

// (does cookie exist?)
if (getcookie('hidden_cookie')) {
    console.log('Hidden cookie was found!');
} else {
    console.log('Still no cookie :-(');
}

// (do any cookies exist?)
if (getcookie()) {
    console.log("You've got cookies to eat!");
} else {
    console.log('No cookies for today :-(');
}

Insert, on duplicate update in PostgreSQL?

I have the same issue for managing account settings as name value pairs. The design criteria is that different clients could have different settings sets.

My solution, similar to JWP is to bulk erase and replace, generating the merge record within your application.

This is pretty bulletproof, platform independent and since there are never more than about 20 settings per client, this is only 3 fairly low load db calls - probably the fastest method.

The alternative of updating individual rows - checking for exceptions then inserting - or some combination of is hideous code, slow and often breaks because (as mentioned above) non standard SQL exception handling changing from db to db - or even release to release.

 #This is pseudo-code - within the application:
 BEGIN TRANSACTION - get transaction lock
 SELECT all current name value pairs where id = $id into a hash record
 create a merge record from the current and update record
  (set intersection where shared keys in new win, and empty values in new are deleted).
 DELETE all name value pairs where id = $id
 COPY/INSERT merged records 
 END TRANSACTION

Switch php versions on commandline ubuntu 16.04

From PHP 5.6 => PHP 7.1

$ sudo a2dismod php5.6
$ sudo a2enmod php7.1

for old linux versions

 $ sudo service apache2 restart

for more recent version

$ systemctl restart apache2

webpack command not working

npm i webpack -g

installs webpack globally on your system, that makes it available in terminal window.

Adding attributes to an XML node

If you serialize the object that you have, you can do something like this by using "System.Xml.Serialization.XmlAttributeAttribute" on every property that you want to be specified as an attribute in your model, which in my opinion is a lot easier:

[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
public class UserNode
{
    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string userName { get; set; }

    [System.Xml.Serialization.XmlAttributeAttribute()]
    public string passWord { get; set; }

    public int Age { get; set; }
    public string Name { get; set; }         
 }

 public class LoginNode 
 {
    public UserNode id { get; set; }
 }

Then you just serialize to XML an instance of LoginNode called "Login", and that's it!

Here you have a few examples to serialize and object to XML, but I would suggest to create an extension method in order to be reusable for other objects.

Aligning rotated xticklabels with their respective xticks

You can set the horizontal alignment of ticklabels, see the example below. If you imagine a rectangular box around the rotated label, which side of the rectangle do you want to be aligned with the tickpoint?

Given your description, you want: ha='right'

n=5

x = np.arange(n)
y = np.sin(np.linspace(-3,3,n))
xlabels = ['Ticklabel %i' % i for i in range(n)]

fig, axs = plt.subplots(1,3, figsize=(12,3))

ha = ['right', 'center', 'left']

for n, ax in enumerate(axs):
    ax.plot(x,y, 'o-')
    ax.set_title(ha[n])
    ax.set_xticks(x)
    ax.set_xticklabels(xlabels, rotation=40, ha=ha[n])

enter image description here

Invoking a PHP script from a MySQL trigger

If you have transaction logs in you MySQL, you can create a trigger for purpose of a log instance creation. A cronjob could monitor this log and based on events created by your trigger it could invoke a php script. That is if you absolutely have no control over you insertion.

How to extract a string using JavaScript Regex?

Your regular expression most likely wants to be

/\nSUMMARY:(.*)$/g

A helpful little trick I like to use is to default assign on match with an array.

var arr = iCalContent.match(/\nSUMMARY:(.*)$/g) || [""]; //could also use null for empty value
return arr[0];

This way you don't get annoying type errors when you go to use arr

How to type in textbox using Selenium WebDriver (Selenium 2) with Java?

You can use JavaScript as well, in case the textfield is dithered.

WebDriver driver=new FirefoxDriver();
driver.get("http://localhost/login.do");
driver.manage().window().maximize();
RemoteWebDriver r=(RemoteWebDriver) driver;
String s1="document.getElementById('username').value='admin'";
r.executeScript(s1);

how do you increase the height of an html textbox

If you want multiple lines consider this:

<textarea rows="2"></textarea>

Specify rows as needed.

pip install from git repo branch

Just to add an extra, if you want to install it in your pip file it can be added like this:

-e git+https://github.com/tangentlabs/django-oscar-paypal.git@issue/34/oscar-0.6#egg=django-oscar-paypal

It will be saved as an egg though.

Display all items in array using jquery

here is solution, i create a text field to dynamic add new items in array my html code is

_x000D_
_x000D_
 <input type="text" id="name">_x000D_
  <input type="button" id="btn" value="Button">_x000D_
  <div id="names">_x000D_
  </div>
_x000D_
_x000D_
_x000D_

now type any thing in text field and click on button this will add item onto array and call function dispaly_arry

_x000D_
_x000D_
$(document).ready(function()_x000D_
{  _x000D_
 function display_array()_x000D_
 {_x000D_
  $("#names").text('');_x000D_
  $.each(names,function(index,value)_x000D_
  {_x000D_
    $('#names').append(value + '<br/>');_x000D_
  });_x000D_
 }_x000D_
 _x000D_
 var names = ['Alex','Billi','Dale'];_x000D_
 display_array();_x000D_
 $('#btn').click(function()_x000D_
 {_x000D_
  var name = $('#name').val();_x000D_
  names.push(name);// appending value to arry _x000D_
  display_array();_x000D_
  _x000D_
 });_x000D_
 _x000D_
});_x000D_
 
_x000D_
_x000D_
_x000D_

showing array elements into div , you can use span but for this solution use same id .!

Create, read, and erase cookies with jQuery

As I know, there is no direct support, but you can use plain-ol' javascript for that:

// Cookies
function createCookie(name, value, days) {
    if (days) {
        var date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        var expires = "; expires=" + date.toGMTString();
    }
    else var expires = "";               

    document.cookie = name + "=" + value + expires + "; path=/";
}

function readCookie(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
    }
    return null;
}

function eraseCookie(name) {
    createCookie(name, "", -1);
}

Force download a pdf link using javascript/ajax/jquery

Using Javascript you can download like this in a simple method

var oReq = new XMLHttpRequest();
// The Endpoint of your server 
var URLToPDF = "https://mozilla.github.io/pdf.js/web/compressed.tracemonkey-pldi-09.pdf";
// Configure XMLHttpRequest
oReq.open("GET", URLToPDF, true);

// Important to use the blob response type
oReq.responseType = "blob";

// When the file request finishes
// Is up to you, the configuration for error events etc.
oReq.onload = function() {
// Once the file is downloaded, open a new window with the PDF
// Remember to allow the POP-UPS in your browser
var file = new Blob([oReq.response], { 
    type: 'application/pdf' 
});

// Generate file download directly in the browser !
saveAs(file, "mypdffilename.pdf");
};

oReq.send();

Body of Http.DELETE request in Angular2

Below is a relevant code example for Angular 4/5 with the new HttpClient.

import { HttpClient } from '@angular/common/http';
import { HttpHeaders } from '@angular/common/http';

public removeItem(item) {
    let options = {
      headers: new HttpHeaders({
        'Content-Type': 'application/json',
      }),
      body: item,
    };

    return this._http
      .delete('/api/menu-items', options)
      .map((response: Response) => response)
      .toPromise()
      .catch(this.handleError);
  }

jQuery $.ajax request of dataType json will not retrieve data from PHP script

I think I know this one...

Try sending your JSON as JSON by using PHP's header() function:

/**
 * Send as JSON
 */
header("Content-Type: application/json", true);

Though you are passing valid JSON, jQuery's $.ajax doesn't think so because it's missing the header.

jQuery used to be fine without the header, but it was changed a few versions back.

ALSO

Be sure that your script is returning valid JSON. Use Firebug or Google Chrome's Developer Tools to check the request's response in the console.

UPDATE

You will also want to update your code to sanitize the $_POST to avoid sql injection attacks. As well as provide some error catching.

if (isset($_POST['get_member'])) {

    $member_id = mysql_real_escape_string ($_POST["get_member"]);

    $query = "SELECT * FROM `members` WHERE `id` = '" . $member_id . "';";

    if ($result = mysql_query( $query )) {

       $row = mysql_fetch_array($result);

       $type = $row['type'];
       $name = $row['name'];
       $fname = $row['fname'];
       $lname = $row['lname'];
       $email = $row['email'];
       $phone = $row['phone'];
       $website = $row['website'];
       $image = $row['image'];

       /* JSON Row */
       $json = array( "type" => $type, "name" => $name, "fname" => $fname, "lname" => $lname, "email" => $email, "phone" => $phone, "website" => $website, "image" => $image );

    } else {

        /* Your Query Failed, use mysql_error to report why */
        $json = array('error' => 'MySQL Query Error');

    }

     /* Send as JSON */
     header("Content-Type: application/json", true);

    /* Return JSON */
    echo json_encode($json);

    /* Stop Execution */
    exit;

}

How to decode Unicode escape sequences like "\u00ed" to proper UTF-8 encoded characters?

$str = '\u0063\u0061\u0074'.'\ud83d\ude38';
$str2 = '\u0063\u0061\u0074'.'\ud83d';

// U+1F638
var_dump(
    "cat\xF0\x9F\x98\xB8" === escape_sequence_decode($str),
    "cat\xEF\xBF\xBD" === escape_sequence_decode($str2)
);

function escape_sequence_decode($str) {

    // [U+D800 - U+DBFF][U+DC00 - U+DFFF]|[U+0000 - U+FFFF]
    $regex = '/\\\u([dD][89abAB][\da-fA-F]{2})\\\u([dD][c-fC-F][\da-fA-F]{2})
              |\\\u([\da-fA-F]{4})/sx';

    return preg_replace_callback($regex, function($matches) {

        if (isset($matches[3])) {
            $cp = hexdec($matches[3]);
        } else {
            $lead = hexdec($matches[1]);
            $trail = hexdec($matches[2]);

            // http://unicode.org/faq/utf_bom.html#utf16-4
            $cp = ($lead << 10) + $trail + 0x10000 - (0xD800 << 10) - 0xDC00;
        }

        // https://tools.ietf.org/html/rfc3629#section-3
        // Characters between U+D800 and U+DFFF are not allowed in UTF-8
        if ($cp > 0xD7FF && 0xE000 > $cp) {
            $cp = 0xFFFD;
        }

        // https://github.com/php/php-src/blob/php-5.6.4/ext/standard/html.c#L471
        // php_utf32_utf8(unsigned char *buf, unsigned k)

        if ($cp < 0x80) {
            return chr($cp);
        } else if ($cp < 0xA0) {
            return chr(0xC0 | $cp >> 6).chr(0x80 | $cp & 0x3F);
        }

        return html_entity_decode('&#'.$cp.';');
    }, $str);
}

How do I toggle an element's class in pure JavaScript?

If you want to toggle a class to an element using native solution, you could try this suggestion. I have tasted it in different cases, with or without other classes onto the element, and I think it works pretty much:

(function(objSelector, objClass){
   document.querySelectorAll(objSelector).forEach(function(o){
      o.addEventListener('click', function(e){
        var $this = e.target,
            klass = $this.className,
            findClass = new RegExp('\\b\\s*' + objClass + '\\S*\\s?', 'g');

        if( !findClass.test( $this.className ) )
            if( klass ) 
                $this.className = klass + ' ' + objClass;
            else 
                $this.setAttribute('class', objClass);
        else 
        {
            klass = klass.replace( findClass, '' );
            if(klass) $this.className = klass;
            else $this.removeAttribute('class');
        }
    });
  });
})('.yourElemetnSelector', 'yourClass');

How do I create variable variables?

Instead of a dictionary you can also use namedtuple from the collections module, which makes access easier.

For example:

# using dictionary
variables = {}
variables["first"] = 34
variables["second"] = 45
print(variables["first"], variables["second"])

# using namedtuple
Variables = namedtuple('Variables', ['first', 'second'])
vars = Variables(34, 45)
print(vars.first, vars.second)

Check if a input box is empty

Quite simple:

<input ng-model="somefield">
<span ng-show="!somefield.length">Please enter something!</span>
<span ng-show="somefield.length">Good boy!</span>

You could also use ng-hide="somefield.length" instead of ng-show="!somefield.length" if that reads more naturally for you.


A better alternative might be to really take advantage of the form abilities of Angular:

<form name="myform">
  <input name="myfield" ng-model="somefield" ng-minlength="5" required>
  <span ng-show="myform.myfield.$error.required">Please enter something!</span>
  <span ng-show="!myform.myfield.$error.required">Good boy!</span>
</form> 

Updated Plnkr here.

Getting attributes of a class

The following is what I want.

Test Data

class Base:
    b = 'b'


class MyClass(Base):
    a = '12'

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

    @classmethod
    def c(cls):
        ...

    @property
    def p(self):
        return self.a

    def my_fun(self):
        return self.name
print([name for name, val in inspect.getmembers(MyClass) if not name.startswith('_') and not callable(val)])  # need `import inspect`
print([_ for _ in dir(MyClass) if not _.startswith('_') and not callable(getattr(MyClass, _))])
# both are equ: ['a', 'b', 'p']

my_instance = MyClass('c')
print([_ for _ in dir(my_instance) if not _.startswith('_') and not callable(getattr(my_instance, _))])
# ['a', 'b', 'name', 'p']

if statement in ng-click

Don't put any Condition Expression in Template.

Do it at the Controller.

Template:

<input ng-click="check(profileForm.$valid)" name="submit" 
       id="submit" value="Save" class="submit" type="submit">

Controller:

$scope.check = function(value) {
    if (value) {
       updateMyProfile();
    }
}

How to check if a "lateinit" variable has been initialized?

Using .isInitialized property one can check initialization state of a lateinit variable.

if (::file.isInitialized) {
    // File is initialized
} else {
    // File is not initialized
}

In plain English, what does "git reset" do?

Checkout points the head at a specific commit.

Reset points a branch at a specific commit. (A branch is a pointer to a commit.)

Incidentally, if your head doesn’t point to a commit that’s also pointed to by a branch then you have a detached head. (turned out to be wrong. See comments...)

jQuery ui dialog change title after load-callback

I tried to implement the result of Nick which is:

$('.selectorUsedToCreateTheDialog').dialog('option', 'title', 'My New title');

But that didn't work for me because i had multiple dialogs on 1 page. In such a situation it will only set the title correct the first time. Trying to staple commands did not work:

    $("#modal_popup").html(data);
    $("#modal_popup").dialog('option', 'title', 'My New Title');
    $("#modal_popup").dialog({ width: 950, height: 550);

I fixed this by adding the title to the javascript function arguments of each dialog on the page:

function show_popup1() {
    $("#modal_popup").html(data);
    $("#modal_popup").dialog({ width: 950, height: 550, title: 'Popup Title of my First Dialog'});
}

function show_popup2() {
    $("#modal_popup").html(data);
    $("#modal_popup").dialog({ width: 950, height: 550, title: 'Popup Title of my Other Dialog'});
}

Why is the Java main method static?

Let me explain these things in a much simpler way:

public static void main(String args[])

All Java applications, except applets, start their execution from main().

The keyword public is an access modifier which allows the member to be called from outside the class.

static is used because it allows main() to be called without having to instantiate a particular instance of that class.

void indicates that main() does not return any value.

Convert DateTime to a specified Format

Easy peasy:

var date = DateTime.Parse("14/11/2011"); // may need some Culture help here
Console.Write(date.ToString("yyyy-MM-dd"));

Take a look at DateTime.ToString() method, Custom Date and Time Format Strings and Standard Date and Time Format Strings

string customFormattedDateTimeString = DateTime.Now.ToString("yyyy-MM-dd");

Sort a two dimensional array based on one column

Assuming your array contains strings, you can use the following:

String[] data = new String[] { 
    "2009.07.25 20:24 Message A",
    "2009.07.25 20:17 Message G",
    "2009.07.25 20:25 Message B",
    "2009.07.25 20:30 Message D",
    "2009.07.25 20:01 Message F",
    "2009.07.25 21:08 Message E",
    "2009.07.25 19:54 Message R"
};

Arrays.sort(data, new Comparator<String>() {
    @Override
    public int compare(String s1, String s2) {
        String t1 = s1.substring(0, 16); // date/time of s1
        String t2 = s2.substring(0, 16); // date/time of s2
        return t1.compareTo(t2);
    }
});

If you have a two-dimensional array, the solution is also very similar:

String[][] data = new String[][] { 
        { "2009.07.25 20:17", "Message G" },
        { "2009.07.25 20:25", "Message B" },
        { "2009.07.25 20:30", "Message D" },
        { "2009.07.25 20:01", "Message F" },
        { "2009.07.25 21:08", "Message E" },
        { "2009.07.25 19:54", "Message R" }
};

Arrays.sort(data, new Comparator<String[]>() {
    @Override
    public int compare(String[] s1, String[] s2) {
        String t1 = s1[0];
        String t2 = s2[0];
        return t1.compareTo(t2);
    }
});

Conditional formatting, entire row based

In my case I wanted to compare values in cells of column E with Cells in Column G

Highlight the selection of cells to be checked in column E.

Select Conditional Format: Highlight cell rules Select one of the choices in my case it was greater than. In the left hand field of pop up use =indirect("g"&row()) where g was the row I was comparing against.

Now the row you are formatting will highlight based on if it is greater than the selection in row G

This works for every cell in Column E compared to cell in Column G of the selection you made for column E.

If G2 is greater than E2 it formats

G3 is greater than E3 it formats etc

Java - Convert integer to string

There are multiple ways:

  • String.valueOf(number) (my preference)
  • "" + number (I don't know how the compiler handles it, perhaps it is as efficient as the above)
  • Integer.toString(number)

How to Split Image Into Multiple Pieces in Python

Here is a concise, pure-python solution that works in both python 3 and 2:

from PIL import Image

infile = '20190206-135938.1273.Easy8thRunnersHopefully.jpg'
chopsize = 300

img = Image.open(infile)
width, height = img.size

# Save Chops of original image
for x0 in range(0, width, chopsize):
   for y0 in range(0, height, chopsize):
      box = (x0, y0,
             x0+chopsize if x0+chopsize <  width else  width - 1,
             y0+chopsize if y0+chopsize < height else height - 1)
      print('%s %s' % (infile, box))
      img.crop(box).save('zchop.%s.x%03d.y%03d.jpg' % (infile.replace('.jpg',''), x0, y0))

Notes:

  • The crops that go over the right and bottom of the original image are adjusted to the original image limit and contain only the original pixels.
  • It's easy to choose a different chopsize for w and h by using two chopsize vars and replacing chopsize as appropriate in the code above.

  • Restoring database from .mdf and .ldf files of SQL Server 2008

    From a script (one that works):

    CREATE DATABASE Northwind
    ON ( FILENAME = 'C:\Program Files\Microsoft SQL Server\MSSQL11.SQLEXPRESS\MSSQL\DATA\Northwind.mdf' )
    LOG ON ( FILENAME = 'C:\Program Files\Microsoft SQL Server\MSSQL11.SQLEXPRESS\MSSQL\DATA\Northwind_log.ldf')
    GO
    

    obviously update the path:

    C:\Program Files\Microsoft SQL Server\MSSQL11.SQLEXPRESS\MSSQL\DATA

    To where your .mdf and .ldf reside.

    What is bootstrapping?

    An example of bootstrapping is in some web frameworks. You call index.php (the bootstrapper), and then it loads the frameworks helpers, models, configuration, and then loads the controller and passes off control to it.

    As you can see, it's a simple file that starts a large process.

    Node.js EACCES error when listening on most ports

    restart was not enough! The only way to solve the problem is by the following:

    You have to kill the service which run at that port.

    at cmd, run as admin, then type : netstat -aon | find /i "listening"

    Then, you will get a list with the active service, search for the port that is running at 4200n and use the process id which is the last column to kill it by

    : taskkill /F /PID 2652

    How can I get last characters of a string

    I am sure this will work....

    var string1="myfile.pdf"
    var esxtenion=string1.substr(string1.length-4)
    

    The value of extension will be ".pdf"

    PadLeft function in T-SQL

    Create Function :

        Create FUNCTION [dbo].[PadLeft]
          (
            @Text NVARCHAR(MAX) ,
            @Replace NVARCHAR(MAX) ,
            @Len INT
          )
    RETURNS NVARCHAR(MAX)
    AS
        BEGIN 
    
    
            DECLARE @var NVARCHAR(MAX) 
    
            SELECT @var = ISNULL(LTRIM(RTRIM(@Text)) , '')
    
    
            RETURN   RIGHT(REPLICATE(@Replace,@Len)+ @var, @Len)
    
    
        END
    

    Example:

    Select dbo.PadLeft('123456','0',8)
    

    Selenium wait until document is ready

    In Java it will like below :-

      private static boolean isloadComplete(WebDriver driver)
        {
            return ((JavascriptExecutor) driver).executeScript("return document.readyState").equals("loaded")
                    || ((JavascriptExecutor) driver).executeScript("return document.readyState").equals("complete");
        }
    

    Purpose of "%matplotlib inline"

    It just means that any graph which we are creating as a part of our code will appear in the same notebook and not in separate window which would happen if we have not used this magic statement.

    JPanel vs JFrame in Java

    JFrame is the window; it can have one or more JPanel instances inside it. JPanel is not the window.

    You need a Swing tutorial:

    http://docs.oracle.com/javase/tutorial/uiswing/

    How to get the row number from a datatable?

    You have two options here.

    1. You can create your own index counter and increment it
    2. Rather than using a foreach loop, you can use a for loop

    The individual row simply represents data, so it will not know what row it is located in.

    "inconsistent use of tabs and spaces in indentation"

    There was a duplicate of this question from here but I thought I would offer a view to do with modern editors and the vast array of features they offer. With python code, anything that needs to be intented in a .py file, needs to either all be intented using the tab key, or by spaces. Convention is to use four spaces for an indentation. Most editors have the ability to visually show on the editor whether the code is being indented with spaces or tabs, which helps greatly for debugging. For example, with atom, going to preferences and then editor you can see the following two options:

    atom editor to show tabs and spaces

    Then if your code is using spaces, you will see small dots where your code is indented:

    enter image description here

    And if it is indented using tabs, you will see something like this:

    enter image description here

    Now if you noticed, you can see that when using tabs, there are more errors/warnings on the left, this is because of something called pep8 pep8 documentation, which is basically a uniform style guide for python, so that all developers mostly code to the same standard and appearance, which helps when trying to understand other peoples code, it is in pep8 which favors the use of spaces to indent rather than tabs. And we can see the editor showing that there is a warning relating to pep8 warning code W191,

    I hope all the above helps you understand the nature of the problem you are having and how to prevent it in the future.

    How can I subset rows in a data frame in R based on a vector of values?

    This will give you what you want:

    eg2011cleaned <- eg2011[!eg2011$ID %in% bg2011missingFromBeg, ]
    

    The error in your second attempt is because you forgot the ,

    In general, for convenience, the specification object[index] subsets columns for a 2d object. If you want to subset rows and keep all columns you have to use the specification object[index_rows, index_columns], while index_cols can be left blank, which will use all columns by default.

    However, you still need to include the , to indicate that you want to get a subset of rows instead of a subset of columns.

    How to send a JSON object using html form data

    You can try something like:

    <html>
    <head>
        <title>test</title>
    </head>
    
    <body>
        <form id="formElem">
            <input type="text" name="firstname" value="Karam">
            <input type="text" name="lastname" value="Yousef">
            <input type="submit">
        </form>
        <div id="decoded"></div>
        <button id="encode">Encode</button>
        <div id="encoded"></div>
    </body>
    <script>
        encode.onclick = async (e) => {
            let response = await fetch('http://localhost:8482/encode', {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json',
                    },
            })
    
            let text = await response.text(); // read response body as text
            data = JSON.parse(text);
            document.querySelector("#encoded").innerHTML = text;
          //  document.querySelector("#encoded").innerHTML = `First name = ${data.firstname} <br/> 
          //                                                  Last name = ${data.lastname} <br/>
          //                                                  Age    = ${data.age}`
        };
    
        formElem.onsubmit = async (e) => {
          e.preventDefault();
          var form = document.querySelector("#formElem");
         // var form = document.forms[0];
    
            data = {
              firstname : form.querySelector('input[name="firstname"]').value,
              lastname : form.querySelector('input[name="lastname"]').value,
              age : 5
            }
    
            let response = await fetch('http://localhost:8482/decode', {
                    method: 'POST', // or 'PUT'
                    headers: {
                        'Content-Type': 'application/json',
                    },
                    body: JSON.stringify(data),
            })
    
            let text = await response.text(); // read response body as text
            document.querySelector("#decoded").innerHTML = text;
        };
    </script>
    </html>
    

    Can I update a JSF component from a JSF backing bean method?

    Everything is possible only if there is enough time to research :)

    What I got to do is like having people that I iterate into a ui:repeat and display names and other fields in inputs. But one of fields was singleSelect - A and depending on it value update another input - B. even ui:repeat do not have id I put and it appeared in the DOM tree

    <ui:repeat id="peopleRepeat"
    value="#{myBean.people}"
    var="person" varStatus="status">
    

    Than the ids in the html were something like:

    myForm:peopleRepeat:0:personType
    myForm:peopleRepeat:1:personType
    

    Than in the view I got one method like:

    <p:ajax event="change"
    listener="#{myBean.onPersonTypeChange(person, status.index)}"/>
    

    And its implementation was in the bean like:

    String componentId = "myForm:peopleRepeat" + idx + "personType";
    PrimeFaces.current().ajax().update(componentId);
    

    So this way I updated the element from the bean with no issues. PF version 6.2

    Good luck and happy coding :)

    How to connect to MySQL Database?

     private void Initialize()
        {
            server = "localhost";
            database = "connectcsharptomysql";
            uid = "username";
            password = "password";
            string connectionString;
            connectionString = "SERVER=" + server + ";" + "DATABASE=" + 
            database + ";" + "U`enter code here`ID=" + uid + ";" + "PASSWORD=" + password + ";";
    
            connection = new MySqlConnection(connectionString);
        }
    

    How can I convert a DateTime to an int?

    string date = DateTime.Now.ToString();
    
    date = date.Replace("/", "");
    date = date.Replace(":", "");
    date = date.Replace(" ", "");
    date = date.Replace("AM", "");
    date = date.Replace("PM", "");            
    return date;
    

    What is RSS and VSZ in Linux memory management

    RSS is Resident Set Size (physically resident memory - this is currently occupying space in the machine's physical memory), and VSZ is Virtual Memory Size (address space allocated - this has addresses allocated in the process's memory map, but there isn't necessarily any actual memory behind it all right now).

    Note that in these days of commonplace virtual machines, physical memory from the machine's view point may not really be actual physical memory.

    c# foreach (property in object)... Is there a simple way of doing this?

    I couldn't get any of the above ways to work, but this worked. The username and password for DirectoryEntry are optional.

       private List<string> getAnyDirectoryEntryPropertyValue(string userPrincipalName, string propertyToSearchFor)
        {
            List<string> returnValue = new List<string>();
            try
            {
                int index = userPrincipalName.IndexOf("@");
                string originatingServer = userPrincipalName.Remove(0, index + 1);
                string path = "LDAP://" + originatingServer; //+ @"/" + distinguishedName;
                DirectoryEntry objRootDSE = new DirectoryEntry(path, PSUsername, PSPassword);
                var objSearcher = new System.DirectoryServices.DirectorySearcher(objRootDSE);
                objSearcher.Filter = string.Format("(&(UserPrincipalName={0}))", userPrincipalName);
                SearchResultCollection properties = objSearcher.FindAll();
    
                ResultPropertyValueCollection resPropertyCollection = properties[0].Properties[propertyToSearchFor];
                foreach (string resProperty in resPropertyCollection)
                {
                    returnValue.Add(resProperty);
                }
            }
            catch (Exception ex)
            {
                returnValue.Add(ex.Message);
                throw;
            }
    
            return returnValue;
        }
    

    how to modify an existing check constraint?

    NO, you can't do it other way than so.

    Converting milliseconds to a date (jQuery/JavaScript)

    Try using this code:

    var datetime = 1383066000000; // anything
    var date = new Date(datetime);
    var options = {
            year: 'numeric', month: 'numeric', day: 'numeric',
        };
    
    var result = date.toLocaleDateString('en', options); // 10/29/2013
    

    See more: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString

    How to remove all .svn directories from my application directories

    What you wrote sends a list of newline separated file names (and paths) to rm, but rm doesn't know what to do with that input. It's only expecting command line parameters.

    xargs takes input, usually separated by newlines, and places them on the command line, so adding xargs makes what you had work:

    find . -name .svn | xargs rm -fr
    

    xargs is intelligent enough that it will only pass as many arguments to rm as it can accept. Thus, if you had a million files, it might run rm 1,000,000/65,000 times (if your shell could accept 65,002 arguments on the command line {65k files + 1 for rm + 1 for -fr}).

    As persons have adeptly pointed out, the following also work:

    find . -name .svn -exec rm -rf {} \;
    find . -depth -name .svn -exec rm -fr {} \;
    find . -type d -name .svn -print0|xargs -0 rm -rf
    

    The first two -exec forms both call rm for each folder being deleted, so if you had 1,000,000 folders, rm would be invoked 1,000,000 times. This is certainly less than ideal. Newer implementations of rm allow you to conclude the command with a + indicating that rm will accept as many arguments as possible:

    find . -name .svn -exec rm -rf {} +
    

    The last find/xargs version uses print0, which makes find generate output that uses \0 as a terminator rather than a newline. Since POSIX systems allow any character but \0 in the filename, this is truly the safest way to make sure that the arguments are correctly passed to rm or the application being executed.

    In addition, there's a -execdir that will execute rm from the directory in which the file was found, rather than at the base directory and a -depth that will start depth first.

    CSS fixed width in a span

    Unfortunately inline elements (or elements having display:inline) ignore the width property. You should use floating divs instead:

    <style type="text/css">
    div.f1 { float: left; width: 20px; }
    div.f2 { float: left; }
    div.f3 { clear: both; }
    </style>
    
    <div class="f1"></div><div class="f2">The Lazy dog</div><div class="f3"></div>
    <div class="f1">AND</div><div class="f2">The Lazy cat</div><div class="f3"></div>
    <div class="f1">OR</div><div class="f2">The active goldfish</div><div class="f3"></div>
    

    Now I see you need to use spans and lists, so we need to rewrite this a little bit:

    <html><head>
    <style type="text/css">
            span.f1 { display: block; float: left; clear: left; width: 60px; }
        li { list-style-type: none; }
        </style>
    
    </head><body>
    <ul>
    <li><span class="f1">&nbsp;</span>The lazy dog.</li>
    <li><span class="f1">AND</span> The lazy cat.</li>
    <li><span class="f1">OR</span> The active goldfish.</li>
    </ul>
    </body>
    </html>
    

    how to activate a textbox if I select an other option in drop down box

    As Umesh Patil answer have comment say that there is problem. I try to edit answer and get reject. And get suggest to post new answer. This code should solve problem they have (Shashi Roy, Gaven, John Higgins).

    <html> 
    <head>  
    <script type="text/javascript">
    function CheckColors(val){
     var element=document.getElementById('othercolor');
     if(val=='others')
       element.style.display='block';
     else  
       element.style.display='none';
    }
    
    </script> 
    </head>
    <body>
      <select name="color" onchange='CheckColors(this.value);'> 
        <option>pick a color</option>  
        <option value="red">RED</option>
        <option value="blue">BLUE</option>
        <option value="others">others</option>
      </select>
    <input type="text" name="othercolor" id="othercolor" style='display:none;'/>
    </body>
    </html>
    

    Run javascript function when user finishes typing instead of on key up?

    Once you detect focus on the text box, on key up do a timeout check, and reset it each time it's triggered.

    When the timeout completes, do your ajax request.

    Download a file from HTTPS using download.file()

    I've succeed with the following code:

    url = "http://d396qusza40orc.cloudfront.net/getdata%2Fdata%2Fss06hid.csv"
    x = read.csv(file=url)
    

    Note that I've changed the protocol from https to http, since the first one doesn't seem to be supported in R.

    How can I format bytes a cell in Excel as KB, MB, GB etc?

    Slight change to make it work on my region, Europe (. as thousands separator, comma as decimal separator):

    [<1000000]#.##0,00" KB";[<1000000000]#.##0,00.." MB";#.##0,00..." GB"
    

    Still same issue on data conversion (1000 != 1024) but it does the job for me.

    Convert Newtonsoft.Json.Linq.JArray to a list of specific object type

    I can think of different method to achieve the same

    IList<SelectableEnumItem> result= array;
    

    or (i had some situation that this one didn't work well)

    var result = (List<SelectableEnumItem>) array;
    

    or use linq extension

    var result = array.CastTo<List<SelectableEnumItem>>();
    

    or

    var result= array.Select(x=> x).ToArray<SelectableEnumItem>();
    

    or more explictly

    var result= array.Select(x=> new SelectableEnumItem{FirstName= x.Name, Selected = bool.Parse(x.selected) });
    

    please pay attention in above solution I used dynamic Object

    I can think of some more solutions that are combinations of above solutions. but I think it covers almost all available methods out there.

    Myself I use the first one

    ASP.NET MVC Global Variables

    The steel is far from hot, but I combined @abatishchev's solution with the answer from this post and got to this result. Hope it's useful:

    public static class GlobalVars
    {
        private const string GlobalKey = "AllMyVars";
    
        static GlobalVars()
        {
            Hashtable table = HttpContext.Current.Application[GlobalKey] as Hashtable;
    
            if (table == null)
            {
                table = new Hashtable();
                HttpContext.Current.Application[GlobalKey] = table;
            }
        }
    
        public static Hashtable Vars
        {
            get { return HttpContext.Current.Application[GlobalKey] as Hashtable; }
        }
    
        public static IEnumerable<SomeClass> SomeCollection
        {
            get { return GetVar("SomeCollection") as IEnumerable<SomeClass>; }
            set { WriteVar("SomeCollection", value); }
        }
    
        internal static DateTime SomeDate
        {
            get { return (DateTime)GetVar("SomeDate"); }
            set { WriteVar("SomeDate", value); }
        }
    
        private static object GetVar(string varName)
        {
            if (Vars.ContainsKey(varName))
            {
                return Vars[varName];
            }
    
            return null;
        }
    
        private static void WriteVar(string varName, object value)
        {
            if (value == null)
            {
                if (Vars.ContainsKey(varName))
                {
                    Vars.Remove(varName);
                }
                return;
            }
    
            if (Vars[varName] == null)
            {
                Vars.Add(varName, value);
            }
            else
            {
                Vars[varName] = value;
            }
        }
    }
    

    What does the ^ (XOR) operator do?

    ^ is the Python bitwise XOR operator. It is how you spell XOR in python:

    >>> 0 ^ 0
    0
    >>> 0 ^ 1
    1
    >>> 1 ^ 0
    1
    >>> 1 ^ 1
    0
    

    XOR stands for exclusive OR. It is used in cryptography because it let's you 'flip' the bits using a mask in a reversable operation:

    >>> 10 ^ 5
    15
    >>> 15 ^ 5
    10
    

    where 5 is the mask; (input XOR mask) XOR mask gives you the input again.

    SQL count rows in a table

    Here is the Query

    select count(*) from tablename
    

    or

    select count(rownum) from studennt
    

    Using Panel or PlaceHolder

    The Placeholder does not render any tags for itself, so it is great for grouping content without the overhead of outer HTML tags.

    The Panel does have outer HTML tags but does have some cool extra properties.

    • BackImageUrl: Gets/Sets the background image's URL for the panel

    • HorizontalAlign: Gets/Sets the
      horizontal alignment of the parent's contents

    • Wrap: Gets/Sets whether the
      panel's content wraps

    There is a good article at startvbnet here.

    Can you write nested functions in JavaScript?

    Is this really possible.

    Yes.

    _x000D_
    _x000D_
    function a(x) {    // <-- function_x000D_
      function b(y) { // <-- inner function_x000D_
        return x + y; // <-- use variables from outer scope_x000D_
      }_x000D_
      return b;       // <-- you can even return a function._x000D_
    }_x000D_
    console.log(a(3)(4));
    _x000D_
    _x000D_
    _x000D_

    npm start error with create-react-app

    For me it was simply that I hadn't added react-scripts to the project so:

    npm i -S react-scripts
    

    If this doesn't work, then rm node_modules as suggested by others

    rm -r node_modules
    npm i
    

    position: fixed doesn't work on iPad and iPhone

    I had this problem on Safari (iOS 10.3.3) - the browser was not redrawing until the touchend event fired. Fixed elements did not appear or were cut off.

    The trick for me was adding transform: translate3d(0,0,0); to my fixed position element.

    .fixed-position-on-mobile {
      position: fixed;
      transform: translate3d(0,0,0);
    }
    

    EDIT - I now know why the transform fixes the issue: hardware-acceleration. Adding the 3D transformation triggers the GPU acceleration making for a smooth transition. For more on hardware-acceleration checkout this article: http://blog.teamtreehouse.com/increase-your-sites-performance-with-hardware-accelerated-css.

    UILabel text margin

    If you don't want to use an extra parent view to set the background, you can subclass UILabel and override textRectForBounds:limitedToNumberOfLines:. I'd add a textEdgeInsets property or similar and then do

    - (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines
    {
      return [super textRectForBounds:UIEdgeInsetsInsetRect(bounds,textEdgeInsets) limitedToNumberOfLines:numberOfLines];
    }
    

    For robustness, you might also want to call [self setNeedsDisplay] in setTextEdgeInsets:, but I usually don't bother.

    How to add not null constraint to existing column in MySQL

    Would like to add:

    After update, such as

    ALTER TABLE table_name modify column_name tinyint(4) NOT NULL;
    

    If you get

    ERROR 1138 (22004): Invalid use of NULL value
    

    Make sure you update the table first to have values in the related column (so it's not null)

    Xcode Debugger: view value of variable

    Try Run->Show->Expressions

    Enter in the name of the array or whatever you're looking for.

    Is there a way to split a widescreen monitor in to two or more virtual monitors?

    It seems a window manager is what you want. The problem is finding one that works.

    I use a tiling window manager in Linux (dwm) and it seems to do exactly what you are after, PLUS it has multiple workspaces which is what I thought you were going for at first.

    A tiling window manager has no concept of "maximized" windows. All windows take up the full amount of space that they are allotted, and they never overlap. When you only have one window up on the screen, it gets the full screen. Open up another window, and it opens next to the first, while the first re-sizes automatically to take up only part of the screen. In dwm, the split between them is adjustable with keystrokes. Additional windows each take up their own allotted space on the screen, and any existing windows re-size to accommodate them depending on the particular layout you have chosen.

    Workspaces use "tags"; any window can have one or more tags, and you can choose to see any windows that have one or more of a certain set of tags at a time. Thus you can hide windows that you don't want to see, and let the other windows take up more space.

    Unfortunately, the few tiling add-ons I've tried for Windows don't work anywhere near as well. Although dwm has a few quirks with certain apps that use an SDI-style interface like Gimp or Pidgin (you can set windows as "floating" above the tiled layout to work around this), I've never had it get confused about where my windows are or shove windows off the screen like some of the window managers I've tried on Windows. If anyone knows of something with equivalent functionality that actually WORKS on Windows, I would love to know about it.

    How to clear the logs properly for a Docker container?

    sudo find /var/lib/docker/containers/ -type f -name "*.log" -delete
    

    Send a SMS via intent

    Try this code. It will work

    Uri smsUri = Uri.parse("tel:123456");
    Intent intent = new Intent(Intent.ACTION_VIEW, smsUri);
    intent.putExtra("sms_body", "sms text");
    intent.setType("vnd.android-dir/mms-sms"); 
    startActivity(intent);
    

    Hope this will help you.

    Why do you need to invoke an anonymous function on the same line?

    This answer is not strictly related to the question, but you might be interested to find out that this kind of syntax feature is not particular to functions. For example, we can always do something like this:

    alert(
        {foo: "I am foo", bar: "I am bar"}.foo
    ); // alerts "I am foo"
    

    Related to functions. As they are objects, which inherit from Function.prototype, we can do things like:

    Function.prototype.foo = function () {
        return function () {
            alert("foo");
        };
    };
    
    var bar = (function () {}).foo();
    
    bar(); // alerts foo
    

    And you know, we don't even have to surround functions with parenthesis in order to execute them. Anyway, as long as we try to assign the result to a variable.

    var x = function () {} (); // this function is executed but does nothing
    
    function () {} (); // syntax error
    

    One other thing you may do with functions, as soon as you declare them, is to invoke the new operator over them and obtain an object. The following are equivalent:

    var obj = new function () {
        this.foo = "bar";
    };
    
    var obj = {
        foo : "bar"
    };
    

    php - insert a variable in an echo string

    You can try this

    $i = 1
    echo '<p class="paragraph'.$i.'"></p>';
    ++i; 
    

    Rendering React Components from Array of Objects

    You can map the list of stations to ReactElements.

    With React >= 16, it is possible to return multiple elements from the same component without needing an extra html element wrapper. Since 16.2, there is a new syntax <> to create fragments. If this does not work or is not supported by your IDE, you can use <React.Fragment> instead. Between 16.0 and 16.2, you can use a very simple polyfill for fragments.

    Try the following

    // Modern syntax >= React 16.2.0
    const Test = ({stations}) => (
      <>
        {stations.map(station => (
          <div className="station" key={station.call}>{station.call}</div>
        ))}
      </>
    ); 
    
    // Modern syntax < React 16.2.0
    // You need to wrap in an extra element like div here
    
    const Test = ({stations}) => (
      <div>
        {stations.map(station => (
          <div className="station" key={station.call}>{station.call}</div>
        ))}
      </div>
    ); 
    
    // old syntax
    var Test = React.createClass({
        render: function() {
            var stationComponents = this.props.stations.map(function(station) {
                return <div className="station" key={station.call}>{station.call}</div>;
            });
            return <div>{stationComponents}</div>;
        }
    });
    
    var stations = [
      {call:'station one',frequency:'000'},
      {call:'station two',frequency:'001'}
    ]; 
    
    ReactDOM.render(
      <div>
        <Test stations={stations} />
      </div>,
      document.getElementById('container')
    );
    

    Don't forget the key attribute!

    https://jsfiddle.net/69z2wepo/14377/

    git pull while not in a git directory

    Using combination pushd, git pull and popd, we can achieve this functionality:

    pushd <path-to-git-repo> && git pull && popd
    

    For example:

    pushd "E:\Fake Directory\gitrepo" && git pull && popd
    

    What exactly does += do in python?

    x += 5 is not exactly the same as saying x = x + 5 in Python.

    Note here:

    In [1]: x = [2, 3, 4]    
    In [2]: y = x    
    In [3]: x += 7, 8, 9    
    In [4]: x
    Out[4]: [2, 3, 4, 7, 8, 9]    
    In [5]: y
    Out[5]: [2, 3, 4, 7, 8, 9]    
    In [6]: x += [44, 55]    
    In [7]: x
    Out[7]: [2, 3, 4, 7, 8, 9, 44, 55]    
    In [8]: y
    Out[8]: [2, 3, 4, 7, 8, 9, 44, 55]    
    In [9]: x = x + [33, 22]    
    In [10]: x
    Out[10]: [2, 3, 4, 7, 8, 9, 44, 55, 33, 22]    
    In [11]: y
    Out[11]: [2, 3, 4, 7, 8, 9, 44, 55]
    

    See for reference: Why does += behave unexpectedly on lists?

    JavaScript private methods

    The module pattern is right in most cases. But if you have thousands of instances, classes save memory. If saving memory is a concern and your objects contain a small amount of private data, but have a lot of public functions, then you'll want all public functions to live in the .prototype to save memory.

    This is what I came up with:

    var MyClass = (function () {
        var secret = {}; // You can only getPriv() if you know this
        function MyClass() {
            var that = this, priv = {
                foo: 0 // ... and other private values
            };
            that.getPriv = function (proof) {
                return (proof === secret) && priv;
            };
        }
        MyClass.prototype.inc = function () {
            var priv = this.getPriv(secret);
            priv.foo += 1;
            return priv.foo;
        };
        return MyClass;
    }());
    var x = new MyClass();
    x.inc(); // 1
    x.inc(); // 2
    

    The object priv contains private properties. It is accessible through the public function getPriv(), but this function returns false unless you pass it the secret, and this is only known inside the main closure.

    Clearing an input text field in Angular2

    This is a solution for reactive forms. Then there is no need to use @ViewChild decorator:

      clear() {
        this.myForm.get('someControlName').reset()
      }
    

    Rewrite URL after redirecting 404 error htaccess

    In your .htaccess file , if you are using apache you can try with

    Rule for Error Page - 404

    ErrorDocument 404 http://www.domain.com/notFound.html

    Maximum execution time in phpMyadmin

    Probabily you are using XMAPP as service, to restart XMAPP properly, you have to open XMAPP control panel un-check both "Svc" mdodules against Apache and MySQL. Then click on exit, now restart XMAPP and you are done.

    You seem to not be depending on "@angular/core". This is an error

    **You should be in the newly created YOUR_APP folder before you hit the ng serve command **

    Lets start from fresh,

    1) install npm

    2) create a new angular app ( ng new <YOUR_APP_NAME> )

    3) go to app folder (cd YOUR_APP_NAME)

    4) ng serve

    I hope it will resolve the issue.

    How to redirect Valgrind's output to a file?

    By default, Valgrind writes its output to stderr. So you need to do something like:

    valgrind a.out > log.txt 2>&1
    

    Alternatively, you can tell Valgrind to write somewhere else; see http://valgrind.org/docs/manual/manual-core.html#manual-core.comment (but I've never tried this).

    'xmlParseEntityRef: no name' warnings while loading xml into a php file

    This is in deed due to characters messing around with the data. Using htmlentities($yourText) worked for me (I had html code inside the xml document). See http://uk3.php.net/htmlentities.

    printing out a 2-D array in Matrix format

    int[][] matrix = {
        {1,2,3},
        {4,5,6},
        {7,8,9},
        {10,11,12}
    };
    
    printMatrix(matrix);
    
    public void printMatrix(int[][] m){
        try{
            int rows = m.length;
            int columns = m[0].length;
            String str = "|\t";
    
            for(int i=0;i<rows;i++){
                for(int j=0;j<columns;j++){
                    str += m[i][j] + "\t";
                }
    
                System.out.println(str + "|");
                str = "|\t";
            }
    
        }catch(Exception e){System.out.println("Matrix is empty!!");}
    }
    

    Output:

    |   1   2   3   |
    |   4   5   6   |
    |   7   8   9   |
    |   10  11  12  |
    

    How do I remove leading whitespace in Python?

    If you want to cut the whitespaces before and behind the word, but keep the middle ones.
    You could use:

    word = '  Hello World  '
    stripped = word.strip()
    print(stripped)
    

    Context.startForegroundService() did not then call Service.startForeground()

    So many answer but none worked in my case.

    I have started service like this.

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        startForegroundService(intent);
    } else {
        startService(intent);
    }
    

    And in my service in onStartCommand

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            Notification.Builder builder = new Notification.Builder(this, ANDROID_CHANNEL_ID)
                    .setContentTitle(getString(R.string.app_name))
                    .setContentText("SmartTracker Running")
                    .setAutoCancel(true);
            Notification notification = builder.build();
            startForeground(NOTIFICATION_ID, notification);
        } else {
            NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                    .setContentTitle(getString(R.string.app_name))
                    .setContentText("SmartTracker is Running...")
                    .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                    .setAutoCancel(true);
            Notification notification = builder.build();
            startForeground(NOTIFICATION_ID, notification);
        }
    

    And don't forgot to set NOTIFICATION_ID non zero

    private static final String ANDROID_CHANNEL_ID = "com.xxxx.Location.Channel";
    private static final int NOTIFICATION_ID = 555;
    

    SO everything was perfect but still crashing on 8.1 so cause was as below.

         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                stopForeground(true);
            } else {
                stopForeground(true);
            }
    

    I have called stop foreground with remove notificaton but once notification removed service become background and background service can not run in android O from background. started after push received.

    So magical word is

       stopSelf();
    

    So far so any reason your service is crashing follow all above steps and enjoy.

    Convert to/from DateTime and Time in Ruby

    require 'time'
    require 'date'
    
    t = Time.now
    d = DateTime.now
    
    dd = DateTime.parse(t.to_s)
    tt = Time.parse(d.to_s)
    

    Changing specific text's color using NSMutableAttributedString in Swift

    You can use as simple extension

    extension String{
    
    func attributedString(subStr: String) -> NSMutableAttributedString{
        let range = (self as NSString).range(of: subStr)
        let attributedString = NSMutableAttributedString(string:self)
        attributedString.addAttribute(NSAttributedString.Key.foregroundColor, value: UIColor.red , range: range)
        
        return attributedString
      }
    }
    
    myLable.attributedText = fullStr.attributedString(subStr: strToChange)
    
      
    

    "Continue" (to next iteration) on VBScript

    We can use a separate function for performing a continue statement work. suppose you have following problem:

    for i=1 to 10
    
    if(condition) then   'for loop body'
    contionue
    End If
    
    Next
    

    Here we will use a function call for for loop body:

    for i=1 to 10
    Call loopbody()
    next
    
    function loopbody()
    
    if(condition) then   'for loop body'
    Exit Function
    End If
    
    End Function
    

    loop will continue for function exit statement....

    The communication object, System.ServiceModel.Channels.ServiceChannel, cannot be used for communication

    I know this is an older post but one thing to watch out for when you cannot change the security is to make sure that your username and password are set.

    I had a service with authenticationMode as UserNameOverTransport, when the username and password were not set for the service client I would get this error.

    Passing 'this' to an onclick event

    In JavaScript this always refers to the “owner” of the function we're executing, or rather, to the object that a function is a method of. When we define our faithful function doSomething() in a page, its owner is the page, or rather, the window object (or global object) of JavaScript.

    How does the "this" keyword work?

    Adding Access-Control-Allow-Origin header response in Laravel 5.3 Passport

    Just add this to your view:

    <?php header("Access-Control-Allow-Origin: *"); ?>
    

    Giving multiple URL patterns to Servlet Filter

    If an URL pattern starts with /, then it's relative to the context root. The /Admin/* URL pattern would only match pages on http://localhost:8080/EMS2/Admin/* (assuming that /EMS2 is the context path), but you have them actually on http://localhost:8080/EMS2/faces/Html/Admin/*, so your URL pattern never matches.

    You need to prefix your URL patterns with /faces/Html as well like so:

    <url-pattern>/faces/Html/Admin/*</url-pattern>
    

    You can alternatively also just reconfigure your web project structure/configuration so that you can get rid of the /faces/Html path in the URLs so that you can just open the page by for example http://localhost:8080/EMS2/Admin/Upload.xhtml.

    Your filter mapping syntax is all fine. However, a simpler way to specify multiple URL patterns is to just use only one <filter-mapping> with multiple <url-pattern> entries:

    <filter-mapping>
        <filter-name>LoginFilter</filter-name>
        <url-pattern>/faces/Html/Employee/*</url-pattern>
        <url-pattern>/faces/Html/Admin/*</url-pattern>
        <url-pattern>/faces/Html/Supervisor/*</url-pattern>
    </filter-mapping>
    

    Format SQL in SQL Server Management Studio

    Azure Data Studio - free and from Microsoft - offers automatic formatting (ctrl + shift + p while editing -> format document). More information about Azure Data Studio here.

    While this is not SSMS, it's great for writing queries, free and an official product from Microsoft. It's even cross-platform. Short story: Just switch to Azure Data Studio to write your queries!

    Update: Actually Azure Data Studio is in some way the recommended tool for writing queries (source)

    Use Azure Data Studio if you: [..] Are mostly editing or executing queries.

    string in namespace std does not name a type

    Nouns.h doesn't include <string>, but it needs to. You need to add

    #include <string>
    

    at the top of that file, otherwise the compiler doesn't know what std::string is when it is encountered for the first time.

    Failed to install Python Cryptography package with PIP and setup.py

    Those two commands fixed it for me:

    brew install openssl
    brew link openssl --force
    

    Source: https://github.com/phusion/passenger/issues/1630#issuecomment-147527656

    asterisk : Unable to connect to remote asterisk (does /var/run/asterisk.ctl exist?)

    Only you need to empty /tmp directory using command & hit reboot your system. now you are able to play on asterisk CLI whatever you want.

    How does += (plus equal) work?

    That is just a short form for:

    sum = sum + value;
    

    MySQL set current date in a DATETIME field on insert

    Since MySQL 5.6.X you can do this:

    ALTER TABLE `schema`.`users` 
    CHANGE COLUMN `created` `created` DATETIME NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP ;
    

    That way your column will be updated with the current timestamp when a new row is inserted, or updated.

    If you're using MySQL Workbench, you can just put CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP in the DEFAULT value field, like so:

    enter image description here

    http://dev.mysql.com/doc/relnotes/mysql/5.6/en/news-5-6-5.html

    'mat-form-field' is not a known element - Angular 5 & Material2

    When using MatAutocompleteModule in your angular application, you need to import Input Module also in app.module.ts

    Please import below:

    import { MatInputModule } from '@angular/material';

    Unix epoch time to Java Date object

    Epoch is the number of seconds since Jan 1, 1970..

    So:

    String epochString = "1081157732";
    long epoch = Long.parseLong( epochString );
    Date expiry = new Date( epoch * 1000 );
    

    For more information: http://www.epochconverter.com/

    Is there a way to get LaTeX to place figures in the same page as a reference to that figure?

    I don't want to sound too negative, but there are occasions when what you want is almost impossible without a lot of "artificial" tuning of page breaks.

    If the callout falls naturally near the bottom of a page, and the figure falls on the following page, moving the figure back one page will probably displace the callout forward.

    I would recommend (as far as possible, and depending on the exact size of the figures):

    • Place the figures with [t] (or [h] if you must)
    • Place the figures as near as possible to the "right" place (differs for [t] and [h])
    • Include the figures from separate files with \input, which will make them much easier to move around when you're doing the final tuning

    In my experience, this is a big eater-up of non-available time (:-)


    In reply to Jon's comment, I think this is an inherently difficult problem, because the LaTeX guys are no slouches. You may like to read Frank Mittelbach's paper.

    Is key-value pair available in Typescript?

    class Pair<T1, T2> {
        private key: T1;
        private value: T2;
    
        constructor(key: T1, value: T2) {
            this.key = key;
            this.value = value;
        }
    
        getKey() {
            return this.key;
        }
    
        getValue() {
            return this.value;
        }
    }
    const myPair = new Pair<string, number>('test', 123);
    console.log(myPair.getKey(), myPair.getValue());
    

    How to echo or print an array in PHP?

    I checked the answer however, (for each) in PHP is deprecated and no longer work with the latest php versions.

    Usually we would convert an array into a string to log it somewhere, perhaps debugging or test etc.

    I would convert the array into a string by doing:

    $Output = implode(",", $SourceArray);
    

    Whereas:

    $output is the result (where the string would be generated

    ",": is the separator (between each array field

    $SourceArray: is your source array.

    I hope this helps

    Why call git branch --unset-upstream to fixup?

    Issue: Your branch is based on 'origin/master', but the upstream is gone.

    Solution: git branch --unset-upstream

    How to start jenkins on different port rather than 8080 using command prompt in Windows?

    For Fedora, RedHat, CentOS and alike, any customization should be done within /etc/sysconfig/jenkins instead of /etc/init.d/jenkins. The purpose of the first file is exactly the customization of the second file.

    So, within /etc/sysconfig/jenkins, there is a the JENKINS_PORT variable that holds the port number on which Jenkins is running.

    What is the best way to delete a value from an array in Perl?

    Is this something you are going to be doing a lot? If so, you may want to consider a different data structure. Grep is going to search the entire array every time and for a large array could be quite costly. If speed is an issue then you may want to consider using a Hash instead.

    In your example, the key would be the number and the value would be the count of elements of that number.

    file_get_contents("php://input") or $HTTP_RAW_POST_DATA, which one is better to get the body of JSON request?

    For JSON data, it's much easier to POST it as "application/json" content-type. If you use GET, you have to URL-encode the JSON in a parameter and it's kind of messy. Also, there is no size limit when you do POST. GET's size if very limited (4K at most).

    MySQL 8.0 - Client does not support authentication protocol requested by server; consider upgrading MySQL client

    Check privileges and username/password for your MySQL user.

    For catching errors it is always useful to use overrided _delegateError method. In your case this has to look like:

    var mysql = require('mysql');
    
    var con = mysql.createConnection({
      host: "localhost",
      user: "root",
      password: "password",
      insecureAuth : true
    });
    
    var _delegateError = con._protocol._delegateError;
    
    con._protocol._delegateError = function(err, sequence) {
        if (err.fatal)
            console.trace('MySQL fatal error: ' + err.message);
    
        return _delegateError.call(this, err, sequence);
    };
    
    con.connect(function(err) {
      if (err) throw err;
    
      console.log("Connected!");
    });
    

    This construction will help you to trace fatal errors.

    Can I install/update WordPress plugins without providing FTP access?

    We use SFTP with SSH (on both our development and live servers), and I have tried (not too hard though) to use the WordPress upload feature. I agree with Toby, upload your plugin(s) to the wp-content/plugins directory and then activate them from there.

    How to determine a user's IP address in node

    In your request object there is a property called connection, which is a net.Socket object. The net.Socket object has a property remoteAddress, therefore you should be able to get the IP with this call:

    request.connection.remoteAddress
    

    See documentation for http and net

    EDIT

    As @juand points out in the comments, the correct method to get the remote IP, if the server is behind a proxy, is request.headers['x-forwarded-for']

    How can I use a Python script in the command line without cd-ing to its directory? Is it the PYTHONPATH?

    With PYTHONPATH set as in your example, you should be able to do

    python -m gmbx
    

    -m option will make Python search for your module in paths Python usually searches modules in, including what you added to PYTHONPATH. When you run interpreter like python gmbx.py, it looks for particular file and PYTHONPATH does not apply.

    Entity Framework Migrations renaming tables and columns

    Table names and column names can be specified as part of the mapping of DbContext. Then there is no need to do it in migrations.

    public class MyContext : DbContext
    {
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Restaurant>()
                .HasMany(p => p.Cuisines)
                .WithMany(r => r.Restaurants)
                .Map(mc =>
                {
                    mc.MapLeftKey("RestaurantId");
                    mc.MapRightKey("CuisineId");
                    mc.ToTable("RestaurantCuisines");
                });
         }
    }
    

    Docker container not starting (docker start)

    What I need is to use Docker with MariaDb on different port /3301/ on my Ubuntu machine because I already had MySql installed and running on 3306.

    To do this after half day searching did it using:

    docker run -it -d -p 3301:3306 -v ~/mdbdata/mariaDb:/var/lib/mysql -e MYSQL_ROOT_PASSWORD=root --name mariaDb mariadb
    

    This pulls the image with latest MariaDb, creates container called mariaDb, and run mysql on port 3301. All data of which is located in home directory in /mdbdata/mariaDb.

    To login in mysql after that can use:

    mysql -u root -proot -h 127.0.0.1 -P3301
    

    Used sources are:

    The answer of Iarks in this article /using -it -d was the key :) /

    how-to-install-and-use-docker-on-ubuntu-16-04

    installing-and-using-mariadb-via-docker

    mariadb-and-docker-use-cases-part-1

    Good luck all!

    Get index of a key in json

    Try this

    var json = '{ "key1" : "watevr1", "key2" : "watevr2", "key3" : "watevr3" }';
    json = $.parseJSON(json);
    
    var i = 0, req_index = "";
    $.each(json, function(index, value){
        if(index == 'key2'){
            req_index = i;
        }
        i++;
    });
    alert(req_index);
    

    Android statusbar icons color

    Yes you can change it. but in api 22 and above, using NotificationCompat.Builder and setColorized(true) :

    NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, context.getPackageName())
                    .setContentTitle(title)
                    .setContentText(message)
                    .setSmallIcon(icon, level)
                    .setLargeIcon(largeIcon)
                    .setContentIntent(intent)
                    .setColorized(true)
                    .setDefaults(0)
                    .setCategory(Notification.CATEGORY_SERVICE)
                    .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                    .setPriority(NotificationCompat.PRIORITY_HIGH);