Programs & Examples On #Disabled control

Disable/Enable Submit Button until all forms have been filled

Just use

document.getElementById('submitbutton').disabled = !cansubmit;

instead of the the if-clause that works only one-way.

Also, for the users who have JS disabled, I'd suggest to set the initial disabled by JS only. To do so, just move the script behind the <form> and call checkform(); once.

Disable submit button when form invalid with AngularJS

Selected response is correct, but someone like me, may have issues with async validation with sending request to the server-side - button will be not disabled during given request processing, so button will blink, which looks pretty strange for the users.

To void this, you just need to handle $pending state of the form:

<form name="myForm">
  <input name="myText" type="text" ng-model="mytext" required />
  <button ng-disabled="myForm.$invalid || myForm.$pending">Save</button>
</form>

asp:TextBox ReadOnly=true or Enabled=false?

Think about it from the browser's point of view. For readonly the browser will send in a variable/value pair. For disabled, it won't.

Run this, then look at the URL after you hit submit:

<html>
<form action=foo.html method=get>
<input name=dis type=text disabled value="dis">
<input name=read type=text readonly value="read">
<input name=normal type=text value="normal">
<input type=submit>
</form>
</html>

How to get random value out of an array?

The array_rand function seems to have an uneven distribution on large arrays, not every array item is equally likely to get picked. Using shuffle on the array and then taking the first element doesn't have this problem:

$myArray = array(1, 2, 3, 4, 5);

// Random shuffle
shuffle($myArray);

// First element is random now
$randomValue = $myArray[0];

Can't find the 'libpq-fe.h header when trying to install pg gem

On Arch Linux you will need to install postgresql-libs:

sudo pacman -Syu postgresql-libs

Defining a `required` field in Bootstrap

Try using required="true" in bootstrap 3

is there a tool to create SVG paths from an SVG file?

Open the svg using Inkscape.

Inkscape is a svg editor it is a bit like Illustrator but as it is built specifically for svg it handles it way better. It is a free software and it's available @ https://inkscape.org/en/

  • ctrl A (select all)
  • shift ctrl C (=Path/Object to paths)
  • ctrl s (save (choose as plain svg))

done

all rect/circle have been converted to path

Calling a class method raises a TypeError in Python

You can instantiate the class by declaring a variable and calling the class as if it were a function:

x = mystuff()
print x.average(9,18,27)

However, this won't work with the code you gave us. When you call a class method on a given object (x), it always passes a pointer to the object as the first parameter when it calls the function. So if you run your code right now, you'll see this error message:

TypeError: average() takes exactly 3 arguments (4 given)

To fix this, you'll need to modify the definition of the average method to take four parameters. The first parameter is an object reference, and the remaining 3 parameters would be for the 3 numbers.

Differences Between vbLf, vbCrLf & vbCr Constants

 Constant   Value               Description
 ----------------------------------------------------------------
 vbCr       Chr(13)             Carriage return
 vbCrLf     Chr(13) & Chr(10)   Carriage return–linefeed combination
 vbLf       Chr(10)             Line feed
  • vbCr : - return to line beginning
    Represents a carriage-return character for print and display functions.

  • vbCrLf : - similar to pressing Enter
    Represents a carriage-return character combined with a linefeed character for print and display functions.

  • vbLf : - go to next line
    Represents a linefeed character for print and display functions.


Read More from Constants Class

'ng' is not recognized as an internal or external command, operable program or batch file

What worked for me was that I was missing an file

.npmrc

which is located under

C:\Users\username

That file should contain

prefix=$(APPDATA)\npm

Also my environment path was pointing to my admin user

SMTP connect() failed PHPmailer - PHP

Troubleshooting

You have add this code:

 $mail->SMTPOptions = array(
        'ssl' => array(
            'verify_peer' => false,
            'verify_peer_name' => false,
            'allow_self_signed' => true
        )
    );

And Enabling Allow less secure apps: "will usually solve the problem for PHPMailer, and it does not really make your app significantly less secure. Reportedly, changing this setting may take an hour or more to take effect, so don't expect an immediate fix"

This work for me!

Converting a number with comma as decimal point to float

Assuming they are in a file or array just do the replace as a batch (i.e. on all at once):

$input = str_replace(array('.', ','), array('', '.'), $input); 

and then process the numbers from there taking full advantage of PHP's loosely typed nature.

using nth-child in tables tr td

table tr td:nth-child(2) {
    background: #ccc;
}

Working example: http://jsfiddle.net/gqr3J/

HTML5 form validation pattern alphanumeric with spaces?

It's quite an old question, but in case it could be useful for anyone, starting from a combination of good responses found here, I've ended using this pattern:

pattern="([^\s][A-z0-9À-ž\s]+)"

It will require at least two characters, making sure it does not start with an empty space but allowing spaces between words, and also allowing special characters such as a, ó, ä, ö.

MVC Razor view nested foreach's model

Another much simpler possibility is that one of your property names is wrong (probably one you just changed in the class). This is what it was for me in RazorPages .NET Core 3.

How to solve java.lang.NoClassDefFoundError?

My two cents in this chain:

Ensure that the classpath contains full paths (/home/user/lib/some_lib.jar instead of ~/lib/some_lib.jar) otherwise you can still face NoClassDefFoundError error.

How to open, read, and write from serial port in C?

For demo code that conforms to POSIX standard as described in Setting Terminal Modes Properly and Serial Programming Guide for POSIX Operating Systems, the following is offered.
This code should execute correctly using Linux on x86 as well as ARM (or even CRIS) processors.
It's essentially derived from the other answer, but inaccurate and misleading comments have been corrected.

This demo program opens and initializes a serial terminal at 115200 baud for non-canonical mode that is as portable as possible.
The program transmits a hardcoded text string to the other terminal, and delays while the output is performed.
The program then enters an infinite loop to receive and display data from the serial terminal.
By default the received data is displayed as hexadecimal byte values.

To make the program treat the received data as ASCII codes, compile the program with the symbol DISPLAY_STRING, e.g.

 cc -DDISPLAY_STRING demo.c

If the received data is ASCII text (rather than binary data) and you want to read it as lines terminated by the newline character, then see this answer for a sample program.


#define TERMINAL    "/dev/ttyUSB0"

#include <errno.h>
#include <fcntl.h> 
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <termios.h>
#include <unistd.h>

int set_interface_attribs(int fd, int speed)
{
    struct termios tty;

    if (tcgetattr(fd, &tty) < 0) {
        printf("Error from tcgetattr: %s\n", strerror(errno));
        return -1;
    }

    cfsetospeed(&tty, (speed_t)speed);
    cfsetispeed(&tty, (speed_t)speed);

    tty.c_cflag |= (CLOCAL | CREAD);    /* ignore modem controls */
    tty.c_cflag &= ~CSIZE;
    tty.c_cflag |= CS8;         /* 8-bit characters */
    tty.c_cflag &= ~PARENB;     /* no parity bit */
    tty.c_cflag &= ~CSTOPB;     /* only need 1 stop bit */
    tty.c_cflag &= ~CRTSCTS;    /* no hardware flowcontrol */

    /* setup for non-canonical mode */
    tty.c_iflag &= ~(IGNBRK | BRKINT | PARMRK | ISTRIP | INLCR | IGNCR | ICRNL | IXON);
    tty.c_lflag &= ~(ECHO | ECHONL | ICANON | ISIG | IEXTEN);
    tty.c_oflag &= ~OPOST;

    /* fetch bytes as they become available */
    tty.c_cc[VMIN] = 1;
    tty.c_cc[VTIME] = 1;

    if (tcsetattr(fd, TCSANOW, &tty) != 0) {
        printf("Error from tcsetattr: %s\n", strerror(errno));
        return -1;
    }
    return 0;
}

void set_mincount(int fd, int mcount)
{
    struct termios tty;

    if (tcgetattr(fd, &tty) < 0) {
        printf("Error tcgetattr: %s\n", strerror(errno));
        return;
    }

    tty.c_cc[VMIN] = mcount ? 1 : 0;
    tty.c_cc[VTIME] = 5;        /* half second timer */

    if (tcsetattr(fd, TCSANOW, &tty) < 0)
        printf("Error tcsetattr: %s\n", strerror(errno));
}


int main()
{
    char *portname = TERMINAL;
    int fd;
    int wlen;
    char *xstr = "Hello!\n";
    int xlen = strlen(xstr);

    fd = open(portname, O_RDWR | O_NOCTTY | O_SYNC);
    if (fd < 0) {
        printf("Error opening %s: %s\n", portname, strerror(errno));
        return -1;
    }
    /*baudrate 115200, 8 bits, no parity, 1 stop bit */
    set_interface_attribs(fd, B115200);
    //set_mincount(fd, 0);                /* set to pure timed read */

    /* simple output */
    wlen = write(fd, xstr, xlen);
    if (wlen != xlen) {
        printf("Error from write: %d, %d\n", wlen, errno);
    }
    tcdrain(fd);    /* delay for output */


    /* simple noncanonical input */
    do {
        unsigned char buf[80];
        int rdlen;

        rdlen = read(fd, buf, sizeof(buf) - 1);
        if (rdlen > 0) {
#ifdef DISPLAY_STRING
            buf[rdlen] = 0;
            printf("Read %d: \"%s\"\n", rdlen, buf);
#else /* display hex */
            unsigned char   *p;
            printf("Read %d:", rdlen);
            for (p = buf; rdlen-- > 0; p++)
                printf(" 0x%x", *p);
            printf("\n");
#endif
        } else if (rdlen < 0) {
            printf("Error from read: %d: %s\n", rdlen, strerror(errno));
        } else {  /* rdlen == 0 */
            printf("Timeout from read\n");
        }               
        /* repeat read to get full message */
    } while (1);
}

For an example of an efficient program that provides buffering of received data yet allows byte-by-byte handing of the input, then see this answer.


Add default value of datetime field in SQL Server to a timestamp

While the marked answer is correct with:

ALTER TABLE YourTable ADD CONSTRAINT DF_YourTable DEFAULT GETDATE() FOR YourColumn

You should always be aware of timezones when adding default datetime values in to a column.

Say for example, this datetime value is designed to indicate when a member joined a website and you want it to be displayed back to the user, GETDATE() will give you the server time so could show discrepancies if the user is in a different locale to the server.

If you expect to deal with international users, it is better in some cases to use GETUTCDATE(), which:

Returns the current database system timestamp as a datetime value. The database time zone offset is not included. This value represents the current UTC time (Coordinated Universal Time). This value is derived from the operating system of the computer on which the instance of SQL Server is running.

ALTER TABLE YourTable ADD CONSTRAINT DF_YourTable DEFAULT GETUTCDATE() FOR YourColumn

When retrieving the values, the front end application/website should transform this value from UTC time to the locale/culture of the user requesting it.

SELECT only rows that contain only alphanumeric characters in MySQL

There is also this:

select m from table where not regexp_like(m, '^[0-9]\d+$')

which selects the rows that contains characters from the column you want (which is m in the example but you can change).

Most of the combinations don't work properly in Oracle platforms but this does. Sharing for future reference.

Case Statement Equivalent in R

i dont like any of these, they are not clear to the reader or the potential user. I just use an anonymous function, the syntax is not as slick as a case statement, but the evaluation is similar to a case statement and not that painful. this also assumes your evaluating it within where your variables are defined.

result <- ( function() { if (x==10 | y< 5) return('foo') 
                         if (x==11 & y== 5) return('bar')
                        })()

all of those () are necessary to enclose and evaluate the anonymous function.

Declare a dictionary inside a static class

The correct syntax ( as tested in VS 2008 SP1), is this:

public static class ErrorCode
{
    public static IDictionary<string, string> ErrorCodeDic;
     static ErrorCode()
    {
        ErrorCodeDic = new Dictionary<string, string>()
            { {"1", "User name or password problem"} };
    }
}

Plugin org.apache.maven.plugins:maven-compiler-plugin or one of its dependencies could not be resolved

I was getting this problem when using IBM RSA 9.6.1 when building a brand new development machine. The problem for me ended up being because of HTTPS on the Global Maven repository. My solution was to create a Maven settings.xml that forced it to use HTTP.

The key to me was that the central repository was empty when I exploded it under Maven Repositories -- > Global Repositories

Using the following settings file worked for me:

<settings>
  <activeProfiles>
    <!--make the profile active all the time -->
    <activeProfile>insecurecentral</activeProfile>
  </activeProfiles>
  <profiles>
    <profile>
      <id>insecurecentral</id>
      <!--Override the repository (and pluginRepository) "central" from the Maven Super POM -->
      <repositories>
        <repository>
          <id>central</id>
          <url>http://repo.maven.apache.org/maven2</url>
          <releases>
            <enabled>true</enabled>
          </releases>
        </repository>
      </repositories>
      <pluginRepositories>
        <pluginRepository>
          <id>central</id>
          <url>http://repo.maven.apache.org/maven2</url>
          <releases>
            <enabled>true</enabled>
          </releases>
        </pluginRepository>
      </pluginRepositories>
    </profile>
  </profiles>
</settings>

I got the idea from this stackoverflow question.

Why is a ConcurrentModificationException thrown and how to debug it

I ran into this exception when try to remove x last items from list. myList.subList(lastIndex, myList.size()).clear(); was the only solution that worked for me.

How to exclude *AutoConfiguration classes in Spring Boot JUnit tests?

I think that the best solution currently for springBoot 2.0 is using profiles

@RunWith(SpringRunner.class)
@SpringBootTest(classes = Application.class, webEnvironment = WebEnvironment.DEFINED_PORT)
@ActiveProfiles("test")
public class ExcludeAutoConfigIntegrationTest {
    // ...
} 

spring.autoconfigure.exclude=org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration

anyway in the following link give 6 different alternatives to solve this.

R * not meaningful for factors ERROR

new[,2] is a factor, not a numeric vector. Transform it first

new$MY_NEW_COLUMN <-as.numeric(as.character(new[,2])) * 5

How to make Sonar ignore some classes for codeCoverage metric?

For me this worked (basically pom.xml level global properties):

<properties>
    <sonar.exclusions>**/Name*.java</sonar.exclusions>
</properties>

According to: http://docs.sonarqube.org/display/SONAR/Narrowing+the+Focus#NarrowingtheFocus-Patterns

It appears you can either end it with ".java" or possibly "*"

to get the java classes you're interested in.

Difference between classification and clustering in data mining?

I believe classification is classifying records in a data set into predefined classes or even defining classes on the go. I look at it as pre-requisite for any valuable data mining, I like to think of it at unsupervised learning i.e. one does not know what he/she is looking for while mining the data and classification serves as a good starting point

