Programs & Examples On #Translation

Translation is the process of replacing strings in an application or website to make interfacing with the application or website easier for people from countries with different languages.

Best practice for localization and globalization of strings and labels

As far as I know, there's a good library called localeplanet for Localization and Internationalization in JavaScript. Furthermore, I think it's native and has no dependencies to other libraries (e.g. jQuery)

Here's the website of library: http://www.localeplanet.com/

Also look at this article by Mozilla, you can find very good method and algorithms for client-side translation: http://blog.mozilla.org/webdev/2011/10/06/i18njs-internationalize-your-javascript-with-a-little-help-from-json-and-the-server/

The common part of all those articles/libraries is that they use a i18n class and a get method (in some ways also defining an smaller function name like _) for retrieving/converting the key to the value. In my explaining the key means that string you want to translate and the value means translated string.
Then, you just need a JSON document to store key's and value's.

For example:

var _ = document.webL10n.get;
alert(_('test'));

And here the JSON:

{ test: "blah blah" }

I believe using current popular libraries solutions is a good approach.

Change Input to Upper Case

**JAVA SCRIPT**
<html>
<body>
<script>
function @ToCaps(obj)
{
obj.value=obj.value.toUpperCase();
}
</script>
<input type="text" onkeyup=@ToCaps(this)"/>
</body>
</html>

**ASP.NET**
Use a css style on the text box, write css like this:

.ToCaps { text-transform: uppercase; }

<asp:TextBox ID="TextBox1" runat="server" CssClass="ToCaps"></asp:Te writxtBox>

**OR**
simply write this code in textbox
<asp:TextBox ID="TextBox1" runat="server" style="text-transform:uppercase"></asp:TextBox>


 **1.Note you don't get intelligence until you type up to style="**  

Run text file as commands in Bash

you can make a shell script with those commands, and then chmod +x <scriptname.sh>, and then just run it by

./scriptname.sh

Its very simple to write a bash script

Mockup sh file:

#!/bin/sh
sudo command1
sudo command2 
.
.
.
sudo commandn

Initializing array of structures

It's called designated initializer which is introduced in C99. It's used to initialize struct or arrays, in this example, struct.

Given

struct point { 
    int x, y;
};

the following initialization

struct point p = { .y = 2, .x = 1 };

is equivalent to the C89-style

struct point p = { 1, 2 };

A regex for version number parsing

(?ms)^((?:\d+(?!\.\*)\.)+)(\d+)?(\.\*)?$|^(\d+)\.\*$|^(\*|\d+)$

Does exactly match your 6 first examples, and rejects the 4 others

  • group 1: major or major.minor or '*'
  • group 2 if exists: minor or *
  • group 3 if exists: *

You can remove '(?ms)'
I used it to indicate to this regexp to be applied on multi-lines through QuickRex

create a text file using javascript

That works better with this :

var fso = new ActiveXObject("Scripting.FileSystemObject");
var a = fso.CreateTextFile("c:\\testfile.txt", true);
a.WriteLine("This is a test.");
a.Close();

http://msdn.microsoft.com/en-us/library/5t9b5c0c(v=vs.84).aspx

.datepicker('setdate') issues, in jQuery

Check that the date you are trying to set it to lies within the allowed date range if the minDate or maxDate options are set.

AWS CLI S3 A client error (403) occurred when calling the HeadObject operation: Forbidden

Check your object owner if you copy the file from another aws account.

In my case, I copy the file from another aws account without acl, so file's owner is the other aws account, it's mean the file belongs to origin account.

To fix it, copy or sync s3 files with acl, example:

aws s3 cp --acl bucket-owner-full-control s3://bucket1/key s3://bucket2/key

Java client certificates over HTTPS/SSL

Finally solved it ;). Got a strong hint here (Gandalfs answer touched a bit on it as well). The missing links was (mostly) the first of the parameters below, and to some extent that I overlooked the difference between keystores and truststores.

The self-signed server certificate must be imported into a truststore:

keytool -import -alias gridserver -file gridserver.crt -storepass $PASS -keystore gridserver.keystore

These properties need to be set (either on the commandline, or in code):

-Djavax.net.ssl.keyStoreType=pkcs12
-Djavax.net.ssl.trustStoreType=jks
-Djavax.net.ssl.keyStore=clientcertificate.p12
-Djavax.net.ssl.trustStore=gridserver.keystore
-Djavax.net.debug=ssl # very verbose debug
-Djavax.net.ssl.keyStorePassword=$PASS
-Djavax.net.ssl.trustStorePassword=$PASS

Working example code:

SSLSocketFactory sslsocketfactory = (SSLSocketFactory) SSLSocketFactory.getDefault();
URL url = new URL("https://gridserver:3049/cgi-bin/ls.py");
HttpsURLConnection conn = (HttpsURLConnection)url.openConnection();
conn.setSSLSocketFactory(sslsocketfactory);
InputStream inputstream = conn.getInputStream();
InputStreamReader inputstreamreader = new InputStreamReader(inputstream);
BufferedReader bufferedreader = new BufferedReader(inputstreamreader);

String string = null;
while ((string = bufferedreader.readLine()) != null) {
    System.out.println("Received " + string);
}

Remove leading zeros from a number in Javascript

We can use four methods for this conversion

  1. parseInt with radix 10
  2. Number Constructor
  3. Unary Plus Operator
  4. Using mathematical functions (subtraction)

_x000D_
_x000D_
const numString = "065";_x000D_
_x000D_
//parseInt with radix=10_x000D_
let number = parseInt(numString, 10);_x000D_
console.log(number);_x000D_
_x000D_
// Number constructor_x000D_
number = Number(numString);_x000D_
console.log(number);_x000D_
_x000D_
// unary plus operator_x000D_
number = +numString;_x000D_
console.log(number);_x000D_
_x000D_
// conversion using mathematical function (subtraction)_x000D_
number = numString - 0;_x000D_
console.log(number);
_x000D_
_x000D_
_x000D_


Update(based on comments): Why doesn't this work on "large numbers"?

For the primitive type Number, the safest max value is 253-1(Number.MAX_SAFE_INTEGER).

_x000D_
_x000D_
console.log(Number.MAX_SAFE_INTEGER);
_x000D_
_x000D_
_x000D_

Now, lets consider the number string '099999999999999999999' and try to convert it using the above methods

_x000D_
_x000D_
const numString = '099999999999999999999';_x000D_
_x000D_
let parsedNumber = parseInt(numString, 10);_x000D_
console.log(`parseInt(radix=10) result: ${parsedNumber}`);_x000D_
_x000D_
parsedNumber = Number(numString);_x000D_
console.log(`Number conversion result: ${parsedNumber}`);_x000D_
_x000D_
parsedNumber = +numString;_x000D_
console.log(`Appending Unary plus operator result: ${parsedNumber}`);_x000D_
_x000D_
parsedNumber = numString - 0;_x000D_
console.log(`Subtracting zero conversion result: ${parsedNumber}`);
_x000D_
_x000D_
_x000D_

All results will be incorrect.

That's because, when converted, the numString value is greater than Number.MAX_SAFE_INTEGER. i.e.,

99999999999999999999 > 9007199254740991

This means all operation performed with the assumption that the stringcan be converted to number type fails.

For numbers greater than 253, primitive BigInt has been added recently. Check browser compatibility of BigInthere.

The conversion code will be like this.

const numString = '099999999999999999999';
const number = BigInt(numString);

P.S: Why radix is important for parseInt?

If radix is undefined or 0 (or absent), JavaScript assumes the following:

  • If the input string begins with "0x" or "0X", radix is 16 (hexadecimal) and the remainder of the string is parsed
  • If the input string begins with "0", radix is eight (octal) or 10 (decimal)
  • If the input string begins with any other value, the radix is 10 (decimal)

Exactly which radix is chosen is implementation-dependent. ECMAScript 5 specifies that 10 (decimal) is used, but not all browsers support this yet.

For this reason, always specify a radix when using parseInt

Extract a substring from a string in Ruby using a regular expression

String1.scan(/<([^>]*)>/).last.first

scan creates an array which, for each <item> in String1 contains the text between the < and the > in a one-element array (because when used with a regex containing capturing groups, scan creates an array containing the captures for each match). last gives you the last of those arrays and first then gives you the string in it.

How to configure Fiddler to listen to localhost?

You cannot. Instead if you machine is named "myMachine", point your browser to http://mymachine instead of http://localhost

Dots in URL causes 404 with ASP.NET mvc and IIS

I was able to solve my particular version of this problem (had to make /customer.html route to /customer, trailing slashes not allowed) using the solution at https://stackoverflow.com/a/13082446/1454265, and substituting path="*.html".

How many values can be represented with n bits?

There's an easier way to think about this. Start with 1 bit. This can obviously represent 2 values (0 or 1). What happens when we add a bit? We can now represent twice as many values: the values we could represent before with a 0 appended and the values we could represent before with a 1 appended.

So the the number of values we can represent with n bits is just 2^n (2 to the power n)

How can I transform string to UTF-8 in C#?

Use the below code snippet to get bytes from csv file

protected byte[] GetCSVFileContent(string fileName)
    {
        StringBuilder sb = new StringBuilder();
        using (StreamReader sr = new StreamReader(fileName, Encoding.Default, true))
        {
            String line;
            // Read and display lines from the file until the end of 
            // the file is reached.
            while ((line = sr.ReadLine()) != null)
            {
                sb.AppendLine(line);
            }
        }
        string allines = sb.ToString();


        UTF8Encoding utf8 = new UTF8Encoding();


        var preamble = utf8.GetPreamble();

        var data = utf8.GetBytes(allines);


        return data;
    }

Call the below and save it as an attachment

           Encoding csvEncoding = Encoding.UTF8;
                   //byte[] csvFile = GetCSVFileContent(FileUpload1.PostedFile.FileName);
          byte[] csvFile = GetCSVFileContent("Your_CSV_File_NAme");


        string attachment = String.Format("attachment; filename={0}.csv", "uomEncoded");

        Response.Clear();
        Response.ClearHeaders();
        Response.ClearContent();
        Response.ContentType = "text/csv";
        Response.ContentEncoding = csvEncoding;
        Response.AppendHeader("Content-Disposition", attachment);
        //Response.BinaryWrite(csvEncoding.GetPreamble());
        Response.BinaryWrite(csvFile);
        Response.Flush();
        Response.End();

python replace single backslash with double backslash

You could use

os.path.abspath(path_with_backlash)

it returns the path with \

The ScriptManager must appear before any controls that need it

The script manager must be put onto the page before it is used. This would be directly on the page itself, or alternatively, if you are using them, on the Master Page.

The markup would be;

 <asp:ScriptManager ID="ScriptManager1" runat="server" LoadScriptsBeforeUI="true"
            EnablePartialRendering="true" />

Remove carriage return in Unix

For UNIX... I've noticed dos2unix removed Unicode headers form my UTF-8 file. Under git bash (Windows), the following script seems to work nicely. It uses sed. Note it only removes carriage-returns at the ends of lines, and preserves Unicode headers.

#!/bin/bash

inOutFile="$1"
backupFile="${inOutFile}~"
mv --verbose "$inOutFile" "$backupFile"
sed -e 's/\015$//g' <"$backupFile" >"$inOutFile"

If statement in select (ORACLE)

SELECT (CASE WHEN ISSUE_DIVISION = ISSUE_DIVISION_2 THEN 1 ELSE 0 END) AS ISSUES
    --  <add any columns to outer select from inner query> 
  FROM
 (  -- your query here --
   select 'CARAT Issue Open' issue_comment, ...., ..., 
          substr(gcrs.stream_name,1,case when instr(gcrs.stream_name,' (')=0 then 100 else  instr(gcrs.stream_name,' (')-1 end) ISSUE_DIVISION,
          case when gcrs.STREAM_NAME like 'NON-GT%' THEN 'NON-GT' ELSE gcrs.STREAM_NAME END as ISSUE_DIVISION_2
     from ....
    where UPPER(ISSUE_STATUS) like '%OPEN%'
 )
 WHERE... -- optional --

How to decode HTML entities using jQuery?

encode:

_x000D_
_x000D_
$("<textarea/>").html('<a>').html(); // return '&lt;a&gt'
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea/>
_x000D_
_x000D_
_x000D_

decode:

_x000D_
_x000D_
$("<textarea/>").html('&lt;a&gt').val() // return '<a>'
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea/>
_x000D_
_x000D_
_x000D_

How to convert string date to Timestamp in java?

You can convert String to Timestamp:

String inDate = "01-01-1990"
DateFormat df = new SimpleDateFormat("MM-dd-yyyy");
Timestamp ts = new Timestamp(((java.util.Date)df.parse(inDate)).getTime());

PHP read and write JSON from file

You need to make the decode function return an array by passing in the true parameter.

json_decode(file_get_contents($file),true);

How to change the hosts file on android

adb shell
su
mount -o rw,remount -t yaffs2 /dev/block/mtdblock3 /system

This assumes your /system is yaffs2 and that it's at /dev/block/mtdblock3 the easier/better way to do this on most Android phones is:

adb shell
su
mount -o remount,rw /system

Done. This just says remount /system read-write, you don't have to specify filesystem or mount location.

Logical Operators, || or OR?

Some languages use short-circuit, and others use full Boolean evaluation (if you know, this is similar to the directive $B in Pascal).

Explanations:

function A(){
    ...Do something..
    return true;
}

function B(){
    ...Do something..
    return true;
}

if ( A() OR B() ) { .....

In this example the function B() will never be executed. Since the function A() returns TRUE, the result of the OR statement is known from the first part without it being necessary to evaluate the second part of the expression.

However with ( A() || B() ), the second part is always evaluated regardless of the value of the first.

For optimized programming, you should always use OR which is faster (except for the case when the first part returns false and second part actually needs to be evaluated).

Render partial from different folder (not shared)

Try using RenderAction("myPartial","Account");

Binding a Button's visibility to a bool value in ViewModel

2 way conversion in c# from boolean to visibility

using System;
using System.Windows;
using System.Windows.Data;

namespace FaceTheWall.converters
{
    class BooleanToVisibilityConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value is Boolean && (bool)value)
            {
                return Visibility.Visible;
            }
            return Visibility.Collapsed;
        }

        public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
        {
            if (value is Visibility && (Visibility)value == Visibility.Visible)
            {
                return true;
            }
            return false;
        }
    }
}

How do I send email with JavaScript without opening the mail client?

Well, PHP can do this easily.

It can be done with the PHP mail() function. Here's what a simple function would look like:

<?php     
$to_email = '[email protected]';
$subject = 'Testing PHP Mail';
$message = 'This mail is sent using the PHP mail function';
$headers = 'From: [email protected]';
mail($to_email,$subject,$message,$headers);
?>

