Programs & Examples On #Vanity url

Get the name of a pandas DataFrame

From here what I understand DataFrames are:

DataFrame is a 2-dimensional labeled data structure with columns of potentially different types. You can think of it like a spreadsheet or SQL table, or a dict of Series objects.

And Series are:

Series is a one-dimensional labeled array capable of holding any data type (integers, strings, floating point numbers, Python objects, etc.).

Series have a name attribute which can be accessed like so:

 In [27]: s = pd.Series(np.random.randn(5), name='something')

 In [28]: s
 Out[28]: 
 0    0.541
 1   -1.175
 2    0.129
 3    0.043
 4   -0.429
 Name: something, dtype: float64

 In [29]: s.name
 Out[29]: 'something'

EDIT: Based on OP's comments, I think OP was looking for something like:

 >>> df = pd.DataFrame(...)
 >>> df.name = 'df' # making a custom attribute that DataFrame doesn't intrinsically have
 >>> print(df.name)
 'df'

Angular: How to download a file from HttpClient?

It took me a while to implement the other responses, as I'm using Angular 8 (tested up to 10). I ended up with the following code (heavily inspired by Hasan).

Note that for the name to be set, the header Access-Control-Expose-Headers MUST include Content-Disposition. To set this in django RF:

http_response = HttpResponse(package, content_type='application/javascript')
http_response['Content-Disposition'] = 'attachment; filename="{}"'.format(filename)
http_response['Access-Control-Expose-Headers'] = "Content-Disposition"

In angular:

  // component.ts
  // getFileName not necessary, you can just set this as a string if you wish
  getFileName(response: HttpResponse<Blob>) {
    let filename: string;
    try {
      const contentDisposition: string = response.headers.get('content-disposition');
      const r = /(?:filename=")(.+)(?:")/
      filename = r.exec(contentDisposition)[1];
    }
    catch (e) {
      filename = 'myfile.txt'
    }
    return filename
  }

  
  downloadFile() {
    this._fileService.downloadFile(this.file.uuid)
      .subscribe(
        (response: HttpResponse<Blob>) => {
          let filename: string = this.getFileName(response)
          let binaryData = [];
          binaryData.push(response.body);
          let downloadLink = document.createElement('a');
          downloadLink.href = window.URL.createObjectURL(new Blob(binaryData, { type: 'blob' }));
          downloadLink.setAttribute('download', filename);
          document.body.appendChild(downloadLink);
          downloadLink.click();
        }
      )
  }

  // service.ts
  downloadFile(uuid: string) {
    return this._http.get<Blob>(`${environment.apiUrl}/api/v1/file/${uuid}/package/`, { observe: 'response', responseType: 'blob' as 'json' })
  }

Display Images Inline via CSS

Place this css in your page:

<style>
   #client_logos {
    display: inline-block;
    width:100%;
    }
  </style>

Replace

<p><img class="alignnone" style="display: inline; margin: 0 10px;" title="heartica_logo" src="https://s3.amazonaws.com/rainleader/assets/heartica_logo.png" alt="" width="150" height="50" /><img class="alignnone" style="display: inline; margin: 0 10px;" title="mouseflow_logo" src="https://s3.amazonaws.com/rainleader/assets/mouseflow_logo.png" alt="" width="150" height="50" /><img class="alignnone" style="display: inline; margin: 0 10px;" title="mouseflow_logo" src="https://s3.amazonaws.com/rainleader/assets/piiholo_logo.png" alt="" width="150" height="50" /></p>

To

<div id="client_logos">
<img style="display: inline; margin: 0 5px;" title="heartica_logo" src="https://s3.amazonaws.com/rainleader/assets/heartica_logo.png" alt="" width="150" height="50" />
<img style="display: inline; margin: 0 5px;" title="mouseflow_logo" src="https://s3.amazonaws.com/rainleader/assets/mouseflow_logo.png" alt="" width="150" height="50" />
<img style="display: inline; margin: 0 5px;" title="piiholo_logo" src="https://s3.amazonaws.com/rainleader/assets/piiholo_logo.png" alt="" width="150" height="50" />
</div>

Best way to check for null values in Java?

if you do not have an access to the commons apache library, the following probably will work ok

if(null != foo && foo.bar()) {
//do something
}

How to open a link in new tab (chrome) using Selenium WebDriver?

The original poster is asking on how to open a link on a new tab. So this is how I have done it in C#.

        IWebDriver driver = new ChromeDriver();
        driver.Manage().Window.Maximize();
        driver.Navigate().GoToUrl("https://microsoft.com");
        IWebElement eventlink = driver.FindElement(By.Id("uhfLogo"));
        Actions action = new Actions(driver);
        action.KeyDown(Keys.Control).MoveToElement(eventlink).Click().Perform(); 

This actually performs a Control+Click on the selected element in order to open the link in a new tab.

Rebasing a Git merge commit

It looks like what you want to do is remove your first merge. You could follow the following procedure:

git checkout master      # Let's make sure we are on master branch
git reset --hard master~ # Let's get back to master before the merge
git pull                 # or git merge remote/master
git merge topic

That would give you what you want.

What causes a java.lang.StackOverflowError

Check for any recusive calls for methods. Mainly it is caused when there is recursive call for a method. A simple example is

public static void main(String... args) {
    Main main = new Main();

    main.testMethod(1);
}

public void testMethod(int i) {
    testMethod(i);

    System.out.println(i);
}

Here the System.out.println(i); will be repeatedly pushed to stack when the testMethod is called.

Signtool error: No certificates were found that met all given criteria with a Windows Store App?

With /debug, when you get this message "After Private Key filter, 0 certs were left.", one reason could be that the pfx file doesn't have the private key. When you export the installed certificate to pfx file ensure to enable the check box to also include the private key.

this in equals method

You have to look how this is called:

someObject.equals(someOtherObj); 

This invokes the equals method on the instance of someObject. Now, inside that method:

public boolean equals(Object obj) {   if (obj == this) { //is someObject equal to obj, which in this case is someOtherObj?     return true;//If so, these are the same objects, and return true   } 

You can see that this is referring to the instance of the object that equals is called on. Note that equals() is non-static, and so must be called only on objects that have been instantiated.

Note that == is only checking to see if there is referential equality; that is, the reference of this and obj are pointing to the same place in memory. Such references are naturally equal:

Object a = new Object(); Object b = a; //sets the reference to b to point to the same place as a Object c = a; //same with c b.equals(c);//true, because everything is pointing to the same place 

Further note that equals() is generally used to also determine value equality. Thus, even if the object references are pointing to different places, it will check the internals to determine if those objects are the same:

FancyNumber a = new FancyNumber(2);//Internally, I set a field to 2 FancyNumber b = new FancyNumber(2);//Internally, I set a field to 2 a.equals(b);//true, because we define two FancyNumber objects to be equal if their internal field is set to the same thing. 

Maven in Eclipse: step by step installation

You have to follow the following steps in the Eclipse IDE

  1. Go to Help - > Install New Software
  2. Click add button at top right corner
  3. In the popup coming, type in name as "Maven" and location as "http://download.eclipse.org/technology/m2e/releases"
  4. Click on OK.

Maven integration for eclipse will be dowloaded and installed. Restart the workspace.

In the .m2 folder(usually under C:\user\ directory) add settings.xml. Give proper proxy and profiles. Now create a new Maven project in eclipse.

What is the reason for having '//' in Python?

To complement these other answers, the // operator also offers significant (3x) performance benefits over /, presuming you want integer division.

$ python -m timeit '20.5 // 2'
100,000,000 loops, best of 3: 14.9 nsec per loop

$ python -m timeit '20.5 / 2'
 10,000,000 loops, best of 3: 48.4 nsec per loop

$ python -m timeit '20 / 2'
 10,000,000 loops, best of 3: 43.0 nsec per loop

$ python -m timeit '20 // 2'
100,000,000 loops, best of 3: 14.4 nsec per loop

How do I select an element in jQuery by using a variable for the ID?

You can do it like this:

row_id = 5;
row = $("body").find('#'+row_id);

Difference between getAttribute() and getParameter()

  • getParameter() returns http request parameters. Those passed from the client to the server. For example http://example.com/servlet?parameter=1. Can only return String

  • getAttribute() is for server-side usage only - you fill the request with attributes that you can use within the same request. For example - you set an attribute in a servlet, and read it from a JSP. Can be used for any object, not just string.

Create an ArrayList of unique values

You can easily do this with a Hashmap. You obviously have a key (which is the String data) and some values.

Loop on all your lines and add them to your Map.

Map<String, List<Integer>> map = new HashMap<>();
...
while (s.hasNext()){
  String stringData = ...
  List<Integer> values = ...
  map.put(stringData,values);
}

Note that in this case, you will keep the last occurence of duplicate lines. If you prefer keeping the first occurence and removing the others, you can add a check with Map.containsKey(String stringData); before putting in the map.

Causes of getting a java.lang.VerifyError

In my case my Android project depends on another Java project compiled for Java 7. java.lang.VerifyError disappeared after I changed Compiler Compliance Level of that Java project to 6.0

Later I found out that this is a Dalvik issue: https://groups.google.com/forum/?fromgroups#!topic/android-developers/sKsMTZ42pwE

How can you create multiple cursors in Visual Studio Code

Cmd+Option+Shift? / ? works for me on newest VSCode 1.29.1 and newest OSX High Sierra 10.13.6, Macbook Pro.

This adds a vertical line up/down on screen, like Option+Click/Vertical Drag does in Sublime Text.

To add multiple cursors at any points in your file, including multiple ones on the same line, do Cmd (or Option)+Click anywhere you want, shown in this video. You may also search for text (Cmd+F) that repeats multiple times, then press Option+Return to add cursors at end of EACH word.

Write a mode method in Java to find the most frequently occurring element in an array

    Arrays.sort(arr);
    int max=0,mode=0,count=0;
    for(int i=0;i<N;i=i+count) {
        count = 1;
        for(int j=i+1; j<N; j++) {
            if(arr[i] == arr[j])
                count++;
        }
        if(count>max) {
            max=count;
            mode = arr[i];
        }
    }

How do you use MySQL's source command to import large files in windows

With xampp I think you need to use the full path at the command line, something like this, perhaps:

C:\xampp\mysql\bin\mysql -u {username} -p {databasename} < file_name.sql

Dynamically allocating an array of objects

Why not have a setSize method.

A* arrayOfAs = new A[5];
for (int i = 0; i < 5; ++i)
{
    arrayOfAs[i].SetSize(3);
}

I like the "copy" but in this case the default constructor isn't really doing anything. The SetSize could copy the data out of the original m_array (if it exists).. You'd have to store the size of the array within the class to do that.
OR
The SetSize could delete the original m_array.

void SetSize(unsigned int p_newSize)
{
    //I don't care if it's null because delete is smart enough to deal with that.
    delete myArray;
    myArray = new int[p_newSize];
    ASSERT(myArray);
}

How to hide a <option> in a <select> menu with CSS?

Late to the game, but most of these seem quite complicated.

Here's how I did it:

var originalSelect = $('#select-2').html();

// filter select-2 on select-1 change
$('#select-1').change(function (e) {

    var selected = $(this).val();

    // reset select ready for filtering
    $('#select-2').html(originalCourseSelect);

    if (selected) {
        // filter
        $('#select-2 option').not('.t' + selected).remove();
    }

});

markup of select-1:

<select id='select-1'>
<option value=''>Please select</option>
<option value='1'>One</option>
<option value='2'>Two</option>
</select>

markup of select-2:

<select id='select-2'>
<option class='t1'>One</option>
<option class='t2'>Two</option>
<option>Always visible</option>
</select>

How can I create a text box for a note in markdown?

You may also use https://www.npmjs.com/package/markdown-it-container

::: warning
*here be dragons*
:::

Will then render as:

<div class="warning">
<em>here be dragons</em>
</div>

JavaScript validation for empty input field

Just add an ID tag to the input element... ie:

and check the value of the element in you javascript:

document.getElementById("question").value

Oh ya, get get firefox/firebug. It's the only way to do javascript.

"The transaction log for database is full due to 'LOG_BACKUP'" in a shared host

This error occurs because the transaction log becomes full due to LOG_BACKUP. Therefore, you can’t perform any action on this database, and In this case, the SQL Server Database Engine will raise a 9002 error.

To solve this issue you should do the following

  • Take a Full database backup.
  • Shrink the log file to reduce the physical file size.
  • Create a LOG_BACKUP.
  • Create a LOG_BACKUP Maintenance Plan to take backup logs frequently.

I wrote an article with all details regarding this error and how to solve it at The transaction log for database ‘SharePoint_Config’ is full due to LOG_BACKUP

Git: How to rebase to a specific commit?

There is another way of doing it or if you wish to move back to more than just one commit.

Here is a an example to move back to n number of commits:

git branch topic master~n

For the sake of this question, this can also be done:

git branch topic master~1

The command works perfectly on git version 2.7.4. Haven't tested it on any other version.

How to update single value inside specific array item in redux

I'm afraid that using map() method of an array may be expensive since entire array is to be iterated. Instead, I combine a new array that consists of three parts:

  • head - items before the modified item
  • the modified item
  • tail - items after the modified item

Here the example I've used in my code (NgRx, yet the machanism is the same for other Redux implementations):

// toggle done property: true to false, or false to true

function (state, action) {
    const todos = state.todos;
    const todoIdx = todos.findIndex(t => t.id === action.id);

    const todoObj = todos[todoIdx];
    const newTodoObj = { ...todoObj, done: !todoObj.done };

    const head = todos.slice(0, todoIdx - 1);
    const tail = todos.slice(todoIdx + 1);
    const newTodos = [...head, newTodoObj, ...tail];
}

How to send a GET request from PHP?

Remember that if you are using a proxy you need to do a little trick in your php code:

(PROXY WITHOUT AUTENTICATION EXAMPLE)

<?php
$aContext = array(
    'http' => array(
        'proxy' => 'proxy:8080',
        'request_fulluri' => true,
    ),
);
$cxContext = stream_context_create($aContext);

$sFile = file_get_contents("http://www.google.com", False, $cxContext);

echo $sFile;
?>

@font-face not working

Using font-face requires a little understanding of browser inconsistencies and may require some changes on the web server itself. First thing you have to do is check the console to see if/what messages are being generated. Is it a permissions issue or resource not found....?

Secondly because each browser is expecting a different font type I would use Font Squirrel to upload your font and then generate the additional files and CSS needed. http://www.fontsquirrel.com/fontface/generator

And finally, versions of FireFox and IE will not allow fonts to be loaded cross domain. You may need to modify your Apache config or .htaccess (Header set Access-Control-Allow-Origin "*")

View JSON file in Browser

In Chrome, use JSONView to view formatted JSON.

To view "local" *.json files: - after install You must open the Extensions option from Window menu. - Check box next to "Allow Access to File URLs" - note that save is automatic (i.e. no explicit save necessary)

Re-open the *.json file and it should be formatted.

PHP header redirect 301 - what are the implications?

Just a tip: using http_response_code is much easier to remember than writing the full header:

http_response_code(301);
header('Location: /option-a'); 
exit;

How to add a progress bar to a shell script?

I have built on the answer provided by fearside

This connects to an Oracle database to retrieve the progress of an RMAN restore.

#!/bin/bash

 # 1. Create ProgressBar function
 # 1.1 Input is currentState($1) and totalState($2)
 function ProgressBar {
 # Process data
let _progress=(${1}*100/${2}*100)/100
let _done=(${_progress}*4)/10
let _left=40-$_done
# Build progressbar string lengths
_fill=$(printf "%${_done}s")
_empty=$(printf "%${_left}s")

# 1.2 Build progressbar strings and print the ProgressBar line
# 1.2.1 Output example:
# 1.2.1.1 Progress : [########################################] 100%
printf "\rProgress : [${_fill// /#}${_empty// /-}] ${_progress}%%"

}

function rman_check {
sqlplus -s / as sysdba <<EOF
set heading off
set feedback off
select
round((sofar/totalwork) * 100,0) pct_done
from
v\$session_longops
where
totalwork > sofar
AND
opname NOT LIKE '%aggregate%'
AND
opname like 'RMAN%';
exit
EOF
}

# Variables
_start=1

# This accounts as the "totalState" variable for the ProgressBar function
_end=100

_rman_progress=$(rman_check)
#echo ${_rman_progress}

# Proof of concept
#for number in $(seq ${_start} ${_end})

while [ ${_rman_progress} -lt 100 ]
do

for number in _rman_progress
do
sleep 10
ProgressBar ${number} ${_end}
done

_rman_progress=$(rman_check)

done
printf '\nFinished!\n'

return in for loop or outside loop

The code is valid (i.e, will compile and execute) in both cases.

One of my lecturers at Uni told us that it is not desirable to have continue, return statements in any loop - for or while. The reason for this is that when examining the code, it is not not immediately clear whether the full length of the loop will be executed or the return or continue will take effect.

See Why is continue inside a loop a bad idea? for an example.

The key point to keep in mind is that for simple scenarios like this it doesn't (IMO) matter but when you have complex logic determining the return value, the code is 'generally' more readable if you have a single return statement instead of several.

With regards to the Garbage Collection - I have no idea why this would be an issue.

jump to line X in nano editor

I am using Linux raspi 4.19.118+ #1311 via ssh Powershell on Win 10 Pro 1909 with German keyboard. nano shortcut Goto Line with "Crtl + Shift + -" was not working Solution: Step 1 - Do Current Position with "Crtl + C" Step 2 - Goto Line with "Crtl + Shift + -" IS working!

I dont know what effects it. But now its working without step 1!

JQuery - Set Attribute value

$("#chk0") is refering to an element with the id chk0. You might try adding id's to the elements. Ids are unique even though the names are the same so that in jQuery you can access a single element by it's id.

How to get user agent in PHP

Use the native PHP $_SERVER['HTTP_USER_AGENT'] variable instead.

Constant pointer vs Pointer to constant

int i;
int j;

int * const ptr1 = &i;

The compiler will stop you changing ptr1.

const int * ptr2 = &i;

The compiler will stop you changing *ptr2.

ptr1 = &j; // error
*ptr1 = 7; // ok

ptr2 = &j; // ok
*ptr2 = 7; // error

Note that you can still change *ptr2, just not by literally typing *ptr2:

i = 4;
printf("before: %d\n", *ptr2); // prints 4
i = 5;
printf("after: %d\n", *ptr2); // prints 5
*ptr2 = 6; // still an error

You can also have a pointer with both features:

const int * const ptr3 = &i;

ptr3 = &j; // error
*ptr3 = 7; // error

How to export a Hive table into a CSV file?

There are ways to change the default delimiter, as shown by other answers.

There are also ways to convert the raw output to csv with some bash scripting. There are 3 delimiters to consider though, not just \001. Things get a bit more complicated when your hive table has maps.

I wrote a bash script that can handle all 3 default delimiters (\001 \002 and \003) from hive and output a csv. The script and some more info are here:

Hive Default Delimiters to CSV

Hive's default delimiters are

Row Delimiter => Control-A ('\001')
Collection Item Delimiter => Control-B ('\002')
Map Key Delimiter => Control-C ('\003')

There are ways to change these delimiters when exporting tables but sometimes you might still get stuck needing to convert this to csv.

Here's a quick bash script that can handle a DB export that's segmented in multiple files and has the default delimiters. It will output a single CSV file.

It is assumed that the segments all have the naming convention 000*_0

INDIRECTORY="path/to/input/directory"
for f in $INDIRECTORY/000*_0; do 
  echo "Processing $f file.."; 
  cat -v $f | 
      LC_ALL=C sed -e "s/^/\"/g" | 
      LC_ALL=C sed -e "s/\^A/\",\"/g" | 
      LC_ALL=C sed -e "s/\^C\^B/\"\":\"\"\"\",\"\"/g" | 
      LC_ALL=C sed -e "s/\^B/\"\",\"\"/g" |  
      LC_ALL=C sed -e "s/\^C/\"\":\"\"/g" | 
      LC_ALL=C sed -e "s/$/\"/g" > $f-temp
done
echo "you,can,echo,your,header,here,if,you,like" > $INDIRECTORY/final_output.csv
cat $INDIRECTORY/*-temp >> $INDIRECTORY/final_output.csv
rm $INDIRECTORY/*-temp

More explanation on the gist

.htaccess or .htpasswd equivalent on IIS?

There isn't a direct 1:1 equivalent.

You can password protect a folder or file using file system permissions. If you are using ASP.Net you can also use some of its built in functions to protect various urls.

If you are trying to port .htaccess files used for url rewriting, check out ISAPI Rewrite: http://www.isapirewrite.com/

Android API 21 Toolbar Padding

Above answer is correct but there is still one thing that might create issues (At least it did create an issue for me)

I used the following and it doesn't work properly on older devices -

android:contentInsetStart="0dp"
android:contentInsetLeft="0dp"
app:contentInsetLeft="0dp"
app:contentInsetStart="0dp"

The trick is here just use the following -

app:contentInsetLeft="0dp"
app:contentInsetStart="0dp"

and get rid of -

android:contentInsetStart="0dp"
android:contentInsetLeft="0dp"

And now it should work fine throughout all the devices.

Hope it helps.

How to change facet labels?

After struggling for a while, what I found is that we can use fct_relevel() and fct_recode() from forcats in conjunction to change the order of the facets as well fix the facet labels. I am not sure if it's supported by design, but it works! Check out the plots below:

library(tidyverse)

before <- mpg %>%
  ggplot(aes(displ, hwy)) + 
  geom_point() +
  facet_wrap(~class)
before

after <- mpg %>%
  ggplot(aes(displ, hwy)) + 
  geom_point() + 
  facet_wrap(
    vars(
      # Change factor level name
      fct_recode(class, "motorbike" = "2seater") %>% 
        # Change factor level order
        fct_relevel("compact")
    )
  )
after

Created on 2020-02-16 by the reprex package (v0.3.0)

How Do I Get the Query Builder to Output Its Raw SQL Query as a String?

Print last query

DB::enableQueryLog();

$query        = DB::getQueryLog();
$lastQuery    = end($query);
print_r($lastQuery);

For a boolean field, what is the naming convention for its getter/setter?

Maybe it is time to start revising this answer? Personally I would vote for setActive() and unsetActive() (alternatives can be setUnActive(), notActive(), disable(), etc. depending on context) since "setActive" implies you activate it at all times, which you don't. It's kind of counter intuitive to say "setActive" but actually remove the active state.

Another problem is, you can can not listen to specifically a SetActive event in a CQRS way, you would need to listen to a 'setActiveEvent' and determine inside that listener wether is was actually set active or not. Or of course determine which event to call when calling setActive() but that then goes against the Separation of Concerns principle.

A good read on this is the FlagArgument article by Martin Fowler: http://martinfowler.com/bliki/FlagArgument.html

However, I come from a PHP background and see this trend being adopted more and more. Not sure how much this lives with Java development.

Length of array in function argument

sizeof only works to find the length of the array if you apply it to the original array.

int a[5]; //real array. NOT a pointer
sizeof(a); // :)

However, by the time the array decays into a pointer, sizeof will give the size of the pointer and not of the array.

int a[5];
int * p = a;
sizeof(p); // :(

As you have already smartly pointed out main receives the length of the array as an argument (argc). Yes, this is out of necessity and is not redundant. (Well, it is kind of reduntant since argv is conveniently terminated by a null pointer but I digress)

There is some reasoning as to why this would take place. How could we make things so that a C array also knows its length?

A first idea would be not having arrays decaying into pointers when they are passed to a function and continuing to keep the array length in the type system. The bad thing about this is that you would need to have a separate function for every possible array length and doing so is not a good idea. (Pascal did this and some people think this is one of the reasons it "lost" to C)

A second idea is storing the array length next to the array, just like any modern programming language does:

a -> [5];[0,0,0,0,0]

But then you are just creating an invisible struct behind the scenes and the C philosophy does not approve of this kind of overhead. That said, creating such a struct yourself is often a good idea for some sorts of problems:

struct {
    size_t length;
    int * elements;
}

Another thing you can think about is how strings in C are null terminated instead of storing a length (as in Pascal). To store a length without worrying about limits need a whopping four bytes, an unimaginably expensive amount (at least back then). One could wonder if arrays could be also null terminated like that but then how would you allow the array to store a null?

What's is the difference between train, validation and test set, in neural networks?

Say you train a model on a training set and then measure its performance on a test set. You think that there is still room for improvement and you try tweaking the hyper-parameters ( If the model is a Neural Network - hyper-parameters are the number of layers, or nodes in the layers ). Now you get a slightly better performance. However, when the model is subjected to another data ( not in the testing and training set ) you may not get the same level of accuracy. This is because you introduced some bias while tweaking the hyper-parameters to get better accuracy on the testing set. You basically have adapted the model and hyper-parameters to produce the best model for that particular training set.

A common solution is to split the training set further to create a validation set. Now you have

  • training set
  • testing set
  • validation set

You proceed as before but this time you use the validation set to test the performance and tweak the hyper-parameters. More specifically, you train multiple models with various hyper-parameters on the reduced training set (i.e., the full training set minus the validation set), and you select the model that performs best on the validation set.

Once you've selected the best performing model on the validation set, you train the best model on the full training set (including the valida- tion set), and this gives you the final model.

Lastly, you evaluate this final model on the test set to get an estimate of the generalization error.

How to create json by JavaScript for loop?

var sels = //Here is your array of SELECTs
var json = { };

for(var i = 0, l = sels.length; i < l; i++) {
  json[sels[i].id] = sels[i].value;
}

How do I clear the previous text field value after submitting the form with out refreshing the entire page?

you can just do as you get that elements value

document.getElementById('numquest').value='';

UIView Hide/Show with animation

func flipViews(fromView: UIView, toView: UIView) {

    toView.frame.origin.y = 0

    self.view.isUserInteractionEnabled = false

    UIView.transition(from: fromView, to: toView, duration: 0.5, options: .transitionFlipFromLeft, completion: { finished in            

        fromView.frame.origin.y = -900

        self.view.isUserInteractionEnabled = true

    })


}

z-index not working with position absolute

z-index only applies to elements that have been given an explicit position. Add position:relative to #popupContent and you should be good to go.

Deleting row from datatable in C#

There several different ways to do it. But You can use the following approach:

List<DataRow> RowsToDelete = new List<DataRow>();

for (int i = 0; i < drr.Length; i++) 
{     
   if(condition to delete the row) 
   {  
       RowsToDelete.Add(drr[i]);     
   } 
}

foreach(var dr in RowsToDelete) 
{     
   drr.Rows.Remove(dr); 
} 

Pattern matching using a wildcard

You're on the right track - the keyword you should be googling is Regular Expressions. R does support them in a more direct way than this using grep() and a few other alternatives.

Here's a detailed discussion: http://www.regular-expressions.info/rlanguage.html

How to get first 5 characters from string

You can get your result by simply use substr():

Syntax substr(string,start,length)

Example

<?php
$myStr = "HelloWordl";
echo substr($myStr,0,5);
?>

Output :

 Hello

Export MySQL database using PHP only

Try the following.

Execute a database backup query from PHP file. Below is an example of using SELECT INTO OUTFILE query for creating table backup:

<?php
$DB_HOST = "localhost";
$DB_USER = "xxx";
$DB_PASS = "xxx";
$DB_NAME = "xxx";

$con = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($con->connect_errno > 0) {
  die('Connection failed [' . $con->connect_error . ']');
}

$tableName  = 'yourtable';
$backupFile = 'backup/yourtable.sql';
$query      = "SELECT * INTO OUTFILE '$backupFile' FROM $tableName";
$result = mysqli_query($con,$query);
?>

To restore the backup you just need to run LOAD DATA INFILE query like this:

<?php
$DB_HOST = "localhost";
$DB_USER = "xxx";
$DB_PASS = "xxx";
$DB_NAME = "xxx";

$con = new mysqli($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if($con->connect_errno > 0) {
  die('Connection failed [' . $con->connect_error . ']');
}

$tableName  = 'yourtable';
$backupFile = 'yourtable.sql';
$query      = "LOAD DATA INFILE 'backupFile' INTO TABLE $tableName";
$result = mysqli_query($con,$query);
?>

How to get the path of the batch script in Windows?

That would be the %CD% variable.

@echo off
echo %CD%

%CD% returns the current directory the batch script is in.

What difference is there between WebClient and HTTPWebRequest classes in .NET?

WebClient is a higher-level abstraction built on top of HttpWebRequest to simplify the most common tasks. For instance, if you want to get the content out of an HttpWebResponse, you have to read from the response stream:

var http = (HttpWebRequest)WebRequest.Create("http://example.com");
var response = http.GetResponse();

var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
var content = sr.ReadToEnd();

With WebClient, you just do DownloadString:

var client = new WebClient();
var content = client.DownloadString("http://example.com");

Note: I left out the using statements from both examples for brevity. You should definitely take care to dispose your web request objects properly.

In general, WebClient is good for quick and dirty simple requests and HttpWebRequest is good for when you need more control over the entire request.

Common HTTPclient and proxy

If your software uses a ProxySelector (for example for using a PAC-script instead of a static host/port) and your HTTPComponents is version 4.3 or above then you can use your ProxySelector for your HttpClient like this:

ProxySelector myProxySelector = ...;
HttpClient myHttpClient = HttpClientBuilder.create().setRoutePlanner(new SystemDefaultRoutePlanner(myProxySelector))).build();

And then do your requests as usual:

HttpGet myRequest = new HttpGet("/");
myHttpClient.execute(myRequest);

How do I give PHP write access to a directory?

I'm running Ubuntu, and as said above nobody:nobody does not work on Ubuntu. You get the error:

chown: invalid group: 'nobody:nobody'

Instead you should use the 'nogroup', like:

chown nobody:nogroup <dirname>

How do I ignore ampersands in a SQL script running from SQL Plus?

set define off <- This is the best solution I found

I also tried...

set define }

I was able to insert several records containing ampersand characters '&' but I cannot use the '}' character into the text So I decided to use "set define off" and everything works as it should.

Copy entire directory contents to another directory?

The following is an example of using JDK7.

public class CopyFileVisitor extends SimpleFileVisitor<Path> {
    private final Path targetPath;
    private Path sourcePath = null;
    public CopyFileVisitor(Path targetPath) {
        this.targetPath = targetPath;
    }

    @Override
    public FileVisitResult preVisitDirectory(final Path dir,
    final BasicFileAttributes attrs) throws IOException {
        if (sourcePath == null) {
            sourcePath = dir;
        } else {
        Files.createDirectories(targetPath.resolve(sourcePath
                    .relativize(dir)));
        }
        return FileVisitResult.CONTINUE;
    }

    @Override
    public FileVisitResult visitFile(final Path file,
    final BasicFileAttributes attrs) throws IOException {
    Files.copy(file,
        targetPath.resolve(sourcePath.relativize(file)));
    return FileVisitResult.CONTINUE;
    }
}

To use the visitor do the following

Files.walkFileTree(sourcePath, new CopyFileVisitor(targetPath));

If you'd rather just inline everything (not too efficient if you use it often, but good for quickies)

    final Path targetPath = // target
    final Path sourcePath = // source
    Files.walkFileTree(sourcePath, new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult preVisitDirectory(final Path dir,
                final BasicFileAttributes attrs) throws IOException {
            Files.createDirectories(targetPath.resolve(sourcePath
                    .relativize(dir)));
            return FileVisitResult.CONTINUE;
        }

        @Override
        public FileVisitResult visitFile(final Path file,
                final BasicFileAttributes attrs) throws IOException {
            Files.copy(file,
                    targetPath.resolve(sourcePath.relativize(file)));
            return FileVisitResult.CONTINUE;
        }
    });

Make HTML5 video poster be same size as video itself

Or you can use simply preload="none" attribute to make VIDEO background visible. And you can use background-size: cover; here.

 video {
   background: transparent url('video-image.jpg') 50% 50% / cover no-repeat ;
 }

 <video preload="none" controls>
   <source src="movie.mp4" type="video/mp4">
   <source src="movie.ogg" type="video/ogg">
 </video>

Closing Application with Exit button

You cannot exit your application. Using android.finish() won't exit the application, it just kills the activity. It's used when we don't want to see the previous activity on back button click. The application automatically exits when you switch off the device. The Android architecture does not support exiting the app. If you want, you can forcefully exit the app, but that's not considered good practice.

String to list in Python

You can use the split() function, which returns a list, to separate them.

letters = 'QH QD JC KD JS'

letters_list = letters.split()

Printing letters_list would now format it like this:

['QH', 'QD', 'JC', 'KD', 'JS']

Now you have a list that you can work with, just like you would with any other list. For example accessing elements based on indexes:

print(letters_list[2])

This would print the third element of your list, which is 'JC'

How to Truncate a string in PHP to the word closest to a certain number of characters?

I used this before

<?php
    $your_desired_width = 200;
    $string = $var->content;
    if (strlen($string) > $your_desired_width) {
        $string = wordwrap($string, $your_desired_width);
        $string = substr($string, 0, strpos($string, "\n")) . " More...";
    }
    echo $string;
?>

What is the difference between Step Into and Step Over in a debugger

Consider the following code with your current instruction pointer (the line that will be executed next, indicated by ->) at the f(x) line in g(), having been called by the g(2) line in main():

public class testprog {
    static void f (int x) {
        System.out.println ("num is " + (x+0)); // <- STEP INTO
    }

    static void g (int x) {
->      f(x); //
        f(1); // <----------------------------------- STEP OVER
    }

    public static void main (String args[]) {
        g(2);
        g(3); // <----------------------------------- STEP OUT OF
    }
}

If you were to step into at that point, you will move to the println() line in f(), stepping into the function call.

If you were to step over at that point, you will move to the f(1) line in g(), stepping over the function call.

Another useful feature of debuggers is the step out of or step return. In that case, a step return will basically run you through the current function until you go back up one level. In other words, it will step through f(x) and f(1), then back out to the calling function to end up at g(3) in main().

libxml install error using pip

just install requirements:

sudo apt-get install libxml2-dev libxslt-dev python-dev

Now, you can install it with pip package management tool:

pip install lxml

For python3 users:

sudo apt-get install libxml2-dev libxslt-dev python3-dev

pip3 install lxml

how to prevent adding duplicate keys to a javascript array

A better alternative is provided in ES6 using Sets. So, instead of declaring Arrays, it is recommended to use Sets if you need to have an array that shouldn't add duplicates.

var array = new Set();
array.add(1);
array.add(2);
array.add(3);

console.log(array);
// Prints: Set(3) {1, 2, 3}

array.add(2); // does not add any new element

console.log(array);
// Still Prints: Set(3) {1, 2, 3}

How can I do SELECT UNIQUE with LINQ?

var uniqueColors = (from dbo in database.MainTable 
                    where dbo.Property == true
                    select dbo.Color.Name).Distinct();

How to detect orientation change in layout in Android?

for Kotilin implementation in the simplest form - only fires when screen changes from portrait <--> landscape if need device a flip detection (180 degree) you'll need to tab in to gravity sensor values

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

val rotation = windowManager.defaultDisplay.rotation

    when (rotation) {            
        0 -> Log.d(TAG,"at zero degree")
        1 -> Log.d(TAG,"at 270 degree")
        2 -> Log.d(TAG,"at 180 degree")
        3 -> Log.d(TAG,"at 90 degree")


    }
}

Merge a Branch into Trunk

The syntax is wrong, it should instead be

svn merge <what(the range)> <from(your dev branch)> <to(trunk/trunk local copy)>

String.Format for Hex

The number 0 in {0:X} refers to the position in the list or arguments. In this case 0 means use the first value, which is Blue. Use {1:X} for the second argument (Green), and so on.

colorstring = String.Format("#{0:X}{1:X}{2:X}{3:X}", Blue, Green, Red, Space);

The syntax for the format parameter is described in the documentation:

Format Item Syntax

Each format item takes the following form and consists of the following components:

{ index[,alignment][:formatString]}

The matching braces ("{" and "}") are required.

Index Component

The mandatory index component, also called a parameter specifier, is a number starting from 0 that identifies a corresponding item in the list of objects. That is, the format item whose parameter specifier is 0 formats the first object in the list, the format item whose parameter specifier is 1 formats the second object in the list, and so on.

Multiple format items can refer to the same element in the list of objects by specifying the same parameter specifier. For example, you can format the same numeric value in hexadecimal, scientific, and number format by specifying a composite format string like this: "{0:X} {0:E} {0:N}".

Each format item can refer to any object in the list. For example, if there are three objects, you can format the second, first, and third object by specifying a composite format string like this: "{1} {0} {2}". An object that is not referenced by a format item is ignored. A runtime exception results if a parameter specifier designates an item outside the bounds of the list of objects.

Alignment Component

The optional alignment component is a signed integer indicating the preferred formatted field width. If the value of alignment is less than the length of the formatted string, alignment is ignored and the length of the formatted string is used as the field width. The formatted data in the field is right-aligned if alignment is positive and left-aligned if alignment is negative. If padding is necessary, white space is used. The comma is required if alignment is specified.

Format String Component

The optional formatString component is a format string that is appropriate for the type of object being formatted. Specify a standard or custom numeric format string if the corresponding object is a numeric value, a standard or custom date and time format string if the corresponding object is a DateTime object, or an enumeration format string if the corresponding object is an enumeration value. If formatString is not specified, the general ("G") format specifier for a numeric, date and time, or enumeration type is used. The colon is required if formatString is specified.

Note that in your case you only have the index and the format string. You have not specified (and do not need) an alignment component.

Can I use conditional statements with EJS templates (in JMVC)?

You can also use else if syntax:

<% if (x === 1) { %>
    <p>Hello world!</p>
<% } else if (x === 2) { %>
    <p>Hi earth!</p>
<% } else { %>
    <p>Hey terra!</p>
<% } %>

Getting value from appsettings.json in .net core

  1. Add the required key here like this. In this case its SecureCookies:

Add the required key here like this. In this case its SecureCookies

  1. In startup.cs, add the constructor

     public Startup(IConfiguration configuration)
     {
         Configuration = configuration;
    
     }
     public IConfiguration Configuration { get; }
    
  2. Access the settings using Configuration["SecureCookies"]

How do I calculate square root in Python?

I hope the below mentioned code will answer your question.

def root(x,a):
    y = 1 / a
    y = float(y)
    print y
    z = x ** y
    print z

base = input("Please input the base value:")
power = float(input("Please input the root value:"))


root(base,power) 

python request with authentication (access_token)

Have you tried the uncurl package (https://github.com/spulec/uncurl)? You can install it via pip, pip install uncurl. Your curl request returns:

>>> uncurl "curl --header \"Authorization:access_token myToken\" https://website.com/id"

requests.get("https://website.com/id",
    headers={
        "Authorization": "access_token myToken"
    },
    cookies={},
)

MVC pattern on Android

There is no universally unique MVC pattern. MVC is a concept rather than a solid programming framework. You can implement your own MVC on any platform. As long as you stick to the following basic idea, you are implementing MVC:

  • Model: What to render
  • View: How to render
  • Controller: Events, user input

Also think about it this way: When you program your model, the model should not need to worry about the rendering (or platform specific code). The model would say to the view, I don't care if your rendering is Android or iOS or Windows Phone, this is what I need you to render. The view would only handle the platform-specific rendering code.

This is particularly useful when you use Mono to share the model in order to develop cross-platform applications.

Round up double to 2 decimal places

The code for specific digits after decimals is:

var roundedString = String(format: "%.2f", currentRatio)

Here the %.2f tells the swift to make this number rounded to 2 decimal places.

What was the strangest coding standard rule that you were forced to follow?

inserting line breaks
(//--------------------------------------------------------------------------------)
between methods in a c# project.

How do you calculate program run time in python?

You might want to take a look at the timeit module:

http://docs.python.org/library/timeit.html

or the profile module:

http://docs.python.org/library/profile.html

There are some additionally some nice tutorials here:

http://www.doughellmann.com/PyMOTW/profile/index.html

http://www.doughellmann.com/PyMOTW/timeit/index.html

And the time module also might come in handy, although I prefer the later two recommendations for benchmarking and profiling code performance:

http://docs.python.org/library/time.html

How do I translate an ISO 8601 datetime string into a Python datetime object?

Because ISO 8601 allows many variations of optional colons and dashes being present, basically CCYY-MM-DDThh:mm:ss[Z|(+|-)hh:mm]. If you want to use strptime, you need to strip out those variations first.

The goal is to generate a UTC datetime object.


If you just want a basic case that work for UTC with the Z suffix like 2016-06-29T19:36:29.3453Z:

datetime.datetime.strptime(timestamp.translate(None, ':-'), "%Y%m%dT%H%M%S.%fZ")

If you want to handle timezone offsets like 2016-06-29T19:36:29.3453-0400 or 2008-09-03T20:56:35.450686+05:00 use the following. These will convert all variations into something without variable delimiters like 20080903T205635.450686+0500 making it more consistent/easier to parse.

import re
# This regex removes all colons and all
# dashes EXCEPT for the dash indicating + or - utc offset for the timezone
conformed_timestamp = re.sub(r"[:]|([-](?!((\d{2}[:]\d{2})|(\d{4}))$))", '', timestamp)
datetime.datetime.strptime(conformed_timestamp, "%Y%m%dT%H%M%S.%f%z" )

If your system does not support the %z strptime directive (you see something like ValueError: 'z' is a bad directive in format '%Y%m%dT%H%M%S.%f%z') then you need to manually offset the time from Z (UTC). Note %z may not work on your system in Python versions < 3 as it depended on the C library support which varies across system/Python build type (i.e., Jython, Cython, etc.).

import re
import datetime

# This regex removes all colons and all
# dashes EXCEPT for the dash indicating + or - utc offset for the timezone
conformed_timestamp = re.sub(r"[:]|([-](?!((\d{2}[:]\d{2})|(\d{4}))$))", '', timestamp)

# Split on the offset to remove it. Use a capture group to keep the delimiter
split_timestamp = re.split(r"([+|-])",conformed_timestamp)
main_timestamp = split_timestamp[0]
if len(split_timestamp) == 3:
    sign = split_timestamp[1]
    offset = split_timestamp[2]
else:
    sign = None
    offset = None

# Generate the datetime object without the offset at UTC time
output_datetime = datetime.datetime.strptime(main_timestamp +"Z", "%Y%m%dT%H%M%S.%fZ" )
if offset:
    # Create timedelta based on offset
    offset_delta = datetime.timedelta(hours=int(sign+offset[:-2]), minutes=int(sign+offset[-2:]))

    # Offset datetime with timedelta
    output_datetime = output_datetime + offset_delta

How do I generate a constructor from class fields using Visual Studio (and/or ReSharper)?

C# added a new feature in Visual Studio 2010 called generate from usage. The intent is to generate the standard code from a usage pattern. One of the features is generating a constructor based off an initialization pattern.

The feature is accessible via the smart tag that will appear when the pattern is detected.

For example, let’s say I have the following class

class MyType { 

}

And I write the following in my application

var v1 = new MyType(42);

A constructor taking an int does not exist so a smart tag will show up and one of the options will be "Generate constructor stub". Selecting that will modify the code for MyType to be the following.

class MyType {
    private int p;
    public MyType(int p) {
        // TODO: Complete member initialization
        this.p = p;
    }
}

Can I use multiple "with"?

Try:

With DependencedIncidents AS
(
    SELECT INC.[RecTime],INC.[SQL] AS [str] FROM
    (
        SELECT A.[RecTime] As [RecTime],X.[SQL] As [SQL] FROM [EventView] AS A 
        CROSS JOIN [Incident] AS X
            WHERE
                patindex('%' + A.[Col] + '%', X.[SQL]) > 0
    ) AS INC
),
lalala AS
(
    SELECT INC.[RecTime],INC.[SQL] AS [str] FROM
    (
        SELECT A.[RecTime] As [RecTime],X.[SQL] As [SQL] FROM [EventView] AS A 
        CROSS JOIN [Incident] AS X
            WHERE
                patindex('%' + A.[Col] + '%', X.[SQL]) > 0
    ) AS INC
)

And yes, you can reference common table expression inside common table expression definition. Even recursively. Which leads to some very neat tricks.

What are the different usecases of PNG vs. GIF vs. JPEG vs. SVG?

I usually go with PNG, as it seems to have a few advantages over GIF. There used to be patent restrictions on GIF, but those have expired.

GIFs are suitable for sharp-edged line art (such as logos) with a limited number of colors. This takes advantage of the format's lossless compression, which favors flat areas of uniform color with well defined edges (in contrast to JPEG, which favors smooth gradients and softer images).

GIFs can be used for small animations and low-resolution film clips.

In view of the general limitation on the GIF image palette to 256 colors, it is not usually used as a format for digital photography. Digital photographers use image file formats capable of reproducing a greater range of colors, such as TIFF, RAW or the lossy JPEG, which is more suitable for compressing photographs.

The PNG format is a popular alternative to GIF images since it uses better compression techniques and does not have a limit of 256 colors, but PNGs do not support animations. The MNG and APNG formats, both derived from PNG, support animations, but are not widely used.

Which terminal command to get just IP address and nothing else?

ip addr|awk '/eth0/ && /inet/ {gsub(/\/[0-9][0-9]/,""); print $2}'

shows all your ips

"Sources directory is already netbeans project" error when opening a project from existing sources

Click File >> Recent Projects > and you should be able to use edit it again. Hope it helps :)

Bootstrap modal z-index

The problem almost always has something to do with "nested" z-indexes. As an Example:

<div style="z-index:1">
  some content A
  <div style="z-index:1000000000">
    some content B
  </div>
</div>
<div style="z-index:10">
  Some content C
</div>

if you look at the z-index only you would expect B,C,A, but because B is nested in a div that is expressly set to 1, it will show up as C,B,A.

Setting position:fixed locks the z-index for that element and all its children, which is why changing that can solve the problem.

The solution is to find the parent element that has the z-index set and either adjust the setting or move the content so the layers and their parent containers stack up the way you want. Firebug in Firefox has a tab in the far right named "Layout" and you can quickly go up the parent elements and see where the z-index is set.

Resize Google Maps marker icon image

So I just had this same issue, but a little different. I already had the icon as an object as Philippe Boissonneault suggests, but I was using an SVG image.

What solved it for me was:
Switch from an SVG image to a PNG and following Catherine Nyo on having an image that is double the size of what you will use.

How to get a variable name as a string in PHP?

I couldn't think of a way to do this efficiently either but I came up with this. It works, for the limited uses below.

shrug

<?php

function varName( $v ) {
    $trace = debug_backtrace();
    $vLine = file( __FILE__ );
    $fLine = $vLine[ $trace[0]['line'] - 1 ];
    preg_match( "#\\$(\w+)#", $fLine, $match );
    print_r( $match );
}

$foo = "knight";
$bar = array( 1, 2, 3 );
$baz = 12345;

varName( $foo );
varName( $bar );
varName( $baz );

?>

// Returns
Array
(
    [0] => $foo
    [1] => foo
)
Array
(
    [0] => $bar
    [1] => bar
)
Array
(
    [0] => $baz
    [1] => baz
)

It works based on the line that called the function, where it finds the argument you passed in. I suppose it could be expanded to work with multiple arguments but, like others have said, if you could explain the situation better, another solution would probably work better.

What's a clean way to stop mongod on Mac OS X?

The solutions provided by others used to work for me but is not working for me anymore, which is as below.

brew services stop mongodb
brew services start mongodb

brew services list gives

Name              Status  User      Plist
mongodb-community started XXXXXXXXX /Users/XXXXXXXXX/Library/LaunchAgents/homebrew.mxcl.mongodb-community.plist

So I used mongodb-community instead of mongodb which worked for me

brew services stop mongodb-community
brew services start mongodb-community

Text to speech(TTS)-Android

Text to speech is built into Android 1.6+. Here is a simple example of how to do it.

TextToSpeech tts = new TextToSpeech(this, this);
tts.setLanguage(Locale.US);
tts.speak("Text to say aloud", TextToSpeech.QUEUE_ADD, null);

More info: http://android-developers.blogspot.com/2009/09/introduction-to-text-to-speech-in.html


Here are instructions on how to download sample code from the Android SDK Manager:

  1. Launch the Android SDK Manager.

    a. On Windows, double-click the SDK Manager.exe file at the root of the Android SDK directory.

    b. On Mac or Linux, open a terminal to the tools/ directory in the Android SDK, then execute android sdk.

  2. Expand the list of packages for the latest Android platform.

  3. Select and download Samples for SDK. When the download is complete, you can find the source code for all samples at this location:

/sdk/samples/android-version/

(i.e. \android-sdk-windows\samples\android-16\ApiDemos\src\com\example\android\apis\app\TextToSpeechActivity.java)

Remove the string on the beginning of an URL

Depends on what you need, you have a couple of choices, you can do:

// this will replace the first occurrence of "www." and return "testwww.com"
"www.testwww.com".replace("www.", "");

// this will slice the first four characters and return "testwww.com"
"www.testwww.com".slice(4);

// this will replace the www. only if it is at the beginning
"www.testwww.com".replace(/^(www\.)/,"");

HTML img tag: title attribute vs. alt attribute?

The ALT attribute is for the visually impaired user that would use a screen reader. If the ALT is missing from ANY image tag, the entire url for the image will be read. If the images are for part of the design of the site, they should still have the ALT but they can be left empty so the url doesn't have to be read for every part of the site.

Handling key-press events (F1-F12) using JavaScript and jQuery, cross-browser

Wow it is very simple. i'm blame to write this, why no one make it before?

$(function(){
    //Yes! use keydown 'cus some keys is fired only in this trigger,
    //such arrows keys
    $("body").keydown(function(e){
         //well you need keep on mind that your browser use some keys 
         //to call some function, so we'll prevent this
         e.preventDefault();

         //now we caught the key code, yabadabadoo!!
         var keyCode = e.keyCode || e.which;

         //your keyCode contains the key code, F1 to F12 
         //is among 112 and 123. Just it.
         console.log(keyCode);       
    });
});

Extract specific columns from delimited file using Awk

I don't know if it's possible to do ranges in awk. You could do a for loop, but you would have to add handling to filter out the columns you don't want. It's probably easier to do this:

awk -F, '{OFS=",";print $1,$2,$3,$4,$5,$6,$7,$8,$9,$10,$20,$21,$22,$23,$24,$25,$30,$33}' infile.csv > outfile.csv

something else to consider - and this faster and more concise:

cut -d "," -f1-10,20-25,30-33 infile.csv > outfile.csv

As to the second part of your question, I would probably write a script in perl that knows how to handle header rows, parsing the columns names from stdin or a file and then doing the filtering. It's probably a tool I would want to have for other things. I am not sure about doing in a one liner, although I am sure it can be done.

How can I temporarily disable a foreign key constraint in MySQL?

To turn off foreign key constraint globally, do the following:

SET GLOBAL FOREIGN_KEY_CHECKS=0;

and remember to set it back when you are done

SET GLOBAL FOREIGN_KEY_CHECKS=1;

WARNING: You should only do this when you are doing single user mode maintenance. As it might resulted in data inconsistency. For example, it will be very helpful when you are uploading large amount of data using a mysqldump output.

Catch error if iframe src fails to load . Error :-"Refused to display 'http://www.google.co.in/' in a frame.."

I have the same problem, chrome can't fire onerror when iframe src load error.

but in my case, I just need make a cross domain http request, so I use script src/onload/onerror instead of iframe. it's working well.

What is the difference between a "function" and a "procedure"?

In terms of ?#/Java, function is the block of code, which return particular value, but procedure is the block of code which return void (nothing). In C#/Java both functions and procedures more often called just methods.

    //This is a function
    public DateTime GetCurrentDate()
    {
        return DateTime.Now.Date;
    }

    //This is a procedure(always return void)
    public void LogMessage()
    {
        Console.WriteLine("Just an example message.");
    }

How to play only the audio of a Youtube video using HTML 5?

_x000D_
_x000D_
var vid = "bpt84ceWAY0",_x000D_
    audio_streams = {},_x000D_
    audio_tag = document.getElementById('youtube');_x000D_
_x000D_
fetch("https://"+vid+"-focus-opensocial.googleusercontent.com/gadgets/proxy?container=none&url=https%3A%2F%2Fwww.youtube.com%2Fget_video_info%3Fvideo_id%3D" + vid).then(response => {_x000D_
    if (response.ok) {_x000D_
        response.text().then(data => {_x000D_
_x000D_
            var data = parse_str(data),_x000D_
                streams = (data.url_encoded_fmt_stream_map + ',' + data.adaptive_fmts).split(',');_x000D_
_x000D_
            streams.forEach(function(s, n) {_x000D_
                var stream = parse_str(s),_x000D_
                    itag = stream.itag * 1,_x000D_
                    quality = false;_x000D_
                console.log(stream);_x000D_
                switch (itag) {_x000D_
                    case 139:_x000D_
                        quality = "48kbps";_x000D_
                        break;_x000D_
                    case 140:_x000D_
                        quality = "128kbps";_x000D_
                        break;_x000D_
                    case 141:_x000D_
                        quality = "256kbps";_x000D_
                        break;_x000D_
                }_x000D_
                if (quality) audio_streams[quality] = stream.url;_x000D_
            });_x000D_
_x000D_
            console.log(audio_streams);_x000D_
_x000D_
            audio_tag.src = audio_streams['128kbps'];_x000D_
            audio_tag.play();_x000D_
        })_x000D_
    }_x000D_
});_x000D_
_x000D_
function parse_str(str) {_x000D_
    return str.split('&').reduce(function(params, param) {_x000D_
        var paramSplit = param.split('=').map(function(value) {_x000D_
            return decodeURIComponent(value.replace('+', ' '));_x000D_
        });_x000D_
        params[paramSplit[0]] = paramSplit[1];_x000D_
        return params;_x000D_
    }, {});_x000D_
}
_x000D_
<audio id="youtube" autoplay controls loop></audio>
_x000D_
_x000D_
_x000D_

Specified cast is not valid?

htmlStr is string then You need to Date and Time variables to string

while (reader.Read())
                {
                    DateTime Date = reader.GetDateTime(0);
                    DateTime Time = reader.GetDateTime(1);
                    htmlStr += "<tr><td>" + Date.ToString() + "</td><td>"  + 
                    Time.ToString() + "</td></tr>";                  
                }

Play local (hard-drive) video file with HTML5 video tag?

It is possible to play a local video file.

<input type="file" accept="video/*"/>
<video controls autoplay></video>

When a file is selected via the input element:

  1. 'change' event is fired
  2. Get the first File object from the input.files FileList
  3. Make an object URL that points to the File object
  4. Set the object URL to the video.src property
  5. Lean back and watch :)

http://jsfiddle.net/dsbonev/cCCZ2/embedded/result,js,html,css/

_x000D_
_x000D_
(function localFileVideoPlayer() {_x000D_
  'use strict'_x000D_
  var URL = window.URL || window.webkitURL_x000D_
  var displayMessage = function(message, isError) {_x000D_
    var element = document.querySelector('#message')_x000D_
    element.innerHTML = message_x000D_
    element.className = isError ? 'error' : 'info'_x000D_
  }_x000D_
  var playSelectedFile = function(event) {_x000D_
    var file = this.files[0]_x000D_
    var type = file.type_x000D_
    var videoNode = document.querySelector('video')_x000D_
    var canPlay = videoNode.canPlayType(type)_x000D_
    if (canPlay === '') canPlay = 'no'_x000D_
    var message = 'Can play type "' + type + '": ' + canPlay_x000D_
    var isError = canPlay === 'no'_x000D_
    displayMessage(message, isError)_x000D_
_x000D_
    if (isError) {_x000D_
      return_x000D_
    }_x000D_
_x000D_
    var fileURL = URL.createObjectURL(file)_x000D_
    videoNode.src = fileURL_x000D_
  }_x000D_
  var inputNode = document.querySelector('input')_x000D_
  inputNode.addEventListener('change', playSelectedFile, false)_x000D_
})()
_x000D_
video,_x000D_
input {_x000D_
  display: block;_x000D_
}_x000D_
_x000D_
input {_x000D_
  width: 100%;_x000D_
}_x000D_
_x000D_
.info {_x000D_
  background-color: aqua;_x000D_
}_x000D_
_x000D_
.error {_x000D_
  background-color: red;_x000D_
  color: white;_x000D_
}
_x000D_
<h1>HTML5 local video file player example</h1>_x000D_
<div id="message"></div>_x000D_
<input type="file" accept="video/*" />_x000D_
<video controls autoplay></video>
_x000D_
_x000D_
_x000D_

Difference between Math.Floor() and Math.Truncate()

Some examples:

Round(1.5) = 2
Round(2.5) = 2
Round(1.5, MidpointRounding.AwayFromZero) = 2
Round(2.5, MidpointRounding.AwayFromZero) = 3
Round(1.55, 1) = 1.6
Round(1.65, 1) = 1.6
Round(1.55, 1, MidpointRounding.AwayFromZero) = 1.6
Round(1.65, 1, MidpointRounding.AwayFromZero) = 1.7

Truncate(2.10) = 2
Truncate(2.00) = 2
Truncate(1.90) = 1
Truncate(1.80) = 1

Python: How to ignore an exception and proceed?

Try this:

try:
    blah()
except:
    pass

How to extract this specific substring in SQL Server?

Assuming they always exist and are not part of your data, this will work:

declare @string varchar(8000) = '23;chair,red [$3]'
select substring(@string, charindex(';', @string) + 1, charindex(' [', @string) - charindex(';', @string) - 1)

Tree view of a directory/folder in Windows?

You can use Internet Explorer to browse folders and files together in tree. It is a file explorer in Favorites Window. You just need replace "favorites folder" to folder which you want see as a root folder

Using MySQL with Entity Framework

Be careful using connector .net, Connector 6.6.5 have a bug, it is not working for inserting tinyint values as identity, for example:

create table person(
    Id tinyint unsigned primary key auto_increment,
    Name varchar(30)
);

if you try to insert an object like this:

Person p;
p = new Person();
p.Name = 'Oware'
context.Person.Add(p);
context.SaveChanges();

You will get a Null Reference Exception:

Referencia a objeto no establecida como instancia de un objeto.:
   en MySql.Data.Entity.ListFragment.WriteSql(StringBuilder sql)
   en MySql.Data.Entity.SelectStatement.WriteSql(StringBuilder sql)
   en MySql.Data.Entity.InsertStatement.WriteSql(StringBuilder sql)
   en MySql.Data.Entity.SqlFragment.ToString()
   en MySql.Data.Entity.InsertGenerator.GenerateSQL(DbCommandTree tree)
   en MySql.Data.MySqlClient.MySqlProviderServices.CreateDbCommandDefinition(DbProviderManifest providerManifest, DbCommandTree commandTree)
   en System.Data.Common.DbProviderServices.CreateCommandDefinition(DbCommandTree commandTree)
   en System.Data.Common.DbProviderServices.CreateCommand(DbCommandTree commandTree)
   en System.Data.Mapping.Update.Internal.UpdateTranslator.CreateCommand(DbModificationCommandTree commandTree)
   en System.Data.Mapping.Update.Internal.DynamicUpdateCommand.CreateCommand(UpdateTranslator translator, Dictionary`2 identifierValues)
   en System.Data.Mapping.Update.Internal.DynamicUpdateCommand.Execute(UpdateTranslator translator, EntityConnection connection, Dictionary`2 identifierValues, List`1 generatedValues)
   en System.Data.Mapping.Update.Internal.UpdateTranslator.Update(IEntityStateManager stateManager, IEntityAdapter adapter)
   en System.Data.EntityClient.EntityAdapter.Update(IEntityStateManager entityCache)
   en System.Data.Objects.ObjectContext.SaveChanges(SaveOptions options)
   en System.Data.Entity.Internal.InternalContext.SaveChanges()
   en System.Data.Entity.Internal.LazyInternalContext.SaveChanges()
   en System.Data.Entity.DbContext.SaveChanges()

Until now I haven't found a solution, I had to change my tinyint identity to unsigned int identity, this solved the problem but this is not the right solution.

If you use an older version of Connector.net (I used 6.4.4) you won't have this problem.

If someone knows about the solution, please contact me.

Cheers!

Oware

Converting strings to floats in a DataFrame

You can try df.column_name = df.column_name.astype(float). As for the NaN values, you need to specify how they should be converted, but you can use the .fillna method to do it.

Example:

In [12]: df
Out[12]: 
     a    b
0  0.1  0.2
1  NaN  0.3
2  0.4  0.5

In [13]: df.a.values
Out[13]: array(['0.1', nan, '0.4'], dtype=object)

In [14]: df.a = df.a.astype(float).fillna(0.0)

In [15]: df
Out[15]: 
     a    b
0  0.1  0.2
1  0.0  0.3
2  0.4  0.5

In [16]: df.a.values
Out[16]: array([ 0.1,  0. ,  0.4])

How to read Data from Excel sheet in selenium webdriver

Your problem is that log4j has not been initialized. It does not affect the outcome of you application in any way, so it's safe to ignore or just initialize Log4J, see: How to initialize log4j properly?

Why doesn't git recognize that my file has been changed, therefore git add not working

When you edit a file in Visual Studio it gets listed in git changes instantly even if the file is not saved. So all you need to do is just to save the file manually (Ctrl+S for the currently displayed file or Ctrl+Shift+S for all project files) and git bash will pick them up.

VB.NET Connection string (Web.Config, App.Config)

Connection in APPConfig

<connectionStrings>
  <add name="ConnectionString" connectionString="Data Source=192.168.1.25;Initial Catalog=Login;Persist Security Info=True;User ID=sa;Password=example.com"   providerName="System.Data.SqlClient" />
</connectionStrings>

In Class.Cs

public string ConnectionString
{
    get
    {
        return System.Configuration.ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
    }
}

Replace input type=file by an image

Working Code:

just hide input part and do like this.

<div class="ImageUpload">
   <label for="FileInput">
      <img src="../../img/Upload_Panel.png" style="width: 18px; margin-top: -316px; margin-left: 900px;"/>
   </label>

  <input id="FileInput" type="file" onchange="readURL(this,'Picture')" style="cursor: pointer;  display: none"/>
</div>

Sending credentials with cross-domain posts?

In jQuery 3 and perhaps earlier versions, the following simpler config also works for individual requests:

$.ajax(
        'https://foo.bar.com,
        {
            dataType: 'json',
            xhrFields: {
                withCredentials: true
            },
            success: successFunc
        }
    );

The full error I was getting in Firefox Dev Tools -> Network tab (in the Security tab for an individual request) was:

An error occurred during a connection to foo.bar.com.SSL peer was unable to negotiate an acceptable set of security parameters.Error code: SSL_ERROR_HANDSHAKE_FAILURE_ALERT

Detecting value change of input[type=text] in jQuery

This combination of events worked for me:

$("#myTextBox").on("input paste", function() {
   alert($(this).val()); 
});

Qt: resizing a QLabel containing a QPixmap while keeping its aspect ratio

The Qt documentations has an Image Viewer example which demonstrates handling resizing images inside a QLabel. The basic idea is to use QScrollArea as a container for the QLabel and if needed use label.setScaledContents(bool) and scrollarea.setWidgetResizable(bool) to fill available space and/or ensure QLabel inside is resizable. Additionally, to resize QLabel while honoring aspect ratio use:

label.setPixmap(pixmap.scaled(width, height, Qt::KeepAspectRatio, Qt::FastTransformation));

The width and height can be set based on scrollarea.width() and scrollarea.height(). In this way there is no need to subclass QLabel.

Timer function to provide time in nano seconds using C++

In general, for timing how long it takes to call a function, you want to do it many more times than just once. If you call your function only once and it takes a very short time to run, you still have the overhead of actually calling the timer functions and you don't know how long that takes.

For example, if you estimate your function might take 800 ns to run, call it in a loop ten million times (which will then take about 8 seconds). Divide the total time by ten million to get the time per call.

How to study design patterns?

The best way is to begin coding with them. Design patterns are a great concept that are hard to apply from just reading about them. Take some sample implementations that you find online and build up around them.

A great resource is the Data & Object Factory page. They go over the patterns, and give you both conceptual and real world examples. Their reference material is great, too.

ORDER BY the IN value list

Just because it is so difficult to find and it has to be spread: in mySQL this can be done much simpler, but I don't know if it works in other SQL.

SELECT * FROM `comments`
WHERE `comments`.`id` IN ('12','5','3','17')
ORDER BY FIELD(`comments`.`id`,'12','5','3','17')

System.currentTimeMillis vs System.nanoTime

System.nanoTime() isn't supported in older JVMs. If that is a concern, stick with currentTimeMillis

Regarding accuracy, you are almost correct. On SOME Windows machines, currentTimeMillis() has a resolution of about 10ms (not 50ms). I'm not sure why, but some Windows machines are just as accurate as Linux machines.

I have used GAGETimer in the past with moderate success.

RVM is not a function, selecting rubies with 'rvm use ...' will not work

Type bash --login from your terminal. And then give rvm use 2.0.0

C# : changing listbox row color?

How about

      MyLB is a listbox

        Label ll = new Label();
        ll.Width = MyLB.Width;
        ll.Content = ss;
        if(///<some condition>///)
            ll.Background = Brushes.LightGreen;
        else
            ll.Background = Brushes.LightPink;
        MyLB.Items.Add(ll);

How can I render HTML from another file in a React component?

You can use dangerouslySetInnerHTML to do this:

import React from 'react';
function iframe() {
    return {
        __html: '<iframe src="./Folder/File.html" width="540" height="450"></iframe>'
    }
}


export default function Exercises() {
    return (
        <div>
            <div dangerouslySetInnerHTML={iframe()} />
        </div>)
}

HTML files must be in the public folder

Abstraction VS Information Hiding VS Encapsulation

Encapsulation- enforcing access to the internal data in a controlled manner or preventing members from being accessed directly.

Abstraction- Hiding the implementation details of certain methods is known as abstraction

Let's understand with the help of an example:-

class Rectangle
{
private int length;
private int breadth;// see the word private that means they cant be accesed from 
outside world.
 //now to make them accessed indirectly define getters and setters methods
void setLength(int length)
{  
// we are adding this condition to prevent users to make any irrelevent changes 
  that is why we have made length private so that they should be set according to 
   certain restrictions
if(length!=0)
{
 this.length=length
 }
void getLength()
{
 return length;
 }
 // same do for breadth
}

now for abstraction define a method that can only be accessed and user doesnt know what is the body of the method and how it is working Let's consider the above example, we can define a method area which calculates the area of the rectangle.

 public int area()
 {
  return length*breadth;
 }

Now, whenever a user uses the above method he will just get the area not the way how it is calculated. We can consider an example of println() method we just know that it is used for printing and we don't know how it prints the data. I have written a blog in detail you can see the below link for more info abstraction vs encapsulation

How do I pass JavaScript variables to PHP?

There are several ways of passing variables from JavaScript to PHP (not the current page, of course).

You could:

  1. Send the information in a form as stated here (will result in a page refresh)
  2. Pass it in Ajax (several posts are on here about that) (without a page refresh)
  3. Make an HTTP request via an XMLHttpRequest request (without a page refresh) like this:

 if (window.XMLHttpRequest){
     xmlhttp = new XMLHttpRequest();
 }

else{
     xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
 }

 var PageToSendTo = "nowitworks.php?";
 var MyVariable = "variableData";
 var VariablePlaceholder = "variableName=";
 var UrlToSend = PageToSendTo + VariablePlaceholder + MyVariable;

 xmlhttp.open("GET", UrlToSend, false);
 xmlhttp.send();

I'm sure this could be made to look fancier and loop through all the variables and whatnot - but I've kept it basic as to make it easier to understand for the novices.

How to get access to HTTP header information in Spring MVC REST controller?

My solution in Header parameters with example is user="test" is:

@RequestMapping(value = "/restURL")
  public String serveRest(@RequestBody String body, @RequestHeader HttpHeaders headers){

System.out.println(headers.get("user"));
}

How can I use pickle to save a dict?

import pickle

dictobj = {'Jack' : 123, 'John' : 456}

filename = "/foldername/filestore"

fileobj = open(filename, 'wb')

pickle.dump(dictobj, fileobj)

fileobj.close()

How to convert DateTime to/from specific string format (both ways, e.g. given Format is "yyyyMMdd")?

You can try these codes

claimantAuxillaryRecord.TPOCDate2  = Convert.ToDateTime(tpoc2[0]).ToString("yyyyMMdd"); 

Or

claimantAuxillaryRecord.TPOCDate2 = Convert.ToDateTime(tpoc2[0]).ToString("yyyyMMdd hh:mm:ss"); 

Using Java to find substring of a bigger string using Regular Expression

"FOO[DOG]".replaceAll("^.*?\\[|\\].*", "");

This will return a string taking only the string inside square brackets.

This remove all string outside from square brackets.

You can test this java sample code online: http://tpcg.io/wZoFu0

You can test this regex from here: https://regex101.com/r/oUAzsS/1

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

I experienced a similar error reply while using the openssl command line interface, while having the correct binary key (-K). The option "-nopad" resolved the issue:

Example generating the error:

echo -ne "\x32\xc8\xde\x5c\x68\x19\x7e\x53\xa5\x75\xe1\x76\x1d\x20\x16\xb2\x72\xd8\x40\x87\x25\xb3\x71\x21\x89\xf6\xca\x46\x9f\xd0\x0d\x08\x65\x49\x23\x30\x1f\xe0\x38\x48\x70\xdb\x3b\xa8\x56\xb5\x4a\xc6\x09\x9e\x6c\x31\xce\x60\xee\xa2\x58\x72\xf6\xb5\x74\xa8\x9d\x0c" | openssl aes-128-cbc -d -K 31323334353637383930313233343536 -iv 79169625096006022424242424242424 | od -t x1

Result:

bad decrypt
140181876450560:error:06065064:digital envelope 
routines:EVP_DecryptFinal_ex:bad decrypt:../crypto/evp/evp_enc.c:535:
0000000 2f 2f 07 02 54 0b 00 00 00 00 00 00 04 29 00 00
0000020 00 00 04 a9 ff 01 00 00 00 00 04 a9 ff 02 00 00
0000040 00 00 04 a9 ff 03 00 00 00 00 0d 79 0a 30 36 38

Example with correct result:

echo -ne "\x32\xc8\xde\x5c\x68\x19\x7e\x53\xa5\x75\xe1\x76\x1d\x20\x16\xb2\x72\xd8\x40\x87\x25\xb3\x71\x21\x89\xf6\xca\x46\x9f\xd0\x0d\x08\x65\x49\x23\x30\x1f\xe0\x38\x48\x70\xdb\x3b\xa8\x56\xb5\x4a\xc6\x09\x9e\x6c\x31\xce\x60\xee\xa2\x58\x72\xf6\xb5\x74\xa8\x9d\x0c" | openssl aes-128-cbc -d -K 31323334353637383930313233343536 -iv 79169625096006022424242424242424 -nopad | od -t x1

Result:

0000000 2f 2f 07 02 54 0b 00 00 00 00 00 00 04 29 00 00
0000020 00 00 04 a9 ff 01 00 00 00 00 04 a9 ff 02 00 00
0000040 00 00 04 a9 ff 03 00 00 00 00 0d 79 0a 30 36 38
0000060 30 30 30 34 31 33 31 2f 2f 2f 2f 2f 2f 2f 2f 2f
0000100

How to get the caller's method name in the called method?

Shorter version:

import inspect

def f1(): f2()

def f2():
    print 'caller name:', inspect.stack()[1][3]

f1()

(with thanks to @Alex, and Stefaan Lippen)

Laravel view not found exception

In my case I was calling View::make('User/index'), where in fact my view was in user directory and it was called index.blade.php. Ergo after I changed it to View@make('user.index') all started working.

Java, Shifting Elements in an Array

public class Test1 {

    public static void main(String[] args) {

        int[] x = { 1, 2, 3, 4, 5, 6 };
        Test1 test = new Test1();
        x = test.shiftArray(x, 2);
        for (int i = 0; i < x.length; i++) {
            System.out.print(x[i] + " ");
        }
    }

    public int[] pushFirstElementToLast(int[] x, int position) {
        int temp = x[0];
        for (int i = 0; i < x.length - 1; i++) {
            x[i] = x[i + 1];
        }
        x[x.length - 1] = temp;
        return x;
    }

    public int[] shiftArray(int[] x, int position) {
        for (int i = position - 1; i >= 0; i--) {
            x = pushFirstElementToLast(x, position);
        }
        return x;
    }
}

How to write a PHP ternary operator

I'd rather than ternary if-statements go with a switch-case. For example:

switch($result->vocation){
case 1:
    echo "Sorcerer";
    break;
case 2:
    echo "Druid";
    break;
case 3:
    echo "Paladin";
    break;
case 4:
    echo "Knight";
    break;
case 5:
    echo "Master Sorcerer";
    break;
case 6:
    echo "Elder Druid";
    break;
case 7:
    echo "Royal Paladin";
    break;
default:
    echo "Elite Knight";
    break;
}

Usage of the backtick character (`) in JavaScript

ECMAScript 6 comes up with a new type of string literal, using the backtick as the delimiter. These literals do allow basic string interpolation expressions to be embedded, which are then automatically parsed and evaluated.

let person = {name: 'RajiniKanth', age: 68, greeting: 'Thalaivaaaa!' };

let usualHtmlStr = "<p>My name is " + person.name + ",</p>\n" +
  "<p>I am " + person.age + " old</p>\n" +
  "<strong>\"" + person.greeting + "\" is what I usually say</strong>";

let newHtmlStr =
 `<p>My name is ${person.name},</p>
  <p>I am ${person.age} old</p>
  <p>"${person.greeting}" is what I usually say</strong>`;

console.log(usualHtmlStr);
console.log(newHtmlStr);

As you can see, we used the ` around a series of characters, which are interpreted as a string literal, but any expressions of the form ${..} are parsed and evaluated inline immediately.

One really nice benefit of interpolated string literals is they are allowed to split across multiple lines:

var Actor = {"name": "RajiniKanth"};

var text =
`Now is the time for all good men like ${Actor.name}
to come to the aid of their
country!`;
console.log(text);
// Now is the time for all good men like RajiniKanth
// to come to the aid of their
// country!

Interpolated Expressions

Any valid expression is allowed to appear inside ${..} in an interpolated string literal, including function calls, inline function expression calls, and even other interpolated string literals!

function upper(s) {
  return s.toUpperCase();
}
var who = "reader"
var text =
`A very ${upper("warm")} welcome
to all of you ${upper(`${who}s`)}!`;
console.log(text);
// A very WARM welcome
// to all of you READERS!

Here, the inner `${who}s` interpolated string literal was a little bit nicer convenience for us when combining the who variable with the "s" string, as opposed to who + "s". Also to keep an note is an interpolated string literal is just lexically scoped where it appears, not dynamically scoped in any way:

function foo(str) {
  var name = "foo";
  console.log(str);
}
function bar() {
  var name = "bar";
  foo(`Hello from ${name}!`);
}
var name = "global";
bar(); // "Hello from bar!"

Using the template literal for the HTML is definitely more readable by reducing the annoyance.

The plain old way:

'<div class="' + className + '">' +
  '<p>' + content + '</p>' +
  '<a href="' + link + '">Let\'s go</a>'
'</div>';

With ECMAScript 6:

`<div class="${className}">
  <p>${content}</p>
  <a href="${link}">Let's go</a>
</div>`
  • Your string can span multiple lines.
  • You don't have to escape quotation characters.
  • You can avoid groupings like: '">'
  • You don't have to use the plus operator.

Tagged Template Literals

We can also tag a template string, when a template string is tagged, the literals and substitutions are passed to function which returns the resulting value.

function myTaggedLiteral(strings) {
  console.log(strings);
}

myTaggedLiteral`test`; //["test"]

function myTaggedLiteral(strings, value, value2) {
  console.log(strings, value, value2);
}
let someText = 'Neat';
myTaggedLiteral`test ${someText} ${2 + 3}`;
//["test", ""]
// "Neat"
// 5

We can use the spread operator here to pass multiple values. The first argument—we called it strings—is an array of all the plain strings (the stuff between any interpolated expressions).

We then gather up all subsequent arguments into an array called values using the ... gather/rest operator, though you could of course have left them as individual named parameters following the strings parameter like we did above (value1, value2, etc.).

function myTaggedLiteral(strings, ...values) {
  console.log(strings);
  console.log(values);
}

let someText = 'Neat';
myTaggedLiteral`test ${someText} ${2 + 3}`;
//["test", ""]
// "Neat"
// 5

The argument(s) gathered into our values array are the results of the already evaluated interpolation expressions found in the string literal. A tagged string literal is like a processing step after the interpolations are evaluated, but before the final string value is compiled, allowing you more control over generating the string from the literal. Let's look at an example of creating reusable templates.

const Actor = {
  name: "RajiniKanth",
  store: "Landmark"
}

const ActorTemplate = templater`<article>
  <h3>${'name'} is a Actor</h3>
  <p>You can find his movies at ${'store'}.</p>

</article>`;

function templater(strings, ...keys) {
  return function(data) {
    let temp = strings.slice();
    keys.forEach((key, i) => {
      temp[i] = temp[i] + data[key];
    });
    return temp.join('');
  }
};

const myTemplate = ActorTemplate(Actor);
console.log(myTemplate);

Raw Strings

Our tag functions receive a first argument we called strings, which is an array. But there’s an additional bit of data included: the raw unprocessed versions of all the strings. You can access those raw string values using the .raw property, like this:

function showraw(strings, ...values) {
  console.log(strings);
  console.log(strings.raw);
}
showraw`Hello\nWorld`;

As you can see, the raw version of the string preserves the escaped \n sequence, while the processed version of the string treats it like an unescaped real new-line. ECMAScript 6 comes with a built-in function that can be used as a string literal tag: String.raw(..). It simply passes through the raw versions of the strings:

console.log(`Hello\nWorld`);
/* "Hello
World" */

console.log(String.raw`Hello\nWorld`);
// "Hello\nWorld"

Oracle comparing timestamp with date

You can truncate the date

SELECT *
FROM Table1
WHERE trunc(field1) = to_Date('2012-01-01','YYY-MM-DD')

Look at the SQL Fiddle for more examples.

How can I catch all the exceptions that will be thrown through reading and writing a file?

Catch the base exception 'Exception'

   try { 
         //some code
   } catch (Exception e) {
        //catches exception and all subclasses 
   }

Changing default shell in Linux

You can change the passwd file directly for the particular user or use the below command

chsh -s /usr/local/bin/bash username

Then log out and log in

How to get the browser to navigate to URL in JavaScript

This works in all browsers:

window.location.href = '...';

If you wanted to change the page without it reflecting in the browser back history, you can do:

window.location.replace('...');

Selecting multiple columns in a Pandas dataframe

I found this method to be very useful:

# iloc[row slicing, column slicing]
surveys_df.iloc [0:3, 1:4]

More details can be found here.

How to compare two lists in python?

a = ['a1','b2','c3']
b = ['a1','b2','c3']
c = ['b2','a1','c3']

# if you care about order
a == b # True
a == c # False

# if you don't care about order AND duplicates
set(a) == set(b) # True
set(a) == set(c) # True

By casting a, b and c as a set, you remove duplicates and order doesn't count. Comparing sets is also much faster and more efficient than comparing lists.

Border Radius of Table is not working

This is my solution using the wrapper, just removing border-collapse might not be helpful always, because you might want to have borders.

_x000D_
_x000D_
.wrapper {_x000D_
  overflow: auto;_x000D_
  border-radius: 6px;_x000D_
  border: 1px solid red;_x000D_
}_x000D_
_x000D_
table {_x000D_
  border-spacing: 0;_x000D_
  border-collapse: collapse;_x000D_
  border-style: hidden;_x000D_
_x000D_
  width:100%;_x000D_
  max-width: 100%;_x000D_
}_x000D_
_x000D_
th, td {_x000D_
  padding: 10px;_x000D_
  border: 1px solid #CCCCCC;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <table>_x000D_
    <thead>_x000D_
      <tr>_x000D_
        <th>Column 1</th>_x000D_
        <th>Column 2</th>_x000D_
        <th>Column 3</th>_x000D_
      </tr>_x000D_
    </thead>_x000D_
_x000D_
    <tbody>_x000D_
      <tr>_x000D_
        <td>Foo Bar boo</td>_x000D_
        <td>Lipsum</td>_x000D_
        <td>Beehuum Doh</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>Dolor sit</td>_x000D_
        <td>ahmad</td>_x000D_
        <td>Polymorphism</td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td>Kerbalium</td>_x000D_
        <td>Caton, gookame kyak</td>_x000D_
        <td>Corona Premium Beer</td>_x000D_
      </tr>_x000D_
    </tbody>_x000D_
  </table>  _x000D_
</div>
_x000D_
_x000D_
_x000D_

This article helped: https://css-tricks.com/table-borders-inside/

Proper way to make HTML nested list?

If you validate , option 1 comes up as an error in html 5, so option 2 is correct.

Split function in oracle to comma separated values with automatic sequence

Oracle Setup:

CREATE OR REPLACE FUNCTION split_String(
  i_str    IN  VARCHAR2,
  i_delim  IN  VARCHAR2 DEFAULT ','
) RETURN SYS.ODCIVARCHAR2LIST DETERMINISTIC
AS
  p_result       SYS.ODCIVARCHAR2LIST := SYS.ODCIVARCHAR2LIST();
  p_start        NUMBER(5) := 1;
  p_end          NUMBER(5);
  c_len CONSTANT NUMBER(5) := LENGTH( i_str );
  c_ld  CONSTANT NUMBER(5) := LENGTH( i_delim );
BEGIN
  IF c_len > 0 THEN
    p_end := INSTR( i_str, i_delim, p_start );
    WHILE p_end > 0 LOOP
      p_result.EXTEND;
      p_result( p_result.COUNT ) := SUBSTR( i_str, p_start, p_end - p_start );
      p_start := p_end + c_ld;
      p_end := INSTR( i_str, i_delim, p_start );
    END LOOP;
    IF p_start <= c_len + 1 THEN
      p_result.EXTEND;
      p_result( p_result.COUNT ) := SUBSTR( i_str, p_start, c_len - p_start + 1 );
    END IF;
  END IF;
  RETURN p_result;
END;
/

Query

SELECT ROWNUM AS ID,
       COLUMN_VALUE AS Data
FROM   TABLE( split_String( 'A,B,C,D' ) );

Output:

ID DATA
-- ----
 1 A
 2 B
 3 C
 4 D

Manifest Merger failed with multiple errors in Android Studio

Happened with me twice when I refractor (Rename with SHIFT + F6) the name of a field in our files and it asks you to change it everywhere and we without paying attention change the name everywhere. For example, if you have a variable name "id" in your Java class and you rename it with SHIFT + F6. If you don't pay attention to the next dialog which will ask you wherever else it is going to change the id and you tick check all it will change all the id in your layout files from the new value.

PHP function to get the subdomain of a URL

if you are using drupal 7

this will help you:

global $base_path;
global $base_root;  
$fulldomain = parse_url($base_root);    
$splitdomain = explode(".", $fulldomain['host']);
$subdomain = $splitdomain[0];

How to change the color of text in javafx TextField?

Setting the -fx-text-fill works for me.

See below:

if (passed) {
    resultInfo.setText("Passed!");
    resultInfo.setStyle("-fx-text-fill: green; -fx-font-size: 16px;");
} else {
    resultInfo.setText("Failed!");
    resultInfo.setStyle("-fx-text-fill: red; -fx-font-size: 16px;");
}

Python, Pandas : write content of DataFrame into text File

You can just use np.savetxt and access the np attribute .values:

np.savetxt(r'c:\data\np.txt', df.values, fmt='%d')

yields:

18 55 1 70
18 55 2 67
18 57 2 75
18 58 1 35
19 54 2 70

or to_csv:

df.to_csv(r'c:\data\pandas.txt', header=None, index=None, sep=' ', mode='a')

Note for np.savetxt you'd have to pass a filehandle that has been created with append mode.

Change keystore password from no password to a non blank password

On my system the password is 'changeit'. On blank if I hit enter then it complains about short password. Hope this helps

enter image description here

Multiple INNER JOIN SQL ACCESS

Access requires parentheses in the FROM clause for queries which include more than one join. Try it this way ...

FROM
    ((tbl_employee
    INNER JOIN tbl_netpay
    ON tbl_employee.emp_id = tbl_netpay.emp_id)
    INNER JOIN tbl_gross
    ON tbl_employee.emp_id = tbl_gross.emp_ID)
    INNER JOIN tbl_tax
    ON tbl_employee.emp_id = tbl_tax.emp_ID;

If possible, use the Access query designer to set up your joins. The designer will add parentheses as required to keep the db engine happy.

DateTimePicker: pick both date and time

You can get it to display time. From that you will probably have to have two controls (one date, one time) the accomplish what you want.

XSLT equivalent for JSON

There is now! I recently created a library, json-transforms, exactly for this purpose:

https://github.com/ColinEberhardt/json-transforms

It uses a combination of JSPath, a DSL modelled on XPath, and a recursive pattern matching approach, inspired directly by XSLT.

Here's a quick example. Given the following JSON object:

const json = {
  "automobiles": [
    { "maker": "Nissan", "model": "Teana", "year": 2011 },
    { "maker": "Honda", "model": "Jazz", "year": 2010 },
    { "maker": "Honda", "model": "Civic", "year": 2007 },
    { "maker": "Toyota", "model": "Yaris", "year": 2008 },
    { "maker": "Honda", "model": "Accord", "year": 2011 }
  ]
};

Here's a transformation:

const jsont = require('json-transforms');
const rules = [
  jsont.pathRule(
    '.automobiles{.maker === "Honda"}', d => ({
      Honda: d.runner()
    })
  ),
  jsont.pathRule(
    '.{.maker}', d => ({
      model: d.match.model,
      year: d.match.year
    })
  ),
  jsont.identity
];

const transformed  = jsont.transform(json, rules);

Which output the following:

{
  "Honda": [
    { "model": "Jazz", "year": 2010 },
    { "model": "Civic", "year": 2007 },
    { "model": "Accord", "year": 2011 }
  ]
}

This transform is composed of three rules. The first matches any automobile which is made by Honda, emitting an object with a Honda property, then recursively matching. The second rule matches any object with a maker property, outputting the model and year properties. The final is the identity transform that recursively matches.

How to execute a shell script in PHP?

You might have disabled the exec privileges, most of the LAMP packages have those disabled. Check your php.ini for this line:

disable_functions = exec

And remove the exec, shell_exec entries if there are there.

Good Luck!

How to configure Visual Studio to use Beyond Compare

If you are using the TFS, you can find the more information in diff/merge configuration in Team Foundation - common Command and Argument values

It shows how to configure the following tools:

  • WinDiff
  • DiffDoc (for Word files)
  • WinMerge
  • Beyond Compare
  • KDiff3
  • Araxis
  • Compare It!
  • SourceGear DiffMerge
  • Beyond Compare 3
  • TortoiseMerge
  • Visual SlickEdit

how to put focus on TextBox when the form load?

it's worked for me set tabindex to 0 this.yourtextbox.TabIndex = 0;

403 Access Denied on Tomcat 8 Manager App without prompting for user/password

  1. Go and Check if a user is created or not if no please create a user by opening a file in /apache-tomcat-9.0.20/tomcat-users.xml add a line into it

    <user username="tomcat" password="tomcat" roles="admin-gui,manager-gui,manager-script" />

  2. Goto /apache-tomcat-9.0.20/webapps/manager/META-INF/ open context.xml comment everything in context tag example:

<Context antiResourceLocking="false" privileged="true" >
     <!--Valve className="org.apache.catalina.valves.RemoteAddrValve"
            allow="127\.\d+\.\d+\.\d+|::1|0:0:0:0:0:0:0:1" /-->
   </Context>

How do I get an object's unqualified (short) class name?

Found on the documentation page of get_class, where it was posted by me at nwhiting dot com.

function get_class_name($object = null)
{
    if (!is_object($object) && !is_string($object)) {
        return false;
    }

    $class = explode('\\', (is_string($object) ? $object : get_class($object)));
    return $class[count($class) - 1];
}

But the idea of namespaces is to structure your code. That also means that you can have classes with the same name in multiple namespaces. So theoretically, the object you pass could have the name (stripped) class name, while still being a totally different object than you expect.

Besides that, you might want to check for a specific base class, in which case get_class doesn't do the trick at all. You might want to check out the operator instanceof.

Reordering arrays

Here is an immutable version for those who are interested:

function immutableMove(arr, from, to) {
  return arr.reduce((prev, current, idx, self) => {
    if (from === to) {
      prev.push(current);
    }
    if (idx === from) {
      return prev;
    }
    if (from < to) {
      prev.push(current);
    }
    if (idx === to) {
      prev.push(self[from]);
    }
    if (from > to) {
      prev.push(current);
    }
    return prev;
  }, []);
}

How to use workbook.saveas with automatic Overwrite

I recommend that before executing SaveAs, delete the file it exists.

If Dir("f:ull\path\with\filename.xls") <> "" Then
    Kill "f:ull\path\with\filename.xls"
End If

It's easier than setting DisplayAlerts off and on, plus if DisplayAlerts remains off due to code crash, it can cause problems if you work with Excel in the same session.

How to create a sticky left sidebar menu using bootstrap 3?

You can also try to use a Polyfill like Fixed-Sticky. Especially when you are using Bootstrap4 the affix component is no longer included:

Dropped the Affix jQuery plugin. We recommend using a position: sticky polyfill instead.

Online SQL Query Syntax Checker

A lot of people, including me, use sqlfiddle.com to test SQL.

Is there a function to copy an array in C/C++?

I like the answer of Ed S., but this only works for fixed size arrays and not when the arrays are defined as pointers.

So, the C++ solution where the arrays are defined as pointers:

#include<algorithm>
...
const int bufferSize = 10;
char* origArray, newArray;
std::copy(origArray, origArray + bufferSize, newArray);

Note: No need to deduct buffersize with 1:

  1. Copies all elements in the range [first, last) starting from first and proceeding to last - 1

See: https://en.cppreference.com/w/cpp/algorithm/copy

How to use a Java8 lambda to sort a stream in reverse order?

Instead of all these complications, this simple step should do the trick for reverse sorting using Lambda .sorted(Comparator.reverseOrder())

Arrays.asList(files).stream()
.filter(file -> isNameLikeBaseLine(file, baseLineFile.getName()))
.sorted(Comparator.reverseOrder()).skip(numOfNewestToLeave)
.forEach(item -> item.delete());

How to round 0.745 to 0.75 using BigDecimal.ROUND_HALF_UP?

double doubleVal = 1.745;
double doubleVal1 = 0.745;
System.out.println(new BigDecimal(doubleVal));
System.out.println(new BigDecimal(doubleVal1));

outputs:

1.74500000000000010658141036401502788066864013671875
0.74499999999999999555910790149937383830547332763671875

Which shows the real value of the two doubles and explains the result you get. As pointed out by others, don't use the double constructor (apart from the specific case where you want to see the actual value of a double).

More about double precision:

Best way to "negate" an instanceof

If you find it more understandable, you can do something like this with Java 8 :

public static final Predicate<Object> isInstanceOfTheClass = 
    objectToTest -> objectToTest instanceof TheClass;

public static final Predicate<Object> isNotInstanceOfTheClass = 
    isInstanceOfTheClass.negate(); // or objectToTest -> !(objectToTest instanceof TheClass)

if (isNotInstanceOfTheClass.test(myObject)) {
    // do something
}

jQuery Scroll to bottom of page/iframe

If you want a nice slow animation scroll, for any anchor with href="#bottom" this will scroll you to the bottom:

$("a[href='#bottom']").click(function() {
  $("html, body").animate({ scrollTop: $(document).height() }, "slow");
  return false;
});

Feel free to change the selector.

how to get the 30 days before date from Todays Date

SELECT (column name) FROM (table name) WHERE (column name) < DATEADD(Day,-30,GETDATE());

Example.

SELECT `name`, `phone`, `product` FROM `tbmMember` WHERE `dateofServicw` < (Day,-30,GETDATE()); 

How to get min, seconds and milliseconds from datetime.now() in python?

Another similar solution:

>>> a=datetime.now()
>>> "%s:%s.%s" % (a.hour, a.minute, a.microsecond)
'14:28.971209'

Yes, I know I didn't get the string formatting perfect.

Correct way to push into state array

you are breaking React principles, you should clone the old state then merge it with the new data, you shouldn't manipulate your state directly, your code should go like this

fetch('http://localhost:8080').then(response => response.json()).then(json ={this.setState({mystate[...this.state.mystate, json]}) })

How to split and modify a string in NodeJS?

If you're using lodash and in the mood for a too-cute-for-its-own-good one-liner:

_.map(_.words('123, 124, 234,252'), _.add.bind(1, 1));

It's surprisingly robust thanks to lodash's powerful parsing capabilities.

If you want one that will also clean non-digit characters out of the string (and is easier to follow...and not quite so cutesy):

_.chain('123, 124, 234,252, n301')
   .replace(/[^\d,]/g, '')
   .words()
   .map(_.partial(_.add, 1))
   .value();

2017 edit:

I no longer recommend my previous solution. Besides being overkill and already easy to do without a third-party library, it makes use of _.chain, which has a variety of issues. Here's the solution I would now recommend:

const str = '123, 124, 234,252';
const arr = str.split(',').map(n => parseInt(n, 10) + 1);

My old answer is still correct, so I'll leave it for the record, but there's no need to use it nowadays.

In a javascript array, how do I get the last 5 elements, excluding the first element?

_x000D_
_x000D_
var y = [1,2,3,4,5,6,7,8,9,10];_x000D_
_x000D_
console.log(y.slice((y.length - 5), y.length))
_x000D_
_x000D_
_x000D_

you can do this!

TypeScript add Object to array with push

class PushObjects {
    testMethod(): Array<number> { 
        //declaration and initialisation of array onject
        var objs: number[] = [1,2,3,4,5,7];
        //push the elements into the array object
        objs.push(100);
        //pop the elements from the array
        objs.pop();
        return objs;
    }   
}

let pushObj = new PushObjects();
//create the button element from the dom object 
let btn = document.createElement('button');
//set the text value of the button
btn.textContent = "Click here";
//button click event
btn.onclick = function () { 

    alert(pushObj.testMethod());

} 

document.body.appendChild(btn);

How to add \newpage in Rmarkdown in a smart way?

In the initialization chunk I define a function

pagebreak <- function() {
  if(knitr::is_latex_output())
    return("\\newpage")
  else
    return('<div style="page-break-before: always;" />')
}

In the markdown part where I want to insert a page break, I type

`r pagebreak()`

Errors: "INSERT EXEC statement cannot be nested." and "Cannot use the ROLLBACK statement within an INSERT-EXEC statement." How to solve this?

what about just store the output to the static table ? Like

-- SubProcedure: subProcedureName
---------------------------------
-- Save the value
DELETE lastValue_subProcedureName
INSERT INTO lastValue_subProcedureName (Value)
SELECT @Value
-- Return the value
SELECT @Value

-- Procedure
--------------------------------------------
-- get last value of subProcedureName
SELECT Value FROM lastValue_subProcedureName

its not ideal, but its so simple and you don't need to rewrite everything.

UPDATE: the previous solution does not work well with parallel queries (async and multiuser accessing) therefore now Iam using temp tables

-- A local temporary table created in a stored procedure is dropped automatically when the stored procedure is finished. 
-- The table can be referenced by any nested stored procedures executed by the stored procedure that created the table. 
-- The table cannot be referenced by the process that called the stored procedure that created the table.
IF OBJECT_ID('tempdb..#lastValue_spGetData') IS NULL
CREATE TABLE #lastValue_spGetData (Value INT)

-- trigger stored procedure with special silent parameter
EXEC dbo.spGetData 1 --silent mode parameter

nested spGetData stored procedure content

-- Save the output if temporary table exists.
IF OBJECT_ID('tempdb..#lastValue_spGetData') IS NOT NULL
BEGIN
    DELETE #lastValue_spGetData
    INSERT INTO #lastValue_spGetData(Value)
    SELECT Col1 FROM dbo.Table1
END

 -- stored procedure return
 IF @silentMode = 0
 SELECT Col1 FROM dbo.Table1

Comparing chars in Java

If your input is a character and the characters you are checking against are mostly consecutive you could try this:

if ((symbol >= 'A' && symbol <= 'Z') || symbol == '?') {
    // ...
}

However if your input is a string a more compact approach (but slower) is to use a regular expression with a character class:

if (symbol.matches("[A-Z?]")) {
    // ...
}

If you have a character you'll first need to convert it to a string before you can use a regular expression:

if (Character.toString(symbol).matches("[A-Z?]")) {
    // ...
}

Order a List (C#) by many fields?

Use ThenBy:

var orderedCustomers = Customer.OrderBy(c => c.LastName).ThenBy(c => c.FirstName)

See MSDN: http://msdn.microsoft.com/en-us/library/bb549422.aspx

disable editing default value of text input

How about disabled=disabled:

<input id="price_from" value="price from " disabled="disabled">????????????

Problem is if you don't want user to edit them, why display them in input? You can hide them even if you want to submit a form. And to display information, just use other tag instead.

How to send email by using javascript or jquery

You can send Email by Jquery just follow these steps 

include this link : <script src="https://smtpjs.com/v3/smtp.js"></script>
after that use this code :

$( document ).ready(function() {
 Email.send({
Host : "smtp.yourisp.com",
Username : "username",
Password : "password",
To : '[email protected]',
From : "[email protected]",
Subject : "This is the subject",
Body : "And this is the body"}).then( message => alert(message));});

Angular no provider for NameService

Angular2 requires you to declare all the injectables in bootstrap function call. Without this your service is not an injectable object.

bootstrap(MyAppComponent,[NameService]);

Increasing the timeout value in a WCF service

In addition to the binding timeouts (which are in Timespans), You may also need this as well. This is in seconds.

<system.web>
    <httpRuntime executionTimeout="600"/><!-- = 10 minutes -->

How do I get the current location of an iframe?

You can use Ra-Ajax and have an iframe wrapped inside e.g. a Window control. Though in general terms I don't encourage people to use iframes (for anything)

Another alternative is to load the HTML on the server and send it directly into the Window as the content of a Label or something. Check out how this Ajax RSS parser is loading the RSS items in the source which can be downloaded here (Open Source - LGPL)

(Disclaimer; I work with Ra-Ajax...)

Excel function to get first word from sentence in other cell

A1                   A2 
Toronto<b> is nice   =LEFT(A1,(FIND("<",A1,1)-1))

Not sure if the syntax is correct but the forumla in A2 will work for you,

How do I install PyCrypto on Windows?

I had Pycharm for python.

  1. Go to pycharm -> file -> setting -> project interpreter

  2. Click on +

  3. Search for "pycrypto" and install the package

Note: If you don't have "Microsoft Visual C++ Compiler for Python 2.7" installed then it will prompt for installation, once installation finished try the above steps it should work fine.

Detect application heap size in Android

This returns max heap size in bytes:

Runtime.getRuntime().maxMemory()

I was using ActivityManager.getMemoryClass() but on CyanogenMod 7 (I didn't test it elsewhere) it returns wrong value if the user sets heap size manually.

Why do we use $rootScope.$broadcast in AngularJS?

Passing data !!!

I wonder why no one mention that $broadcast accept a parameter where you can pass an Object that will be received by $on using a callback function

Example:

// the object to transfert
var myObject = {
    status : 10
}

$rootScope.$broadcast('status_updated', myObject);
$scope.$on('status_updated', function(event, obj){
    console.log(obj.status); // 10
})

SQL Server database restore error: specified cast is not valid. (SqlManagerUI)

The GUI can be fickle at times. The error you got when using T-SQL is because you're trying to overwrite an existing database, but did not specify to overwrite/replace the existing database. The following might work:

Use Master
Go
RESTORE DATABASE Publications
  FROM DISK = 'C:\Publications_backup_2012_10_15_010004_5648316.bak'
  WITH 
    MOVE 'Publications' TO 'C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS2008R2\MSSQL\DATA\Publications.mdf',--adjust path
    MOVE 'Publications_log' TO 'C:\Program Files\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS2008R2\MSSQL\DATA\Publications.ldf'
, REPLACE -- Add REPLACE to specify the existing database which should be overwritten.

How to wait for 2 seconds?

Try this example:

exec DBMS_LOCK.sleep(5);

This is the whole script:

SELECT TO_CHAR (SYSDATE, 'MM-DD-YYYY HH24:MI:SS') "Start Date / Time" FROM DUAL;

exec DBMS_LOCK.sleep(5);

SELECT TO_CHAR (SYSDATE, 'MM-DD-YYYY HH24:MI:SS') "End Date / Time" FROM DUAL;

What is the format specifier for unsigned short int?

Here is a good table for printf specifiers. So it should be %hu for unsigned short int.

And link to Wikipedia "C data types" too.

How can I change column types in Spark SQL's DataFrame?

df.select($"long_col".cast(IntegerType).as("int_col"))

SQL Server Group By Month

Restrict the dimension of the NVARCHAR to 7, supplied to CONVERT to show only "YYYY-MM"

SELECT CONVERT(NVARCHAR(7),PaymentDate,120) [Month], SUM(Amount) [TotalAmount]
FROM Payments
GROUP BY CONVERT(NVARCHAR(7),PaymentDate,120)
ORDER BY [Month]

checking if number entered is a digit in jquery

With jQuery's validation plugin you could do something like this, assuming that the form is called form and the value to validate is called nrInput

$("form").validate({
            errorElement: "div",
            errorClass: "error-highlight",
            onblur: true,
            onsubmit: true,
            focusInvalid: true,
            rules:{
                'nrInput': {
                    number: true,
                    required: true
                }
            });

This also handles decimal values.

Why is Java Vector (and Stack) class considered obsolete or deprecated?

You can use the synchronizedCollection/List method in java.util.Collection to get a thread-safe collection from a non-thread-safe one.

Could not load file or assembly 'System.Web.WebPages.Razor, Version=3.0.0.0

Another option is to update the Microsoft.AspnNet.Mvc NuGet package. Be careful, because NuGet update does not update the Web.Config. You should update all previous version numbers to updated number. For example if you update from asp.net MVC 4.0.0.0 to 5.0.0.0, then this should be replaced in the Web.Config:

    <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
      <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
      <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
    </sectionGroup>
  </configSections>

 <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />

<pages
    validateRequest="false"
    pageParserFilterType="System.Web.Mvc.ViewTypeParserFilter, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
    pageBaseType="System.Web.Mvc.ViewPage, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
    userControlBaseType="System.Web.Mvc.ViewUserControl, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
  <controls>
    <add assembly="System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" namespace="System.Web.Mvc" tagPrefix="mvc" />
  </controls>
</pages>

Using $state methods with $stateChangeStart toState and fromState in Angular ui-router

Suggestion 1

When you add an object to $stateProvider.state that object is then passed with the state. So you can add additional properties which you can read later on when needed.

Example route configuration

$stateProvider
.state('public', {
    abstract: true,
    module: 'public'
})
.state('public.login', {
    url: '/login',
    module: 'public'
})
.state('tool', {
    abstract: true,
    module: 'private'
})
.state('tool.suggestions', {
    url: '/suggestions',
    module: 'private'
});

The $stateChangeStart event gives you acces to the toState and fromState objects. These state objects will contain the configuration properties.

Example check for the custom module property

$rootScope.$on('$stateChangeStart', function(e, toState, toParams, fromState, fromParams) {
    if (toState.module === 'private' && !$cookies.Session) {
        // If logged out and transitioning to a logged in page:
        e.preventDefault();
        $state.go('public.login');
    } else if (toState.module === 'public' && $cookies.Session) {
        // If logged in and transitioning to a logged out page:
        e.preventDefault();
        $state.go('tool.suggestions');
    };
});

I didn't change the logic of the cookies because I think that is out of scope for your question.

Suggestion 2

You can create a Helper to get you this to work more modular.

Value publicStates

myApp.value('publicStates', function(){
    return {
      module: 'public',
      routes: [{
        name: 'login', 
        config: { 
          url: '/login'
        }
      }]
    };
});

Value privateStates

myApp.value('privateStates', function(){
    return {
      module: 'private',
      routes: [{
        name: 'suggestions', 
        config: { 
          url: '/suggestions'
        }
      }]
    };
});

The Helper

myApp.provider('stateshelperConfig', function () {
  this.config = {
    // These are the properties we need to set
    // $stateProvider: undefined
    process: function (stateConfigs){
      var module = stateConfigs.module;
      $stateProvider = this.$stateProvider;
      $stateProvider.state(module, {
        abstract: true,
        module: module
      });
      angular.forEach(stateConfigs, function (route){
        route.config.module = module;
        $stateProvider.state(module + route.name, route.config);
      });
    }
  };

  this.$get = function () {
    return {
      config: this.config
    };
  };
});

Now you can use the helper to add the state configuration to your state configuration.

myApp.config(['$stateProvider', '$urlRouterProvider', 
    'stateshelperConfigProvider', 'publicStates', 'privateStates',
  function ($stateProvider, $urlRouterProvider, helper, publicStates, privateStates) {
    helper.config.$stateProvider = $stateProvider;
    helper.process(publicStates);
    helper.process(privateStates);
}]);

This way you can abstract the repeated code, and come up with a more modular solution.

Note: the code above isn't tested

jQuery/Javascript function to clear all the fields of a form

    <form id="form" method="post" action="action.php">
      <input type="text" class="removeLater" name="name" /> Username<br/>
      <input type="text" class="removeLater" name="pass" /> Password<br/>
      <input type="text" class="removeLater" name="pass2" /> Password again<br/>
    </form>
    <script>
$(function(){
    $("form").submit(function(e){
         //do anything you want
         //& remove values
         $(".removeLater").val('');
    }

});
</script>

How could others, on a local network, access my NodeJS app while it's running on my machine?

I had this problem. The solution was to allow node.js through the server's firewall.

No grammar constraints (DTD or XML schema) detected for the document

Try understanding the suggestion given in warning messages, it's helps sometime.

I also had the same issues, after doing some research i found the solution and fixed by adding the below line at the beginning

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xml>

which lead to some other issue in my case. Which i solved by reading the suggestions, which again turned into the another problem, which has been solved understanding the original cause, that the first link was broken (not found). Below are the step by step images which explains what has been done to resolve the issue completely.

enter image description here

enter image description here

enter image description here

enter image description here

enter image description here

How to Make A Chevron Arrow Using CSS?

Responsive Chevrons / arrows

they resize automatically with your text and are colored the same color. Plug and play :)
jsBin demo playground

enter image description here

_x000D_
_x000D_
body{
  font-size: 25px; /* Change font and  see the magic! */
  color: #f07;     /* Change color and see the magic! */
} 

/* RESPONSIVE ARROWS */
[class^=arr-]{
  border:       solid currentColor;
  border-width: 0 .2em .2em 0;
  display:      inline-block;
  padding:      .20em;
}
.arr-right {transform:rotate(-45deg);}
.arr-left  {transform:rotate(135deg);}
.arr-up    {transform:rotate(-135deg);}
.arr-down  {transform:rotate(45deg);}
_x000D_
This is <i class="arr-right"></i> .arr-right<br>
This is <i class="arr-left"></i> .arr-left<br>
This is <i class="arr-up"></i> .arr-up<br>
This is <i class="arr-down"></i> .arr-down
_x000D_
_x000D_
_x000D_

How to create a shortcut using PowerShell

I don't know any native cmdlet in powershell but you can use com object instead:

$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut("$Home\Desktop\ColorPix.lnk")
$Shortcut.TargetPath = "C:\Program Files (x86)\ColorPix\ColorPix.exe"
$Shortcut.Save()

you can create a powershell script save as set-shortcut.ps1 in your $pwd

param ( [string]$SourceExe, [string]$DestinationPath )

$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut($DestinationPath)
$Shortcut.TargetPath = $SourceExe
$Shortcut.Save()

and call it like this

Set-ShortCut "C:\Program Files (x86)\ColorPix\ColorPix.exe" "$Home\Desktop\ColorPix.lnk"

If you want to pass arguments to the target exe, it can be done by:

#Set the additional parameters for the shortcut  
$Shortcut.Arguments = "/argument=value"  

before $Shortcut.Save().

For convenience, here is a modified version of set-shortcut.ps1. It accepts arguments as its second parameter.

param ( [string]$SourceExe, [string]$ArgumentsToSourceExe, [string]$DestinationPath )
$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut($DestinationPath)
$Shortcut.TargetPath = $SourceExe
$Shortcut.Arguments = $ArgumentsToSourceExe
$Shortcut.Save()

Error: vector does not name a type

You forgot to add std:: namespace prefix to vector class name.

Why is &#65279; appearing in my HTML?

Before clear space (trim)

Then replace with RegEx .replace("/\xEF\xBB\xBF/", "")

I'm working on Javascript, I did with JavaScript.

How to parse JSON string in Typescript

Type-safe JSON.parse

You can continue to use JSON.parse, as TS is a JS superset. There is still a problem left: JSON.parse returns any, which undermines type safety. Here are two options for stronger types:

1. User-defined type guards (playground)

Custom type guards are the simplest solution and often sufficient for external data validation:

// For example, you expect to parse a given value with `MyType` shape
type MyType = { name: string; description: string; }

// Validate this value with a custom type guard
function isMyType(o: any): o is MyType {
  return "name" in o && "description" in o
}

A JSON.parse wrapper can then take a type guard as input and return the parsed, typed value:

const safeJsonParse = <T>(guard: (o: any) => o is T) => (text: string): ParseResult<T> => {
  const parsed = JSON.parse(text)
  return guard(parsed) ? { parsed, hasError: false } : { hasError: true }
}

type ParseResult<T> =
  | { parsed: T; hasError: false; error?: undefined }
  | { parsed?: undefined; hasError: true; error?: unknown }
Usage example:
const json = '{ "name": "Foo", "description": "Bar" }';
const result = safeJsonParse(isMyType)(json) // result: ParseResult<MyType>
if (result.hasError) {
  console.log("error :/")  // further error handling here
} else {
  console.log(result.parsed.description) // result.parsed now has type `MyType`
}

safeJsonParse might be extended to fail fast or try/catch JSON.parse errors.

2. External libraries

Writing type guard functions manually becomes cumbersome, if you need to validate many different values. There are libraries to assist with this task - examples (no comprehensive list):

More infos

set environment variable in python script

bash:

LD_LIBRARY_PATH=my_path
sqsub -np $1 /path/to/executable

Similar, in Python:

import os
import subprocess
import sys

os.environ['LD_LIBRARY_PATH'] = "my_path" # visible in this process + all children
subprocess.check_call(['sqsub', '-np', sys.argv[1], '/path/to/executable'],
                      env=dict(os.environ, SQSUB_VAR="visible in this subprocess"))

clientHeight/clientWidth returning different values on different browsers

The body element takes the available width, which is usually your browser viewport. As such, it will be different dimensions cross browser due to browser chrome borders, scrollbars, vertical space being take up by menus and whatnot...

The fact that the heights also vary, also tells me you set the body/html height to 100% through css since the height is usually dependant on elements inside the body..

Unless you set the width of the body element to a fixed value through css or it's style property, it's dimensions will as a rule, always vary cross browsers/versions and perhaps even depending on plugins you installed for the browser. Constant values in such a case is more an exception to the rule...

When you invoke .clientWidth on other elements that do not take the automatic width of the browser viewport, it will always return the elements 'width' + 'padding'. So a div with width 200 and a padding of 20 will have clientWidth = 240 (20 padding left and right).

The main reason however, why one would invoke clientWidth, is exactly due to possible expected discrepancies in results. If you know you will get a constant width and the value is known, then invoking clientWidth is redundant...