Clustering on the other end falls under supervised learning i.e. one know what parameters to look for, the correlation between them along with critical levels. I believe it requires some understanding of statistics and maths

How do I handle Database Connections with Dapper in .NET?

I wrap connection with the helper class:

public class ConnectionFactory
{
    private readonly string _connectionName;

    public ConnectionFactory(string connectionName)
    {
        _connectionName = connectionName;
    }

    public IDbConnection NewConnection() => new SqlConnection(_connectionName);

    #region Connection Scopes

    public TResult Scope<TResult>(Func<IDbConnection, TResult> func)
    {
        using (var connection = NewConnection())
        {
            connection.Open();
            return func(connection);
        }
    }

    public async Task<TResult> ScopeAsync<TResult>(Func<IDbConnection, Task<TResult>> funcAsync)
    {
        using (var connection = NewConnection())
        {
            connection.Open();
            return await funcAsync(connection);
        }
    }

    public void Scope(Action<IDbConnection> func)
    {
        using (var connection = NewConnection())
        {
            connection.Open();
            func(connection);
        }
    }

    public async Task ScopeAsync<TResult>(Func<IDbConnection, Task> funcAsync)
    {
        using (var connection = NewConnection())
        {
            connection.Open();
            await funcAsync(connection);
        }
    }

    #endregion Connection Scopes
}

Examples of usage:

public class PostsService
{
    protected IConnectionFactory Connection;

    // Initialization here ..

    public async Task TestPosts_Async()
    {
        // Normal way..
        var posts = Connection.Scope(cnn =>
        {
            var state = PostState.Active;
            return cnn.Query<Post>("SELECT * FROM [Posts] WHERE [State] = @state;", new { state });
        });

        // Async way..
        posts = await Connection.ScopeAsync(cnn =>
        {
            var state = PostState.Active;
            return cnn.QueryAsync<Post>("SELECT * FROM [Posts] WHERE [State] = @state;", new { state });
        });
    }
}

So I don't have to explicitly open the connection every time. Additionally, you can use it this way for the convenience' sake of the future refactoring:

var posts = Connection.Scope(cnn =>
{
    var state = PostState.Active;
    return cnn.Query<Post>($"SELECT * FROM [{TableName<Post>()}] WHERE [{nameof(Post.State)}] = @{nameof(state)};", new { state });
});

What is TableName<T>() can be found in this answer.

Kotlin Error : Could not find org.jetbrains.kotlin:kotlin-stdlib-jre7:1.0.7

replace

implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:$kotlin_version"

with

implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"

Since the version with jre is absolute , just replace and sync the project

Official Documentation here Thanks for the link @ ROMANARMY

Happy Coding :)

How to acces external json file objects in vue.js app

I have recently started working on a project using Vue JS, JSON Schema. I am trying to access nested JSON Objects from a JSON Schema file in the Vue app. I tried the below code and now I can load different JSON objects inside different Vue template tags. In the script tag add the below code

import  {JsonObject1name, JsonObject2name} from 'your Json file path';

Now you can access JsonObject1,2 names in data section of export default part as below:

data: () => ({ 
  
  schema: JsonObject1name,
  schema1: JsonObject2name,   
  
  model: {} 
}),

Now you can load the schema, schema1 data inside Vue template according to your requirement. See below code for example :

      <SchemaForm id="unique name representing your Json object1" class="form"  v-model="model" :schema="schema" :components="components">
      </SchemaForm>  

      <SchemaForm id="unique name representing your Json object2" class="form" v-model="model" :schema="schema1" :components="components">
      </SchemaForm>

SchemaForm is the local variable name for @formSchema/native library. I have implemented the data of different JSON objects through forms in different CSS tabs.

I hope this answer helps someone. I can help if there are any questions.

MySql Table Insert if not exist otherwise update

Jai is correct that you should use INSERT ... ON DUPLICATE KEY UPDATE.

Note that you do not need to include datenum in the update clause since it's the unique key, so it should not change. You do need to include all of the other columns from your table. You can use the VALUES() function to make sure the proper values are used when updating the other columns.

Here is your update re-written using the proper INSERT ... ON DUPLICATE KEY UPDATE syntax for MySQL:

INSERT INTO AggregatedData (datenum,Timestamp)
VALUES ("734152.979166667","2010-01-14 23:30:00.000")
ON DUPLICATE KEY UPDATE 
  Timestamp=VALUES(Timestamp)

How to add multiple values to a dictionary key in python?

How about

a["abc"] = [1, 2]

This will result in:

>>> a
{'abc': [1, 2]}

Is that what you were looking for?

Export and import table dump (.sql) using pgAdmin

An another way, you can do it easily with CMD on Windows

Put your installed version (mine is 11).

cd C:\Program Files\PostgreSQL\11\bin\

and run simple query

psql -U <postgre_username> -d <db_name> < <C:\path\data_dump.sql>

enter password then wait the final console message.

Change WPF window background image in C# code

img.UriSource = new Uri("pack://application:,,,/images/" + fileName, UriKind.Absolute);

Eclipse reports rendering library more recent than ADT plug-in

The Reason for Warning is your using Old ADT (Android development tools), so Update your ADT by following the procedures below

Procedure 1:

  1. Inside Eclipse Click Help menu
  2. Choose Check for Updates
  3. It will show Required Updates in that window choose All options using Check box or else choose ADT Updated.

enter image description here

Procedure 2:

Click Help > Install New Software. In the Work with field, enter: https://dl-ssl.google.com/android/eclipse/ Select Developer Tools / Android Development Tools. Click Next and complete the wizard.

How do I clear the content of a div using JavaScript?

You can do it the DOM way as well:

var div = document.getElementById('cart_item');
while(div.firstChild){
    div.removeChild(div.firstChild);
}

What is the --save option for npm install?

npm install --save or npm install --save-dev why we choose 1 options between this two while installing package in our project.

things is clear from the above answers that npm install --save will add entry in the dependency field in pacakage.json file and other one in dev-dependency.

So question arises why we need entry of our installing module in pacakge.json file because whenever we check-in code in git or giving our code to some one we always give it or check it without node-modules because it is very large in size and also available at common place so to avoid this we do that.

so then how other person will get all the modules that is specifically or needed for that project so answers is from the package.json file that have the entry of all the required packages for running or developing that project.

so after getting the code we simply need to run the npm install command it will read the package.json file and install the necessary required packages.

Github: Can I see the number of downloads for a repo?

Answer from 2019:

  1. For number of clones you can use https://developer.github.com/v3/repos/traffic/#clones (but be aware that it returns count only for last 14 days)
  2. For get downloads number of your assets (files attached to the release), you can use https://developer.github.com/v3/repos/releases/#get-a-single-release (exactly "download_count" property of the items of assets list in response)

Get drop down value

Use the value property of the <select> element. For example:

var value = document.getElementById('your_select_id').value;
alert(value);

Proper way to empty a C-String

Depends on what you mean by emptying. If you just want an empty string, you could do

buffer[0] = 0;

If you want to set every element to zero, do

memset(buffer, 0, 80);

Create HTML table using Javascript

The problem is that if you try to write a <table> or a <tr> or <td> tag using JS every time you insert a new tag the browser will try to close it as it will think that there is an error on the code.

Instead of writing your table line by line, concatenate your table into a variable and insert it once created:

<script language="javascript" type="text/javascript">
<!--

var myArray    = new Array();
    myArray[0] = 1;
    myArray[1] = 2.218;
    myArray[2] = 33;
    myArray[3] = 114.94;
    myArray[4] = 5;
    myArray[5] = 33;
    myArray[6] = 114.980;
    myArray[7] = 5;

    var myTable= "<table><tr><td style='width: 100px; color: red;'>Col Head 1</td>";
    myTable+= "<td style='width: 100px; color: red; text-align: right;'>Col Head 2</td>";
    myTable+="<td style='width: 100px; color: red; text-align: right;'>Col Head 3</td></tr>";

    myTable+="<tr><td style='width: 100px;                   '>---------------</td>";
    myTable+="<td     style='width: 100px; text-align: right;'>---------------</td>";
    myTable+="<td     style='width: 100px; text-align: right;'>---------------</td></tr>";

  for (var i=0; i<8; i++) {
    myTable+="<tr><td style='width: 100px;'>Number " + i + " is:</td>";
    myArray[i] = myArray[i].toFixed(3);
    myTable+="<td style='width: 100px; text-align: right;'>" + myArray[i] + "</td>";
    myTable+="<td style='width: 100px; text-align: right;'>" + myArray[i] + "</td></tr>";
  }  
   myTable+="</table>";

 document.write( myTable);

//-->
</script> 

If your code is in an external JS file, in HTML create an element with an ID where you want your table to appear:

<div id="tablePrint"> </div>

And in JS instead of document.write(myTable) use the following code:

document.getElementById('tablePrint').innerHTML = myTable;

How to get files in a relative path in C#

Write it like this:

string[] files = Directory.GetFiles(@".\Archive", "*.zip");

. is for relative to the folder where you started your exe, and @ to allow \ in the name.

When using filters, you pass it as a second parameter. You can also add a third parameter to specify if you want to search recursively for the pattern.

In order to get the folder where your .exe actually resides, use:

var executingPath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);

Detect the Internet connection is offline?

 if(navigator.onLine){
  alert('online');
 } else {
  alert('offline');
 }

How to convert Java String to JSON Object

Converting the String to JsonNode using ObjectMapper object :

ObjectMapper mapper = new ObjectMapper();

// For text string
JsonNode = mapper.readValue(mapper.writeValueAsString("Text-string"), JsonNode.class)

// For Array String
JsonNode = mapper.readValue("[\"Text-Array\"]"), JsonNode.class)

// For Json String 
String json = "{\"id\" : \"1\"}";
ObjectMapper mapper = new ObjectMapper();
JsonFactory factory = mapper.getFactory();
JsonParser jsonParser = factory.createParser(json);
JsonNode node = mapper.readTree(jsonParser);

How to do something to each file in a directory with a batch script

I had some malware that marked all files in a directory as hidden/system/readonly. If anyone else finds themselves in this situation, cd into the directory and run for /f "delims=|" %f in ('forfiles') do attrib -s -h -r %f.

Return Boolean Value on SQL Select Statement

I do it like this:

SELECT 1 FROM [dbo].[User] WHERE UserID = 20070022

Seeing as a boolean can never be null (at least in .NET), it should default to false or you can set it to that yourself if it's defaulting true. However 1 = true, so null = false, and no extra syntax.

Note: I use Dapper as my micro orm, I'd imagine ADO should work the same.

Merge unequal dataframes and replace missing rows with 0

Take a look at the help page for merge. The all parameter lets you specify different types of merges. Here we want to set all = TRUE. This will make merge return NA for the values that don't match, which we can update to 0 with is.na():

zz <- merge(df1, df2, all = TRUE)
zz[is.na(zz)] <- 0

> zz
  x y
1 a 0
2 b 1
3 c 0
4 d 0
5 e 0

Updated many years later to address follow up question

You need to identify the variable names in the second data table that you aren't merging on - I use setdiff() for this. Check out the following:

df1 = data.frame(x=c('a', 'b', 'c', 'd', 'e', NA))
df2 = data.frame(x=c('a', 'b', 'c'),y1 = c(0,1,0), y2 = c(0,1,0))

#merge as before
df3 <- merge(df1, df2, all = TRUE)
#columns in df2 not in df1
unique_df2_names <- setdiff(names(df2), names(df1))
df3[unique_df2_names][is.na(df3[, unique_df2_names])] <- 0 

Created on 2019-01-03 by the reprex package (v0.2.1)

.NET Events - What are object sender & EventArgs e?

Manually cast the sender to the type of your custom control, and then use it to delete or disable etc. Eg, something like this:

private void myCustomControl_Click(object sender, EventArgs e)
{
  ((MyCustomControl)sender).DoWhatever();
}

The 'sender' is just the object that was actioned (eg clicked).

The event args is subclassed for more complex controls, eg a treeview, so that you can know more details about the event, eg exactly where they clicked.

How to extract numbers from string in c?

You can do it with strtol, like this:

char *str = "ab234cid*(s349*(20kd", *p = str;
while (*p) { // While there are more characters to process...
    if ( isdigit(*p) || ( (*p=='-'||*p=='+') && isdigit(*(p+1)) )) {
        // Found a number
        long val = strtol(p, &p, 10); // Read number
        printf("%ld\n", val); // and print it.
    } else {
        // Otherwise, move on to the next character.
        p++;
    }
}

Link to ideone.

How to call a function after a div is ready?

Through jQuery.ready function you can specify function that's executed when DOM is loaded. Whole DOM, not any div you want.

So, you should use ready in a bit different way

$.ready(function() {
    createGrid();
});

This is in case when you dont use AJAX to load your div

Error Code: 1290. The MySQL server is running with the --secure-file-priv option so it cannot execute this statement

If you changed my.ini and restarted mysql and you still get this error please check your file path and replace "\" to "/". I solved my proplem after replacing.

XSS prevention in JSP/Servlet web application

If you want to make sure that your $ operator does not suffer from XSS hack you can implement ServletContextListener and do some checks there.

The complete solution at: http://pukkaone.github.io/2011/01/03/jsp-cross-site-scripting-elresolver.html

@WebListener
public class EscapeXmlELResolverListener implements ServletContextListener {
    private static final Logger LOG = LoggerFactory.getLogger(EscapeXmlELResolverListener.class);


    @Override
    public void contextInitialized(ServletContextEvent event) {
        LOG.info("EscapeXmlELResolverListener initialized ...");        
        JspFactory.getDefaultFactory()
                .getJspApplicationContext(event.getServletContext())
                .addELResolver(new EscapeXmlELResolver());

    }

    @Override
    public void contextDestroyed(ServletContextEvent event) {
        LOG.info("EscapeXmlELResolverListener destroyed");
    }


    /**
     * {@link ELResolver} which escapes XML in String values.
     */
    public class EscapeXmlELResolver extends ELResolver {

        private ThreadLocal<Boolean> excludeMe = new ThreadLocal<Boolean>() {
            @Override
            protected Boolean initialValue() {
                return Boolean.FALSE;
            }
        };

        @Override
        public Object getValue(ELContext context, Object base, Object property) {

            try {
                    if (excludeMe.get()) {
                        return null;
                    }

                    // This resolver is in the original resolver chain. To prevent
                    // infinite recursion, set a flag to prevent this resolver from
                    // invoking the original resolver chain again when its turn in the
                    // chain comes around.
                    excludeMe.set(Boolean.TRUE);
                    Object value = context.getELResolver().getValue(
                            context, base, property);

                    if (value instanceof String) {
                        value = StringEscapeUtils.escapeHtml4((String) value);
                    }
                    return value;
            } finally {
                excludeMe.remove();
            }
        }