This will send a background e-mail to the recipient specified in the $to_email.

The above example uses hard coded values in the source code for the email address and other details for simplicity.

Let’s assume you have to create a contact us form for users fill in the details and then submit.

  1. Users can accidently or intentional inject code in the headers which can result in sending spam mail
  2. To protect your system from such attacks, you can create a custom function that sanitizes and validates the values before the mail is sent.

Let’s create a custom function that validates and sanitizes the email address using the filter_var() built in function.

Here's an example code:

<?php 
function sanitize_my_email($field) {
    $field = filter_var($field, FILTER_SANITIZE_EMAIL);
    if (filter_var($field, FILTER_VALIDATE_EMAIL)) {
        return true;
    } else {
        return false;
    }
}
$to_email = '[email protected]';
$subject = 'Testing PHP Mail';
$message = 'This mail is sent using the PHP mail ';
$headers = 'From: [email protected]';
//check if the email address is invalid $secure_check
$secure_check = sanitize_my_email($to_email);
if ($secure_check == false) {
    echo "Invalid input";
} else { //send email 
    mail($to_email, $subject, $message, $headers);
    echo "This email is sent using PHP Mail";
}
?>

We will now let this be a separate PHP file, for example sendmail.php.

Then, will use this file on form submission, using the action attribute of the form, like:

<form action="sendmail.php" method="post">
   <input type="text" value="Your Name: ">
   <input type="password" value="Set Up A Passworrd">
   <input type="submit" value="Signup">
   <input type="reset" value="Reset Form">
</form>

Hope I could help

What is the syntax for an inner join in LINQ to SQL?

var list = (from u in db.Users join c in db.Customers on u.CustomerId equals c.CustomerId where u.Username == username
   select new {u.UserId, u.CustomerId, u.ClientId, u.RoleId, u.Username, u.Email, u.Password, u.Salt, u.Hint1, u.Hint2, u.Hint3, u.Locked, u.Active,c.ProfilePic}).First();

Write table names you want, and initialize the select to get the result of fields.

Oracle timestamp data type

The number in parentheses specifies the precision of fractional seconds to be stored. So, (0) would mean don't store any fraction of a second, and use only whole seconds. The default value if unspecified is 6 digits after the decimal separator.

So an unspecified value would store a date like:

TIMESTAMP 24-JAN-2012 08.00.05.993847 AM

And specifying (0) stores only:

TIMESTAMP(0) 24-JAN-2012 08.00.05 AM

See Oracle documentation on data types.

Spring MVC 4: "application/json" Content Type is not being set correctly

As other people have commented, because the return type of your method is String Spring won't feel need to do anything with the result.

If you change your signature so that the return type is something that needs marshalling, that should help:

@RequestMapping(value = "/json", method = RequestMethod.GET, produces = "application/json")
@ResponseBody
public Map<String, Object> bar() {
    HashMap<String, Object> map = new HashMap<String, Object>();
    map.put("test", "jsonRestExample");
    return map;
}

Examples for string find in Python

if x is a string and you search for y which also a string their is two cases : case 1: y is exist in x so x.find(y) = the index (the position) of the y in x . case 2: y is not exist so x.find (y) = -1 this mean y is not found in x.

SVN: Is there a way to mark a file as "do not commit"?

I would instead write a helper bash script that runs svn commit on all the files you need to and none of the ones you don't. This way you have much more control.