        @Override
        public Class<?> getCommonPropertyType(ELContext context, Object base) {
            return null;
        }

        @Override
        public Iterator<FeatureDescriptor> getFeatureDescriptors(ELContext context, Object base){
            return null;
        }

        @Override
        public Class<?> getType(ELContext context, Object base, Object property) {
            return null;
        }

        @Override
        public boolean isReadOnly(ELContext context, Object base, Object property) {
            return true;
        }

        @Override
        public void setValue(ELContext context, Object base, Object property, Object value){
            throw new UnsupportedOperationException();
        }

    }

}

Again: This only guards the $. Please also see other answers.

Add all files to a commit except a single file?

I use git add --patch quite a bit and wanted something like this to avoid having to hit d all the time through the same files. I whipped up a very hacky couple of git aliases to get the job done:

[alias]
    HELPER-CHANGED-FILTERED = "!f() { git status --porcelain | cut -c4- | ( [[ \"$1\" ]] && egrep -v \"$1\" || cat ); }; f"
    ap                      = "!git add --patch -- $(git HELPER-CHANGED-FILTERED 'min.(js|css)$' || echo 'THIS_FILE_PROBABLY_DOESNT_EXIST' )"

In my case I just wanted to ignore certain minified files all the time, but you could make it use an environment variable like $GIT_EXCLUDE_PATTERN for a more general use case.

jQuery .attr("disabled", "disabled") not working in Chrome

Mostly disabled attribute doesn't work with the anchor tags from HTML-5 onwards. Hence we have change it to ,let's say 'button' and style it accordingly with appropriate color,border-style etc. That's the most apt solution for any similar issue users are facing in Chrome . Only few elements support 'disabled' attribute: Span , select, option, textarea, input , button.

What is an optional value in Swift?

When i started to learn Swift it was very difficult to realize why optional.

Lets think in this way. Let consider a class Person which has two property name and company.

class Person: NSObject {
    
    var name : String //Person must have a value so its no marked as optional
    var companyName : String? ///Company is optional as a person can be unemployed that is nil value is possible
    
    init(name:String,company:String?) {
        
        self.name = name
        self.companyName = company
        
    }
}

Now lets create few objects of Person

var tom:Person = Person.init(name: "Tom", company: "Apple")//posible
var bob:Person = Person.init(name: "Bob", company:nil) // also Possible because company is marked as optional so we can give Nil

But we can not pass Nil to name

var personWithNoName:Person = Person.init(name: nil, company: nil)

Now Lets talk about why we use optional?. Lets consider a situation where we want to add Inc after company name like apple will be apple Inc. We need to append Inc after company name and print.

print(tom.companyName+" Inc") ///Error saying optional is not unwrapped.
print(tom.companyName!+" Inc") ///Error Gone..we have forcefully unwrap it which is wrong approach..Will look in Next line
print(bob.companyName!+" Inc") ///Crash!!!because bob has no company and nil can be unwrapped.

Now lets study why optional takes into place.

if let companyString:String = bob.companyName{///Compiler safely unwrap company if not nil.If nil,no unwrap.
    
    print(companyString+" Inc") //Will never executed and no crash!!!
}

Lets replace bob with tom

if let companyString:String = tom.companyName{///Compiler safely unwrap company if not nil.If nil,no unwrap.
    
    print(companyString+" Inc") //Will executed and no crash!!!
}

And Congratulation! we have properly deal with optional?

So the realization points are

  1. We will mark a variable as optional if its possible to be nil
  2. If we want to use this variable somewhere in code compiler will remind you that we need to check if we have proper deal with that variable if it contain nil.

Thank you...Happy Coding

How to remove button shadow (android)

Another alternative is to add

style="?android:attr/borderlessButtonStyle"

to your Button xml as documented here http://developer.android.com/guide/topics/ui/controls/button.html

An example would be

<Button
android:id="@+id/button_send"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/button_send"
android:onClick="sendMessage"
style="?android:attr/borderlessButtonStyle" />

OnChange event using React JS for drop down

Thank you Felix Kling, but his answer need a little change:

var MySelect = React.createClass({
 getInitialState: function() {
     return {
         value: 'select'
     }
 },
 change: function(event){
     this.setState({value: event.target.value});
 },
 render: function(){
    return(
       <div>
           <select id="lang" onChange={this.change.bind(this)} value={this.state.value}>
              <option value="select">Select</option>
              <option value="Java">Java</option>
              <option value="C++">C++</option>
           </select>
           <p></p>
           <p>{this.state.value}</p>
       </div>
    );
 }
});
React.render(<MySelect />, document.body); 

JavaScript .replace only replaces first Match

From w3schools

The replace() method searches for a match between a substring (or regular expression) and a string, and replaces the matched substring with a new substring

Would be better to use a regex here then:

textTitle.replace(/ /g, '%20');

How to go up a level in the src path of a URL in HTML?

Supposing you have the following file structure:

-css
  --index.css
-images
  --image1.png
  --image2.png
  --image3.png

In CSS you can access image1, for example, using the line ../images/image1.png.

NOTE: If you are using Chrome, it may doesn't work and you will get an error that the file could not be found. I had the same problem, so I just deleted the entire cache history from chrome and it worked.

how to fire event on file select

<input type="file" @change="onFileChange" class="input upload-input" ref="inputFile"/>

onFileChange(e) {
    //upload file and then delete it from input 
    self.$refs.inputFile.value = ''
}

The network adapter could not establish the connection - Oracle 11g

I had the similar issue. its resolved for me with a simple command.

lsnrctl start

The Network Adapter exception is caused because:

  1. The database host name or port number is wrong (OR)
  2. The database TNSListener has not been started. The TNSListener may be started with the lsnrctl utility.

Try to start the listener using the command prompt:

  1. Click Start, type cmd in the search field, and when cmd shows up in the list of options, right click it and select ‘Run as Administrator’.
  2. At the Command Prompt window, type lsnrctl start without the quotes and press Enter.
  3. Type Exit and press Enter.

Hope it helps.

Regular expression to match numbers with or without commas and decimals in text

\d+(,\d+)*(\.\d+)?

This assumes that there is always at least one digit before or after any comma or decimal and also assumes that there is at most one decimal and that all the commas precede the decimal.

Generating random numbers with normal distribution in Excel

Rand() does generate a uniform distribution of random numbers between 0 and 1, but the norminv (or norm.inv) function is taking the uniform distributed Rand() as an input to generate the normally distributed sample set.

Group By Eloquent ORM

Eloquent uses the query builder internally, so you can do:

$users = User::orderBy('name', 'desc')
                ->groupBy('count')
                ->having('count', '>', 100)
                ->get();

Using global variables between files?

You can think of Python global variables as "module" variables - and as such they are much more useful than the traditional "global variables" from C.

A global variable is actually defined in a module's __dict__ and can be accessed from outside that module as a module attribute.

So, in your example:

# ../myproject/main.py

# Define global myList
# global myList  - there is no "global" declaration at module level. Just inside
# function and methods
myList = []

# Imports
import subfile

# Do something
subfile.stuff()
print(myList[0])

And:

# ../myproject/subfile.py

# Save "hey" into myList
def stuff():
     # You have to make the module main available for the 
     # code here.
     # Placing the import inside the function body will
     # usually avoid import cycles - 
     # unless you happen to call this function from 
     # either main or subfile's body (i.e. not from inside a function or method)
     import main
     main.mylist.append("hey")

How to activate a specific worksheet in Excel?

Would the following Macro help you?

Sub activateSheet(sheetname As String)
'activates sheet of specific name
    Worksheets(sheetname).Activate
End Sub

Basically you want to make use of the .Activate function. Or you can use the .Select function like so:

Sub activateSheet(sheetname As String)
'selects sheet of specific name
    Sheets(sheetname).Select
End Sub

Regular Expression to get a string between parentheses in Javascript

Ported Mr_Green's answer to a functional programming style to avoid use of temporary global variables.

var matches = string2.split('[')
  .filter(function(v){ return v.indexOf(']') > -1})
  .map( function(value) { 
    return value.split(']')[0]
  })

Finding row index containing maximum value using R

See ?order. You just need the last index (or first, in decreasing order), so this should do the trick:

order(matrix[,2],decreasing=T)[1]

What's the difference between Apache's Mesos and Google's Kubernetes

"I understand both are server cluster management software."

This statement isn't entirely true. Kubernetes doesn't manage server clusters, it orchestrates containers such that they work together with minimal hassle and exposure. Kubernetes allows you to define parts of your application as "pods" (one or more containers) that are delivered by "deployments" or "daemon sets" (and a few others) and exposed to the outside world via services. However, Kubernetes doesn't manage the cluster itself (there are tools that can provision, configure and scale clusters for you, but those are not part of Kubernetes itself).

Mesos on the other hand comes closer to "cluster management" in that it can control what's running where, but not just in terms of scheduling containers. Mesos also manages standalone software running on the cluster servers. Even though it's mostly used as an alternative to Kubernetes, Mesos can easily work with Kubernetes as while the functionality overlaps in many areas, Mesos can do more (but on the overlapping parts Kubernetes tends to be better).

Convert a date format in PHP

Use:

implode('-', array_reverse(explode('-', $date)));

Without the date conversion overhead, I am not sure it'll matter much.

What Vim command(s) can be used to quote/unquote words?

VIM for vscode does it awsomely. It's based one vim-surround if you don't use vscode.

Some examples:

"test" with cursor inside quotes type cs"' to end up with 'test'

"test" with cursor inside quotes type ds" to end up with test

"test" with cursor inside quotes type cs"t and enter 123> to end up with <123>test

test with cursor on word test type ysaw) to end up with (test)

Permission denied on CopyFile in VBS

Another thing to check is if any applications still have a hold on the file.

Had some issues with MoveFile. Part of my permissions problem was that my script opens the file (in this case in Excel), makes a modification, closes it, then moves it to a "processed" folder.

In debugging a couple things, the script crashed a few times. Digging into the permission denied error I found that I had 4 instances of Excel running in the background because the script was never able to properly terminate the application due to said crashes. Apparently one of them still had a hold on the file and, thusly, "permission denied."

How to use _CRT_SECURE_NO_WARNINGS

Under "Project -> Properties -> C/C++ -> Preprocessor -> Preprocessor Definitions" add _CRT_SECURE_NO_WARNINGS

mysqld: Can't change dir to data. Server doesn't start

In my case, I had installed the data directory to a different location. So the data directory really wasn't in the default location. Therefore, when I ran the mysqld command from the command prompt, I had to specify the data directory manually:

mysqld --datadir=D:/MySQLData/Data

Here's the documentation for mysqld command-line arguments.

How can I protect my .NET assemblies from decompilation?

One thing to keep in mind is that you want to do this in a way that makes business sense. To do that, you need to define your goals. So, exactly what are your goals?

Preventing piracy? That goal is not achievable. Even native code can be decompiled or cracked; the multitude of warez available online (even for products like Windows and Photoshop) is proof a determined hacker can always gain access.

If you can't prevent piracy, then how about merely reducing it? This, too, is misguided. It only takes one person cracking your code for it to be available to everyone. You have to be lucky every time. The pirates only have to be lucky once.

I put it to you the goal should be to maximize profits. You appear to believe that stopping piracy is necessary to this endeavor. It is not. Profit is simply revenue minus costs. Stopping piracy increases costs. It takes effort, which means adding cost somewhere in the process, and so reduces that side of the equation. Protecting your product also fails to increase your revenue. I know you look at all those pirates and see all the money you could make if only they would pay your license fees instead, but the reality is this will never happen. There is some hyperbole here, but it generally holds that pirates who are unable to crack your security will either find a similar product they can crack or do without. They will never buy it instead, and therefore they do not represent lost sales.

Additionally, securing your product actually reduces revenue. There are two reasons for this. One is the small percentage of customers who have trouble with your activation or security, and therefore decide not to buy again or ask for their money back. The other is the small percentage of people who actually try a pirated version of software to make sure it works before buying. Limiting the pirated distribution of your product (if you are somehow able to succeed at this) prevents these people from ever trying your product, and so they will never buy it. Moreover, piracy can also help your product spread to a wider audience, thus reaching more people who will be willing to pay for it.

A better strategy is to assume that your product will be pirated, and think about ways to take advantage of the situation. A couple more links on the topic:
How do i prevent my code from being stolen?
Securing a .NET Application

The easiest way to replace white spaces with (underscores) _ in bash

You can do it using only the shell, no need for tr or sed