For example, with one line, you can commit all files with extension .h and .cpp to which you made changes (and which wouldn't cause a conflict):

svn commit -m "" `svn status | grep "^M.*[h|cpp]$" | awk '{print $2}' | tr "\\n" " "`

Change / add extensions to the [h|cpp] part. Add a log message in between the quotes of -m "" if needed.

How to get instance variables in Python?

Sometimes you want to filter the list based on public/private vars. E.g.

def pub_vars(self):
    """Gives the variable names of our instance we want to expose
    """
    return [k for k in vars(self) if not k.startswith('_')]

How to redirect cin and cout to files?

Here is a short code snippet for shadowing cin/cout useful for programming contests:

#include <bits/stdc++.h>

using namespace std;

int main() {
    ifstream cin("input.txt");
    ofstream cout("output.txt");

    int a, b;   
    cin >> a >> b;
    cout << a + b << endl;
}

This gives additional benefit that plain fstreams are faster than synced stdio streams. But this works only for the scope of single function.

Global cin/cout redirect can be written as:

#include <bits/stdc++.h>

using namespace std;

void func() {
    int a, b;
    std::cin >> a >> b;
    std::cout << a + b << endl;
}

int main() {
    ifstream cin("input.txt");
    ofstream cout("output.txt");

    // optional performance optimizations    
    ios_base::sync_with_stdio(false);
    std::cin.tie(0);

    std::cin.rdbuf(cin.rdbuf());
    std::cout.rdbuf(cout.rdbuf());

    func();
}

Note that ios_base::sync_with_stdio also resets std::cin.rdbuf. So the order matters.

See also Significance of ios_base::sync_with_stdio(false); cin.tie(NULL);

Std io streams can also be easily shadowed for the scope of single file, which is useful for competitive programming:

#include <bits/stdc++.h>

using std::endl;

std::ifstream cin("input.txt");
std::ofstream cout("output.txt");

int a, b;

void read() {
    cin >> a >> b;
}

void write() {
    cout << a + b << endl;
}

int main() {
    read();
    write();
}

But in this case we have to pick std declarations one by one and avoid using namespace std; as it would give ambiguity error:

error: reference to 'cin' is ambiguous
     cin >> a >> b;
     ^
note: candidates are: 
std::ifstream cin
    ifstream cin("input.txt");
             ^
    In file test.cpp
std::istream std::cin
    extern istream cin;  /// Linked to standard input
                   ^

See also How do you properly use namespaces in C++?, Why is "using namespace std" considered bad practice? and How to resolve a name collision between a C++ namespace and a global function?

Express.js Response Timeout

In case you would like to use timeout middleware and exclude a specific route:

var timeout = require('connect-timeout');
app.use(timeout('5s')); //set 5s timeout for all requests

app.use('/my_route', function(req, res, next) {
    req.clearTimeout(); // clear request timeout
    req.setTimeout(20000); //set a 20s timeout for this request
    next();
}).get('/my_route', function(req, res) {
    //do something that takes a long time
});

Read file line by line using ifstream in C++

This is a general solution to loading data into a C++ program, and uses the readline function. This could be modified for CSV files, but the delimiter is a space here.

int n = 5, p = 2;

int X[n][p];

ifstream myfile;

myfile.open("data.txt");

string line;
string temp = "";
int a = 0; // row index 

while (getline(myfile, line)) { //while there is a line
     int b = 0; // column index
     for (int i = 0; i < line.size(); i++) { // for each character in rowstring
          if (!isblank(line[i])) { // if it is not blank, do this
              string d(1, line[i]); // convert character to string
              temp.append(d); // append the two strings
        } else {
              X[a][b] = stod(temp);  // convert string to double
              temp = ""; // reset the capture
              b++; // increment b cause we have a new number
        }
    }

  X[a][b] = stod(temp);
  temp = "";
  a++; // onto next row
}

How to use onBlur event on Angular2?

You can also use (focusout) event:

Use (eventName) for while binding event to DOM, basically () is used for event binding. Also you can use ngModel to get two way binding for your model. With the help of ngModel you can manipulate model variable value inside your component.

Do this in HTML file

<input type="text" [(ngModel)]="model" (focusout)="someMethodWithFocusOutEvent($event)">

And in your (component) .ts file

export class AppComponent { 
 model: any;
 constructor(){ }
 someMethodWithFocusOutEvent(){
   console.log('Your method called');
   // Do something here
 }
}

How to delete specific columns with VBA?

You say you want to delete any column with the title "Percent Margin of Error" so let's try to make this dynamic instead of naming columns directly.

Sub deleteCol()

On Error Resume Next

Dim wbCurrent As Workbook
Dim wsCurrent As Worksheet
Dim nLastCol, i As Integer

Set wbCurrent = ActiveWorkbook
Set wsCurrent = wbCurrent.ActiveSheet
'This next variable will get the column number of the very last column that has data in it, so we can use it in a loop later
nLastCol = wsCurrent.Cells.Find("*", LookIn:=xlValues, SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column

'This loop will go through each column header and delete the column if the header contains "Percent Margin of Error"
For i = nLastCol To 1 Step -1
    If InStr(1, wsCurrent.Cells(1, i).Value, "Percent Margin of Error", vbTextCompare) > 0 Then
        wsCurrent.Columns(i).Delete Shift:=xlShiftToLeft
    End If
Next i

End Sub

With this you won't need to worry about where you data is pasted/imported to, as long as the column headers are in the first row.

EDIT: And if your headers aren't in the first row, it would be a really simple change. In this part of the code: If InStr(1, wsCurrent.Cells(1, i).Value, "Percent Margin of Error", vbTextCompare) change the "1" in Cells(1, i) to whatever row your headers are in.

EDIT 2: Changed the For section of the code to account for completely empty columns.

What does the "$" sign mean in jQuery or JavaScript?

In JavaScript it has no special significance (no more than a or Q anyway). It is just an uninformative variable name.

In jQuery the variable is assigned a copy of the jQuery function. This function is heavily overloaded and means half a dozen different things depending on what arguments it is passed. In this particular example you are passing it a string that contains a selector, so the function means "Create a jQuery object containing the element with the id Text".

Visual Studio Code open tab in new window

With Visual Studio 1.43 (Q1 2020), the Ctrl+K then O keyboard shortcut will work for a file.

See issue 89989:

It should be possible to e.g. invoke the "Open Active File in New Window" command and open that file into an empty workspace in the web.

new windows -- https://user-images.githubusercontent.com/900690/73733120-aa0f6680-473b-11ea-8bcd-f2f71b75b496.png

How to install MySQLdb package? (ImportError: No module named setuptools)

If MySQLdb's now distributed in a way that requires setuptools, your choices are either to download the latter (e.g. from here) or refactor MySQLdb's setup.py to bypass setuptools (maybe just importing setup and Extension from plain distutils instead might work, but you may also need to edit some of the setup_*.py files in the same directory).

Depending on how your site's Python installation is configured, installing extensions for your own individual use without requiring sysadm rights may be hard, but it's never truly impossible if you have shell access. You'll need to tweak your Python's sys.path to start with a directory of your own that's your personal equivalent of the system-wide site pacages directory, e.g. by setting PYTHONPATH persistently in your own environment, and then manually place in said personal directory what normal installs would normally place in site-packages (and/or subdirectories thereof).

How to get last 7 days data from current datetime to last 7 days in sql server

If you want to do it using Pentaho DI, you can use "Modified JavaScript" Step and write the below function:

dateAdd(d1, "d", -7);  // d1 is the current date and "d" is the date identifier

Check the image below: [Assuming current date is : 22 December 2014]

enter image description here

Hope it helps :)

What does the 'export' command do?

In simple terms, environment variables are set when you open a new shell session. At any time if you change any of the variable values, the shell has no way of picking that change. that means the changes you made become effective in new shell sessions. The export command, on the other hand, provides the ability to update the current shell session about the change you made to the exported variable. You don't have to wait until new shell session to use the value of the variable you changed.

How to display a list inline using Twitter's Bootstrap

I couldn't find anything specific within the bootstrap.css file. So, I added the css to a custom css file.

.inline li {
    display: inline;
}

How to save username and password with Mercurial?

mercurial_keyring installation on Mac OSX using MacPorts:

sudo port install py-keyring
sudo port install py-mercurial_keyring

Add the following to ~/.hgrc:

# Add your username if you haven't already done so.
[ui]
username = [email protected]

[extensions]
mercurial_keyring =

Adding script tag to React/JSX

You can use npm postscribe to load script in react component

postscribe('#mydiv', '<script src="https://use.typekit.net/foobar.js"></script>')

Select last row in MySQL

Many answers here say the same (order by your auto increment), which is OK, provided you have an autoincremented column that is indexed.

On a side note, if you have such field and it is the primary key, there is no performance penalty for using order by versus select max(id). The primary key is how data is ordered in the database files (for InnoDB at least), and the RDBMS knows where that data ends, and it can optimize order by id + limit 1 to be the same as reach the max(id)

Now the road less traveled is when you don't have an autoincremented primary key. Maybe the primary key is a natural key, which is a composite of 3 fields... Not all is lost, though. From a programming language you can first get the number of rows with

SELECT Count(*) - 1 AS rowcount FROM <yourTable>;

and then use the obtained number in the LIMIT clause

SELECT * FROM orderbook2
LIMIT <number_from_rowcount>, 1

Unfortunately, MySQL will not allow for a sub-query, or user variable in the LIMIT clause

How to deal with missing src/test/java source folder in Android/Maven project?

I realise this annoying thing too since latest m2e-android plugin upgrade (version 0.4.2), it happens in both new project creation and existing project import (if you don't use src/test/java).

It looks like m2e-android (or perhaps m2e) now always trying to add src/test/java as a source folder, regardless of whether it is actually existed in your project directory, in the .classpath file:

<classpathentry kind="src" output="bin/classes" path="src/test/java">
  <attributes>
    <attribute name="maven.pomderived" value="true"/>
  </attributes>
</classpathentry>

As it is already added in the project metadata file, so if you trying to add the source folder via Eclipse, Eclipse will complain that the classpathentry is already exist:

enter image description here

There are several ways to fix it, the easiest is manually create src/test/java directory in the file system, then refresh your project by press F5 and run Maven -> Update Project (Right click project, choose Maven -> Update Project...), this should fix the missing required source folder: 'src/test/java' error.

Redirecting from HTTP to HTTPS with PHP

Try something like this (should work for Apache and IIS):

if (empty($_SERVER['HTTPS']) || $_SERVER['HTTPS'] === "off") {
    $location = 'https://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    header('HTTP/1.1 301 Moved Permanently');
    header('Location: ' . $location);
    exit;
}

What Ruby IDE do you prefer?

Ruby in Steel: http://www.sapphiresteel.com/Products/Ruby-In-Steel/Ruby-In-Steel-Developer-Overview

A Visual Studio based Ruby IDE. Fast Debugger. Intellisense.

How to give ASP.NET access to a private key in a certificate in the certificate store?

  1. Create / Purchase certificate. Make sure it has a private key.
  2. Import the certificate into the "Local Computer" account. Best to use Certificates MMC. Make sure to check "Allow private key to be exported"
  3. Based upon which, IIS 7.5 Application Pool's identity use one of the following.

    • IIS 7.5 Website is running under ApplicationPoolIdentity. Open MMC => Add Certificates (Local computer) snap-in => Certificates (Local Computer) => Personal => Certificates => Right click the certificate of interest => All tasks => Manage private key => Add IIS AppPool\AppPoolName and grant it Full control. Replace "AppPoolName" with the name of your application pool (sometimes IIS_IUSRS)
    • IIS 7.5 Website is running under NETWORK SERVICE. Using Certificates MMC, added "NETWORK SERVICE" to Full Trust on certificate in "Local Computer\Personal".
    • IIS 7.5 Website is running under "MyIISUser" local computer user account. Using Certificates MMC, added "MyIISUser" (a new local computer user account) to Full Trust on certificate in "Local Computer\Personal".

Update based upon @Phil Hale comment:

Beware, if you're on a domain, your domain will be selected by default in the 'from location box'. Make sure to change that to "Local Computer". Change the location to "Local Computer" to view the app pool identities.

Connect to SQL Server database from Node.js

We just released preview driver for Node.JS for SQL Server connectivity. You can find it here: Introducing the Microsoft Driver for Node.JS for SQL Server.

The driver supports callbacks (here, we're connecting to a local SQL Server instance):

// Query with explicit connection
var sql = require('node-sqlserver');
var conn_str = "Driver={SQL Server Native Client 11.0};Server=(local);Database=AdventureWorks2012;Trusted_Connection={Yes}";

sql.open(conn_str, function (err, conn) {
    if (err) {
        console.log("Error opening the connection!");
        return;
    }
    conn.queryRaw("SELECT TOP 10 FirstName, LastName FROM Person.Person", function (err, results) {
        if (err) {
            console.log("Error running query!");
            return;
        }
        for (var i = 0; i < results.rows.length; i++) {
            console.log("FirstName: " + results.rows[i][0] + " LastName: " + results.rows[i][1]);
        }
    });
});

Alternatively, you can use events (here, we're connecting to SQL Azure a.k.a Windows Azure SQL Database):

// Query with streaming
var sql = require('node-sqlserver');
var conn_str = "Driver={SQL Server Native Client 11.0};Server={tcp:servername.database.windows.net,1433};UID={username};PWD={Password1};Encrypt={Yes};Database={databasename}";

var stmt = sql.query(conn_str, "SELECT FirstName, LastName FROM Person.Person ORDER BY LastName OFFSET 0 ROWS FETCH NEXT 10 ROWS ONLY");
stmt.on('meta', function (meta) { console.log("We've received the metadata"); });
stmt.on('row', function (idx) { console.log("We've started receiving a row"); });
stmt.on('column', function (idx, data, more) { console.log(idx + ":" + data);});
stmt.on('done', function () { console.log("All done!"); });
stmt.on('error', function (err) { console.log("We had an error :-( " + err); });

If you run into any problems, please file an issue on Github: https://github.com/windowsazure/node-sqlserver/issues

How to calculate a time difference in C++

If you are using:

tstart = clock();

// ...do something...

tend = clock();

Then you will need the following to get time in seconds:

time = (tend - tstart) / (double) CLOCKS_PER_SEC;

Put a Delay in Javascript

This thread has a good discussion and a useful solution:

function pause( iMilliseconds )
{
    var sDialogScript = 'window.setTimeout( function () { window.close(); }, ' + iMilliseconds + ');';
    window.showModalDialog('javascript:document.writeln ("<script>' + sDialogScript + '<' + '/script>")');
}

Unfortunately it appears that this doesn't work in some versions of IE, but the thread has many other worthy proposals if that proves to be a problem for you.

How to "properly" print a list?

I was inspired by @AniMenon to write a pythonic more general solution.

mylist = ['x', 3, 'b']
print('[{}]'.format(', '.join(map('{}'.format, mylist))))

It only uses the format method. No trace of str, and it allows for the fine tuning of the elements format. For example, if you have float numbers as elements of the list, you can adjust their format, by adding a conversion specifier, in this case :.2f

mylist = [1.8493849, -6.329323, 4000.21222111]
print("[{}]".format(', '.join(map('{:.2f}'.format, mylist))))

The output is quite decent:

[1.85, -6.33, 4000.21]

How to get on scroll events?

Listen to window:scroll event for window/document level scrolling and element's scroll event for element level scrolling.

window:scroll

@HostListener('window:scroll', ['$event'])
onWindowScroll($event) {

}

or

<div (window:scroll)="onWindowScroll($event)">

scroll

@HostListener('scroll', ['$event'])
onElementScroll($event) {

}

or

<div (scroll)="onElementScroll($event)">

@HostListener('scroll', ['$event']) won't work if the host element itself is not scroll-able.

Examples

Android BroadcastReceiver within Activity

You need to define the receiver as a class in the manifest and it will receive the intent:

<application
  ....
  <receiver android:name=".ToastReceiver">
    <intent-filter>
      <action android:name="com.unitedcoders.android.broadcasttest.SHOWTOAST"/>
    </intent-filter>
  </receiver>
</application>

And you don't need to create the class manually inside ToastDisplay.

In the code you provided, you must be inside ToastDisplay activity to actually receive the Intent.

Try-Catch-End Try in VBScript doesn't seem to work

VBScript doesn't have Try/Catch. (VBScript language reference. If it had Try, it would be listed in the Statements section.)

On Error Resume Next is the only error handling in VBScript. Sorry. If you want try/catch, JScript is an option. It's supported everywhere that VBScript is and has the same capabilities.

Check if table exists in SQL Server

Also note that if for any reason you need to check for a temporary table you can do this:

if OBJECT_ID('tempdb..#test') is not null
 --- temp table exists

How to use UTF-8 in resource properties with ResourceBundle

The ResourceBundle#getBundle() uses under the covers PropertyResourceBundle when a .properties file is specified. This in turn uses by default Properties#load(InputStream) to load those properties files. As per the javadoc, they are by default read as ISO-8859-1.

public void load(InputStream inStream) throws IOException

Reads a property list (key and element pairs) from the input byte stream. The input stream is in a simple line-oriented format as specified in load(Reader) and is assumed to use the ISO 8859-1 character encoding; that is each byte is one Latin1 character. Characters not in Latin1, and certain special characters, are represented in keys and elements using Unicode escapes as defined in section 3.3 of The Java™ Language Specification.

So, you'd need to save them as ISO-8859-1. If you have any characters beyond ISO-8859-1 range and you can't use \uXXXX off top of head and you're thus forced to save the file as UTF-8, then you'd need to use the native2ascii tool to convert an UTF-8 saved properties file to an ISO-8859-1 saved properties file wherein all uncovered characters are converted into \uXXXX format. The below example converts a UTF-8 encoded properties file text_utf8.properties to a valid ISO-8859-1 encoded properties file text.properties.

native2ascii -encoding UTF-8 text_utf8.properties text.properties

When using a sane IDE such as Eclipse, this is already automatically done when you create a .properties file in a Java based project and use Eclipse's own editor. Eclipse will transparently convert the characters beyond ISO-8859-1 range to \uXXXX format. See also below screenshots (note the "Properties" and "Source" tabs on bottom, click for large):

"Properties" tab "Source" tab

Alternatively, you could also create a custom ResourceBundle.Control implementation wherein you explicitly read the properties files as UTF-8 using InputStreamReader, so that you can just save them as UTF-8 without the need to hassle with native2ascii. Here's a kickoff example:

public class UTF8Control extends Control {
    public ResourceBundle newBundle
        (String baseName, Locale locale, String format, ClassLoader loader, boolean reload)
            throws IllegalAccessException, InstantiationException, IOException
    {
        // The below is a copy of the default implementation.
        String bundleName = toBundleName(baseName, locale);
        String resourceName = toResourceName(bundleName, "properties");
        ResourceBundle bundle = null;
        InputStream stream = null;
        if (reload) {
            URL url = loader.getResource(resourceName);
            if (url != null) {
                URLConnection connection = url.openConnection();
                if (connection != null) {
                    connection.setUseCaches(false);
                    stream = connection.getInputStream();
                }
            }
        } else {
            stream = loader.getResourceAsStream(resourceName);
        }
        if (stream != null) {
            try {
                // Only this line is changed to make it to read properties files as UTF-8.
                bundle = new PropertyResourceBundle(new InputStreamReader(stream, "UTF-8"));
            } finally {
                stream.close();
            }
        }
        return bundle;
    }
}

This can be used as follows:

ResourceBundle bundle = ResourceBundle.getBundle("com.example.i18n.text", new UTF8Control());

See also:

How to store date/time and timestamps in UTC time zone with JPA and Hibernate

To the best of my knowledge, you need to put your entire Java app in UTC timezone (so that Hibernate will store dates in UTC), and you'll need to convert to whatever timezone desired when you display stuff (at least we do it this way).

At startup, we do:

TimeZone.setDefault(TimeZone.getTimeZone("Etc/UTC"));

And set the desired timezone to the DateFormat:

fmt.setTimeZone(TimeZone.getTimeZone("Europe/Budapest"))

How to install "make" in ubuntu?

I have no idea what linux distribution "ubuntu centOS" is. Ubuntu and CentOS are two different distributions.

To answer the question in the header: To install make in ubuntu you have to install build-essentials

sudo apt-get install build-essential

How to read existing text files without defining path

As your project is a console project you can pass the path to the text files that you want to read via the string[] args

static void Main(string[] args)
{
}

Within Main you can check if arguments are passed

if (args.Length == 0){ System.Console.WriteLine("Please enter a parameter");}

Extract an argument

string fileToRead = args[0];

Nearly all languages support the concept of argument passing and follow similar patterns to C#.

For more C# specific see http://msdn.microsoft.com/en-us/library/vstudio/cb20e19t.aspx

Can I set the cookies to be used by a WKWebView?

I have tried all of the answers above but none of them work. After so many attempts I've finally found a reliable way to set WKWebview cookie.

First you have to create an instance of WKProcessPool and set it to the WKWebViewConfiguration that is to be used to initialize the WkWebview itself:

    private lazy var mainWebView: WKWebView = {
        let webConfiguration = WKWebViewConfiguration()
        webConfiguration.processPool = WKProcessPool()
        let webView = WKWebView(frame: .zero, configuration: webConfiguration)
        webView.navigationDelegate = self
        return webView
    }()

Setting WKProcessPool is the most important step here. WKWebview makes use of process isolation - which means it runs on a different process than the process of your app. This can sometimes cause conflict and prevent your cookie from being synced properly with the WKWebview.

Now let's look at the definition of WKProcessPool

The process pool associated with a web view is specified by its web view configuration. Each web view is given its own Web Content process until an implementation-defined process limit is reached; after that, web views with the same process pool end up sharing Web Content processes.

Pay attention to the last sentence if you plan to use the same WKWebview for subsequence requests

web views with the same process pool end up sharing Web Content processes

what I means is that if you don't use the same instance of WKProcessPool each time you configure a WKWebView for the same domain (maybe you have a VC A that contains a WKWebView and you want to create different instances of VC A in different places), there can be conflict setting cookies. To solve the problem, after the first creation of the WKProcessPool for a WKWebView that loads domain B, I save it in a singleton and use that same WKProcessPool every time I have to create a WKWebView that loads the same domain B

private lazy var mainWebView: WKWebView = {
    let webConfiguration = WKWebViewConfiguration()
    if Enviroment.shared.processPool == nil {
        Enviroment.shared.processPool = WKProcessPool()
    }
    webConfiguration.processPool = Enviroment.shared.processPool!
    webConfiguration.processPool = WKProcessPool()
    let webView = WKWebView(frame: .zero, configuration: webConfiguration)
    webView.navigationDelegate = self
    return webView
}()

After the initialization process, you can load an URLRequest inside the completion block of httpCookieStore.setCookie. Here, you have to attach the cookie to the request header otherwise it won't work.

P/s: I stole the extension from the fantastic answer above by Dan Loewenherz

mainWebView.configuration.websiteDataStore.httpCookieStore.setCookie(your_cookie) {
        self.mainWebView.load(your_request, with: [your_cookie])
}

extension WKWebView {
   func load(_ request: URLRequest, with cookies: [HTTPCookie]) {
      var request = request
      let headers = HTTPCookie.requestHeaderFields(with: cookies)
      for (name, value) in headers {
         request.addValue(value, forHTTPHeaderField: name)
      }        
      load(request)
   }
}

Issue with background color in JavaFX 8

panel.setStyle("-fx-background-color: #FFFFFF;");

How to generate a HTML page dynamically using PHP?

I suggest you to use URL rewrite mod is enough for your problem,I have the same problem but using URL rewrite mod and getting good SEO response. I can give you a small example. Example is that you consider WordPress , here the data is stored in database but using URL rewrite mod many WordPress websites getting good responses from Google and got rank also.

Example: wordpress url with out url rewrite mod -- domain.com/?p=123 after url rewrite mode -- domain.com/{title of article} like domain.com/seo-url-rewrite-mod

i think you have understood what i want to say you

Image Processing: Algorithm Improvement for 'Coca-Cola Can' Recognition

This may be a very naive idea (or may not work at all), but the dimensions of all the coke cans are fixed. So may be if the same image contains both a can and a bottle then you can tell them apart by size considerations (bottles are going to be larger). Now because of missing depth (i.e. 3D mapping to 2D mapping) its possible that a bottle may appear shrunk and there isn't a size difference. You may recover some depth information using stereo-imaging and then recover the original size.

hide/show a image in jquery

What image do you want to hide? Assuming all images, the following should work:

$("img").hide();

Otherwise, using selectors, you could find all images that are child elements of the containing div, and hide those.

However, i strongly recommend you read the Jquery docs, you could have figured it out yourself: http://docs.jquery.com/Main_Page

What exactly does the Access-Control-Allow-Credentials header do?

By default, CORS does not include cookies on cross-origin requests. This is different from other cross-origin techniques such as JSON-P. JSON-P always includes cookies with the request, and this behavior can lead to a class of vulnerabilities called cross-site request forgery, or CSRF.

In order to reduce the chance of CSRF vulnerabilities in CORS, CORS requires both the server and the client to acknowledge that it is ok to include cookies on requests. Doing this makes cookies an active decision, rather than something that happens passively without any control.

The client code must set the withCredentials property on the XMLHttpRequest to true in order to give permission.

However, this header alone is not enough. The server must respond with the Access-Control-Allow-Credentials header. Responding with this header to true means that the server allows cookies (or other user credentials) to be included on cross-origin requests.

You also need to make sure your browser isn't blocking third-party cookies if you want cross-origin credentialed requests to work.

Note that regardless of whether you are making same-origin or cross-origin requests, you need to protect your site from CSRF (especially if your request includes cookies).

Hibernate SessionFactory vs. JPA EntityManagerFactory

EntityManagerFactory is the standard implementation, it is the same across all the implementations. If you migrate your ORM for any other provider like EclipseLink, there will not be any change in the approach for handling the transaction. In contrast, if you use hibernate’s session factory, it is tied to hibernate APIs and cannot migrate to new vendor.

How to examine processes in OS X's Terminal?

You can just use top It will display everything running on your OSX

No connection could be made because the target machine actively refused it 127.0.0.1:3446

With similar pattern, my rest client is calling the service API, the service called successfully when debugging, but not working on the published code. Error was: Unable to connect to the remote server.

Inner Exception: System.Net.Sockets.SocketException (0x80004005): No connection could be made because the target machine actively refused it serviceIP:443 at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress) at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Exception& exception)

Resolution: Set the proxy in Web config.

<system.net>
    <defaultProxy useDefaultCredentials="true">
      <proxy proxyaddress="http://proxy_ip:portno/" usesystemdefault="True"/>
    </defaultProxy>
</system.net>

Java current machine name and logged in user?

To get the currently logged in user:

System.getProperty("user.name"); //platform independent 

and the hostname of the machine:

java.net.InetAddress localMachine = java.net.InetAddress.getLocalHost();
System.out.println("Hostname of local machine: " + localMachine.getHostName());

Reading InputStream as UTF-8

String file = "";

try {

    InputStream is = new FileInputStream(filename);
    String UTF8 = "utf8";
    int BUFFER_SIZE = 8192;

    BufferedReader br = new BufferedReader(new InputStreamReader(is,
            UTF8), BUFFER_SIZE);
    String str;
    while ((str = br.readLine()) != null) {
        file += str;
    }
} catch (Exception e) {

}

Try this,.. :-)

Getting Image from API in Angular 4/5+?

angular 5 :

 getImage(id: string): Observable<Blob> {
    return this.httpClient.get('http://myip/image/'+id, {responseType: "blob"});
}

Passing data through intent using Serializable

This code may help you:

public class EN implements Serializable {
//... you don't need implement any methods when you implements Serializable
}

Putting data. Create new Activity with extra:

EN enumb = new EN();
Intent intent = new Intent(getActivity(), NewActivity.class);
intent.putExtra("en", enumb); //second param is Serializable
startActivity(intent);

Obtaining data from new activity:

public class NewActivity extends Activity {

    private EN en;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        try {
            super.onCreate(savedInstanceState);

            Bundle extras = getIntent().getExtras();
            if (extras != null) {
                en = (EN)getIntent().getSerializableExtra("en"); //Obtaining data 
            }
//...

Are the PUT, DELETE, HEAD, etc methods available in most web browsers?

I believe those comments refer specifically to the browsers, i.e., clicking links and submitting forms, not XMLHttpRequest. XMLHttpRequest is just a custom client that you wrote in JavaScript that uses the browser as a runtime.

UPDATE: To clarify, I did not mean (though I did write) that you wrote XMLHttpRequest; I meant that you wrote the code that uses XMLHttpRequest. The browsers do not natively support XMLHttpRequest. XMLHttpRequest comes from the JavaScript runtime, which may be hosted by a browser, although it isn't required to be (see Rhino). That's why people say browsers don't support PUT and DELETE—because it's actually JavaScript that is supporting them.

Applying CSS styles to all elements inside a DIV

If you're looking for a shortcut for writing out all of your selectors, then a CSS Preprocessor (Sass, LESS, Stylus, etc.) can do what you're looking for. However, the generated styles must be valid CSS.

Sass:

#applyCSS {
    .ui-bar-a {
       color: blue;
    }
    .ui-bar-a .ui-link-inherit {
       color: orange;
    }
    background: #CCC;
}

Generated CSS:

#applyCSS {
  background: #CCC;
}

#applyCSS .ui-bar-a {
  color: blue;
}