$ str="This is just a test"
$ echo ${str// /_}
This_is_just_a_test

"No X11 DISPLAY variable" - what does it mean?

Very Easy, Had this same problem then what i did was to download and install an app that would help in displaying then fixed the error.

Download this app xming:

http://sourceforge.net/project/downloading.php?

Install, then use settings on this link:

http://www.geo.mtu.edu/geoschem/docs/putty_install.html or follow this steps:

Installing/Configuring PuTTy and Xming

Once PuTTy and Xming have been downloaded to the PC, install according to their respective instructions.

Configuring Xming

Once Xming is installed, run the application called 'XLaunch' and verify that the settings are as shown:

  • select Default entries on Display Settings windows, click next
  • click next on Session Type window.
  • click next on Additional parameters window(Notice clipboard checkbox is true)
  • save configuration and click to finish.

Configuring PuTTy

After installing PuTTy, double-click on the PuTTy icon on the desktop and configure as shown:

This shows creating a login profile then saving it.

  • On ssh -> X11, click on checkbox to enable X11 forwarding.
  • on X display location textbox, type localhost:0.0

save profile then connect remotely to server to test.

Cheers!!!

macro run-time error '9': subscript out of range

"Subscript out of range" indicates that you've tried to access an element from a collection that doesn't exist. Is there a "Sheet1" in your workbook? If not, you'll need to change that to the name of the worksheet you want to protect.

How to reload a page after the OK click on the Alert Page

use confirm box instead....

    var r = confirm("Successful Message!");
    if (r == true){
      window.location.reload();
    }

Docker - Ubuntu - bash: ping: command not found

Alternatively you can use a Docker image which already has ping installed, e.g. busybox:

docker run --rm busybox ping SERVER_NAME -c 2

HTTP Error 404 when running Tomcat from Eclipse

First, stop your Tomcat, then double click your server, click Server Locations and check Use Tomcat Installation (takes control of Tomcat installation).

What is an IIS application pool?

Assume scenario where swimmers swim in swimming pool in the areas reserved for them.what happens if swimmers swim other than the areas reserved for them,the whole thing would become mess.similarly iis uses application pools to seperate one process from another.

What does the C++ standard state the size of int, long type to be?

The C++ standard does not specify the size of integral types in bytes, but it specifies minimum ranges they must be able to hold. You can infer minimum size in bits from the required range. You can infer minimum size in bytes from that and the value of the CHAR_BIT macro that defines the number of bits in a byte. In all but the most obscure platforms it's 8, and it can't be less than 8.

One additional constraint for char is that its size is always 1 byte, or CHAR_BIT bits (hence the name). This is stated explicitly in the standard.

The C standard is a normative reference for the C++ standard, so even though it doesn't state these requirements explicitly, C++ requires the minimum ranges required by the C standard (page 22), which are the same as those from Data Type Ranges on MSDN:

  1. signed char: -127 to 127 (note, not -128 to 127; this accommodates 1's-complement and sign-and-magnitude platforms)
  2. unsigned char: 0 to 255
  3. "plain" char: same range as signed char or unsigned char, implementation-defined
  4. signed short: -32767 to 32767
  5. unsigned short: 0 to 65535
  6. signed int: -32767 to 32767
  7. unsigned int: 0 to 65535
  8. signed long: -2147483647 to 2147483647
  9. unsigned long: 0 to 4294967295
  10. signed long long: -9223372036854775807 to 9223372036854775807
  11. unsigned long long: 0 to 18446744073709551615

A C++ (or C) implementation can define the size of a type in bytes sizeof(type) to any value, as long as

  1. the expression sizeof(type) * CHAR_BIT evaluates to a number of bits high enough to contain required ranges, and
  2. the ordering of type is still valid (e.g. sizeof(int) <= sizeof(long)).

Putting this all together, we are guaranteed that:

  • char, signed char, and unsigned char are at least 8 bits
  • signed short, unsigned short, signed int, and unsigned int are at least 16 bits
  • signed long and unsigned long are at least 32 bits
  • signed long long and unsigned long long are at least 64 bits

No guarantee is made about the size of float or double except that double provides at least as much precision as float.

The actual implementation-specific ranges can be found in <limits.h> header in C, or <climits> in C++ (or even better, templated std::numeric_limits in <limits> header).

For example, this is how you will find maximum range for int:

C:

#include <limits.h>
const int min_int = INT_MIN;
const int max_int = INT_MAX;

C++:

#include <limits>
const int min_int = std::numeric_limits<int>::min();
const int max_int = std::numeric_limits<int>::max();

How can I compile and run c# program without using visual studio?

If you have a project ready and just want to change some code and then build. Check out MSBuild which is located in the Microsoft.Net under windows directory.

C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild "C:\Projects\MyProject.csproj" /p:Configuration=Debug;DeployOnBuild=True;PackageAsSingleFile=False;outdir=C:\Projects\MyProjects\Publish\

(Please do not edit, leave as a single line)

... The line above broken up for readability

C:\Windows\Microsoft.NET\Framework\v4.0.30319\msbuild "C:\Projects\MyProject.csproj"
/p:Configuration=Debug;DeployOnBuild=True;PackageAsSingleFile=False;
outdir=C:\Projects\MyProjects\Publish\

Submit a form in a popup, and then close the popup

I know this is an old question, but I stumbled across it when I was having a similar issue, and just wanted to share how I ended achieving the results you requested so future people can pick what works best for their situation.

First, I utilize the onsubmit event in the form, and pass this to the function to make it easier to deal with this particular form.

<form action="/system/wpacert" onsubmit="return closeSelf(this);" method="post" enctype="multipart/form-data"  name="certform">
    <div>Certificate 1: <input type="file" name="cert1"/></div>
    <div>Certificate 2: <input type="file" name="cert2"/></div>
    <div>Certificate 3: <input type="file" name="cert3"/></div>

    <div><input type="submit" value="Upload"/></div>
</form>

In our function, we'll submit the form data, and then we'll close the window. This will allow it to submit the data, and once it's done, then it'll close the window and return you to your original window.

<script type="text/javascript">
  function closeSelf (f) {
     f.submit();
     window.close();
  }
</script>

Hope this helps someone out. Enjoy!


Option 2: This option will let you submit via AJAX, and if it's successful, it'll close the window. This prevents windows from closing prior to the data being submitted. Credits to http://jquery.malsup.com/form/ for their work on the jQuery Form Plugin

First, remove your onsubmit/onclick events from the form/submit button. Place an ID on the form so AJAX can find it.

<form action="/system/wpacert" method="post" enctype="multipart/form-data"  id="certform">
    <div>Certificate 1: <input type="file" name="cert1"/></div>
    <div>Certificate 2: <input type="file" name="cert2"/></div>
    <div>Certificate 3: <input type="file" name="cert3"/></div>

    <div><input type="submit" value="Upload"/></div>
</form>

Second, you'll want to throw this script at the bottom, don't forget to reference the plugin. If the form submission is successful, it'll close the window.

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.js"></script> 
<script src="http://malsup.github.com/jquery.form.js"></script> 

    <script>
       $(document).ready(function () {
          $('#certform').ajaxForm(function () {
          window.close();
          });
       });
    </script>

onSaveInstanceState () and onRestoreInstanceState ()

onRestoreInstanceState() is called only when recreating activity after it was killed by the OS. Such situation happen when:

  • orientation of the device changes (your activity is destroyed and recreated).
  • there is another activity in front of yours and at some point the OS kills your activity in order to free memory (for example). Next time when you start your activity onRestoreInstanceState() will be called.

In contrast: if you are in your activity and you hit Back button on the device, your activity is finish()ed (i.e. think of it as exiting desktop application) and next time you start your app it is started "fresh", i.e. without saved state because you intentionally exited it when you hit Back.

Other source of confusion is that when an app loses focus to another app onSaveInstanceState() is called but when you navigate back to your app onRestoreInstanceState() may not be called. This is the case described in the original question, i.e. if your activity was NOT killed during the period when other activity was in front onRestoreInstanceState() will NOT be called because your activity is pretty much "alive".

All in all, as stated in the documentation for onRestoreInstanceState():

Most implementations will simply use onCreate(Bundle) to restore their state, but it is sometimes convenient to do it here after all of the initialization has been done or to allow subclasses to decide whether to use your default implementation. The default implementation of this method performs a restore of any view state that had previously been frozen by onSaveInstanceState(Bundle).

As I read it: There is no reason to override onRestoreInstanceState() unless you are subclassing Activity and it is expected that someone will subclass your subclass.

I need to get all the cookies from the browser

Modern approach.

let c = document.cookie.split(";").reduce( (ac, cv, i) => Object.assign(ac, {[cv.split('=')[0]]: cv.split('=')[1]}), {});

console.log(c);

;)

How can I access Google Sheet spreadsheets only with Javascript?

There's a solution that does not require one to publish the spreadsheet. However, the sheet does need to be 'Shared'. More specifically, one needs to share the sheet in a manner where anyone with the link can access the spreadsheet. Once this is done, one can use the Google Sheets HTTP API.

First up, you need an Google API key. Head here: https://developers.google.com/places/web-service/get-api-key NB. Please be aware of the security ramifications of having an API key made available to the public: https://support.google.com/googleapi/answer/6310037

Get all data for a spreadsheet - warning, this can be a lot of data.

https://sheets.googleapis.com/v4/spreadsheets/{spreadsheetId}/?key={yourAPIKey}&includeGridData=true

Get sheet metadata

https://sheets.googleapis.com/v4/spreadsheets/{spreadsheetId}/?key={yourAPIKey}

Get a range of cells

https://sheets.googleapis.com/v4/spreadsheets/{spreadsheetId}/values/{sheetName}!{cellRange}?key={yourAPIKey}

Now armed with this information, one can use AJAX to retrieve data and then manipulate it in JavaScript. I would recommend using axios.

var url = "https://sheets.googleapis.com/v4/spreadsheets/{spreadsheetId}/?key={yourAPIKey}&includeGridData=true";                                                             
axios.get(url)
  .then(function (response) {
    console.log(response);                                                                                                                                                    
  })
  .catch(function (error) {
    console.log(error);                                                                                                                                                       
  });                

getContext is not a function

Actually we get this error also when we create canvas in javascript as below.

document.createElement('canvas');

Here point to be noted we have to provide argument name correctly as 'canvas' not anything else.

Thanks

How does Java deal with multiple conditions inside a single IF statement

Yes, Java (similar to other mainstream languages) uses lazy evaluation short-circuiting which means it evaluates as little as possible.

This means that the following code is completely safe:

if(p != null && p.getAge() > 10)

Also, a || b never evaluates b if a evaluates to true.

MySQL DAYOFWEEK() - my week begins with monday

Try to use the WEEKDAY() function.

Returns the weekday index for date (0 = Monday, 1 = Tuesday, … 6 = Sunday).

what happens when you type in a URL in browser

First the computer looks up the destination host. If it exists in local DNS cache, it uses that information. Otherwise, DNS querying is performed until the IP address is found.

Then, your browser opens a TCP connection to the destination host and sends the request according to HTTP 1.1 (or might use HTTP 1.0, but normal browsers don't do it any more).

The server looks up the required resource (if it exists) and responds using HTTP protocol, sends the data to the client (=your browser)

The browser then uses HTML parser to re-create document structure which is later presented to you on screen. If it finds references to external resources, such as pictures, css files, javascript files, these are is delivered the same way as the HTML document itself.

How to compile and run C/C++ in a Unix console/Mac terminal?

I found this link with directions:

http://www.wesg.ca/2007/11/how-to-write-and-compile-c-programs-on-mac-os-x/

Basically you do:

gcc hello.c
./a.out (or with the output file of the first command)

Html encode in PHP

I searched for hours, and I tried almost everything suggested.
This worked for almost every entity :

$input = "ažškunrukiš ? àéò ??? ©€ ?? ? ?? ? R?";


echo htmlentities($input, ENT_HTML5  , 'UTF-8');

result :

&amacr;&zcaron;&scaron;&kcedil;&umacr;&ncedil;r&umacr;&kcedil;&imacr;&scaron; &cir; &agrave;&eacute;&ograve; &forall;&part;&ReverseElement; &copy;&euro; &clubs;&diamondsuit; &twoheadrightarrow; &harr;&nrarr; &swarr; &Rfr;&rx;rx;

Using subprocess to run Python script on Windows

For example, to execute following with command prompt or BATCH file we can use this:

C:\Python27\python.exe "C:\Program files(x86)\dev_appserver.py" --host 0.0.0.0 --post 8080 "C:\blabla\"

Same thing to do with Python, we can do this:

subprocess.Popen(['C:/Python27/python.exe', 'C:\\Program files(x86)\\dev_appserver.py', '--host', '0.0.0.0', '--port', '8080', 'C:\\blabla'], shell=True)

or

subprocess.Popen(['C:/Python27/python.exe', 'C:/Program files(x86)/dev_appserver.py', '--host', '0.0.0.0', '--port', '8080', 'C:/blabla'], shell=True)

Selected tab's color in Bottom Navigation View

If you want to change icons' and texts' colors programmatically:

ColorStateList iconsColorStates = new ColorStateList(
            new int[][]{
                    new int[]{-android.R.attr.state_checked},
                    new int[]{android.R.attr.state_checked}
            },
            new int[]{
                    Color.parseColor("#123456"),
                    Color.parseColor("#654321")
            });

    ColorStateList textColorStates = new ColorStateList(
            new int[][]{
                    new int[]{-android.R.attr.state_checked},
                    new int[]{android.R.attr.state_checked}
            },
            new int[]{
                    Color.parseColor("#123456"),
                    Color.parseColor("#654321")
            });

    navigation.setItemIconTintList(iconsColorStates);
    navigation.setItemTextColor(textColorStates);

Why is vertical-align:text-top; not working in CSS

position:absolute;
top:0px; 
margin:5px;

Solved my problem.

Bootstrap 3 : Vertically Center Navigation Links when Logo Increasing The Height of Navbar

Bootstrap sets the height of the navbar automatically to 50px. The padding above and below links is set to 15px. I think that bootstrap is adding padding to your logo.

You can either remove some of the padding above and below your logo or you can add more padding above and below links.

Adding more padding should look something like this:

nav.navbar-inverse>li>a {
 padding-top: 25px;
 padding-bottom: 25px;
}

Transparent background on winforms?

A simple solution to get a transparent background in a windows form is to overwrite the OnPaintBackground method like this:

protected override void OnPaintBackground(PaintEventArgs e)
{
    //empty implementation
}

(Notice that the base.OnpaintBackground(e) is removed from the function)

RedirectToAction with parameter

....

int parameter = Convert.ToInt32(Session["Id"].ToString());

....

return RedirectToAction("ActionName", new { Id = parameter });

What do <o:p> elements do anyway?

Couldn't find any official documentation (no surprise there) but according to this interesting article, those elements are injected in order to enable Word to convert the HTML back to fully compatible Word document, with everything preserved.

The relevant paragraph:

Microsoft added the special tags to Word's HTML with an eye toward backward compatibility. Microsoft wanted you to be able to save files in HTML complete with all of the tracking, comments, formatting, and other special Word features found in traditional DOC files. If you save a file in HTML and then reload it in Word, theoretically you don't loose anything at all.

This makes lots of sense.

For your specific question.. the o in the <o:p> means "Office namespace" so anything following the o: in a tag means "I'm part of Office namespace" - in case of <o:p> it just means paragraph, the equivalent of the ordinary <p> tag.

I assume that every HTML tag has its Office "equivalent" and they have more.

Move to another EditText when Soft Keyboard Next is clicked on Android

Simple way :

  • Auto move cursor to next edittext
  • If edittext is last input -> hidden keyboard

Add this to edittext field in .xml file

android:inputType="textCapWords"

How to apply CSS to iframe?

var $head = $("#eFormIFrame").contents().find("head");

$head.append($("<link/>", {
    rel: "stylesheet",
    href: url,
    type: "text/css"
}));

jQuery: using a variable as a selector

You're thinking too complicated. It's actually just $('#'+openaddress).

Textarea onchange detection

Code I have used for IE 11 without jquery and just for a single textarea:

Javascript:

// Impede que o comentário tenha mais de num_max caracteres
var internalChange= 0; // important, prevent reenter
function limit_char(max)
{ 
    if (internalChange == 1)
    {
        internalChange= 0;
        return;
    }
    internalChange= 1;
    // <form> and <textarea> are the ID's of your form and textarea objects
    <form>.<textarea>.value= <form>.<textarea>.value.substring(0,max);
}

and html:

<TEXTAREA onpropertychange='limit_char(5)' ...

Cannot inline bytecode built with JVM target 1.8 into bytecode that is being built with JVM target 1.6

app/build.gradle

android {
    ...
    compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_8
        targetCompatibility JavaVersion.VERSION_1_8
    }

    kotlinOptions {
        jvmTarget = JavaVersion.VERSION_1_8.toString()
    }
}

GL

Use Java 8 language features

Make a div fill the height of the remaining screen space

There's a ton of answers now, but I found using height: 100vh; to work on the div element that needs to fill up the entire vertical space available.

In this way, I do not need to play around with display or positioning. This came in handy when using Bootstrap to make a dashboard wherein I had a sidebar and a main. I wanted the main to stretch and fill the entire vertical space so that I could apply a background colour.

div {
    height: 100vh;
}

Supports IE9 and up: click to see the link

ORDER BY date and time BEFORE GROUP BY name in mysql

As I am not allowed to comment on user1908688's answer, here a hint for MariaDB users:

SELECT *
FROM (
     SELECT *
     ORDER BY date ASC, time ASC
     LIMIT 18446744073709551615
     ) AS sub
GROUP BY sub.name

https://mariadb.com/kb/en/mariadb/why-is-order-by-in-a-from-subquery-ignored/

javascript toISOString() ignores timezone offset

It will be very helpful to get current date and time.

var date=new Date();
  var today=new Date(date.getTime() - (date.getTimezoneOffset() * 60000)).toISOString().replace(/T/, ' ').replace(/\..+/, '');  

How to use cookies in Python Requests

Summary (@Freek Wiekmeijer, @gtalarico) other's answer:

Logic of Login

  • Many resource(pages, api) need authentication, then can access, otherwise 405 Not Allowed
  • Common authentication=grant access method are:
    • cookie
    • auth header
      • Basic xxx
      • Authorization xxx

How use cookie in requests to auth

  1. first get/generate cookie
  2. send cookie for following request
  • manual set cookie in headers
  • auto process cookie by requests's
    • session to auto manage cookies
    • response.cookies to manually set cookies

use requests's session auto manage cookies

curSession = requests.Session() 
# all cookies received will be stored in the session object

payload={'username': "yourName",'password': "yourPassword"}
curSession.post(firstUrl, data=payload)
# internally return your expected cookies, can use for following auth

# internally use previously generated cookies, can access the resources
curSession.get(secondUrl)

curSession.get(thirdUrl)

manually control requests's response.cookies

payload={'username': "yourName",'password': "yourPassword"}
resp1 = requests.post(firstUrl, data=payload)

# manually pass previously returned cookies into following request
resp2 = requests.get(secondUrl, cookies= resp1.cookies)

resp3 = requests.get(thirdUrl, cookies= resp2.cookies)

Get current date in DD-Mon-YYY format in JavaScript/Jquery

Here's a simple solution, using TypeScript:

  convertDateStringToDate(dateStr) {
    //  Convert a string like '2020-10-04T00:00:00' into '4/Oct/2020'
    let months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
    let date = new Date(dateStr);
    let str = date.getDate()
                + '/' + months[date.getMonth()]
                + '/' + date.getFullYear()
    return str;
  }

(Yeah, I know the question was about JavaScript, but I'm sure I won't be the only Angular developer coming across this article !)

python for increment inner loop

for a in range(1):

    for b in range(3):
        a = b*2
        print(a)

As per your question, you want to iterate the outer loop with help of the inner loop.

  1. In outer loop, we are iterating the inner loop 1 time.
  2. In the inner loop, we are iterating the 3 digits which are in the multiple of 2, starting from 0.

    Output:
    0
    2
    4
    

JS file gets a net::ERR_ABORTED 404 (Not Found)

As mentionned in comments: you need a way to send your static files to the client. This can be achieved with a reverse proxy like Nginx, or simply using express.static().

Put all your "static" (css, js, images) files in a folder dedicated to it, different from where you put your "views" (html files in your case). I'll call it static for the example. Once it's done, add this line in your server code:

app.use("/static", express.static('./static/'));

This will effectively serve every file in your "static" folder via the /static route.

Querying your index.js file in the client thus becomes:

<script src="static/index.js"></script>

MetadataException when using Entity Framework Entity Connection

I had the same problem with three projects in one solution and all of the suggestions didn't work until I made a reference in the reference file of the web site project to the project where the edmx file sits.

Convert time span value to format "hh:mm Am/Pm" using C#

Very simple by using the string format

on .ToSTring("") :

  • if you use "hh" ->> The hour, using a 12-hour clock from 01 to 12.

  • if you use "HH" ->> The hour, using a 24-hour clock from 00 to 23.

  • if you add "tt" ->> The Am/Pm designator.

exemple converting from 23:12 to 11:12 Pm :

DateTime d = new DateTime(1, 1, 1, 23, 12, 0);
var res = d.ToString("hh:mm tt");   // this show  11:12 Pm
var res2 = d.ToString("HH:mm");  // this show  23:12

Console.WriteLine(res);
Console.WriteLine(res2);

Console.Read();

wait a second that is not all you need to care about something else is the system Culture because the same code executed on windows with other langage especialy with difrent culture langage will generate difrent result with the same code

exemple of windows set to Arabic langage culture will show like that :

// 23:12 ?

? means Evening (first leter of ????) .

in another system culture depend on what is set on the windows regional and language option, it will show // 23:12 du.

you can change between different format on windows control panel under windows regional and language -> current format (combobox) and change... apply it do a rebuild (execute) of your app and watch what iam talking about.

so who can I force showing Am and Pm Words in English event if the culture of the current system isn't set to English ?

easy just by adding two lines : ->

the first step add using System.Globalization; on top of your code

and modifing the Previous code to be like this :

DateTime d = new DateTime(1, 1, 1, 23, 12, 0);
var res = d.ToString("HH:mm tt", CultureInfo.InvariantCulture); // this show  11:12 Pm

InvariantCulture => using default English Format.

another question I want to have the pm to be in Arabic or specific language, even if I use windows set to English (or other language) regional format?

Soution for Arabic Exemple :

DateTime d = new DateTime(1, 1, 1, 23, 12, 0);
var res = d.ToString("HH:mm tt", CultureInfo.CreateSpecificCulture("ar-AE")); 

this will show // 23:12 ?

event if my system is set to an English region format. you can change "ar-AE" if you want to another language format. there is a list of each language and its format.

exemples : ar ar-SA Arabic ar-BH ar-BH Arabic (Bahrain) ar-DZ ar-DZ Arabic (Algeria) ar-EG ar-EG Arabic (Egypt)

Calling a PHP function from an HTML form in the same file

This is the better way that I use to create submit without loading in a form.

You can use some CSS to stylise the iframe the way you want.

A php result will be loaded into the iframe.

<form method="post" action="test.php" target="view">
  <input type="text" name="anyname" palceholder="Enter your name"/>
  <input type="submit" name="submit" value="submit"/>
  </form>
<iframe name="view" frameborder="0" style="width:100%">
  </iframe>

Convert float64 column to int64 in Pandas

This seems to be a little buggy in Pandas 0.23.4?

If there are np.nan values then this will throw an error as expected:

df['col'] = df['col'].astype(np.int64)

But doesn't change any values from float to int as I would expect if "ignore" is used:

df['col'] = df['col'].astype(np.int64,errors='ignore') 

It worked if I first converted np.nan:

df['col'] = df['col'].fillna(0).astype(np.int64)
df['col'] = df['col'].astype(np.int64)

Now I can't figure out how to get null values back in place of the zeroes since this will convert everything back to float again:

df['col']  = df['col'].replace(0,np.nan)

Difference between @Mock and @InjectMocks

@Mock creates a mock. @InjectMocks creates an instance of the class and injects the mocks that are created with the @Mock (or @Spy) annotations into this instance.

Note you must use @RunWith(MockitoJUnitRunner.class) or Mockito.initMocks(this) to initialize these mocks and inject them (JUnit 4).

With JUnit 5, you must use @ExtendWith(MockitoExtension.class).

@RunWith(MockitoJUnitRunner.class) // JUnit 4
// @ExtendWith(MockitoExtension.class) for JUnit 5
public class SomeManagerTest {

    @InjectMocks
    private SomeManager someManager;

    @Mock
    private SomeDependency someDependency; // this will be injected into someManager
 
     // tests...

}

PHP Accessing Parent Class Variable

all the properties and methods of the parent class is inherited in the child class so theoretically you can access them in the child class but beware using the protected keyword in your class because it throws a fatal error when used in the child class.
as mentioned in php.net

The visibility of a property or method can be defined by prefixing the declaration with the keywords public, protected or private. Class members declared public can be accessed everywhere. Members declared protected can be accessed only within the class itself and by inherited and parent classes. Members declared as private may only be accessed by the class that defines the member.

Using BeautifulSoup to search HTML for string

text='Python' searches for elements that have the exact text you provided:

import re
from BeautifulSoup import BeautifulSoup

html = """<p>exact text</p>
   <p>almost exact text</p>"""
soup = BeautifulSoup(html)
print soup(text='exact text')
print soup(text=re.compile('exact text'))

Output

[u'exact text']
[u'exact text', u'almost exact text']

"To see if the string 'Python' is located on the page http://python.org":

import urllib2
html = urllib2.urlopen('http://python.org').read()
print 'Python' in html # -> True

If you need to find a position of substring within a string you could do html.find('Python').

How to get all Windows service names starting with a common word?

sc queryex type= service state= all | find /i "NATION"
  • use /i for case insensitive search
  • the white space after type=is deliberate and required

git stash -> merge stashed change with current changes

tl;dr

Run git add first.


I just discovered that if your uncommitted changes are added to the index (i.e. "staged", using git add ...), then git stash apply (and, presumably, git stash pop) will actually do a proper merge. If there are no conflicts, you're golden. If not, resolve them as usual with git mergetool, or manually with an editor.

To be clear, this is the process I'm talking about:

mkdir test-repo && cd test-repo && git init
echo test > test.txt
git add test.txt && git commit -m "Initial version"

# here's the interesting part:

# make a local change and stash it:
echo test2 > test.txt
git stash

# make a different local change:
echo test3 > test.txt

# try to apply the previous changes:
git stash apply
# git complains "Cannot apply to a dirty working tree, please stage your changes"

# add "test3" changes to the index, then re-try the stash:
git add test.txt
git stash apply
# git says: "Auto-merging test.txt"
# git says: "CONFLICT (content): Merge conflict in test.txt"

... which is probably what you're looking for.

How can I make Bootstrap 4 columns all the same height?

You just have to use class="row-eq-height" with your class="row" to get equal height columns for previous bootstrap versions.

but with bootstrap 4 this comes natively.

check this link --http://getbootstrap.com.vn/examples/equal-height-columns/

Bringing a subview to be in front of all other views

try this:

self.view.layer.zPosition = 1;

How to get values and keys from HashMap?

You have to follow the following sequence of opeartions:

  • Convert Map to MapSet with map.entrySet();
  • Get the iterator with Mapset.iterator();
  • Get Map.Entry with iterator.next();
  • use Entry.getKey() and Entry.getValue()
# define Map
for (Map.Entry entry: map.entrySet)
    System.out.println(entry.getKey() + entry.getValue);

javaw.exe cannot find path

Just update your eclipse.ini file (you can find it in the root-directory of eclipse) by this:

-vm
path/javaw.exe

for example:

-vm 
C:/Program Files/Java/jdk1.7.0_09/jre/bin/javaw.exe

What is JAVA_HOME? How does the JVM find the javac path stored in JAVA_HOME?

The command prompt wouldn't use JAVA_HOME to find javac.exe, it would use PATH.

assign headers based on existing row in dataframe in R

A new answer that uses dplyr and tidyr:

Extracts the desired column names and converts to a list

library(tidyverse)

col_names <- raw_dta %>% 
  slice(2) %>%
  pivot_longer(
    cols = "X2":"X10", # until last named column
    names_to = "old_names",
    values_to = "new_names") %>% 
  pull(new_names)

Removes the incorrect rows and adds the correct column names

dta <- raw_dta %>% 
  slice(-1, -2) %>% # Removes the rows containing new and original names
  set_names(., nm = col_names)

Finding child element of parent pure javascript

You have a parent element, you want to get all child of specific attribute 1. get the parent 2. get the parent nodename by using parent.nodeName.toLowerCase() convert the nodename to lower case e.g DIV will be div 3. for further specific purpose, get an attribute of the parent e.g parent.getAttribute("id"). this will give you id of the parent 4. Then use document.QuerySelectorAll(paret.nodeName.toLowerCase()+"#"_parent.getAttribute("id")+" input " ); if you want input children of the parent node

_x000D_
_x000D_
let parent = document.querySelector("div.classnameofthediv")_x000D_
let parent_node = parent.nodeName.toLowerCase()_x000D_
let parent_clas_arr = parent.getAttribute("class").split(" ");_x000D_
let parent_clas_str = '';_x000D_
  parent_clas_arr.forEach(e=>{_x000D_
     parent_clas_str +=e+'.';_x000D_
  })_x000D_
let parent_class_name = parent_clas_str.substr(0, parent_clas_str.length-1)  //remove the last dot_x000D_
let allchild = document.querySelectorAll(parent_node+"."+parent_class_name+" input")
_x000D_
_x000D_
_x000D_

How to return a struct from a function in C++?

Here is an edited version of your code which is based on ISO C++ and which works well with G++:

#include <string.h>
#include <iostream>
using namespace std;

#define NO_OF_TEST 1

struct studentType {
    string studentID;
    string firstName;
    string lastName;
    string subjectName;
    string courseGrade;
    int arrayMarks[4];
    double avgMarks;
};

studentType input() {
    studentType newStudent;
    cout << "\nPlease enter student information:\n";

    cout << "\nFirst Name: ";
    cin >> newStudent.firstName;

    cout << "\nLast Name: ";
    cin >> newStudent.lastName;

    cout << "\nStudent ID: ";
    cin >> newStudent.studentID;

    cout << "\nSubject Name: ";
    cin >> newStudent.subjectName;

    for (int i = 0; i < NO_OF_TEST; i++) {
        cout << "\nTest " << i+1 << " mark: ";
        cin >> newStudent.arrayMarks[i];
    }

    return newStudent;
}

int main() {
    studentType s;
    s = input();

    cout <<"\n========"<< endl << "Collected the details of "
        << s.firstName << endl;

    return 0;
}

How to resolve the "EVP_DecryptFInal_ex: bad decrypt" during file decryption

I think the Key and IV used for encryption using command line and decryption using your program are not same.

Please note that when you use the "-k" (different from "-K"), the input given is considered as a password from which the key is derived. Generally in this case, there is no need for the "-iv" option as both key and password will be derived from the input given with "-k" option.

It is not clear from your question, how you are ensuring that the Key and IV are same between encryption and decryption.

In my suggestion, better use "-K" and "-iv" option to explicitly specify the Key and IV during encryption and use the same for decryption. If you need to use "-k", then use the "-p" option to print the key and iv used for encryption and use the same in your decryption program.

More details can be obtained at https://www.openssl.org/docs/manmaster/apps/enc.html

Insert HTML from CSS

No you cannot. The only thing you can do is to insert content. Like so:

p:after {
    content: "yo";
}

Changing :hover to touch/click for mobile devices

Well I agree with above answers but still there can be an another way to do this and it is by using media queries.

Suppose this is what you want to do :

body.nontouch nav a:hover {
    background: yellow;
}

then you can do this by media query as :

@media(hover: hover) and (pointer: fine) {
    nav a:hover {
        background: yellow;
    }
}

And for more details you can visit this page.

Drop shadow for PNG image in CSS

You can't do this reliably across all browsers. Microsoft no longer supports DX filters as of IE10+, so none of the solutions here work fully:

https://msdn.microsoft.com/en-us/library/hh801215(v=vs.85).aspx

The only property that works reliably across all browsers is box-shadow, and this just puts the border on your element (e.g. a div), resulting in a square border:

box-shadow: horizontalOffset verticalOffset blurDistance spreadDistance color inset;

e.g.

box-shadow: -2px 6px 12px 6px #CCCED0;

If you happen to have an image that is 'square' but with uniform rounded corners, the drop shadow works with border-radius, so you could always emulate the rounded corners of your image in your div.

Here's the Microsoft documentation for box-shadow:

https://msdn.microsoft.com/en-us/library/gg589484(v=vs.85).aspx

Color different parts of a RichTextBox string

I created this Function after researching on the internet since I wanted to print an XML string when you select a row from a data grid view.

static void HighlightPhrase(RichTextBox box, string StartTag, string EndTag, string ControlTag, Color color1, Color color2)
{
    int pos = box.SelectionStart;
    string s = box.Text;
    for (int ix = 0; ; )
    {
        int jx = s.IndexOf(StartTag, ix, StringComparison.CurrentCultureIgnoreCase);
        if (jx < 0) break;
        int ex = s.IndexOf(EndTag, ix, StringComparison.CurrentCultureIgnoreCase);
        box.SelectionStart = jx;
        box.SelectionLength = ex - jx + 1;
        box.SelectionColor = color1;
        
        int bx = s.IndexOf(ControlTag, ix, StringComparison.CurrentCultureIgnoreCase);
        int bxtest = s.IndexOf(StartTag, (ex + 1), StringComparison.CurrentCultureIgnoreCase);
        if (bx == bxtest)
        {
            box.SelectionStart = ex + 1;
            box.SelectionLength = bx - ex + 1;
            box.SelectionColor = color2;
        }
        
        ix = ex + 1;
    }
    box.SelectionStart = pos;
    box.SelectionLength = 0;
}

and this is how you call it

   HighlightPhrase(richTextBox1, "<", ">","</", Color.Red, Color.Black);

What is ROWS UNBOUNDED PRECEDING used for in Teradata?

It's the "frame" or "range" clause of window functions, which are part of the SQL standard and implemented in many databases, including Teradata.

A simple example would be to calculate the average amount in a frame of three days. I'm using PostgreSQL syntax for the example, but it will be the same for Teradata:

WITH data (t, a) AS (
  VALUES(1, 1),
        (2, 5),
        (3, 3),
        (4, 5),
        (5, 4),
        (6, 11)
)
SELECT t, a, avg(a) OVER (ORDER BY t ROWS BETWEEN 1 PRECEDING AND 1 FOLLOWING)
FROM data
ORDER BY t

... which yields:

t  a  avg
----------
1  1  3.00
2  5  3.00
3  3  4.33
4  5  4.00
5  4  6.67
6 11  7.50

As you can see, each average is calculated "over" an ordered frame consisting of the range between the previous row (1 preceding) and the subsequent row (1 following).

When you write ROWS UNBOUNDED PRECEDING, then the frame's lower bound is simply infinite. This is useful when calculating sums (i.e. "running totals"), for instance:

WITH data (t, a) AS (
  VALUES(1, 1),
        (2, 5),
        (3, 3),
        (4, 5),
        (5, 4),
        (6, 11)
)
SELECT t, a, sum(a) OVER (ORDER BY t ROWS BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW)
FROM data
ORDER BY t

yielding...

t  a  sum
---------
1  1    1
2  5    6
3  3    9
4  5   14
5  4   18
6 11   29

Here's another very good explanations of SQL window functions.

Populate one dropdown based on selection in another

Setup mine within a closure and with straight JavaScript, explanation provided in comments

_x000D_
_x000D_
(function() {_x000D_
_x000D_
  //setup an object fully of arrays_x000D_
  //alternativly it could be something like_x000D_
  //{"yes":[{value:sweet, text:Sweet}.....]}_x000D_
  //so you could set the label of the option tag something different than the name_x000D_
  var bOptions = {_x000D_
    "yes": ["sweet", "wohoo", "yay"],_x000D_
    "no": ["you suck!", "common son"]_x000D_
  };_x000D_
_x000D_
  var A = document.getElementById('A');_x000D_
  var B = document.getElementById('B');_x000D_
_x000D_
  //on change is a good event for this because you are guarenteed the value is different_x000D_
  A.onchange = function() {_x000D_
    //clear out B_x000D_
    B.length = 0;_x000D_
    //get the selected value from A_x000D_
    var _val = this.options[this.selectedIndex].value;_x000D_
    //loop through bOption at the selected value_x000D_
    for (var i in bOptions[_val]) {_x000D_
      //create option tag_x000D_
      var op = document.createElement('option');_x000D_
      //set its value_x000D_
      op.value = bOptions[_val][i];_x000D_
      //set the display label_x000D_
      op.text = bOptions[_val][i];_x000D_
      //append it to B_x000D_
      B.appendChild(op);_x000D_
    }_x000D_
  };_x000D_
  //fire this to update B on load_x000D_
  A.onchange();_x000D_
_x000D_
})();
_x000D_
<select id='A' name='A'>_x000D_
  <option value='yes' selected='selected'>yes_x000D_
  <option value='no'> no_x000D_
</select>_x000D_
<select id='B' name='B'>_x000D_
</select>
_x000D_
_x000D_
_x000D_

Super-simple example of C# observer/observable with delegates

I've tied together a couple of the great examples above (thank you as always to Mr. Skeet and Mr. Karlsen) to include a couple of different Observables and utilized an interface to keep track of them in the Observer and allowed the Observer to to "observe" any number of Observables via an internal list:

namespace ObservablePattern
{
    using System;
    using System.Collections.Generic;

    internal static class Program
    {
        private static void Main()
        {
            var observable = new Observable();
            var anotherObservable = new AnotherObservable();

            using (IObserver observer = new Observer(observable))
            {
                observable.DoSomething();
                observer.Add(anotherObservable);
                anotherObservable.DoSomething();
            }

            Console.ReadLine();
        }
    }

    internal interface IObservable
    {
        event EventHandler SomethingHappened;
    }

    internal sealed class Observable : IObservable
    {
        public event EventHandler SomethingHappened;

        public void DoSomething()
        {
            var handler = this.SomethingHappened;

            Console.WriteLine("About to do something.");
            if (handler != null)
            {
                handler(this, EventArgs.Empty);
            }
        }
    }

    internal sealed class AnotherObservable : IObservable
    {
        public event EventHandler SomethingHappened;

        public void DoSomething()
        {
            var handler = this.SomethingHappened;

            Console.WriteLine("About to do something different.");
            if (handler != null)
            {
                handler(this, EventArgs.Empty);
            }
        }
    }

    internal interface IObserver : IDisposable
    {
        void Add(IObservable observable);

        void Remove(IObservable observable);
    }

    internal sealed class Observer : IObserver
    {
        private readonly Lazy<IList<IObservable>> observables =
            new Lazy<IList<IObservable>>(() => new List<IObservable>());

        public Observer()
        {
        }

        public Observer(IObservable observable) : this()
        {
            this.Add(observable);
        }

        public void Add(IObservable observable)
        {
            if (observable == null)
            {
                return;
            }

            lock (this.observables)
            {
                this.observables.Value.Add(observable);
                observable.SomethingHappened += HandleEvent;
            }
        }

        public void Remove(IObservable observable)
        {
            if (observable == null)
            {
                return;
            }

            lock (this.observables)
            {
                observable.SomethingHappened -= HandleEvent;
                this.observables.Value.Remove(observable);
            }
        }

        public void Dispose()
        {
            for (var i = this.observables.Value.Count - 1; i >= 0; i--)
            {
                this.Remove(this.observables.Value[i]);
            }
        }

        private static void HandleEvent(object sender, EventArgs args)
        {
            Console.WriteLine("Something happened to " + sender);
        }
    }
}

HAX kernel module is not installed

Turning off HyperV on windows 8.1 did the trick for me

dism.exe /Online /Disable-Feature:Microsoft-Hyper-V

Moving x-axis to the top of a plot in matplotlib

You've got to do some extra massaging if you want the ticks (not labels) to show up on the top and bottom (not just the top). The only way I could do this is with a minor change to unutbu's code:

import matplotlib.pyplot as plt
import numpy as np
column_labels = list('ABCD')
row_labels = list('WXYZ')
data = np.random.rand(4, 4)
fig, ax = plt.subplots()
heatmap = ax.pcolor(data, cmap=plt.cm.Blues)

# put the major ticks at the middle of each cell
ax.set_xticks(np.arange(data.shape[1]) + 0.5, minor=False)
ax.set_yticks(np.arange(data.shape[0]) + 0.5, minor=False)

# want a more natural, table-like display
ax.invert_yaxis()
ax.xaxis.tick_top()
ax.xaxis.set_ticks_position('both') # THIS IS THE ONLY CHANGE

ax.set_xticklabels(column_labels, minor=False)
ax.set_yticklabels(row_labels, minor=False)
plt.show()

Output:

enter image description here

Proper MIME type for OTF fonts

As of February 2017, RFC 8081 adds font/* media types, which are also listed in the IANA Media Types list. font/otf is in this list.

Environment variables in Eclipse

For the people who want to override the Environment Variable of OS in Eclipse project, refer to @MAX answer too.

It's useful when you have release project end eclipse project at the same machine.

The release project can use the OS Environment Variable for test usage and eclipse project can override it for development usage.

HTTP 415 unsupported media type error when calling Web API 2 endpoint

I was trying to write a code that would work on both Mac and Windows. The code was working fine on Windows, but was giving the response as 'Unsupported Media Type' on Mac. Here is the code I used and the following line made the code work on Mac as well:

Request.AddHeader "Content-Type", "application/json"

Here is the snippet of my code:

Dim Client As New WebClient
Dim Request As New WebRequest
Dim Response As WebResponse
Dim Distance As String

Client.BaseUrl = "http://1.1.1.1:8080/config"
Request.AddHeader "Content-Type", "application/json" *** The line that made the code work on mac

Set Response = Client.Execute(Request)

Do sessions really violate RESTfulness?

HTTP transaction, basic access authentication, is not suitable for RBAC, because basic access authentication uses the encrypted username:password every time to identify, while what is needed in RBAC is the Role the user wants to use for a specific call. RBAC does not validate permissions on username, but on roles.

You could tric around to concatenate like this: usernameRole:password, but this is bad practice, and it is also inefficient because when a user has more roles, the authentication engine would need to test all roles in concatenation, and that every call again. This would destroy one of the biggest technical advantages of RBAC, namely a very quick authorization-test.

So that problem cannot be solved using basic access authentication.

To solve this problem, session-maintaining is necessary, and that seems, according to some answers, in contradiction with REST.

That is what I like about the answer that REST should not be treated as a religion. In complex business cases, in healthcare, for example, RBAC is absolutely common and necessary. And it would be a pity if they would not be allowed to use REST because all REST-tools designers would treat REST as a religion.

For me there are not many ways to maintain a session over HTTP. One can use cookies, with a sessionId, or a header with a sessionId.

If someone has another idea I will be glad to hear it.

How do I modify the URL without reloading the page?

NOTE: If you are working with an HTML5 browser then you should ignore this answer. This is now possible as can be seen in the other answers.

There is no way to modify the URL in the browser without reloading the page. The URL represents what the last loaded page was. If you change it (document.location) then it will reload the page.

One obvious reason being, you write a site on www.mysite.com that looks like a bank login page. Then you change the browser URL bar to say www.mybank.com. The user will be totally unaware that they are really looking at www.mysite.com.

jQuery send HTML data through POST

_x000D_
_x000D_
jQuery.post(post_url,{ content: "John" } )_x000D_
 .done(function( data ) {_x000D_
   _x000D_
   _x000D_
 });_x000D_
 
_x000D_
_x000D_
_x000D_

I used the technique what u have replied above, it works fine but my problem is i need to generate a pdf conent using john as text . I have been able to echo the passed data. but getting empty in when generating pdf uisng below content ples check

_x000D_
_x000D_
ob_start();_x000D_
        _x000D_
   include_once(JPATH_SITE .'/components/com_gaevents/pdfgenerator.php');_x000D_
   $content = ob_get_clean();_x000D_
   _x000D_
  _x000D_
  _x000D_
    $test = $_SESSION['content'] ;_x000D_
  _x000D_
   require_once(JPATH_SITE.'/html2pdf/html2pdf.class.php');_x000D_
            $html2pdf = new HTML2PDF('P', 'A4', 'en', true, 'UTF-8',0 );   _x000D_
    $html2pdf->setDefaultFont('Arial');_x000D_
    $html2pdf->WriteHTML($test);
_x000D_
_x000D_
_x000D_

Loop through files in a folder using VBA?

Here's my interpretation as a Function Instead:

'#######################################################################
'# LoopThroughFiles
'# Function to Loop through files in current directory and return filenames
'# Usage: LoopThroughFiles ActiveWorkbook.Path, "txt" 'inputDirectoryToScanForFile
'# https://stackoverflow.com/questions/10380312/loop-through-files-in-a-folder-using-vba
'#######################################################################
Function LoopThroughFiles(inputDirectoryToScanForFile, filenameCriteria) As String

    Dim StrFile As String
    'Debug.Print "in LoopThroughFiles. inputDirectoryToScanForFile: ", inputDirectoryToScanForFile

    StrFile = Dir(inputDirectoryToScanForFile & "\*" & filenameCriteria)
    Do While Len(StrFile) > 0
        Debug.Print StrFile
        StrFile = Dir

    Loop

End Function

WHERE statement after a UNION in SQL?

select column1..... from table1
where column1=''
union
select column1..... from table2
where column1= ''

Declare variable in table valued function

There are two flavors of table valued functions. One that is just a select statement and one that can have more rows than just a select statement.

This can not have a variable:

create function Func() returns table
as
return
select 10 as ColName

You have to do like this instead:

create function Func()
returns @T table(ColName int)
as
begin
  declare @Var int
  set @Var = 10
  insert into @T(ColName) values (@Var)
  return
end

PersistentObjectException: detached entity passed to persist thrown by JPA and Hibernate

In your entity definition, you're not specifying the @JoinColumn for the Account joined to a Transaction. You'll want something like this:

@Entity
public class Transaction {
    @ManyToOne(cascade = {CascadeType.ALL},fetch= FetchType.EAGER)
    @JoinColumn(name = "accountId", referencedColumnName = "id")
    private Account fromAccount;
}

EDIT: Well, I guess that would be useful if you were using the @Table annotation on your class. Heh. :)

Moment JS start and end of given month

_x000D_
_x000D_
const year = 2014;_x000D_
const month = 09;_x000D_
_x000D_
// months start at index 0 in momentjs, so we subtract 1_x000D_
const startDate = moment([year, month - 1, 01]).format("YYYY-MM-DD");_x000D_
_x000D_
// get the number of days for this month_x000D_
const daysInMonth = moment(startDate).daysInMonth();_x000D_
_x000D_
// we are adding the days in this month to the start date (minus the first day)_x000D_
const endDate = moment(startDate).add(daysInMonth - 1, 'days').format("YYYY-MM-DD");_x000D_
_x000D_
console.log(`start date: ${startDate}`);_x000D_
console.log(`end date:   ${endDate}`);
_x000D_
<script_x000D_
src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js">_x000D_
</script>
_x000D_
_x000D_
_x000D_

cannot load such file -- bundler/setup (LoadError)

For me the problem was associating RVM Ruby with Passenger. So I needed to integrate RVM ruby wrapper to passenger config file.

I find out rvm ruby wrapper path with command:

passenger-config --ruby-command

I took the path from the result and entered to a passenger config in nginx/passenger.conf:

passenger_root /usr/lib/ruby/vendor_ruby/phusion_passenger/locations.ini;
passenger_ruby /usr/local/rvm/gems/ruby-2.3.1/wrappers/ruby;

How do you overcome the HTML form nesting limitation?

Use an iframe for the nested form. If they need to share fields, then... it's not really nested.

How to set the width of a RaisedButton in Flutter?

i would recommend using a MaterialButton, than you can do it like this:

new MaterialButton( 
 height: 40.0, 
 minWidth: 70.0, 
 color: Theme.of(context).primaryColor, 
 textColor: Colors.white, 
 child: new Text("push"), 
 onPressed: () => {}, 
 splashColor: Colors.redAccent,
)

Difference between java.lang.RuntimeException and java.lang.Exception

From oracle documentation:

Here's the bottom line guideline: If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.

Runtime exceptions represent problems that are the result of a programming problem and as such, the API client code cannot reasonably be expected to recover from them or to handle them in any way.

RuntimeExceptions are like "exceptions by invalid use of an api" examples of runtimeexceptions: IllegalStateException, NegativeArraySizeException, NullpointerException

With the Exceptions you must catch it explicitly because you can still do something to recover. Examples of Exceptions are: IOException, TimeoutException, PrintException...

Difference between using gradlew and gradle

gradlew is a wrapper(w - character) that uses gradle.

Under the hood gradlew performs three main things:

  • Download and install the correct gradle version
  • Parse the arguments
  • Call a gradle task

Using Gradle Wrapper we can distribute/share a project to everybody to use the same version and Gradle's functionality(compile, build, install...) even if it has not been installed.

To create a wrapper run:

gradle wrapper

This command generate:

gradle-wrapper.properties will contain the information about the Gradle distribution

*./ Is used on Unix to specify the current directory

Convert a list of objects to an array of one of the object's properties

You are looking for

MyList.Select(x=>x.Name).ToArray();

Since Select is an Extension method make sure to add that namespace by adding a

using System.Linq

to your file - then it will show up with Intellisense.

How do I get the list of keys in a Dictionary?

To get list of all keys

using System.Linq;
List<String> myKeys = myDict.Keys.ToList();

System.Linq is supported in .Net framework 3.5 or above. See the below links if you face any issue in using System.Linq

Visual Studio Does not recognize System.Linq

System.Linq Namespace

Getting value from table cell in JavaScript...not jQuery

Guess I'm going to answer my own questions....Sarfraz was close but not quite right. The correct answer is:

alert(col.firstChild.value);

New og:image size for Facebook share?

EDIT: The current best practices regarding Open Graph image sizes are officially outlined here: https://developers.facebook.com/docs/sharing/best-practices#images


There was a post in the Facebook developers group today, where one of the FB guys uploaded a PDF containing their new rules about image sizes – since that seems to be available only if you’re a member of the group, I uploaded it here: http://www.sendspace.com/file/ghqwhr

And they also said they will post about it in the developer blog in the coming days, so keep checking there as well

To summarize the linked document:

  • Minimum size in pixels is 600x315
  • Recommended size is 1200x630 - Images this size will get a larger display treatment.
  • Aspect ratio should be 1.91:1

How do I convert a Python 3 byte-string variable into a regular string?

UPDATED:

TO NOT HAVE ANY b and quotes at first and end

How to convert bytes as seen to strings, even in weird situations.

As your code may have unrecognizable characters to 'utf-8' encoding, it's better to use just str without any additional parameters:

some_bad_bytes = b'\x02-\xdfI#)'
text = str( some_bad_bytes )[2:-1]

print(text)
Output: \x02-\xdfI

if you add 'utf-8' parameter, to these specific bytes, you should receive error.

As PYTHON 3 standard says, text would be in utf-8 now with no concern.

Using Transactions or SaveChanges(false) and AcceptAllChanges()?

Because some database can throw an exception at dbContextTransaction.Commit() so better this:

using (var context = new BloggingContext()) 
{ 
  using (var dbContextTransaction = context.Database.BeginTransaction()) 
  { 
    try 
    { 
      context.Database.ExecuteSqlCommand( 
          @"UPDATE Blogs SET Rating = 5" + 
              " WHERE Name LIKE '%Entity Framework%'" 
          ); 

      var query = context.Posts.Where(p => p.Blog.Rating >= 5); 
      foreach (var post in query) 
      { 
          post.Title += "[Cool Blog]"; 
      } 

      context.SaveChanges(false); 

      dbContextTransaction.Commit(); 

      context.AcceptAllChanges();
    } 
    catch (Exception) 
    { 
      dbContextTransaction.Rollback(); 
    } 
  } 
} 

Running AngularJS initialization code when view is loaded

When your view loads, so does its associated controller. Instead of using ng-init, simply call your init() method in your controller:

$scope.init = function () {
    if ($routeParams.Id) {
        //get an existing object
    } else {
        //create a new object
    }
    $scope.isSaving = false;
}
...
$scope.init();

Since your controller runs before ng-init, this also solves your second issue.

Fiddle


As John David Five mentioned, you might not want to attach this to $scope in order to make this method private.

var init = function () {
    // do something
}
...
init();

See jsFiddle


If you want to wait for certain data to be preset, either move that data request to a resolve or add a watcher to that collection or object and call your init method when your data meets your init criteria. I usually remove the watcher once my data requirements are met so the init function doesnt randomly re-run if the data your watching changes and meets your criteria to run your init method.

var init = function () {
    // do something
}
...
var unwatch = scope.$watch('myCollecitonOrObject', function(newVal, oldVal){
                    if( newVal && newVal.length > 0) {
                        unwatch();
                        init();
                    }
                });

Media Queries - In between two widths

_x000D_
_x000D_
.class {_x000D_
    display: none;_x000D_
}_x000D_
@media (min-width:400px) and (max-width:900px) {_x000D_
    .class {_x000D_
        display: block; /* just an example display property */_x000D_
    }_x000D_
}
_x000D_
_x000D_
_x000D_