#applyCSS .ui-bar-a .ui-link-inherit {
  color: orange;
}

Can I map a hostname *and* a port with /etc/hosts?

No, that's not possible. The port is not part of the hostname, so it has no meaning in the hosts-file.

What does double question mark (??) operator mean in PHP

It's the "null coalescing operator", added in php 7.0. The definition of how it works is:

It returns its first operand if it exists and is not NULL; otherwise it returns its second operand.

So it's actually just isset() in a handy operator.

Those two are equivalent1:

$foo = $bar ?? 'something';
$foo = isset($bar) ? $bar : 'something';

Documentation: http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.coalesce

In the list of new PHP7 features: http://php.net/manual/en/migration70.new-features.php#migration70.new-features.null-coalesce-op

And original RFC https://wiki.php.net/rfc/isset_ternary


EDIT: As this answer gets a lot of views, little clarification:

1There is a difference: In case of ??, the first expression is evaluated only once, as opposed to ? :, where the expression is first evaluated in the condition section, then the second time in the "answer" section.

Entity framework left join

If you prefer method call notation, you can force a left join using SelectMany combined with DefaultIfEmpty. At least on Entity Framework 6 hitting SQL Server. For example:

using(var ctx = new MyDatabaseContext())
{
    var data = ctx
    .MyTable1
    .SelectMany(a => ctx.MyTable2
      .Where(b => b.Id2 == a.Id1)
      .DefaultIfEmpty()
      .Select(b => new
      {
        a.Id1,
        a.Col1,
        Col2 = b == null ? (int?) null : b.Col2,
      }));
}

(Note that MyTable2.Col2 is a column of type int). The generated SQL will look like this:

SELECT 
    [Extent1].[Id1] AS [Id1], 
    [Extent1].[Col1] AS [Col1], 
    CASE WHEN ([Extent2].[Col2] IS NULL) THEN CAST(NULL AS int) ELSE  CAST( [Extent2].[Col2] AS int) END AS [Col2]
    FROM  [dbo].[MyTable1] AS [Extent1]
    LEFT OUTER JOIN [dbo].[MyTable2] AS [Extent2] ON [Extent2].[Id2] = [Extent1].[Id1]

How to format a URL to get a file from Amazon S3?

Perhaps not what the OP was after, but for those searching the URL to simply access a readable object on S3 is more like:

https://<region>.amazonaws.com/<bucket-name>/<key>

Where <region> is something like s3-ap-southeast-2.

Click on the item in the S3 GUI to get the link for your bucket.

How do I prevent 'git diff' from using a pager?

Just follow below instructions.

  1. Just type vi ~/.gitconfig in your terminal.
  2. Paste LESS="-F -X $LESS" line.
  3. Press :wq and enter.
  4. Restart your terminal.

Appending to 2D lists in Python

You haven't created three different empty lists. You've created one empty list, and then created a new list with three references to that same empty list. To fix the problem use this code instead:

listy = [[] for i in range(3)]

Running your example code now gives the result you probably expected:

>>> listy = [[] for i in range(3)]
>>> listy[1] = [1,2]
>>> listy
[[], [1, 2], []]
>>> listy[1].append(3)
>>> listy
[[], [1, 2, 3], []]
>>> listy[2].append(1)
>>> listy
[[], [1, 2, 3], [1]]

How to exit an if clause

Effectively what you're describing are goto statements, which are generally panned pretty heavily. Your second example is far easier to understand.

However, cleaner still would be:

if some_condition:
   ...
   if condition_a:
       your_function1()
   else:
       your_function2()

...

def your_function2():
   if condition_b:
       # do something
       # and then exit the outer if block
   else:
       # more code here

How to draw text using only OpenGL methods?

This article describes how to render text in OpenGL using various techniques.

With only using opengl, there are several ways:

  • using glBitmap
  • using textures
  • using display lists

How do you add CSS with Javascript?

Here's my general-purpose function which parametrizes the CSS selector and rules, and optionally takes in a css filename (case-sensitive) if you wish to add to a particular sheet instead (otherwise, if you don't provide a CSS filename, it will create a new style element and append it to the existing head. It will make at most one new style element and re-use it on future function calls). Works with FF, Chrome, and IE9+ (maybe earlier too, untested).

function addCssRules(selector, rules, /*Optional*/ sheetName) {
    // We want the last sheet so that rules are not overridden.
    var styleSheet = document.styleSheets[document.styleSheets.length - 1];
    if (sheetName) {
        for (var i in document.styleSheets) {
            if (document.styleSheets[i].href && document.styleSheets[i].href.indexOf(sheetName) > -1) {
                styleSheet = document.styleSheets[i];
                break;
            }
        }
    }
    if (typeof styleSheet === 'undefined' || styleSheet === null) {
        var styleElement = document.createElement("style");
        styleElement.type = "text/css";
        document.head.appendChild(styleElement);
        styleSheet = styleElement.sheet;
    }

    if (styleSheet) {
        if (styleSheet.insertRule)
            styleSheet.insertRule(selector + ' {' + rules + '}', styleSheet.cssRules.length);
        else if (styleSheet.addRule)
            styleSheet.addRule(selector, rules);
    }
}

Room - Schema export directory is not provided to the annotation processor so we cannot export the schema

@mikejonesguy answer is perfect, just in case you plan to test room migrations (recommended), add the schema location to the source sets.

In your build.gradle file you specify a folder to place these generated schema JSON files. As you update your schema, you’ll end up with several JSON files, one for every version. Make sure you commit every generated file to source control. The next time you increase your version number again, Room will be able to use the JSON file for testing.

build.gradle

android {

    // [...]

    defaultConfig {

        // [...]

        javaCompileOptions {
            annotationProcessorOptions {
                arguments = ["room.schemaLocation": "$projectDir/schemas".toString()]
            }
        }
    }

    // add the schema location to the source sets
    // used by Room, to test migrations
    sourceSets {
        androidTest.assets.srcDirs += files("$projectDir/schemas".toString())
    }

    // [...]
}

How to loop through a plain JavaScript object with the objects as members?

forEach2

( found here) :

var lunch = {
    sandwich: 'ham',
    age: 48,
};
lunch.forEach2(function (item, key) {
    console.log(key);
    console.log(item);
});

Code:

if (!Object.prototype.forEach2) {
    Object.defineProperty(Object.prototype, 'forEach2', {
        value: function (callback, thisArg) {
            if (this == null) {
                throw new TypeError('Not an object');
            }
            thisArg = thisArg || window;
            for (var key in this) {
                if (this.hasOwnProperty(key)) {
                    callback.call(thisArg, this[key], key, this);
                }
            }
        }
    });
}

How to impose maxlength on textArea in HTML using JavaScript

The maxlength attribute is supported in Internet Explorer 10, Firefox, Chrome, and Safari.

Note: The maxlength attribute of the <textarea> tag is not supported in Internet Explorer 9 and earlier versions, or in Opera.

from HTML maxlength Attribute w3schools.com

For IE8 or earlier versions you have to use the following

//only call this function in IE
function maxLengthLimit($textarea){
    var maxlength = parseInt($textarea.attr("maxlength"));
    //in IE7,maxlength attribute can't be got,I don't know why...
    if($.browser.version=="7.0"){
        maxlength = parseInt($textarea.attr("length"));
    }
    $textarea.bind("keyup blur",function(){
        if(this.value.length>maxlength){
            this.value=this.value.substr(0,maxlength);
        }
    });
}

P.S.

The maxlength attribute of the <input> tag is supported in all major browsers.

from HTML maxlength Attribute w3schools.com

Getting 404 Not Found error while trying to use ErrorDocument

When we apply local url, ErrorDocument directive expect the full path from DocumentRoot. There fore,

 ErrorDocument 404 /yourfoldernames/errors/404.html

What is the difference between canonical name, simple name and class name in Java Class?

getName() – returns the name of the entity (class, interface, array class, primitive type, or void) represented by this Class object, as a String.

getCanonicalName() – returns the canonical name of the underlying class as defined by the Java Language Specification.

getSimpleName() – returns the simple name of the underlying class, that is the name it has been given in the source code.

package com.practice;

public class ClassName {
public static void main(String[] args) {

  ClassName c = new ClassName();
  Class cls = c.getClass();

  // returns the canonical name of the underlying class if it exists
  System.out.println("Class = " + cls.getCanonicalName());    //Class = com.practice.ClassName
  System.out.println("Class = " + cls.getName());             //Class = com.practice.ClassName
  System.out.println("Class = " + cls.getSimpleName());       //Class = ClassName
  System.out.println("Class = " + Map.Entry.class.getName());             // -> Class = java.util.Map$Entry
  System.out.println("Class = " + Map.Entry.class.getCanonicalName());    // -> Class = java.util.Map.Entry
  System.out.println("Class = " + Map.Entry.class.getSimpleName());       // -> Class = Entry 
  }
}

One difference is that if you use an anonymous class you can get a null value when trying to get the name of the class using the getCanonicalName()

Another fact is that getName() method behaves differently than the getCanonicalName() method for inner classes. getName() uses a dollar as the separator between the enclosing class canonical name and the inner class simple name.

To know more about retrieving a class name in Java.

How to easily duplicate a Windows Form in Visual Studio?

Just rename the class the designer references.

But a better solution is to create a new instance of the same class at run time.

Or better yet, create a parent form that various implementations inherit from.

Can a PDF file's print dialog be opened with Javascript?

I usually do something similar to the approach given by How to Use JavaScript to Print a PDF (eHow.com), using an iframe.

  1. a function to house the print trigger...

    function printTrigger(elementId) {
        var getMyFrame = document.getElementById(elementId);
        getMyFrame.focus();
        getMyFrame.contentWindow.print();
    }
    
  2. an button to give the user access...

    (an onClick on an a or button or input or whatever you wish)

    <input type="button" value="Print" onclick="printTrigger('iFramePdf');" />
    
  3. an iframe pointing to your PDF...

    <iframe id="iFramePdf" src="myPdfUrl.pdf" style="display:none;"></iframe>
    

Bonus Idea #1 - Create the iframe and add it to your page within the printTrigger(); so that the PDF isn't loaded until the user clicks your "Print" button, then the javascript can attack! the iframe and trigger the print dialog.


Bonus Idea #2 - Extra credit if you disable your "Print" button and give the user a little loading spinner or something after they click it, so that they know something's in process instead of clicking it repeatedly!

How to prevent browser to invoke basic auth popup and handle 401 error using Jquery?

In Safari, you can use synchronous requests to avoid the browser to display the popup. Of course, synchronous requests should only be used in this case to check user credentials... You can use a such request before sending the actual request which may cause a bad user experience if the content (sent or received) is quite heavy.

    var xmlhttp=new XMLHttpRequest;
    xmlhttp.withCredentials=true;
    xmlhttp.open("POST",<YOUR UR>,false,username,password);
    xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
    xmlhttp.setRequestHeader('X-Requested-With', 'XMLHttpRequest');

Is it better to return null or empty collection?

Depends on your contract and your concrete case. Generally it's best to return empty collections, but sometimes (rarely):

  • null might mean something more specific;
  • your API (contract) might force you to return null.