Using Mockito to mock classes with generic parameters

One other way around this is to use @Mock annotation instead. Doesn't work in all cases, but looks much sexier :)

Here's an example:

@RunWith(MockitoJUnitRunner.class)
public class FooTests {

    @Mock
    public Foo<Bar> fooMock;

    @Test
    public void testFoo() {
        when(fooMock.getValue()).thenReturn(new Bar());
    }
}

The MockitoJUnitRunner initializes the fields annotated with @Mock.

How can I provide multiple conditions for data trigger in WPF?

Use MultiDataTrigger type

<Style TargetType="ListBoxItem">
    <Style.Triggers>
      <DataTrigger Binding="{Binding Path=State}" Value="WA">
        <Setter Property="Foreground" Value="Red" />
      </DataTrigger>    
      <MultiDataTrigger>
        <MultiDataTrigger.Conditions>
          <Condition Binding="{Binding Path=Name}" Value="Portland" />
          <Condition Binding="{Binding Path=State}" Value="OR" />
        </MultiDataTrigger.Conditions>
        <Setter Property="Background" Value="Cyan" />
      </MultiDataTrigger>
    </Style.Triggers>
  </Style>

Enabling HTTPS on express.js

Including Points:

  1. SSL setup
    1. In config/local.js
    2. In config/env/production.js