Some concrete examples:

  • an UI component (from a library out of your control), might be rendering an empty table if an empty collection is passed, or no table at all, if null is passed.
  • in a Object-to-XML (JSON/whatever), where null would mean the element is missing, while an empty collection would render a redundant (and possibly incorrect) <collection />
  • you are using or implementing an API which explicitly states that null should be returned/passed

Laravel Eloquent update just if changes have been made

You're already doing it!

save() will check if something in the model has changed. If it hasn't it won't run a db query.

Here's the relevant part of code in Illuminate\Database\Eloquent\Model@performUpdate:

protected function performUpdate(Builder $query, array $options = [])
{
    $dirty = $this->getDirty();

    if (count($dirty) > 0)
    {
        // runs update query
    }

    return true;
}

The getDirty() method simply compares the current attributes with a copy saved in original when the model is created. This is done in the syncOriginal() method:

public function __construct(array $attributes = array())
{
    $this->bootIfNotBooted();

    $this->syncOriginal();

    $this->fill($attributes);
}

public function syncOriginal()
{
    $this->original = $this->attributes;

    return $this;
}

If you want to check if the model is dirty just call isDirty():

if($product->isDirty()){
    // changes have been made
}

Or if you want to check a certain attribute:

if($product->isDirty('price')){
    // price has changed
}

How to update a plot in matplotlib?

All of the above might be true, however for me "online-updating" of figures only works with some backends, specifically wx. You just might try to change to this, e.g. by starting ipython/pylab by ipython --pylab=wx! Good luck!

How to disable SSL certificate checking with Spring RestTemplate?

@Bean(name = "restTemplateByPassSSL")
public RestTemplate restTemplateByPassSSL()
        throws KeyStoreException, NoSuchAlgorithmException, KeyManagementException {
    TrustStrategy acceptingTrustStrategy = (X509Certificate[] chain, String authType) -> true;
    HostnameVerifier hostnameVerifier = (s, sslSession) -> true;
    SSLContext sslContext = SSLContexts.custom().loadTrustMaterial(null, acceptingTrustStrategy).build();
    SSLConnectionSocketFactory csf = new SSLConnectionSocketFactory(sslContext, hostnameVerifier);
    CloseableHttpClient httpClient = HttpClients.custom().setSSLSocketFactory(csf).build();
    HttpComponentsClientHttpRequestFactory requestFactory = new HttpComponentsClientHttpRequestFactory();
    requestFactory.setHttpClient(httpClient);

    return new RestTemplate(requestFactory);
}

Is there a way to specify a default property value in Spring XML?

<foo name="port">
   <value>${my.server.port:8088}</value>
</foo>

should work for you to have 8088 as default port

See also: http://blog.callistaenterprise.se/2011/11/17/configure-your-spring-web-application/

Concatenating strings doesn't work as expected

Your code, as written, works. You’re probably trying to achieve something unrelated, but similar:

std::string c = "hello" + "world";

This doesn’t work because for C++ this seems like you’re trying to add two char pointers. Instead, you need to convert at least one of the char* literals to a std::string. Either you can do what you’ve already posted in the question (as I said, this code will work) or you do the following:

std::string c = std::string("hello") + "world";

Hide text within HTML?

<div style="display:none;">CREDITS_HERE</div>

Init function in javascript and how it works

Self invoking anonymous function (SIAF)

Self-invoking functions runs instantly, even if DOM isn't completely ready.

jQuery document.ready vs self calling anonymous function

Change the Textbox height?

for me, the best approach is remove border of the textbox, and place it inside a Panel, which can be customized as you like.

Sharing a variable between multiple different threads

AtomicBoolean

The succinct Answer by NPE sums up your three options. I'll add some example code for the second item listed there: AtomicBoolean.

You can think of the AtomicBoolean class as providing some thread-safety wrapping around a boolean value.

If you instantiate the AtomicBoolean only once, then you need not worry about the visibility issue in the Java Memory Model that requires volatile as a solution (the first item in that other Answer). Also, you need not concern yourself with synchronization (the third item in that other Answer) because AtomicBoolean performs that function of protecting multi-threaded access to its internal boolean value.

Let's look at some example code.

Firstly, in modern Java we generally do not address the Thread class directly. We now have the Executors framework to simplify handling of threads.

This code below is using Project Loom technology, coming to a future version of Java. Preliminary builds available now, built on early-access Java 16. This makes for simpler coding, with ExecutorService being AutoCloseable for convenient use with try-with-resources syntax. But Project Loom is not related to the point of this Answer; it just makes for simpler code that is easier to understand as “structured concurrency”.

The idea here is that we have three threads: the original thread, plus a ExecutorService that will create two more threads. The two new threads both report the value of our AtomicBoolean. The first new thread does so immediately, while the other waits 10 seconds before reporting. Meanwhile, our main thread sleeps for 5 seconds, wakes, changes the AtomicBoolean object’s contained value, and then waits for that second thread to wake and complete its work the report on the now-altered AtomicBoolean contained value. While we are installing seconds between each event, this is merely for dramatic demonstration. The real point is that these threads could coincidently try to access the AtomicBoolean simultaneously, but that object will protect access to its internal boolean value in a thread-safe manner. Protecting against simultaneous access is the job of the Atomic… classes.

try (
        ExecutorService executorService = Executors.newVirtualThreadExecutor() ;
)
{
    AtomicBoolean flag = new AtomicBoolean( true );

    // This task, when run, will immediately report the flag.
    Runnable task1 = ( ) -> System.out.println( "First task reporting flag = " + flag.get() + ". " + Instant.now() );

    // This task, when run, will wait several seconds, then report the flag. Meanwhile, code below waits a shorter time before *changing* the flag.
    Runnable task2 = ( ) -> {
        try { Thread.sleep( Duration.ofSeconds( 10 ) ); } catch ( InterruptedException e ) { e.printStackTrace(); }
        System.out.println( "Second task reporting flag = " + flag.get() + ". " + Instant.now() );
    };

    executorService.submit( task1 );
    executorService.submit( task2 );

    // Wait for first task to complete, so sleep here briefly. But wake before the sleeping second task awakens.
    try { Thread.sleep( Duration.ofSeconds( 5 ) ); } catch ( InterruptedException e ) { e.printStackTrace(); }
    System.out.println( "INFO - Original thread waking up, and setting flag to false. " + Instant.now() );
    flag.set( false );
}
// At this point, with Project Loom technology, the flow-of-control blocks until the submitted tasks are done.
// Also, the `ExecutorService` is automatically closed/shutdown by this point, via try-with-resources syntax.
System.out.println( "INFO - Tasks on background threads are done. The `AtomicBoolean` and threads are gone." + Instant.now() );

Methods such as AtomicBoolean#get and AtomicBoolean#set are built to be thread-safe, to internally protect access to the boolean value nested within. Read up on the various other methods as well.

When run:

First task reporting flag = true. 2021-01-05T06:42:17.367337Z
INFO - Original thread waking up, and setting flag to false. 2021-01-05T06:42:22.367456Z
Second task reporting flag = false. 2021-01-05T06:42:27.369782Z
INFO - Tasks on background threads are done. The `AtomicBoolean` and threads are gone.2021-01-05T06:42:27.372597Z

Pro Tip: When engaging in threaded code in Java, always study the excellent book, Java Concurrency in Practice by Brian Goetz et al.

Order discrete x scale by frequency/value

Try manually setting the levels of the factor on the x-axis. For example:

library(ggplot2)
# Automatic levels
ggplot(mtcars, aes(factor(cyl))) + geom_bar()    

ggplot of the cars dataset with factor levels automatically determined

# Manual levels
cyl_table <- table(mtcars$cyl)
cyl_levels <- names(cyl_table)[order(cyl_table)]
mtcars$cyl2 <- factor(mtcars$cyl, levels = cyl_levels)
# Just to be clear, the above line is no different than:
# mtcars$cyl2 <- factor(mtcars$cyl, levels = c("6","4","8"))
# You can manually set the levels in whatever order you please. 
ggplot(mtcars, aes(cyl2)) + geom_bar()

ggplot of the cars dataset with factor levels reordered manually

As James pointed out in his answer, reorder is the idiomatic way of reordering factor levels.

mtcars$cyl3 <- with(mtcars, reorder(cyl, cyl, function(x) -length(x)))
ggplot(mtcars, aes(cyl3)) + geom_bar()

ggplot of the cars dataset with factor levels reordered using the reorder function

Windows 7: unable to register DLL - Error Code:0X80004005

Use following command should work on windows 7. don't forget to enclose the dll name with full path in double quotations.

C:\Windows\SysWOW64>regsvr32 "c:\dll.name" 

Rotate camera in Three.js with mouse

This might serve as a good starting point for moving/rotating/zooming a camera with mouse/trackpad (in typescript):

class CameraControl {
    zoomMode: boolean = false
    press: boolean = false
    sensitivity: number = 0.02

    constructor(renderer: Three.Renderer, public camera: Three.PerspectiveCamera, updateCallback:() => void){
        renderer.domElement.addEventListener('mousemove', event => {
            if(!this.press){ return }

            if(event.button == 0){
                camera.position.y -= event.movementY * this.sensitivity
                camera.position.x -= event.movementX * this.sensitivity        
            } else if(event.button == 2){
                camera.quaternion.y -= event.movementX * this.sensitivity/10
                camera.quaternion.x -= event.movementY * this.sensitivity/10
            }

            updateCallback()
        })    

        renderer.domElement.addEventListener('mousedown', () => { this.press = true })
        renderer.domElement.addEventListener('mouseup', () => { this.press = false })
        renderer.domElement.addEventListener('mouseleave', () => { this.press = false })

        document.addEventListener('keydown', event => {
            if(event.key == 'Shift'){
                this.zoomMode = true
            }
        })

        document.addEventListener('keyup', event => {
            if(event.key == 'Shift'){
                this.zoomMode = false
            }
        })

        renderer.domElement.addEventListener('mousewheel', event => {
            if(this.zoomMode){ 
                camera.fov += event.wheelDelta * this.sensitivity
                camera.updateProjectionMatrix()
            } else {
                camera.position.z += event.wheelDelta * this.sensitivity
            }

            updateCallback()
        })
    }
}

drop it in like:

this.cameraControl = new CameraControl(renderer, camera, () => {
    // you might want to rerender on camera update if you are not rerendering all the time
    window.requestAnimationFrame(() => renderer.render(scene, camera))
})

Controls:

  • move while [holding mouse left / single finger on trackpad] to move camera in x/y plane
  • move [mouse wheel / two fingers on trackpad] to move up/down in z-direction
  • hold shift + [mouse wheel / two fingers on trackpad] to zoom in/out via increasing/decreasing field-of-view
  • move while holding [mouse right / two fingers on trackpad] to rotate the camera (quaternion)

Additionally:

If you want to kinda zoom by changing the 'distance' (along yz) instead of changing field-of-view you can bump up/down camera's position y and z while keeping the ratio of position's y and z unchanged like:

// in mousewheel event listener in zoom mode
const ratio = camera.position.y / camera.position.z
camera.position.y += (event.wheelDelta * this.sensitivity * ratio)
camera.position.z += (event.wheelDelta * this.sensitivity)

angular.element vs document.getElementById or jQuery selector with spin (busy) control

This worked for me well.

angular.forEach(element.find('div'), function(node)
{
  if(node.id == 'someid'){
    //do something
  }
  if(node.className == 'someclass'){
    //do something
  }
});

Programmatically extract contents of InstallShield setup.exe

On Linux there is unshield, which worked well for me (even if the GUI includes custom deterrents like license key prompts). It is included in the repositories of all major distributions (arch, suse, debian- and fedora-based) and its source is available at https://github.com/twogood/unshield

Find out which remote branch a local branch is tracking

Two choices:

% git rev-parse --abbrev-ref --symbolic-full-name @{u}
origin/mainline

or

% git for-each-ref --format='%(upstream:short)' "$(git symbolic-ref -q HEAD)"
origin/mainline

Difference between "read commited" and "repeatable read"

My observation on initial accepted solution.

Under RR (default mysql) - If a tx is open and a SELECT has been fired, another tx can NOT delete any row belonging to previous READ result set until previous tx is committed (in fact delete statement in the new tx will just hang), however the next tx can delete all rows from the table without any trouble. Btw, a next READ in previous tx will still see the old data until it is committed.

Upload Progress Bar in PHP

Gears and HTML5 have a progress event in the HttpRequest object for submitting a file upload via AJAX.

http://developer.mozilla.org/en/Using_files_from_web_applications

Your other options as already answered by others are:

  1. Flash based uploader.
  2. Java based uploader.
  3. A second comet-style request to the web server or a script to report the size of data received. Some webservers like Lighttpd provide modules to do this in-process to save the overhead of calling an external script or process.

Technically there is a forth option, similar to YouTube upload, with Gears or HTML5 you can use blobs to split a file into small chunks and individually upload each chunk. On completion of each chunk you can update the progress status.

How to launch an EXE from Web page (asp.net)

How about something like:

<a href="\\DangerServer\Downloads\MyVirusArchive.exe" 
  type="application/octet-stream">Don't download this file!</a>

Getting date format m-d-Y H:i:s.u from milliseconds

Based on @ArchCodeMonkey answer.

If you have declare(strict_types=1) you must cast second argument to string

enter image description here

Insert/Update/Delete with function in SQL Server

Functions are not meant to be used that way, if you wish to perform data change you can just create a Stored Proc for that.

How to change port number in vue-cli project

An alternative approach with vue-cli version 3 is to add a .env file in the root project directory (along side package.json) with the contents:

PORT=3000

Running npm run serve will now indicate the app is running on port 3000.

How to generate Entity Relationship (ER) Diagram of a database using Microsoft SQL Server Management Studio?

Diagrams are back as of the June 11 2019 release

Download latest

as stated:

Yes, we’ve heard the feedback; Database Diagrams is back.

SQL Server Management Studio (SSMS) 18.1 is now generally available


?? Latest Version Does Not Included It ??

Sadly, the last version of SSMS to have database diagrams as a feature was version v17.9.

Since that version, the newer preview versions starting at v18.* have, in their words "...feature has been deprecated".

Hope is not lost though, for one can still download and use v17.9 to use database diagrams which as an aside for this question is technically not a ER diagramming tool.


As of this writing it is unclear if the release version of 18 will have the feature, I hope so because it is a feature I use extensively.

How to create a self-signed certificate with OpenSSL

I can't comment, so I will put this as a separate answer. I found a few issues with the accepted one-liner answer:

  • The one-liner includes a passphrase in the key.
  • The one-liner uses SHA-1 which in many browsers throws warnings in console.

Here is a simplified version that removes the passphrase, ups the security to suppress warnings and includes a suggestion in comments to pass in -subj to remove the full question list:

openssl genrsa -out server.key 2048
openssl rsa -in server.key -out server.key
openssl req -sha256 -new -key server.key -out server.csr -subj '/CN=localhost'
openssl x509 -req -sha256 -days 365 -in server.csr -signkey server.key -out server.crt

Replace 'localhost' with whatever domain you require. You will need to run the first two commands one by one as OpenSSL will prompt for a passphrase.

To combine the two into a .pem file:

cat server.crt server.key > cert.pem

Passing vector by reference

You can pass vector by reference just like this:

void do_something(int el, std::vector<int> &arr){
    arr.push_back(el);
}

However, note that this function would always add a new element at the back of the vector, whereas your array function actually modifies the first element (or initializes it value).

In order to achieve exactly the same result you should write:

void do_something(int el, std::vector<int> &arr){
    if (arr.size() == 0) { // can't modify value of non-existent element
        arr.push_back(el);
    } else {
        arr[0] = el;
    }
}

In this way you either add the first element (if the vector is empty) or modify its value (if there first element already exists).

Why do I keep getting Delete 'cr' [prettier/prettier]?

Try this. It works for me:

yarn run lint --fix

or

npm run lint -- --fix

Marquee text in Android

TextView textView = (TextView) this.findViewById(R.id.textview_marquee);  
textView.setEllipsize(TruncateAt.MARQUEE);
textView.setText("General Information... general information... General Information");
textView.setSelected(true);
textView.setSingleLine(true);

How to remove all ListBox items?

isn't the same as the Winform and Webform way?

listBox1.Items.Clear();

Multiprocessing a for loop?

You can simply use multiprocessing.Pool:

from multiprocessing import Pool

def process_image(name):
    sci=fits.open('{}.fits'.format(name))
    <process>

if __name__ == '__main__':
    pool = Pool()                         # Create a multiprocessing Pool
    pool.map(process_image, data_inputs)  # process data_inputs iterable with pool

How to refresh the data in a jqGrid?

var newdata= //You call Ajax peticion//

$("#idGrid").clearGridData();

$("#idGrid").jqGrid('setGridParam', {data:newdata)});
$("#idGrid").trigger("reloadGrid");

in event update data table

Command line for looking at specific port

For port 80, the command would be : netstat -an | find "80" For port n, the command would be : netstat -an | find "n"

Here, netstat is the instruction to your machine

-a : Displays all connections and listening ports -n : Displays all address and instructions in numerical format (This is required because output from -a can contain machine names)

Then, a find command to "Pattern Match" the output of previous command.

Keyboard shortcut to "untab" (move a block of code to the left) in eclipse / aptana?

Shift-tab does that in Flex Builder (Based on Eclipse) - SO it hopefully should work in regular eclipse :)

Primefaces valueChangeListener or <p:ajax listener not firing for p:selectOneMenu

<p:ajax listener="#{my.handleChange}" update="id of component that need to be rerender after change" process="@this" />



import javax.faces.component.UIOutput;
import javax.faces.event.AjaxBehaviorEvent;

public void handleChange(AjaxBehaviorEvent vce){  
  String name= (String) ((UIOutput) vce.getSource()).getValue();
}

What is the max size of localStorage values?

I really like cdmckay's answer, but it does not really look good to check the size in a real time: it is just too slow (2 seconds for me). This is the improved version, which is way faster and more exact, also with an option to choose how big the error can be (default 250,000, the smaller error is - the longer the calculation is):

function getLocalStorageMaxSize(error) {
  if (localStorage) {
    var max = 10 * 1024 * 1024,
        i = 64,
        string1024 = '',
        string = '',
        // generate a random key
        testKey = 'size-test-' + Math.random().toString(),
        minimalFound = 0,
        error = error || 25e4;

    // fill a string with 1024 symbols / bytes    
    while (i--) string1024 += 1e16;

    i = max / 1024;

    // fill a string with 'max' amount of symbols / bytes    
    while (i--) string += string1024;

    i = max;

    // binary search implementation
    while (i > 1) {
      try {
        localStorage.setItem(testKey, string.substr(0, i));
        localStorage.removeItem(testKey);

        if (minimalFound < i - error) {
          minimalFound = i;
          i = i * 1.5;
        }
        else break;
      } catch (e) {
        localStorage.removeItem(testKey);
        i = minimalFound + (i - minimalFound) / 2;
      }
    }

    return minimalFound;
  }
}

To test:

console.log(getLocalStorageMaxSize()); // takes .3s
console.log(getLocalStorageMaxSize(.1)); // takes 2s, but way more exact

This works dramatically faster for the standard error; also it can be much more exact when necessary.

HttpClient does not exist in .net 4.0: what can I do?

Here's a "translation" to HttpWebRequest (needed rather than WebClient in order to set the referrer). (Uses System.Net and System.IO):

    HttpWebRequest http = (HttpWebRequest)HttpWebRequest.Create(requestUrl))
    http.Referer = referrer;
    HttpWebResponse response = (HttpWebResponse )http.GetResponse();
    using (StreamReader sr = new StreamReader(response.GetResponseStream()))
    {
        string responseJson = sr.ReadToEnd();
        // more stuff
    }

Get screen width and height in Android

I updated answer for Kotlin language!

For Kotlin: You should call Window Manager and get metrics. After that easy way.

val displayMetrics = DisplayMetrics()
windowManager.defaultDisplay.getMetrics(displayMetrics)

var width = displayMetrics.widthPixels
var height = displayMetrics.heightPixels

How can we use it effectively in independent activity way with Kotlin language?

Here, I created a method in general Kotlin class. You can use it in all activities.

private val T_GET_SCREEN_WIDTH:String = "screen_width"
private val T_GET_SCREEN_HEIGHT:String = "screen_height"

private fun getDeviceSizes(activity:Activity, whichSize:String):Int{

    val displayMetrics = DisplayMetrics()
    activity.windowManager.defaultDisplay.getMetrics(displayMetrics)

    return when (whichSize){
        T_GET_SCREEN_WIDTH -> displayMetrics.widthPixels
        T_GET_SCREEN_HEIGHT -> displayMetrics.heightPixels
        else -> 0 // Error
    }
}

Contact: @canerkaseler

C++ Dynamic Shared Library on Linux

myclass.h

#ifndef __MYCLASS_H__
#define __MYCLASS_H__

class MyClass
{
public:
  MyClass();

  /* use virtual otherwise linker will try to perform static linkage */
  virtual void DoSomething();

private:
  int x;
};

#endif

myclass.cc

#include "myclass.h"
#include <iostream>

using namespace std;

extern "C" MyClass* create_object()
{
  return new MyClass;
}

extern "C" void destroy_object( MyClass* object )
{
  delete object;
}

MyClass::MyClass()
{
  x = 20;
}

void MyClass::DoSomething()
{
  cout<<x<<endl;
}

class_user.cc

#include <dlfcn.h>
#include <iostream>
#include "myclass.h"

using namespace std;

int main(int argc, char **argv)
{
  /* on Linux, use "./myclass.so" */
  void* handle = dlopen("myclass.so", RTLD_LAZY);

  MyClass* (*create)();
  void (*destroy)(MyClass*);

  create = (MyClass* (*)())dlsym(handle, "create_object");
  destroy = (void (*)(MyClass*))dlsym(handle, "destroy_object");

  MyClass* myClass = (MyClass*)create();
  myClass->DoSomething();
  destroy( myClass );
}

On Mac OS X, compile with:

g++ -dynamiclib -flat_namespace myclass.cc -o myclass.so
g++ class_user.cc -o class_user

On Linux, compile with:

g++ -fPIC -shared myclass.cc -o myclass.so
g++ class_user.cc -ldl -o class_user

If this were for a plugin system, you would use MyClass as a base class and define all the required functions virtual. The plugin author would then derive from MyClass, override the virtuals and implement create_object and destroy_object. Your main application would not need to be changed in any way.

How can we programmatically detect which iOS version is device running on?

I know I am too late to answer this question. I am not sure does my method still working on low iOS versions (< 5.0):

NSString *platform = [UIDevice currentDevice].model;

NSLog(@"[UIDevice currentDevice].model: %@",platform);
NSLog(@"[UIDevice currentDevice].description: %@",[UIDevice currentDevice].description);
NSLog(@"[UIDevice currentDevice].localizedModel: %@",[UIDevice currentDevice].localizedModel);
NSLog(@"[UIDevice currentDevice].name: %@",[UIDevice currentDevice].name);
NSLog(@"[UIDevice currentDevice].systemVersion: %@",[UIDevice currentDevice].systemVersion);
NSLog(@"[UIDevice currentDevice].systemName: %@",[UIDevice currentDevice].systemName);

You can get these results:

[UIDevice currentDevice].model: iPhone
[UIDevice currentDevice].description: <UIDevice: 0x1cd75c70>
[UIDevice currentDevice].localizedModel: iPhone
[UIDevice currentDevice].name: Someones-iPhone002
[UIDevice currentDevice].systemVersion: 6.1.3
[UIDevice currentDevice].systemName: iPhone OS

javascript variable reference/alias

edit to my previous answer: if you want to count a function's invocations, you might want to try:

var countMe = ( function() {
  var c = 0;

  return function() {
    c++;
    return c;
  }
})();

alert(countMe()); // Alerts "1"
alert(countMe()); // Alerts "2"

Here, c serves as the counter, and you do not have to use arguments.callee.

Using a custom (ttf) font in CSS

You need to use the css-property font-face to declare your font. Have a look at this fancy site: http://www.font-face.com/

Example:

@font-face {
  font-family: MyHelvetica;
  src: local("Helvetica Neue Bold"),
       local("HelveticaNeue-Bold"),
       url(MgOpenModernaBold.ttf);
  font-weight: bold;
}

See also: MDN @font-face

Getting the base url of the website and globally passing it to twig in Symfony 2

In Symfony 5 and in the common situation of a controller method use the injected Request object:

public function controllerFunction(Request $request, LoggerInterface $logger)
  ...
  $scheme = $request->getSchemeAndHttpHost();
  $logger->info('Domain is: ' . $scheme);
  ...
  //prepare to render
  $retarray = array(
    ...
    'scheme' => $scheme,
    ...
    );
  return $this->render('Template.html.twig', $retarray);
}

How to disable Compatibility View in IE

Adding a tag to your page will not control the UI in the Internet Control Panel (the dialog that appears when you selection Tools -> Options). If you're looking at your homepage which could be google.com, msn.com, about:blank or example.com, the Internet Control Panel has no way of knowing what the contents of your page may be, and it will not download it in the background.

Have a look at this document on MSDN which discussed compatibility mode and how to turn it off for your site.

MySQL select one column DISTINCT, with corresponding other columns

SELECT DISTINCT (column1), column2
FROM table1
GROUP BY column1

Java how to replace 2 or more spaces with single space in string and delete leading and trailing spaces

This worked for me

scan= filter(scan, " [\\s]+", " ");
scan= sac.trim();

where filter is following function and scan is the input string:

public String filter(String scan, String regex, String replace) {
    StringBuffer sb = new StringBuffer();

    Pattern pt = Pattern.compile(regex);
    Matcher m = pt.matcher(scan);

    while (m.find()) {
        m.appendReplacement(sb, replace);
    }

    m.appendTail(sb);

    return sb.toString();
}

XMLHttpRequest module not defined/found

XMLHttpRequest is a built-in object in web browsers.

It is not distributed with Node; you have to install it separately,

  1. Install it with npm,

    npm install xmlhttprequest
    
  2. Now you can require it in your code.

    var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest;
    var xhr = new XMLHttpRequest();
    

That said, the http module is the built-in tool for making HTTP requests from Node.

Axios is a library for making HTTP requests which is available for Node and browsers that is very popular these days.

"Insert if not exists" statement in SQLite

For a unique column, use this:

INSERT OR REPLACE INTO table () values();

For more information, see: sqlite.org/lang_insert

How to check if object has been disposed in C#

If you're not sure whether the object has been disposed or not, you should call the Dispose method itself rather than methods such as Close. While the framework doesn't guarantee that the Dispose method must run without exceptions even if the object had previously been disposed, it's a common pattern and to my knowledge implemented on all disposable objects in the framework.

The typical pattern for Dispose, as per Microsoft:

public void Dispose() 
{
    Dispose(true);

    // Use SupressFinalize in case a subclass
    // of this type implements a finalizer.
    GC.SuppressFinalize(this);      
}

protected virtual void Dispose(bool disposing)
{
    // If you need thread safety, use a lock around these 
    // operations, as well as in your methods that use the resource.
    if (!_disposed)
    {
        if (disposing) {
            if (_resource != null)
                _resource.Dispose();
                Console.WriteLine("Object disposed.");
        }

        // Indicate that the instance has been disposed.
        _resource = null;
        _disposed = true;   
    }
}

Notice the check on _disposed. If you were to call a Dispose method implementing this pattern, you could call Dispose as many times as you wanted without hitting exceptions.

SQL Server stored procedure parameters

You are parsing wrong parameter combination.here you passing @TaskName = and @ID instead of @TaskName = .SP need only one parameter.

Matplotlib 2 Subplots, 1 Colorbar

The solution of using a list of axes by abevieiramota works very well until you use only one row of images, as pointed out in the comments. Using a reasonable aspect ratio for figsize helps, but is still far from perfect. For example:

import numpy as np
import matplotlib.pyplot as plt

fig, axes = plt.subplots(nrows=1, ncols=3, figsize=(9.75, 3))
for ax in axes.flat:
    im = ax.imshow(np.random.random((10,10)), vmin=0, vmax=1)

fig.colorbar(im, ax=axes.ravel().tolist())

plt.show()

1 x 3 image array

The colorbar function provides the shrink parameter which is a scaling factor for the size of the colorbar axes. It does require some manual trial and error. For example:

fig.colorbar(im, ax=axes.ravel().tolist(), shrink=0.75)

1 x 3 image array with shrunk colorbar

Failed to instantiate module [$injector:unpr] Unknown provider: $routeProvider

In my case it was because the file was minified with wrong scope. Use Array!

app.controller('StoreController', ['$http', function($http) {
    ...
}]);

Coffee syntax:

app.controller 'StoreController', Array '$http', ($http) ->
  ...

Access restriction: The type 'Application' is not API (restriction on required library rt.jar)

Remove Existing/Configured System Library: Eclipse(IDE) -> Project Explorer -> Project Name-> (Option) Build Path -> Configure Build Path -> Java Build Path -> Libraries -> (Select) JRE System Library [(For me)jre1.8.0_231] -> Remove.

Currently you are at same location: Eclipse(IDE) -> Project Explorer -> Project Name-> (Option) Build Path -> Configure Build Path -> Java Build Path -> Libraries