HTTP and WS handling

  1. The app must run on HTTP in development so we can easily debug our app.
  2. The app must run on HTTPS in production for security concern.
  3. App production HTTP request should always redirect to https.

SSL configuration

In Sailsjs there are two ways to configure all the stuff, first is to configure in config folder with each one has their separate files (like database connection regarding settings lies within connections.js ). And second is configure on environment base file structure, each environment files presents in config/env folder and each file contains settings for particular env.

Sails first looks in config/env folder and then look forward to config/ *.js

Now lets setup ssl in config/local.js.

var local = {
   port: process.env.PORT || 1337,
   environment: process.env.NODE_ENV || 'development'
};

if (process.env.NODE_ENV == 'production') {
    local.ssl = {
        secureProtocol: 'SSLv23_method',
        secureOptions: require('constants').SSL_OP_NO_SSLv3,
        ca: require('fs').readFileSync(__dirname + '/path/to/ca.crt','ascii'),
        key: require('fs').readFileSync(__dirname + '/path/to/jsbot.key','ascii'),
        cert: require('fs').readFileSync(__dirname + '/path/to/jsbot.crt','ascii')
    };
    local.port = 443; // This port should be different than your default port
}

module.exports = local;

Alternative you can add this in config/env/production.js too. (This snippet also show how to handle multiple CARoot certi)

Or in production.js

module.exports = {
    port: 443,
    ssl: {
        secureProtocol: 'SSLv23_method',
        secureOptions: require('constants').SSL_OP_NO_SSLv3,
        ca: [
            require('fs').readFileSync(__dirname + '/path/to/AddTrustExternalCARoot.crt', 'ascii'),
            require('fs').readFileSync(__dirname + '/path/to/COMODORSAAddTrustCA.crt', 'ascii'),
            require('fs').readFileSync(__dirname + '/path/to/COMODORSADomainValidationSecureServerCA.crt', 'ascii')
        ],
        key: require('fs').readFileSync(__dirname + '/path/to/jsbot.key', 'ascii'),
        cert: require('fs').readFileSync(__dirname + '/path/to/jsbot.crt', 'ascii')
    }
};

http/https & ws/wss redirection

Here ws is Web Socket and wss represent Secure Web Socket, as we set up ssl then now http and ws both requests become secure and transform to https and wss respectively.

There are many source from our app will receive request like any blog post, social media post but our server runs only on https so when any request come from http it gives “This site can’t be reached” error in client browser. And we loss our website traffic. So we must redirect http request to https, same rules allow for websocket otherwise socket will fails.

So we need to run same server on port 80 (http), and divert all request to port 443(https). Sails first compile config/bootstrap.js file before lifting server. Here we can start our express server on port 80.

In config/bootstrap.js (Create http server and redirect all request to https)

module.exports.bootstrap = function(cb) {
    var express = require("express"),
        app = express();

    app.get('*', function(req, res) {  
        if (req.isSocket) 
            return res.redirect('wss://' + req.headers.host + req.url)  

        return res.redirect('https://' + req.headers.host + req.url)  
    }).listen(80);
    cb();
};

Now you can visit http://www.yourdomain.com, it will redirect to https://www.yourdomain.com

How do I create and read a value from cookie?

Mozilla provides a simple framework for reading and writing cookies with full unicode support along with examples of how to use it.

Once included on the page, you can set a cookie:

docCookies.setItem(name, value);

read a cookie:

docCookies.getItem(name);

or delete a cookie:

docCookies.removeItem(name);

For example:

// sets a cookie called 'myCookie' with value 'Chocolate Chip'
docCookies.setItem('myCookie', 'Chocolate Chip');

// reads the value of a cookie called 'myCookie' and assigns to variable
var myCookie = docCookies.getItem('myCookie');

// removes the cookie called 'myCookie'
docCookies.removeItem('myCookie');

See more examples and details on Mozilla's document.cookie page.

A version of this simple js file is on github.

How to use View.OnTouchListener instead of onClick

Presumably, if one wants to use an OnTouchListener rather than an OnClickListener, then the extra functionality of the OnTouchListener is needed. This is a supplemental answer to show more detail of how an OnTouchListener can be used.

Define the listener

Put this somewhere in your activity or fragment.

private View.OnTouchListener handleTouch = new View.OnTouchListener() {

    @Override
    public boolean onTouch(View v, MotionEvent event) {

        int x = (int) event.getX();
        int y = (int) event.getY();

        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                Log.i("TAG", "touched down");
                break;
            case MotionEvent.ACTION_MOVE:
                Log.i("TAG", "moving: (" + x + ", " + y + ")");
                break;
            case MotionEvent.ACTION_UP:
                Log.i("TAG", "touched up");
                break;
        }

        return true;
    }
};

Set the listener

Set the listener in onCreate (for an Activity) or onCreateView (for a Fragment).

myView.setOnTouchListener(handleTouch);

Notes

  • getX and getY give you the coordinates relative to the view (that is, the top left corner of the view). They will be negative when moving above or to the left of your view. Use getRawX and getRawY if you want the absolute screen coordinates.
  • You can use the x and y values to determine things like swipe direction.

How to set and reference a variable in a Jenkinsfile

We got around this by adding functions to the environment step, i.e.:

environment {
    ENVIRONMENT_NAME = defineEnvironment() 
}
...
def defineEnvironment() {
    def branchName = "${env.BRANCH_NAME}"
    if (branchName == "master") {
        return 'staging'
    }
    else {
        return 'test'
    }
}

jQuery getJSON save result into variable

You can't get value when calling getJSON, only after response.

var myjson;
$.getJSON("http://127.0.0.1:8080/horizon-update", function(json){
    myjson = json;
});