Now Add Same System Library Again: Add Library -> JRE System Library -> Workspace default JRE ((For me)jre1.8.0_231) -> Finish -> Apply -> Close.

Now wait to finish it.

How to access ssis package variables inside script component

Strongly typed var don't seem to be available, I have to do the following in order to get access to them:

String MyVar = Dts.Variables["MyVarName"].Value.ToString();

Difference between if () { } and if () : endif;

I would use the first option if at all possible, regardless of the new option. The syntax is standard and everyone knows it. It's also backwards compatible.

Creating a .p12 file

I'm debugging an issue I'm having with SSL connecting to a database (MySQL RDS) using an ORM called, Prisma. The database connection string requires a PKCS12 (.p12) file (if interested, described here), which brought me here.

I know the question has been answered, but I found the following steps (in Github Issue#2676) to be helpful for creating a .p12 file and wanted to share. Good luck!

  1. Generate 2048-bit RSA private key:

    openssl genrsa -out key.pem 2048

  2. Generate a Certificate Signing Request:

    openssl req -new -sha256 -key key.pem -out csr.csr

  3. Generate a self-signed x509 certificate suitable for use on web servers.

    openssl req -x509 -sha256 -days 365 -key key.pem -in csr.csr -out certificate.pem

  4. Create SSL identity file in PKCS12 as mentioned here

    openssl pkcs12 -export -out client-identity.p12 -inkey key.pem -in certificate.pem

R multiple conditions in if statement

Read this thread R - boolean operators && and ||.

Basically, the & is vectorized, i.e. it acts on each element of the comparison returning a logical array with the same dimension as the input. && is not, returning a single logical.

Regex to get string between curly braces

/\{([^}]+)\}/

/        - delimiter
\{       - opening literal brace escaped because it is a special character used for quantifiers eg {2,3}
(        - start capturing
[^}]     - character class consisting of
    ^    - not
    }    - a closing brace (no escaping necessary because special characters in a character class are different)
+        - one or more of the character class
)        - end capturing
\}       - the closing literal brace
/        - delimiter

How do you get the currently selected <option> in a <select> via JavaScript?

This will do it for you:

var yourSelect = document.getElementById( "your-select-id" );
alert( yourSelect.options[ yourSelect.selectedIndex ].value )

numpy max vs amax vs maximum

np.max is just an alias for np.amax. This function only works on a single input array and finds the value of maximum element in that entire array (returning a scalar). Alternatively, it takes an axis argument and will find the maximum value along an axis of the input array (returning a new array).

>>> a = np.array([[0, 1, 6],
                  [2, 4, 1]])
>>> np.max(a)
6
>>> np.max(a, axis=0) # max of each column
array([2, 4, 6])

The default behaviour of np.maximum is to take two arrays and compute their element-wise maximum. Here, 'compatible' means that one array can be broadcast to the other. For example:

>>> b = np.array([3, 6, 1])
>>> c = np.array([4, 2, 9])
>>> np.maximum(b, c)
array([4, 6, 9])

But np.maximum is also a universal function which means that it has other features and methods which come in useful when working with multidimensional arrays. For example you can compute the cumulative maximum over an array (or a particular axis of the array):

>>> d = np.array([2, 0, 3, -4, -2, 7, 9])
>>> np.maximum.accumulate(d)
array([2, 2, 3, 3, 3, 7, 9])

This is not possible with np.max.

You can make np.maximum imitate np.max to a certain extent when using np.maximum.reduce:

>>> np.maximum.reduce(d)
9
>>> np.max(d)
9

Basic testing suggests the two approaches are comparable in performance; and they should be, as np.max() actually calls np.maximum.reduce to do the computation.

Create an ArrayList with multiple object types?

You can always create an ArrayList of Objects. But it will not be very useful to you. Suppose you have created the Arraylist like this:

List<Object> myList = new ArrayList<Object>();

and add objects to this list like this:

myList.add(new Integer("5"));

myList.add("object");

myList.add(new Object());

You won't face any problem while adding and retrieving the object but it won't be very useful. You have to remember at what location each type of object is it in order to use it. In this case after retrieving, all you can do is calling the methods of Object on them.

python NameError: name 'file' is not defined

file is not defined in Python3, which you are using apparently. The package you're instaling is not suitable for Python 3, instead, you should install Python 2.7 and try again.

See: http://docs.python.org/release/3.0/whatsnew/3.0.html#builtins

Uninstalling Android ADT

The only way to remove the ADT plugin from Eclipse is to go to Help > About Eclipse/About ADT > Installation Details.

Select a plug-in you want to uninstall, then click Uninstall... button at the bottom.

enter image description here

If you cannot remove ADT from this location, then your best option is probably to start fresh with a clean Eclipse install.

get everything between <tag> and </tag> with php

You can also try:

function getTagValue($string, $tag)
{
    $pattern = "/<{$tag}>(.*?)<\/{$tag}>/s";
    preg_match($pattern, $string, $matches);
    return isset($matches[1]) ? $matches[1] : '';
}

It returns empty string in case of no match.

CSS background image alt attribute

You can achieve this by putting the alt tag in the div were your image will appear.

Example:

<div id="yourImage" alt="nameOfImage"></div>

TextView bold via xml file?

use textstyle property as bold

android:textStyle = "bold";

The Android emulator is not starting, showing "invalid command-line parameter"

Remember to run "android update avd -n avd_name" after change in Android SDK path.

C# if/then directives for debug vs release

It is worth noting here that one of the most significant differences between conditionally executing code based on #if DEBUG versus if(System.Diagnostics.Debugger.IsAttached) is that the compiler directive changes the code that is compiled. That is, if you have two different statements in an #if DEBUG/#else/#endif conditional block, only one of them will appear in the compiled code. This is an important distinction because it allows you do do things such as conditionally compile method definitions to be public void mymethod() versus internal void mymethod() depending on build type so that you can, for example, run unit tests on debug builds that will not break access control on production builds, or conditionally compile helper functions in debug builds that will not appear in the final code if they would violate security in some way should they escape into the wild. The IsAttached property, on the other hand, does not affect the compiled code. Both sets of code are in all of the builds - the IsAttached condition will only affect what is executed. This by itself can present a security issue.

Can you have multiline HTML5 placeholder text in a <textarea>?

The html5 spec expressly rejects new lines in the place holder field. Versions of Webkit /will/ insert new lines when presented with line feeds in the placeholder, however this is incorrect behaviour and should not be relied upon.

I guess paragraphs aren't brief enough for w3 ;)

Having trouble setting working directory

Maybe it is the case that you have your path in couple of lines, you used enter to make it? If so, then part of you paths might look like that "/\nData/" instead of "/Data/", which causes the problem. Just set it to be in one line and issue is solved!

Can a main() method of class be invoked from another class in java

if I got your question correct...

main() method is defined in the class below...

public class ToBeCalledClass{

   public static void main (String args[ ]) {
      System.out.println("I am being called");
   }
}

you want to call this main method in another class.

public class CallClass{

    public void call(){
       ToBeCalledClass.main(null);
    }
}

Switch: Multiple values in one case?

you can try this.

switch (Valor)
            {
                case (Valor1 & Valor2):

                    break;               
            }

How to get a complete list of ticker symbols from Yahoo Finance?

I had same problem, but I think I have simple solution(code is from my RoR app): Extract industry ids from yahoo.finance.sectors and add it to db:

    select = "select * from yahoo.finance.sectors"
    generate_query select
    @data.each do |data|
      data["industry"].each do |ind|
        unless ind.kind_of?(Array)
          unless ind["id"].nil?
            id = ind["id"].to_i
            if id > 0
              Industry.where(id: id).first_or_create(name: ind["name"]).update_attribute(:name, ind["name"])
            end
          end
        end
      end
    end

Extract all comanies with their symbols with industry ids:

    ids = Industry.all.map{|ind| "'#{ind.id.to_s}'" }.join(",")
    select = "select * from yahoo.finance.industry where id in"
    generate_query select, ids
    @data.each do |ts|
      unless ts.kind_of?(Array) || ts["company"].nil?
        if ts["company"].count == 2 && ts["company"].first[0] == "name"
          t = ts["company"]
          Ticket.find_or_create_by_symbol(symbol: t["symbol"], name: t["name"] ).update_attribute(:name, t["name"])
        else
          ts["company"].each do |t|
            Ticket.find_or_create_by_symbol(symbol: t["symbol"], name: t["name"] ).update_attribute(:name, t["name"])
          end
        end
      end
    end
  end

Connection hellper:

def generate_query(select, ids = nil)
    if params[:form] || params[:action] == "sectors" || params[:controller] == "tickets"
      if params[:action] == "sectors" || params[:controller] == "tickets"
        if ids.nil?
          query= select
        else
          query= "#{select} (#{ids})"
        end
      else
        if params[:form][:ids]
          @conditions = params_parse params[:form][:ids]
          query = "#{select} (#{@conditions})"
        end
      end
      yql_execut(query)
    end
  end

  def yql_execut(query)
    # TODO: OAuth ACCESS (http://developer.yahoo.com/yql/guide/authorization.html)
    base_url = "http://query.yahooapis.com/v1/public/yql?&format=json&env=store%3A%2F%2Fdatatables.org%2Falltableswithkeys&q="
    dirty_data = JSON.parse(HTTParty.get(base_url +  URI.encode(query)).body)
    if dirty_data["query"]["results"] == nil
      @data, @count, @table_head = nil
    else
      @data = dirty_data["query"]["results"].to_a[0][1].to_a
      @count = dirty_data["query"]["count"]
      if @count == 1
        @table_head = @data.map{|h| h[0].capitalize}
      else
        @table_head = @data.to_a.first.to_a.map{|h| h[0].capitalize}
      end
    end
  end

Sorry for mess, but this is first testing version for my project and I needed it very fast. There are some helpers variabels and other things for my app, sorry for it. But I have question: Have many symbols do you have? I have 5500.

How do I draw a circle in iOS Swift?

Add in view did load

    //Circle Points

     var CircleLayer   = CAShapeLayer() 

    let center = CGPoint (x: myCircleView.frame.size.width / 2, y: myCircleView.frame.size.height / 2)
    let circleRadius = myCircleView.frame.size.width / 2
    let circlePath = UIBezierPath(arcCenter: center, radius: circleRadius, startAngle: CGFloat(M_PI), endAngle: CGFloat(M_PI * 4), clockwise: true)
    CircleLayer.path = circlePath.cgPath
   CircleLayer.strokeColor = UIColor.red.cgColor
    CircleLayer.fillColor = UIColor.blue.cgColor
    CircleLayer.lineWidth = 8
    CircleLayer.strokeStart = 0
    CircleLayer.strokeEnd  = 1
    Self.View.layer.addSublayer(CircleLayer)

Ruby: How to iterate over a range, but in set increments?

rng.step(n=1) {| obj | block } => rng

Iterates over rng, passing each nth element to the block. If the range contains numbers or strings, natural ordering is used. Otherwise step invokes succ to iterate through range elements. The following code uses class Xs, which is defined in the class-level documentation.

range = Xs.new(1)..Xs.new(10)
range.step(2) {|x| puts x}
range.step(3) {|x| puts x}

produces:

1 x
3 xxx
5 xxxxx
7 xxxxxxx
9 xxxxxxxxx
1 x
4 xxxx
7 xxxxxxx
10 xxxxxxxxxx

Reference: http://ruby-doc.org/core/classes/Range.html

......

How to see data from .RData file?

You can also import the data via the "Import Dataset" tab in RStudio, under "global environment." Use the text data option in the drop down list and select your .RData file from the folder. Once the import is complete, it will display the data in the console. Hope this helps.

Convert an NSURL to an NSString

In Swift :- var str_url = yourUrl.absoluteString

It will result a url in string.

Node.js, can't open files. Error: ENOENT, stat './path/to/file'

Here the code to use your app.js

input specifies file name

res.download(__dirname+'/'+input);

Node.js: printing to console without a trailing newline?

None of these solutions work for me, process.stdout.write('ok\033[0G') and just using '\r' just create a new line but don't overwrite on Mac OSX 10.9.2.

EDIT: I had to use this to replace the current line:

process.stdout.write('\033[0G');
process.stdout.write('newstuff');

How to write UTF-8 in a CSV file

From your shell run:

pip2 install unicodecsv

And (unlike the original question) presuming you're using Python's built in csv module, turn
import csv into
import unicodecsv as csv in your code.

__init__() missing 1 required positional argument

The problem is with, you

def __init__(self, data):

when you create object from DHT class you should pass parameter the data should be dict type, like

data={'one':1,'two':2,'three':3}
dhtObj=DHT(data)

But in your code youshould to change is

data={'one':1,'two':2,'three':3}
if __name__ == '__main__': DHT(data).showData()

Or

if __name__ == '__main__': DHT({'one':1,'two':2,'three':3}).showData()

window.open(url, '_blank'); not working on iMac/Safari

To use window.open() in safari you must put it in an element's onclick event attribute.

For example: <button class='btn' onclick='window.open("https://www.google.com", "_blank");'>Open Google search</button>

How to use the CancellationToken property?

You can implement your work method as follows:

private static void Work(CancellationToken cancelToken)
{
    while (true)
    {
        if(cancelToken.IsCancellationRequested)
        {
            return;
        }
        Console.Write("345");
    }
}

That's it. You always need to handle cancellation by yourself - exit from method when it is appropriate time to exit (so that your work and data is in consistent state)

UPDATE: I prefer not writing while (!cancelToken.IsCancellationRequested) because often there are few exit points where you can stop executing safely across loop body, and loop usually have some logical condition to exit (iterate over all items in collection etc.). So I believe it's better not to mix that conditions as they have different intention.

Cautionary note about avoiding CancellationToken.ThrowIfCancellationRequested():

Comment in question by Eamon Nerbonne:

... replacing ThrowIfCancellationRequested with a bunch of checks for IsCancellationRequested exits gracefully, as this answer says. But that's not just an implementation detail; that affects observable behavior: the task will no longer end in the cancelled state, but in RanToCompletion. And that can affect not just explicit state checks, but also, more subtly, task chaining with e.g. ContinueWith, depending on the TaskContinuationOptions used. I'd say that avoiding ThrowIfCancellationRequested is dangerous advice.

commands not found on zsh

If you like me, you will have two terminals app, one is the default terminal with bash as the default shell and another iTerm 2 with zsh as its shell. To have both commands and zsh in iTerm 2 from bash, you need to do the following:

On iTerm 2, go to preferences (or command ,). Then go to the profile tab and go down to command. As you can see on the picture below, you need to select command option and paste path of zsh shell (to find the path, you can do which zsh).

enter image description here

At this point you will have the zsh as your default shell ONLY for iTerm 2 and you will have bash as the global default shell on default mac terminal app. Next, we are still missing the commands from bash in zsh. So to do this, you need to go on your bash (where you have your commands working) and get the PATH variable from env (use this command to do that: env | grep PATH).