How to read first N lines of a file?

There is no specific method to read number of lines exposed by file object.

I guess the easiest way would be following:

lines =[]
with open(file_name) as f:
    lines.extend(f.readline() for i in xrange(N))

MS Excel showing the formula in a cell instead of the resulting value

Check for spaces in your formula before the "=". example' =A1' instean '=A1'

Static variables in C++

A static variable declared in a header file outside of the class would be file-scoped in every .c file which includes the header. That means separate copy of a variable with same name is accessible in each of the .c files where you include the header file.

A static class variable on the other hand is class-scoped and the same static variable is available to every compilation unit that includes the header containing the class with static variable.

JPanel setBackground(Color.BLACK) does nothing

If your panel is 'not opaque' (transparent) you wont see your background color.

How to use if-else logic in Java 8 stream forEach

In most cases, when you find yourself using forEach on a Stream, you should rethink whether you are using the right tool for your job or whether you are using it the right way.

Generally, you should look for an appropriate terminal operation doing what you want to achieve or for an appropriate Collector. Now, there are Collectors for producing Maps and Lists, but no out of-the-box collector for combining two different collectors, based on a predicate.

Now, this answer contains a collector for combining two collectors. Using this collector, you can achieve the task as

Pair<Map<KeyType, Animal>, List<KeyType>> pair = animalMap.entrySet().stream()
    .collect(conditional(entry -> entry.getValue() != null,
            Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue),
            Collectors.mapping(Map.Entry::getKey, Collectors.toList()) ));
Map<KeyType,Animal> myMap = pair.a;
List<KeyType> myList = pair.b;

But maybe, you can solve this specific task in a simpler way. One of you results matches the input type; it’s the same map just stripped off the entries which map to null. If your original map is mutable and you don’t need it afterwards, you can just collect the list and remove these keys from the original map as they are mutually exclusive:

List<KeyType> myList=animalMap.entrySet().stream()
    .filter(pair -> pair.getValue() == null)
    .map(Map.Entry::getKey)
    .collect(Collectors.toList());

animalMap.keySet().removeAll(myList);

Note that you can remove mappings to null even without having the list of the other keys:

animalMap.values().removeIf(Objects::isNull);

or

animalMap.values().removeAll(Collections.singleton(null));

If you can’t (or don’t want to) modify the original map, there is still a solution without a custom collector. As hinted in Alexis C.’s answer, partitioningBy is going into the right direction, but you may simplify it:

Map<Boolean,Map<KeyType,Animal>> tmp = animalMap.entrySet().stream()
    .collect(Collectors.partitioningBy(pair -> pair.getValue() != null,
                 Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue)));
Map<KeyType,Animal> myMap = tmp.get(true);
List<KeyType> myList = new ArrayList<>(tmp.get(false).keySet());

The bottom line is, don’t forget about ordinary Collection operations, you don’t have to do everything with the new Stream API.

How to solve : SQL Error: ORA-00604: error occurred at recursive SQL level 1

One possible explanation is a database trigger that fires for each DROP TABLE statement. To find the trigger, query the _TRIGGERS dictionary views:

select * from all_triggers
where trigger_type in ('AFTER EVENT', 'BEFORE EVENT')

disable any suspicious trigger with

   alter trigger <trigger_name> disable;

and try re-running your DROP TABLE statement

git push rejected: error: failed to push some refs

If you are the only the person working on the project, what you can do is:

 git checkout master
 git push origin +HEAD

This will set the tip of origin/master to the same commit as master (and so delete the commits between 41651df and origin/master)

What is function overloading and overriding in php?

Method overloading occurs when two or more methods with same method name but different number of parameters in single class. PHP does not support method overloading. Method overriding means two methods with same method name and same number of parameters in two different classes means parent class and child class.

Xcode - ld: library not found for -lPods

If the project uses CocoaPods be aware to always open the .xcworkspace file instead of the .xcodeproj file.

Could not find method android() for arguments

You are using the wrong build.gradle file.

In your top-level file you can't define an android block.

Just move this part inside the module/build.gradle file.

android {
    compileSdkVersion 17
    buildToolsVersion '23.0.0'
}
dependencies {
    compile files('app/libs/junit-4.12-JavaDoc.jar')
}
apply plugin: 'maven'

Force div element to stay in same place, when page is scrolled

You can do this replacing position:absolute; by position:fixed;.

Get month and year from date cells Excel

Try this formula (it will return value from A1 as is if it's not a date):

=TEXT(A1,"mm-yyyy")

Or this formula (it's more strict, it will return #VALUE error if A1 is not date):

=TEXT(MONTH(A1),"00")&"-"&YEAR(A1)

How to initialize a variable of date type in java?

tl;dr

Use Instant, replacement for java.util.Date.

Instant.now()  // Capture current moment as seen in UTC.

If you must have a Date, convert.

java.util.Date.from( Instant.now() ) 

java.time

The java.util.Date & .Calendar classes have been supplanted by the java.time framework built into Java 8 and later. The new classes are a tremendous improvement, inspired by the successful Joda-Time library.

The java.time classes tend to use static factory methods rather than constructors for instantiating objects.

To get the current moment in UTC time zone:

Instant instant = Instant.now();

To get the current moment in a particular time zone:

ZoneId zoneId = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = ZonedDateTime.now( zoneId );

If you must have a java.util.Date for use with other classes not yet updated for the java.time types, convert from Instant.

java.util.Date date = java.util.Date.from( zdt.toInstant() );

Table of date-time types in Java, both modern and legacy.


About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

How to get key names from JSON using jq

You can use:

$ jq 'keys' file.json
$ cat file.json:
{ "Archiver-Version" : "Plexus Archiver", "Build-Id" : "", "Build-Jdk" : "1.7.0_07", "Build-Number" : "", "Build-Tag" : "", "Built-By" : "cporter", "Created-By" : "Apache Maven", "Implementation-Title" : "northstar", "Implementation-Vendor-Id" : "com.test.testPack", "Implementation-Version" : "testBox", "Manifest-Version" : "1.0", "appname" : "testApp", "build-date" : "02-03-2014-13:41", "version" : "testBox" }

$ jq 'keys' file.json
[
  "Archiver-Version",
  "Build-Id",
  "Build-Jdk",
  "Build-Number",
  "Build-Tag",
  "Built-By",
  "Created-By",
  "Implementation-Title",
  "Implementation-Vendor-Id",
  "Implementation-Version",
  "Manifest-Version",
  "appname",
  "build-date",
  "version"
]

UPDATE: To create a BASH array using these keys:

Using BASH 4+:

mapfile -t arr < <(jq -r 'keys[]' ms.json)

On older BASH you can do:

arr=()
while IFS='' read -r line; do
   arr+=("$line")
done < <(jq 'keys[]' ms.json)

Then print it:

printf "%s\n" ${arr[@]}

"Archiver-Version"
"Build-Id"
"Build-Jdk"
"Build-Number"
"Build-Tag"
"Built-By"
"Created-By"
"Implementation-Title"
"Implementation-Vendor-Id"
"Implementation-Version"
"Manifest-Version"
"appname"
"build-date"
"version"

Docker compose, running containers in net:host

Those documents are outdated. I'm guessing the 1.6 in the URL is for Docker 1.6, not Compose 1.6. Check out the correct syntax here: https://docs.docker.com/compose/compose-file/#network_mode. You are looking for network_mode when using the v2 YAML format.

Validate email with a regex in jQuery

This : /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/i is not working for below Gmail case

[email protected] [email protected]

Below Regex will cover all the E-mail Points: I have tried the all Possible Points and my Test case get also pass because of below regex

I found this Solution from this URL:

Regex Solution link

/(?:((?:[\w-]+(?:\.[\w-]+)*)@(?:(?:[\w-]+\.)*\w[\w-]{0,66})\.(?:[a-z]{2,6}(?:\.[a-z]{2})?));*)/g

PHP CSV string to array

Slightly shorter version, without unnecessary second variable:

$csv = <<<'ENDLIST'
"12345","Computers","Acer","4","Varta","5.93","1","0.04","27-05-2013"
"12346","Computers","Acer","5","Decra","5.94","1","0.04","27-05-2013"
ENDLIST;

$arr = explode("\n", $csv);
foreach ($arr as &$line) {
  $line = str_getcsv($line);
}

Wrap a text within only two lines inside div

CSS only

    line-height: 1.5;
    white-space: normal;
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 2;
    -webkit-box-orient: vertical;

Font scaling based on width of container

This web component changes the font size so the inner text width matches the container width. Check the demo.

You can use it like this:

<full-width-text>Lorem Ipsum</full-width-text>

How to show all of columns name on pandas dataframe?

If you just want to see all the columns you can do something of this sort as a quick fix

cols = data_all2.columns

now cols will behave as a iterative variable that can be indexed. for example

cols[11:20]

C# - using List<T>.Find() with custom objects

You can use find with a Predicate as follows:

list.Find(x => x.Id == IdToFind);

This will return the first object in the list which meets the conditions defined by the predicate (ie in my example I am looking for an object with an ID).

How to automatically generate getters and setters in Android Studio

Android Studio & Windows :

fn + alt + insert

Image of Menu

How do I base64 encode a string efficiently using Excel VBA?

As Mark C points out, you can use the MSXML Base64 encoding functionality as described here.

I prefer late binding because it's easier to deploy, so here's the same function that will work without any VBA references:

Function EncodeBase64(text As String) As String
  Dim arrData() As Byte
  arrData = StrConv(text, vbFromUnicode)

  Dim objXML As Variant
  Dim objNode As Variant

  Set objXML = CreateObject("MSXML2.DOMDocument")
  Set objNode = objXML.createElement("b64")

  objNode.dataType = "bin.base64"
  objNode.nodeTypedValue = arrData
  EncodeBase64 = objNode.text

  Set objNode = Nothing
  Set objXML = Nothing
End Function

PDO closing connection

I created a derived class to have a more self-documented instruction instead of $conn=null;.

class CMyPDO extends PDO {
    public function __construct($dsn, $username = null, $password = null, array $options = null) {
        parent::__construct($dsn, $username, $password, $options);
    }

    static function getNewConnection() {
        $conn=null;
        try {
            $conn = new CMyPDO("mysql:host=$host;dbname=$dbname",$user,$pass);
        }
        catch (PDOException $exc) {
            echo $exc->getMessage();
        }
        return $conn;
    }

    static function closeConnection(&$conn) {
        $conn=null;
    }
}

So I can call my code between:

$conn=CMyPDO::getNewConnection();
// my code
CMyPDO::closeConnection($conn);

Text in a flex container doesn't wrap in IE11

I had a similar issue with overflowing images in a flex wrapper.

Adding either flex-basis: 100%; or flex: 1; to the overflowing child fixed worked for me.

mailto link multiple body lines

  1. Use a single body parameter within the mailto string
  2. Use %0D%0A as newline

The mailto URI Scheme is specified by by RFC2368 (July 1998) and RFC6068 (October 2010).
Below is an extract of section 5 of this last RFC:

[...] line breaks in the body of a message MUST be encoded with "%0D%0A".
Implementations MAY add a final line break to the body of a message even if there is no trailing "%0D%0A" in the body [...]

See also in section 6 the example from the same RFC:

<mailto:[email protected]?body=send%20current-issue%0D%0Asend%20index>

The above mailto body corresponds to:

send current-issue
send index

Java word count program

You can use String.split (read more here) instead of charAt, you will get good results. If you want to use charAt for some reason then try trimming the string before you count the words that way you won't have the extra space and an extra word

How to make a smooth image rotation in Android?

Maybe, something like this will help:

Runnable runnable = new Runnable() {
    @Override
    public void run() {
        imageView.animate().rotationBy(360).withEndAction(this).setDuration(3000).setInterpolator(new LinearInterpolator()).start();
    }
};

imageView.animate().rotationBy(360).withEndAction(runnable).setDuration(3000).setInterpolator(new LinearInterpolator()).start();

By the way, you can rotate by more than 360 like:

imageView.animate().rotationBy(10000)...

Python 101: Can't open file: No such file or directory

Prior to running python, type cd in the commmand line, and it will tell you the directory you are currently in. When python runs, it can only access files in this directory. hello.py needs to be in this directory, so you can move hello.py from its existing location to this folder as you would move any other file in Windows or you can change directories and run python in the directory hello.py is.

Edit: Python cannot access the files in the subdirectory unless a path to it provided. You can access files in any directory by providing the path. python C:\Python27\Projects\hello.p

How do I determine whether my calculation of pi is accurate?

Since I'm the current world record holder for the most digits of pi, I'll add my two cents:

Unless you're actually setting a new world record, the common practice is just to verify the computed digits against the known values. So that's simple enough.

In fact, I have a webpage that lists snippets of digits for the purpose of verifying computations against them: http://www.numberworld.org/digits/Pi/


But when you get into world-record territory, there's nothing to compare against.

Historically, the standard approach for verifying that computed digits are correct is to recompute the digits using a second algorithm. So if either computation goes bad, the digits at the end won't match.

This does typically more than double the amount of time needed (since the second algorithm is usually slower). But it's the only way to verify the computed digits once you've wandered into the uncharted territory of never-before-computed digits and a new world record.


Back in the days where supercomputers were setting the records, two different AGM algorithms were commonly used:

These are both O(N log(N)^2) algorithms that were fairly easy to implement.

However, nowadays, things are a bit different. In the last three world records, instead of performing two computations, we performed only one computation using the fastest known formula (Chudnovsky Formula):

Enter image description here

This algorithm is much harder to implement, but it is a lot faster than the AGM algorithms.

Then we verify the binary digits using the BBP formulas for digit extraction.

Enter image description here

This formula allows you to compute arbitrary binary digits without computing all the digits before it. So it is used to verify the last few computed binary digits. Therefore it is much faster than a full computation.

The advantage of this is:

  1. Only one expensive computation is needed.

The disadvantage is:

  1. An implementation of the Bailey–Borwein–Plouffe (BBP) formula is needed.
  2. An additional step is needed to verify the radix conversion from binary to decimal.

I've glossed over some details of why verifying the last few digits implies that all the digits are correct. But it is easy to see this since any computation error will propagate to the last digits.


Now this last step (verifying the conversion) is actually fairly important. One of the previous world record holders actually called us out on this because, initially, I didn't give a sufficient description of how it worked.

So I've pulled this snippet from my blog:

N = # of decimal digits desired
p = 64-bit prime number

Enter image description here

Compute A using base 10 arithmetic and B using binary arithmetic.

Enter image description here

If A = B, then with "extremely high probability", the conversion is correct.


For further reading, see my blog post Pi - 5 Trillion Digits.