Once you have that, go to your iTerm 2 and paste your path on "send text at start" option.

export PATH=/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin && clear

Just reopen iTerm 2 and we are done!

rawQuery(query, selectionArgs)

see below code it may help you.

String q = "SELECT * FROM customer";
Cursor mCursor = mDb.rawQuery(q, null);

or

String q = "SELECT * FROM customer WHERE _id = " + customerDbId  ;
Cursor mCursor = mDb.rawQuery(q, null);

"dd/mm/yyyy" date format in excel through vba

I got it

Cells(1, 1).Value = StartDate
Cells(1, 1).NumberFormat = "dd/mm/yyyy"

Basically, I need to set the cell format, instead of setting the date.

JavaScript file upload size validation

No Yes, using the File API in newer browsers. See TJ's answer for details.

If you need to support older browsers as well, you will have to use a Flash-based uploader like SWFUpload or Uploadify to do this.

The SWFUpload Features Demo shows how the file_size_limit setting works.

Note that this (obviously) needs Flash, plus the way it works is a bit different from normal upload forms.

Can I set an unlimited length for maxJsonLength in web.config?

If you are encountering this sort of issue in View, you can use below method to resolve that. Here Iused Newtonsoft package .

@using Newtonsoft.Json
<script type="text/javascript">
    var partData = @Html.Raw(JsonConvert.SerializeObject(ViewBag.Part));
</script>

WCFTestClient The HTTP request is unauthorized with client authentication scheme 'Anonymous'

I had this error too , and finally this codes worked for me in dot net core 3.1

first install svcutil in command prompt : dotnet tool install --global dotnet-svcutil

Then close command prompt and open it again.

Then create the Reference.cs in command prompt :

dotnet-svcutil http://YourService.com/SayHello.svc

(It needs an enter key and UserName and Password)

Add a folder named Connected Services to project root.

Copy Reference.cs file to Connected Services folder.

Add these 4 lines to Reference.cs after lines where creating BasicHttpBinding and setting MaxBufferSize :

result.Security.Mode = BasicHttpSecurityMode.TransportCredentialOnly;
result.Security.Transport.ClientCredentialType = HttpClientCredentialType.Basic;
result.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.None;
result.Security.Message.ClientCredentialType = BasicHttpMessageCredentialType.UserName;

Use this service in your Controller :

public async Task<string> Get()
    {
        try
        {
            var client = new EstelamClient();
            client.ClientCredentials.UserName.UserName = "YourUserName";
            client.ClientCredentials.UserName.Password = "YourPassword";
            var res = await client.EmployeeCheckAsync("service parameters");
            return res.ToString();
        }
        catch (Exception ex)
        {
            return ex.Message + " ************ stack : " + ex.StackTrace;
        }

    }

Do not forget install these packages in .cshtml :

<PackageReference Include="System.ServiceModel.Duplex" Version="4.6.*" />
<PackageReference Include="System.ServiceModel.Http" Version="4.6.*" />
<PackageReference Include="System.ServiceModel.NetTcp" Version="4.6.*" />
<PackageReference Include="System.ServiceModel.Security" Version="4.6.*" />

Android: show soft keyboard automatically when focus is on an EditText

Why this answer - Because above solution will show your keyboard but it will not vanish if you click anywhere other that EditText. So you need to do something to make the keybaord disappear when EditText loses focus.

You can achieve this by doing the following steps:

  1. Make the parent view(content view of your activity) clickable and focusable by adding the following attributes

        android:clickable="true" 
        android:focusableInTouchMode="true" 
    
  2. Implement a hideKeyboard() method

        public void hideKeyboard(View view) {
            InputMethodManager inputMethodManager =(InputMethodManager)getSystemService(Activity.INPUT_METHOD_SERVICE);
            inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(),InputMethodManager.HIDE_IMPLICIT_ONLY );
        }
    
  3. Lastly, set the onFocusChangeListener of your edittext.

        edittext.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                if (!hasFocus) {
                    hideKeyboard(v);
                }
            }
        });
    

ES6 export all values from object

Why not just do a named export of the object:

let values = { a: 1, b: 2, c: 3 }
export { values }

or

export let values = { a: 1, b: 2, c: 3 }

and then a named import where you need it:

import { values } from './my-module'

let foo = values.a
let { a, b, c } = values

or

import { values as myModule } from './my-module'

let foo = myModule.a
let { a, b, c } = myModule

can do default export as well:

let values = { a: 1, b: 2, c: 3 }
export default values 

or

export default { a: 1, b: 2, c: 3 }

and then consume it:

import whateverIcallIt from './my-Module'

let foo = whateverIcallIt.a
let {a, b, c } = whateverIcallIt

If you want to export a bunch of individual values, say a bunch of constants, you can:

export const a = 1
export const b = 2
//...

or even

export const a = 1,
             b = 2,
             c = 3,
//...

and then import them individually:

import { a, b, c } from './my-module'

What are the undocumented features and limitations of the Windows FINDSTR command?

I'd like to report a bug regarding the section Source of data to search in the first answer when using en dash (–) or em dash (—) within the filename.

More specifically, if you are about to use the first option - filenames specified as arguments, the file won't be found. As soon as you use either option 2 - stdin via redirection or 3 - data stream from a pipe, findstr will find the file.

For example, this simple batch script:

echo off
chcp 1250 > nul
set INTEXTFILE1=filename with – dash.txt
set INTEXTFILE2=filename with — dash.txt

rem 3 way of findstr use with en dashed filename
echo.
echo Filename with en dash:
echo.
echo 1. As argument
findstr . "%INTEXTFILE1%"
echo.
echo 2. As stdin via redirection
findstr . < "%INTEXTFILE1%"
echo.
echo 3. As datastream from a pipe
type "%INTEXTFILE1%" | findstr .
echo.
echo.
rem The same set of operations with em dashed filename
echo Filename with em dash:
echo.
echo 1. As argument
findstr . "%INTEXTFILE2%"
echo.
echo 2. As stdin via redirection
findstr . < "%INTEXTFILE2%"
echo.
echo 3. As datastream from a pipe
type "%INTEXTFILE2%" | findstr .
echo.

pause

will print:

Filename with en dash:

  1. As argument
    FINDSTR: Cannot open filename with - dash.txt

  2. As stdin via redirection
    I am the file with an en dash.

  3. As datastream from a pipe
    I am the file with an en dash.

Filename with em dash:

  1. As argument
    FINDSTR: Cannot open filename with - dash.txt

  2. As stdin via redirection
    I am the file with an em dash.

  3. As datastream from a pipe
    I am the file with an em dash.

Hope it helps.

M.

How to determine if a list of polygon points are in clockwise order?

Here's swift 3.0 solution based on answers above:

    for (i, point) in allPoints.enumerated() {
        let nextPoint = i == allPoints.count - 1 ? allPoints[0] : allPoints[i+1]
        signedArea += (point.x * nextPoint.y - nextPoint.x * point.y)
    }

    let clockwise  = signedArea < 0

The program can’t start because MSVCR71.dll is missing from your computer. Try reinstalling the program to fix this program

MY SOLUTION!!!!!!! I fixed this problem when I was trying to install business objects. When the installer failed to register .dll's I inputted the MSVCR71.dll into both system32 and sysWOW64 then clicked retry. Installation finished. I did try adding this in before and after install but, install still failed.

Write Array to Excel Range

add ExcelUtility class to your project and enjoy it.

ExcelUtility.cs File content:

using System;
using Microsoft.Office.Interop.Excel;

static class ExcelUtility
{
    public static void WriteArray<T>(this _Worksheet sheet, int startRow, int startColumn, T[,] array)
    {
        var row = array.GetLength(0);
        var col = array.GetLength(1);
        Range c1 = (Range) sheet.Cells[startRow, startColumn];
        Range c2 = (Range) sheet.Cells[startRow + row - 1, startColumn + col - 1];
        Range range = sheet.Range[c1, c2];
        range.Value = array;
    }

    public static bool SaveToExcel<T>(T[,] data, string path)
    {
        try
        {
            //Start Excel and get Application object.
            var oXl = new Application {Visible = false};

            //Get a new workbook.
            var oWb = (_Workbook) (oXl.Workbooks.Add(""));
            var oSheet = (_Worksheet) oWb.ActiveSheet;
            //oSheet.WriteArray(1, 1, bufferData1);

            oSheet.WriteArray(1, 1, data);

            oXl.Visible = false;
            oXl.UserControl = false;
            oWb.SaveAs(path, XlFileFormat.xlWorkbookDefault, Type.Missing,
                Type.Missing, false, false, XlSaveAsAccessMode.xlNoChange,
                Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing);
            oWb.Close(false);
            oXl.Quit();
        }
        catch (Exception e)
        {
            return false;
        }

        return true;
    }
}

usage :

var data = new[,]
{
    {11, 12, 13, 14, 15, 16, 17, 18, 19, 20},
    {21, 22, 23, 24, 25, 26, 27, 28, 29, 30},
    {31, 32, 33, 34, 35, 36, 37, 38, 39, 40}
};

ExcelUtility.SaveToExcel(data, "test.xlsx");

Best Regards!

How to use if-else option in JSTL

This is good and efficient approach as per time complexity prospect. Once it will get a true condition , it will not check any other after this. In multiple If , it will check each and condition.

   <c:choose>
      <c:when test="${condtion1}">
        do something condtion1
      </c:when>
      <c:when test="${condtion2}">
        do something condtion2
      </c:when>
      ......
      ......
      ...... 
      .......

      <c:when test="${condtionN}">
        do something condtionn N
      </c:when>


      <c:otherwise>
        do this w
      </c:otherwise>
    </c:choose>

java.lang.NullPointerException: Attempt to invoke virtual method on a null object reference

Your app is crashing at:

welcomePlayer.setText("Welcome Back, " + String.valueOf(mPlayer.getName(this)) + " !");

because mPlayer=null.

You forgot to initialize Player mPlayer in your PlayGame Activity.

mPlayer = new Player(context,"");

javascript if number greater than number

You can "cast" to number using the Number constructor..

var number = new Number("8"); // 8 number

You can also call parseInt builtin function:

var number = parseInt("153"); // 153 number

How do I capture the output of a script if it is being ran by the task scheduler?

You can write to a log file on the lines that you want to output like this:

@echo off
echo Debugging started >C:\logfile.txt
echo More stuff
echo Debugging stuff >>C:\logfile.txt
echo Hope this helps! >>C:\logfile.txt

This way you can choose which commands to output if you don't want to trawl through everything, just get what you need to see. The > will output it to the file specified (creating the file if it doesn't exist and overwriting it if it does). The >> will append to the file specified (creating the file if it doesn't exist but appending to the contents if it does).

difference between @size(max = value ) and @min(value) @max(value)

From the documentation I get the impression that in your example it would be intended to use:

@Range(min= SEQ_MIN_VALUE, max= SEQ_MAX_VALUE)

Checks whether the annotated value lies between (inclusive) the specified minimum and maximum. Supported data types:

BigDecimal, BigInteger, CharSequence, byte, short, int, long and the respective wrappers of the primitive types

ValueError: Wrong number of items passed - Meaning and suggestions?

Not sure if this is relevant to your question but it might be relevant to someone else in the future: I had a similar error. Turned out that the df was empty (had zero rows) and that is what was causing the error in my command.

How to add to an existing hash in Ruby

my_hash = {:a => 5}
my_hash[:key] = "value"

Closing Excel Application Process in C# after Data Access

Killing Excel is not always easy; see this article: 50 Ways to Kill Excel

This article takes the best advice from Microsoft (MS Knowlege Base Article) on how to get Excel to quit nicely, but then also makes sure about it by killing the process if necessary. I like having a second parachute.

Make sure to Close any open workbooks, Quit the application and Release the xlApp object. Finally check to see if the process is still alive and if so then kill it.

This article also makes sure that we don't kill all Excel processes but only kills the exact process that was started.

See also Get Process from Window Handle

Here is the code I use: (works every time)

Sub UsingExcel()

    'declare process; will be used later to attach the Excel process
    Dim XLProc As Process

    'call the sub that will do some work with Excel
    'calling Excel in a separate routine will ensure that it is 
    'out of scope when calling GC.Collect
    'this works better especially in debug mode
    DoOfficeWork(XLProc)

    'Do garbage collection to release the COM pointers
    'http://support.microsoft.com/kb/317109
    GC.Collect()
    GC.WaitForPendingFinalizers()

    'I prefer to have two parachutes when dealing with the Excel process
    'this is the last answer if garbage collection were to fail
    If Not XLProc Is Nothing AndAlso Not XLProc.HasExited Then
        XLProc.Kill()
    End If

End Sub

'http://msdn.microsoft.com/en-us/library/ms633522%28v=vs.85%29.aspx
<System.Runtime.InteropServices.DllImport("user32.dll", SetLastError:=True)> _
    Private Shared Function GetWindowThreadProcessId(ByVal hWnd As IntPtr, _
    ByRef lpdwProcessId As Integer) As Integer
End Function

Private Sub ExcelWork(ByRef XLProc As Process)

    'start the application using late binding
    Dim xlApp As Object = CreateObject("Excel.Application")

    'or use early binding
    'Dim xlApp As Microsoft.Office.Interop.Excel

    'get the window handle
    Dim xlHWND As Integer = xlApp.hwnd

    'this will have the process ID after call to GetWindowThreadProcessId
    Dim ProcIdXL As Integer = 0

    'get the process ID
    GetWindowThreadProcessId(xlHWND, ProcIdXL)

    'get the process
    XLProc = Process.GetProcessById(ProcIdXL)


    'do some work with Excel here using xlApp

    'be sure to save and close all workbooks when done

    'release all objects used (except xlApp) using NAR(x)


    'Quit Excel 
    xlApp.quit()

    'Release
    NAR(xlApp)

End Sub

Private Sub NAR(ByVal o As Object)
    'http://support.microsoft.com/kb/317109
    Try
        While (System.Runtime.InteropServices.Marshal.ReleaseComObject(o) > 0)
        End While
    Catch
    Finally
        o = Nothing
    End Try
End Sub

Split string into array

Do you care for non-English names? If so, all of the presented solutions (.split(''), [...str], Array.from(str), etc.) may give bad results, depending on language:

"????? ???????".split("") // the current president of India, Pranab Mukherjee
// returns ["?", "?", "?", "?", "?", " ", "?", "?", "?", "?", "?", "?", "?"]
// but should return ["??", "?", "?", "?", " ", "??", "?", "??", "??"]

Consider using the grapheme-splitter library for a clean standards-based split: https://github.com/orling/grapheme-splitter