Programs & Examples On #Ado

Microsoft ActiveX Data Objects (ADO) is a COM based package for accessing databases such as SQL Server or data sources such as Excel spreadsheets. ADO.NET provides improvements over ADO along with integration with the .NET Framework for .NET developers. ADO.NET tag should be used for ADO.NET specific questions.

Is there a way to retrieve the view definition from a SQL Server using plain ADO?

For users of SQL 2000, the actual command that will provide this information is:

select c.text
from sysobjects     o
join syscomments    c on c.id = o.id
where o.name = '<view_name_here>'
  and o.type      = 'V'

Is it better to return null or empty collection?

If an empty collection makes sense semantically, that's what I prefer to return. Returning an empty collection for GetMessagesInMyInbox() communicates "you really do not have any messages in your inbox", whereas returning null might be useful to communicate that insufficient data is available to say what the list that might be returned ought to look like.

python-pandas and databases like mysql

For the record, here is an example using a sqlite database:

import pandas as pd
import sqlite3

with sqlite3.connect("whatever.sqlite") as con:
    sql = "SELECT * FROM table_name"
    df = pd.read_sql_query(sql, con)
    print df.shape

jQuery toggle animation

I dont think adding dual functions inside the toggle function works for a registered click event (Unless I'm missing something)

For example:

$('.btnName').click(function() {
 top.$('#panel').toggle(function() {
   $(this).animate({ 
     // style change
   }, 500);
   },
   function() {
   $(this).animate({ 
     // style change back
   }, 500);
 });

Having issues with a MySQL Join that needs to meet multiple conditions

If you join the facilities table twice you will get what you are after:

select u.* 
from room u 
  JOIN facilities_r fu1 on fu1.id_uc = u.id_uc and fu1.id_fu = '4'
  JOIN facilities_r fu2 on fu2.id_uc = u.id_uc and fu2.id_fu = '3' 
where 1 and vizibility='1' 
group by id_uc 
order by u_premium desc, id_uc desc

How do I run Redis on Windows?

MS Open Tech recently made a version of Redis available for download on Github. They say that it isn't production ready yet, but keep an eye on it.

Github repo

Download releases as MSIs

How to make child process die after parent exits?

As other people have pointed out, relying on the parent pid to become 1 when the parent exits is non-portable. Instead of waiting for a specific parent process ID, just wait for the ID to change:

pit_t pid = getpid();
switch (fork())
{
    case -1:
    {
        abort(); /* or whatever... */
    }
    default:
    {
        /* parent */
        exit(0);
    }
    case 0:
    {
        /* child */
        /* ... */
    }
}

/* Wait for parent to exit */
while (getppid() != pid)
    ;

Add a micro-sleep as desired if you don't want to poll at full speed.

This option seems simpler to me than using a pipe or relying on signals.

How to get Node.JS Express to listen only on localhost?

Thanks for the info, think I see the problem. This is a bug in hive-go that only shows up when you add a host. The last lines of it are:

app.listen(3001);
console.log("... port %d in %s mode", app.address().port, app.settings.env);

When you add the host on the first line, it is crashing when it calls app.address().port.

The problem is the potentially asynchronous nature of .listen(). Really it should be doing that console.log call inside a callback passed to listen. When you add the host, it tries to do a DNS lookup, which is async. So when that line tries to fetch the address, there isn't one yet because the DNS request is running, so it crashes.

Try this:

app.listen(3001, 'localhost', function() {
  console.log("... port %d in %s mode", app.address().port, app.settings.env);
});

Run PowerShell command from command prompt (no ps1 script)

Run it on a single command line like so:

powershell.exe -ExecutionPolicy Bypass -NoLogo -NonInteractive -NoProfile 
  -WindowStyle Hidden -Command "Get-AppLockerFileInformation -Directory <folderpath> 
  -Recurse -FileType <type>"

PHP Remove elements from associative array

The way to do this to take your nested target array and copy it in single step to a non-nested array. Delete the key(s) and then assign the final trimmed array to the nested node of the earlier array. Here is a code to make it simple:

$temp_array = $list['resultset'][0];

unset($temp_array['badkey1']);
unset($temp_array['badkey2']);

$list['resultset'][0] = $temp_array;

How to change the background color of Action Bar's Option Menu in Android 4.2?

Within your app theme you can set the android:itemBackground property to change the color of the action menu.

For example:

_x000D_
_x000D_
<style name="AppThemeDark" parent="Theme.AppCompat.Light.DarkActionBar">_x000D_
        <item name="colorPrimary">@color/drk_colorPrimary</item>_x000D_
        <item name="colorPrimaryDark">@color/drk_colorPrimaryDark</item>_x000D_
        <item name="colorAccent">@color/drk_colorAccent</item>_x000D_
        <item name="actionBarStyle">@style/NoTitle</item>_x000D_
        <item name="windowNoTitle">true</item>_x000D_
        <item name="android:textColor">@color/white</item>_x000D_
_x000D_
        <!-- THIS IS WHERE YOU CHANGE THE COLOR -->_x000D_
        <item name="android:itemBackground">@color/drk_colorPrimary</item>_x000D_
</style>
_x000D_
_x000D_
_x000D_

How can I check if a Perl array contains a particular value?

Simply turn the array into a hash:

my %params = map { $_ => 1 } @badparams;

if(exists($params{$someparam})) { ... }

You can also add more (unique) params to the list:

$params{$newparam} = 1;

And later get a list of (unique) params back:

@badparams = keys %params;

php - push array into array - key issue

Use this..

$res_arr_values = array();
while ($row = mysql_fetch_array($result, MYSQL_ASSOC))
{
    $res_arr_values[] = $row;
}

history.replaceState() example?

Here is a minimal, contrived example.

console.log( window.location.href );  // whatever your current location href is
window.history.replaceState( {} , 'foo', '/foo' );
console.log( window.location.href );  // oh, hey, it replaced the path with /foo

There is more to replaceState() but I don't know what exactly it is that you want to do with it.

Is there a sleep function in JavaScript?

If you are looking to block the execution of code with call to sleep, then no, there is no method for that in JavaScript.

JavaScript does have setTimeout method. setTimeout will let you defer execution of a function for x milliseconds.

setTimeout(myFunction, 3000);

// if you have defined a function named myFunction 
// it will run after 3 seconds (3000 milliseconds)

Remember, this is completely different from how sleep method, if it existed, would behave.

function test1()
{    
    // let's say JavaScript did have a sleep function..
    // sleep for 3 seconds
    sleep(3000);

    alert('hi'); 
}

If you run the above function, you will have to wait for 3 seconds (sleep method call is blocking) before you see the alert 'hi'. Unfortunately, there is no sleep function like that in JavaScript.

function test2()
{
    // defer the execution of anonymous function for 
    // 3 seconds and go to next line of code.
    setTimeout(function(){ 

        alert('hello');
    }, 3000);  

    alert('hi');
}

If you run test2, you will see 'hi' right away (setTimeout is non blocking) and after 3 seconds you will see the alert 'hello'.

Javascript: best Singleton pattern

Why use a constructor and prototyping for a single object?

The above is equivalent to:

var earth= {
    someMethod: function () {
        if (console && console.log)
            console.log('some method');                             
    }
};
privateFunction1();
privateFunction2();

return {
    Person: Constructors.Person,
    PlanetEarth: earth
};

How to find the 'sizeof' (a pointer pointing to an array)?

My solution to this problem is to save the length of the array into a struct Array as a meta-information about the array.

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

struct Array
{
    int length;

    double *array;
};

typedef struct Array Array;

Array* NewArray(int length)
{
    /* Allocate the memory for the struct Array */
    Array *newArray = (Array*) malloc(sizeof(Array));

    /* Insert only non-negative length's*/
    newArray->length = (length > 0) ? length : 0;

    newArray->array = (double*) malloc(length*sizeof(double));

    return newArray;
}

void SetArray(Array *structure,int length,double* array)
{
    structure->length = length;
    structure->array = array;
}

void PrintArray(Array *structure)
{       
    if(structure->length > 0)
    {
        int i;
        printf("length: %d\n", structure->length);
        for (i = 0; i < structure->length; i++)
            printf("%g\n", structure->array[i]);
    }
    else
        printf("Empty Array. Length 0\n");
}

int main()
{
    int i;
    Array *negativeTest, *days = NewArray(5);

    double moreDays[] = {1,2,3,4,5,6,7,8,9,10};

    for (i = 0; i < days->length; i++)
        days->array[i] = i+1;

    PrintArray(days);

    SetArray(days,10,moreDays);

    PrintArray(days);

    negativeTest = NewArray(-5);

    PrintArray(negativeTest);

    return 0;
}

But you have to care about set the right length of the array you want to store, because the is no way to check this length, like our friends massively explained.

How to Set RadioButtonFor() in ASp.net MVC 2 as Checked by default

You need to add 'checked' htmlAttribute in RadioButtonFor, if the radiobutton's value matches with Model.Gender value.

@{
        foreach (var item in Model.GenderList)
        {
            <div class="btn-group" role="group">
               <label class="btn btn-default">
                   @Html.RadioButtonFor(m => m.Gender, item.Key, (int)Model.Gender==item.Key ? new { @checked = "checked" } : null)
                   @item.Value
              </label>
            </div>
        }
    }

For complete code see below link: To render bootstrap radio button group with default checked. stackoverflow answer link

How do I create a readable diff of two spreadsheets using git diff?

Diff Doc may be what you're looking for.

  • Compare documents of MS Word (DOC, DOCX etc), Excel, PDF, Rich Text (RTF), Text, HTML, XML, PowerPoint, or Wordperfect and retain formatting
  • Choose any portion of any document (file) and compare it against any portion of the same or different document (file).

How do I get the result of a command in a variable in windows?

If you have to capture all the command output you can use a batch like this:

@ECHO OFF
IF NOT "%1"=="" GOTO ADDV
SET VAR=
FOR /F %%I IN ('DIR *.TXT /B /O:D') DO CALL %0 %%I
SET VAR
GOTO END

:ADDV
SET VAR=%VAR%!%1

:END

All output lines are stored in VAR separated with "!".

@John: is there any practical use for this? I think you should watch PowerShell or any other programming language capable to perform scripting tasks easily (Python, Perl, PHP, Ruby)

Intersect Two Lists in C#

You need to first transform data1, in your case by calling ToString() on each element.

Use this if you want to return strings.

List<int> data1 = new List<int> {1,2,3,4,5};
List<string> data2 = new List<string>{"6","3"};

var newData = data1.Select(i => i.ToString()).Intersect(data2);

Use this if you want to return integers.

List<int> data1 = new List<int> {1,2,3,4,5};
List<string> data2 = new List<string>{"6","3"};

var newData = data1.Intersect(data2.Select(s => int.Parse(s));

Note that this will throw an exception if not all strings are numbers. So you could do the following first to check:

int temp;
if(data2.All(s => int.TryParse(s, out temp)))
{
    // All data2 strings are int's
}

Handle ModelState Validation in ASP.NET Web API

Maybe not what you were looking for, but perhaps nice for someone to know:

If you are using .net Web Api 2 you could just do the following:

if (!ModelState.IsValid)
     return BadRequest(ModelState);

Depending on the model errors, you get this result:

{
   Message: "The request is invalid."
   ModelState: {
       model.PropertyA: [
            "The PropertyA field is required."
       ],
       model.PropertyB: [
             "The PropertyB field is required."
       ]
   }
}

Checking for empty or null List<string>

You can use Count property of List in c#

please find below code which checks list empty and null both in a single condition

if(myList == null || myList.Count == 0)
{
    //Do Something 
}

How to set border's thickness in percentages?

Take a look at calc() specification. Here is an example of usage:

border-right:1px solid;
border-left:1px solid;
width:calc(100% - 2px);

Setting Custom ActionBar Title from Fragment

Save ur Answer in String[] object and set it OnTabChange() in MainActivity as Belowwww

String[] object = {"Fragment1","Fragment2","Fragment3"};

public void OnTabChange(String tabId)
{
int pos =mTabHost.getCurrentTab();     //To get tab position
 actionbar.setTitle(object.get(pos));
}


//Setting in View Pager
public void onPageSelected(int arg0) {
    mTabHost.setCurrentTab(arg0);
actionbar.setTitle(object.get(pos));
}

How to throw a C++ exception

You could define a message to throw when a certain error occurs:

throw std::invalid_argument( "received negative value" );

or you could define it like this:

std::runtime_error greatScott("Great Scott!");          
double getEnergySync(int year) {                        
    if (year == 1955 || year == 1885) throw greatScott; 
    return 1.21e9;                                      
}                                                       

Typically, you would have a try ... catch block like this:

try {
// do something that causes an exception
}catch (std::exception& e){ std::cerr << "exception: " << e.what() << std::endl; }

java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient

Run hive in debug mode

hive -hiveconf hive.root.logger=DEBUG,console

and then execute

show tables

can find the actual problem

Defining array with multiple types in TypeScript

If you are interested in getting an array of either numbers or strings, you could define a type that will take an array of either

type Tuple = Array<number | string>
const example: Tuple = [1, "message"]
const example2: Tuple = ["message", 1]

If you expect an array of a specific order (i.e. number and a string)

type Tuple = [number, string]
const example: Tuple = [1, "message"]
const example2: Tuple = ["messsage", 1] // Type 'string' is not assignable to type 'number'.

Multiline strings in VB.NET

I figured out how to use both <![CDATA[ along with <%= for variables, which allows you to code without worry.

You basically have to terminate the CDATA tags before the VB variable and then re-add it after so the CDATA does not capture the VB code. You need to wrap the entire code block in a tag because you will you have multiple CDATA blocks.

Dim script As String = <code><![CDATA[
  <script type="text/javascript">
    var URL = ']]><%= domain %><![CDATA[/mypage.html';
  </script>]]>
</code>.value

"code ." Not working in Command Line for Visual Studio Code on OSX/Mac

For Mac OSX: There is a way to install Visual Studio Code through Brew-Cask.

  1. First, install 'Homebrew' from here.
  2. Now run following command and it will install latest Visual Studio Code on your Mac.

    $> brew cask install visual-studio-code

Above command should install Visual Studio Code and also set up the command-line calling of Visual Studio Code.

If above steps don't work then you can do it manually. By following Microsoft Visual Studio Code documentation given here.

How to change the color of an image on hover

Ok, try this:

Get the image with the transparent circle - http://i39.tinypic.com/15s97vd.png Put that image in a html element and change that element's background color via css. This way you get the logo with the circle in the color defined in the stylesheet.

The html

<div class="badassColorChangingLogo">
    <img src="http://i39.tinypic.com/15s97vd.png" /> 
    Or download the image and change the path to the downloaded image in your machine
</div>

The css

div.badassColorChangingLogo{
    background-color:white;
}
div.badassColorChangingLogo:hover{
    background-color:blue;
}

Keep in mind that this wont work on non-alpha capable browsers like ie6, and ie7. for ie you can use a js fix. Google ddbelated png fix and you can get the script.

How to Replace dot (.) in a string in Java

Use Apache Commons Lang:

String a= "\\*\\";
str = StringUtils.replace(xpath, ".", a);

or with standalone JDK:

String a = "\\*\\"; // or: String a = "/*/";
String replacement = Matcher.quoteReplacement(a);
String searchString = Pattern.quote(".");
String str = xpath.replaceAll(searchString, replacement);

How to get text from each cell of an HTML table?

Another C# example. I just made an extension method for it.

public static string GetCellFromTable(this IWebElement table, int rowIndex, int columnIndex)
    {
        return table.FindElements(By.XPath("./tbody/tr"))[rowIndex].FindElements(By.XPath("./td"))[columnIndex].Text;
    }

How do I determine k when using k-means clustering?

Hi I'll make it simple and straight to explain, I like to determine clusters using 'NbClust' library.

Now, how to use the 'NbClust' function to determine the right number of clusters: You can check the actual project in Github with actual data and clusters - Extention to this 'kmeans' algorithm also performed using the right number of 'centers'.

Github Project Link: https://github.com/RutvijBhutaiya/Thailand-Customer-Engagement-Facebook

Is a slash ("/") equivalent to an encoded slash ("%2F") in the path portion of an HTTP URL

I also have a site that has numerous urls with urlencoded characters. I am finding that many web APIs (including Google webmaster tools and several Drupal modules) trip over urlencoded characters. Many APIs automatically decode urls at some point in their process and then use the result as a URL or HTML. When I find one of these problems, I usually double encode the results (which turns %2f into %252f) for that API. However, this will break other APIs which are not expecting double encoding, so this is not a universal solution.

Personally I am getting rid of as many special characters in my URLs as possible.

Also, I am using id numbers in my URLs which do not depend on urldecoding:

example.com/blog/my-amazing-blog%2fstory/yesterday

becomes:

example.com/blog/12354/my-amazing-blog%2fstory/yesterday

in this case, my code only uses 12354 to look for the article, and the rest of the URL gets ignored by my system (but is still used for SEO.) Also, this number should appear BEFORE the unused URL components. that way, the url will still work, even if the %2f gets decoded incorrectly.

Also, be sure to use canonical tags to ensure that url mistakes don't translate into duplicate content.

Cloning git repo causes error - Host key verification failed. fatal: The remote end hung up unexpectedly

Well, from sourceTree I couldn't resolve this issue but I created sshkey from bash and at least it works from git-bash.

https://confluence.atlassian.com/bitbucket/set-up-an-ssh-key-728138079.html

PHP CSV string to array

You can convert CSV string to Array with this function.

    function csv2array(
        $csv_string,
        $delimiter = ",",
        $skip_empty_lines = true,
        $trim_fields = true,
        $FirstLineTitle = false
    ) {
        $arr = array_map(
            function ( $line ) use ( &$result, &$FirstLine, $delimiter, $trim_fields, $FirstLineTitle ) {
                if ($FirstLineTitle && !$FirstLine) {
                    $FirstLine = explode( $delimiter, $result[0] );
                }
                $lineResult = array_map(
                    function ( $field ) {
                        return str_replace( '!!Q!!', '"', utf8_decode( urldecode( $field ) ) );
                    },
                    $trim_fields ? array_map( 'trim', explode( $delimiter, $line ) ) : explode( $delimiter, $line )
                );
                return $FirstLineTitle ? array_combine( $FirstLine, $lineResult ) : $lineResult;
            },
            ($result = preg_split(
                $skip_empty_lines ? ( $trim_fields ? '/( *\R)+/s' : '/\R+/s' ) : '/\R/s',
                preg_replace_callback(
                    '/"(.*?)"/s',
                    function ( $field ) {
                        return urlencode( utf8_encode( $field[1] ) );
                    },
                    $enc = preg_replace( '/(?<!")""/', '!!Q!!', $csv_string )
                )
            ))
        );
        return $FirstLineTitle ? array_splice($arr, 1) : $arr;
    }

Can't connect to Postgresql on port 5432

I had this same issue. I originally installed version 10 because that was the default install with Ubuntu 18.04. I later upgraded to 13.2 because I wanted the latest version. I made all the config modifications, but it was still just binging to 1207.0.0.1 and then I thought - maybe it is looking at the config files for version 10. I modified those and restarted the postgres service. Bingo! It was binding to 0.0.0.0

I will need to completely remove 10 and ensure that I am forcing the service to run under version 13.2, so if you upgraded from another version, try updating the other config files in that older directory.

JAXB: how to marshall map into <key>value</key>

There may be a valid reason why you want to do this, but generating this kind of XML is generally best avoided. Why? Because it means that the XML elements of your map are dependent on the runtime contents of your map. And since XML is usually used as an external interface or interface layer this is not desirable. Let me explain.

The Xml Schema (xsd) defines the interface contract of your XML documents. In addition to being able to generate code from the XSD, JAXB can also generate the XML schema for you from the code. This allows you to restrict the data exchanged over the interface to the pre-agreed structures defined in the XSD.

In the default case for a Map<String, String>, the generated XSD will restrict the map element to contain multiple entry elements each of which must contain one xs:string key and one xs:string value. That's a pretty clear interface contract.

What you describe is that you want the xml map to contain elements whose name will be determined by the content of the map at runtime. Then the generated XSD can only specify that the map must contain a list of elements whose type is unknown at compile time. This is something that you should generally avoid when defining an interface contract.

To achieve a strict contract in this case, you should use an enumerated type as the key of the map instead of a String. E.g.

public enum KeyType {
 KEY, KEY2;
}

@XmlJavaTypeAdapter(MapAdapter.class)
Map<KeyType , String> mapProperty;

That way the keys which you want to become elements in XML are known at compile time so JAXB should be able to generate a schema that would restrict the elements of map to elements using one of the predefined keys KEY or KEY2.

On the other hand, if you wish to simplify the default generated structure

<map>
    <entry>
        <key>KEY</key>
        <value>VALUE</value>
    </entry>
    <entry>
        <key>KEY2</key>
        <value>VALUE2</value>
    </entry>
</map>

To something simpler like this

<map>
    <item key="KEY" value="VALUE"/>
    <item key="KEY2" value="VALUE2"/>
</map>

You can use a MapAdapter that converts the Map to an array of MapElements as follows:

class MapElements {
    @XmlAttribute
    public String key;
    @XmlAttribute
    public String value;

    private MapElements() {
    } //Required by JAXB

    public MapElements(String key, String value) {
        this.key = key;
        this.value = value;
    }
}


public class MapAdapter extends XmlAdapter<MapElements[], Map<String, String>> {
    public MapAdapter() {
    }

    public MapElements[] marshal(Map<String, String> arg0) throws Exception {
        MapElements[] mapElements = new MapElements[arg0.size()];
        int i = 0;
        for (Map.Entry<String, String> entry : arg0.entrySet())
            mapElements[i++] = new MapElements(entry.getKey(), entry.getValue());

        return mapElements;
    }

    public Map<String, String> unmarshal(MapElements[] arg0) throws Exception {
        Map<String, String> r = new TreeMap<String, String>();
        for (MapElements mapelement : arg0)
            r.put(mapelement.key, mapelement.value);
        return r;
    }
}

CSS to hide INPUT BUTTON value text

The difference some of you are seeing in solutions that work or not in the different IEs may be due to having compatibility mode on or off. In IE8, text-indent works just fine unless compatibility mode is turned on. If compatibility mode is on, then font-size and line-height do the trick but can mess up Firefox's display.

So we can use a css hack to let firefox ignore our ie rule.. like so...

text-indent:-9999px;
*font-size: 0px; line-height: 0;

How to find the first and second maximum number?

If you want the second highest number you can use

=LARGE(E4:E9;2)

although that doesn't account for duplicates so you could get the same result as the Max

If you want the largest number that is smaller than the maximum number you can use this version

=LARGE(E4:E9;COUNTIF(E4:E9;MAX(E4:E9))+1)

Repeat command automatically in Linux

sleep already returns 0. As such, I'm using:

while sleep 3 ; do ls -l ; done

This is a tiny bit shorter than mikhail's solution. A minor drawback is that it sleeps before running the target command for the first time.

Redraw datatables after using ajax to refresh the table content?

This is how I feed my table with data retrieved by ajax (not sure if this is the best practice tough, but it feels intuitive and works well):

/* initialise table */
oTable1 = $( '.tables table' ).dataTable
( {
    'sPaginationType': 'full_numbers',
    'bLengthChange': false,
    'aaData': [],
    'aoColumns': [{"sTitle": "Tables"}],
    'bAutoWidth': true
} );


 /*retrieve data*/
function getArr( conf_csv_path )
{
    $.ajax
    ({
        url  : 'my_url'
        success  : function( obj ) 
        {
            update_table( obj );
        }
    });
}


/* build table data */
function update_table( arr )
{        
    oTable1.fnClearTable();
    for ( input in arr )
    {
        oTable1.fnAddData( [ arr[input] );
    }                                
}

DSO missing from command line

DSO here means Dynamic Shared Object; since the error message says it's missing from the command line, I guess you have to add it to the command line.

That is, try adding -lpthread to your command line.

Property 'value' does not exist on type 'Readonly<{}>'

The problem is you haven't declared your interface state replace any with your suitable variable type of the 'value'

Here is a good reference

interface AppProps {
   //code related to your props goes here
}

interface AppState {
   value: any
}

class App extends React.Component<AppProps, AppState> {
  // ...
}

How to remove focus without setting focus to another control?

android:descendantFocusability="beforeDescendants"

using the following in the activity with some layout options below seemed to work as desired.

 getWindow().getDecorView().findViewById(android.R.id.content).clearFocus();

in connection with the following parameters on the root view.

<?xml
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:descendantFocusability="beforeDescendants" />

https://developer.android.com/reference/android/view/ViewGroup#attr_android:descendantFocusability

Answer thanks to: https://forums.xamarin.com/discussion/1856/how-to-disable-auto-focus-on-edit-text

About windowSoftInputMode

There's yet another point of contention to be aware of. By default, Android will automatically assign initial focus to the first EditText or focusable control in your Activity. It naturally follows that the InputMethod (typically the soft keyboard) will respond to the focus event by showing itself. The windowSoftInputMode attribute in AndroidManifest.xml, when set to stateAlwaysHidden, instructs the keyboard to ignore this automatically-assigned initial focus.

<activity
    android:name=".MyActivity"
    android:windowSoftInputMode="stateAlwaysHidden"/>

great reference

how to get curl to output only http response body (json) and no other headers etc

I was executing a get request an also want to see just the response and nothing else, seems like magic is done with -silent,-s option.

From the curl man page:

-s, --silent Silent or quiet mode. Don't show progress meter or error messages. Makes Curl mute. It will still output the data you ask for, potentially even to the terminal/stdout unless you redirect it.

Below the examples:

curl -s "http://host:8080/some/resource"
curl -silent "http://host:8080/some/resource"

Using custom headers

curl -s -H "Accept: application/json" "http://host:8080/some/resource")

Using POST method with a header

curl -s -X POST -H "Content-Type: application/json" "http://host:8080/some/resource") -d '{ "myBean": {"property": "value"}}'

You can also customize the output for specific values with -w, below the options I use to get just response codes of the curl:

curl -s -o /dev/null -w "%{http_code}" "http://host:8080/some/resource"

#1062 - Duplicate entry for key 'PRIMARY'

I solved it by changing the "lock" property from "shared" to "exclusive":

ALTER TABLE `table` 
CHANGE COLUMN `ID` `ID` INT(11) NOT NULL AUTO_INCREMENT COMMENT '' , LOCK = EXCLUSIVE;

Improve subplot size/spacing with many subplots in matplotlib

import matplotlib.pyplot as plt

fig = plt.figure(figsize=(10,60))
plt.subplots_adjust( ... )

The plt.subplots_adjust method:

def subplots_adjust(*args, **kwargs):
    """
    call signature::

      subplots_adjust(left=None, bottom=None, right=None, top=None,
                      wspace=None, hspace=None)

    Tune the subplot layout via the
    :class:`matplotlib.figure.SubplotParams` mechanism.  The parameter
    meanings (and suggested defaults) are::

      left  = 0.125  # the left side of the subplots of the figure
      right = 0.9    # the right side of the subplots of the figure
      bottom = 0.1   # the bottom of the subplots of the figure
      top = 0.9      # the top of the subplots of the figure
      wspace = 0.2   # the amount of width reserved for blank space between subplots
      hspace = 0.2   # the amount of height reserved for white space between subplots

    The actual defaults are controlled by the rc file
    """
    fig = gcf()
    fig.subplots_adjust(*args, **kwargs)
    draw_if_interactive()

or

fig = plt.figure(figsize=(10,60))
fig.subplots_adjust( ... )

The size of the picture matters.

"I've tried messing with hspace, but increasing it only seems to make all of the graphs smaller without resolving the overlap problem."

Thus to make more white space and keep the sub plot size the total image needs to be bigger.

Could not calculate build plan: Plugin org.apache.maven.plugins:maven-resources-plugin:2.5 or one of its dependencies could not be resolved

his issue is happening due to change of protocol from http to https for central repository. please refer following link for more details. https://support.sonatype.com/hc/en-us/articles/360041287334-Central-501-HTTPS-Required 

In order to fix the problem, copy following into your pom.ml file. This will set the repository url to use https.

<repositories>
        <repository>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
            <id>central</id>
            <name>Central Repository</name>
            <url>https://repo.maven.apache.org/maven2</url>
        </repository>
    </repositories>
    <pluginRepositories>
        <pluginRepository>
            <releases>
                <updatePolicy>never</updatePolicy>
            </releases>
            <snapshots>
                <enabled>false</enabled>
            </snapshots>
            <id>central</id>
            <name>Central Repository</name>
            <url>https://repo.maven.apache.org/maven2</url>
        </pluginRepository>
    </pluginRepositories>

Parse JSON file using GSON

One thing that to be remembered while solving such problems is that in JSON file, a { indicates a JSONObject and a [ indicates JSONArray. If one could manage them properly, it would be very easy to accomplish the task of parsing the JSON file. The above code was really very helpful for me and I hope this content adds some meaning to the above code.

The Gson JsonReader documentation explains how to handle parsing of JsonObjects and JsonArrays:

  • Within array handling methods, first call beginArray() to consume the array's opening bracket. Then create a while loop that accumulates values, terminating when hasNext() is false. Finally, read the array's closing bracket by calling endArray().
  • Within object handling methods, first call beginObject() to consume the object's opening brace. Then create a while loop that assigns values to local variables based on their name. This loop should terminate when hasNext() is false. Finally, read the object's closing brace by calling endObject().

How can I change the class of an element with jQuery>

<script>
$(document).ready(function(){
      $('button').attr('class','btn btn-primary');
}); </script>

Change bundle identifier in Xcode when submitting my first app in IOS

Just edit the Project name by single click on the Top of project navigator window, will work in this case. You need not to try any other thing. :)

Laravel migration table field's type change

update: 31 Oct 2018, Still usable on laravel 5.7 https://laravel.com/docs/5.7/migrations#modifying-columns

To make some change to existing db, you can modify column type by using change() in migration.

This is what you could do

Schema::table('orders', function ($table) {
    $table->string('category_id')->change();
});

please note you need to add doctrine/dbal dependency to composer.json for more information you can find it here http://laravel.com/docs/5.1/migrations#modifying-columns

How can I find the current OS in Python?

If you want user readable data but still detailed, you can use platform.platform()

>>> import platform
>>> platform.platform()
'Linux-3.3.0-8.fc16.x86_64-x86_64-with-fedora-16-Verne'

platform also has some other useful methods:

>>> platform.system()
'Windows'
>>> platform.release()
'XP'
>>> platform.version()
'5.1.2600'

Here's a few different possible calls you can make to identify where you are

import platform
import sys

def linux_distribution():
  try:
    return platform.linux_distribution()
  except:
    return "N/A"

print("""Python version: %s
dist: %s
linux_distribution: %s
system: %s
machine: %s
platform: %s
uname: %s
version: %s
mac_ver: %s
""" % (
sys.version.split('\n'),
str(platform.dist()),
linux_distribution(),
platform.system(),
platform.machine(),
platform.platform(),
platform.uname(),
platform.version(),
platform.mac_ver(),
))

The outputs of this script ran on a few different systems (Linux, Windows, Solaris, MacOS) and architectures (x86, x64, Itanium, power pc, sparc) is available here: https://github.com/hpcugent/easybuild/wiki/OS_flavor_name_version

e.g. Solaris on sparc gave:

Python version: ['2.6.4 (r264:75706, Aug  4 2010, 16:53:32) [C]']
dist: ('', '', '')
linux_distribution: ('', '', '')
system: SunOS
machine: sun4u
platform: SunOS-5.9-sun4u-sparc-32bit-ELF
uname: ('SunOS', 'xxx', '5.9', 'Generic_122300-60', 'sun4u', 'sparc')
version: Generic_122300-60
mac_ver: ('', ('', '', ''), '')

How to pass an array to a function in VBA?

Your function worked for me after changing its declaration to this ...

Function processArr(Arr As Variant) As String

You could also consider a ParamArray like this ...

Function processArr(ParamArray Arr() As Variant) As String
    'Dim N As Variant
    Dim N As Long
    Dim finalStr As String
    For N = LBound(Arr) To UBound(Arr)
        finalStr = finalStr & Arr(N)
    Next N
    processArr = finalStr
End Function

And then call the function like this ...

processArr("foo", "bar")

__proto__ VS. prototype in JavaScript

What about using __proto__ for static methods?

function Foo(name){
  this.name = name
  Foo.__proto__.collection.push(this)
  Foo.__proto__.count++

}

Foo.__proto__.count=0
Foo.__proto__.collection=[]

var bar = new Foo('bar')
var baz = new Foo('baz')

Foo.count;//2
Foo.collection // [{...}, {...}]
bar.count // undefined

Python matplotlib multiple bars

I did this solution: if you want plot more than one plot in one figure, make sure before plotting next plots you have set right matplotlib.pyplot.hold(True) to able adding another plots.

Concerning the datetime values on the X axis, a solution using the alignment of bars works for me. When you create another bar plot with matplotlib.pyplot.bar(), just use align='edge|center' and set width='+|-distance'.

When you set all bars (plots) right, you will see the bars fine.

How can you find the height of text on an HTML canvas?

I'm writing a terminal emulator so I needed to draw rectangles around characters.

var size = 10
var lineHeight = 1.2 // CSS "line-height: normal" is between 1 and 1.2
context.font = size+'px/'+lineHeight+'em monospace'
width = context.measureText('m').width
height = size * lineHeight

Obviously if you want the exact amount of space the character takes up, it won't help. But it'll give you a good approximation for certain uses.

Add line break to ::after or ::before pseudo-element content

Add line break to ::after or ::before pseudo-element content

.yourclass:before {
    content: 'text here first \A  text here second';
    white-space: pre;
}

Uncaught TypeError: Cannot set property 'onclick' of null

Make sure your javascript is being executed after your element(s) have loaded, perhaps try putting the js file call just before the tag or use the defer attribute in your script, like so: <script src="app.js" defer></script> this makes sure that your script will be executed after the dom has loaded.

Changing image sizes proportionally using CSS?

Put it as a background on your holder e.g.

<div style="background:url(path/to/image/myimage.jpg) center center; width:120px; height:120px;">
&nbsp;
</div>

This will center your image inside a 120x120 div chopping off any excess of the image

Xcode error - Thread 1: signal SIGABRT

You are trying to load a XIB named DetailViewController, but no such XIB exists or it's not member of your current target.

Convert float to std::string in C++

If you're worried about performance, check out the Boost::lexical_cast library.

How to run iPhone emulator WITHOUT starting Xcode?

You can get it to launch via spotlight if you create an Automator launcher for it:

  1. Open Automator.app
  2. Choose type of Application
  3. Select Actions > Library > Utilities > Launch Application
  4. Open the dropdown of applications that can be launched and choose Other
  5. You can't directly select the Simulator app because it's inside the Xcode.app package. So instead you'll have to navigate to it in a separate Finder window and drag it onto the file selector window. It will be at one of the following paths depending on your version of Xcode (oldest to newest):
    • /Applications/Xcode.app/Contents/Developer/iOS Simulator.app
    • /Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Applications/iOS Simulator.app
    • /Applications/Xcode.app/Contents/Developer/Applications/Simulator.app
  6. Finally, save this Automator app in your applications folder as iOS Simulator.app

Create Automator app

To get a nice icon for the Automator app you just made, you can do the following:

  1. Right click iOS Simulator.app and choose Get Info
  2. Click the icon in the upper left corner and do Cmd-C to copy it
  3. Right click your Automator app and choose Get Info
  4. Click the icon in the upper left corner and do Cmd-V to paste

Copy icon

VBA EXCEL To Prompt User Response to Select Folder and Return the Path as String Variable

Consider:

Function GetFolder() As String
    Dim fldr As FileDialog
    Dim sItem As String
    Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
    With fldr
        .Title = "Select a Folder"
        .AllowMultiSelect = False
        .InitialFileName = Application.DefaultFilePath
        If .Show <> -1 Then GoTo NextCode
        sItem = .SelectedItems(1)
    End With
NextCode:
    GetFolder = sItem
    Set fldr = Nothing
End Function

This code was adapted from Ozgrid

and as jkf points out, from Mr Excel

Python handling socket.error: [Errno 104] Connection reset by peer

You can try to add some time.sleep calls to your code.

It seems like the server side limits the amount of requests per timeunit (hour, day, second) as a security issue. You need to guess how many (maybe using another script with a counter?) and adjust your script to not surpass this limit.

In order to avoid your code from crashing, try to catch this error with try .. except around the urllib2 calls.

Best way to check function arguments?

There are different ways to check what a variable is in Python. So, to list a few:

  • isinstance(obj, type) function takes your variable, obj and gives you True is it is the same type of the type you listed.

  • issubclass(obj, class) function that takes in a variable obj, and gives you True if obj is a subclass of class. So for example issubclass(Rabbit, Animal) would give you a True value

  • hasattr is another example, demonstrated by this function, super_len:


def super_len(o):
    if hasattr(o, '__len__'):
        return len(o)

    if hasattr(o, 'len'):
        return o.len

    if hasattr(o, 'fileno'):
        try:
            fileno = o.fileno()
        except io.UnsupportedOperation:
            pass
        else:
            return os.fstat(fileno).st_size

    if hasattr(o, 'getvalue'):
        # e.g. BytesIO, cStringIO.StringI
        return len(o.getvalue())

hasattr leans more towards duck-typing, and something that is usually more pythonic but that term is up opinionated.

Just as a note, assert statements are usually used in testing, otherwise, just use if/else statements.

Measuring execution time of a function in C++

In Scott Meyers book I found an example of universal generic lambda expression that can be used to measure function execution time. (C++14)

auto timeFuncInvocation = 
    [](auto&& func, auto&&... params) {
        // get time before function invocation
        const auto& start = std::chrono::high_resolution_clock::now();
        // function invocation using perfect forwarding
        std::forward<decltype(func)>(func)(std::forward<decltype(params)>(params)...);
        // get time after function invocation
        const auto& stop = std::chrono::high_resolution_clock::now();
        return stop - start;
     };

The problem is that you are measure only one execution so the results can be very differ. To get a reliable result you should measure a large number of execution. According to Andrei Alexandrescu lecture at code::dive 2015 conference - Writing Fast Code I:

Measured time: tm = t + tq + tn + to

where:

tm - measured (observed) time

t - the actual time of interest

tq - time added by quantization noise

tn - time added by various sources of noise

to - overhead time (measuring, looping, calling functions)

According to what he said later in the lecture, you should take a minimum of this large number of execution as your result. I encourage you to look at the lecture in which he explains why.

Also there is a very good library from google - https://github.com/google/benchmark. This library is very simple to use and powerful. You can checkout some lectures of Chandler Carruth on youtube where he is using this library in practice. For example CppCon 2017: Chandler Carruth “Going Nowhere Faster”;

Example usage:

#include <iostream>
#include <chrono>
#include <vector>
auto timeFuncInvocation = 
    [](auto&& func, auto&&... params) {
        // get time before function invocation
        const auto& start = high_resolution_clock::now();
        // function invocation using perfect forwarding
        for(auto i = 0; i < 100000/*largeNumber*/; ++i) {
            std::forward<decltype(func)>(func)(std::forward<decltype(params)>(params)...);
        }
        // get time after function invocation
        const auto& stop = high_resolution_clock::now();
        return (stop - start)/100000/*largeNumber*/;
     };

void f(std::vector<int>& vec) {
    vec.push_back(1);
}

void f2(std::vector<int>& vec) {
    vec.emplace_back(1);
}
int main()
{
    std::vector<int> vec;
    std::vector<int> vec2;
    std::cout << timeFuncInvocation(f, vec).count() << std::endl;
    std::cout << timeFuncInvocation(f2, vec2).count() << std::endl;
    std::vector<int> vec3;
    vec3.reserve(100000);
    std::vector<int> vec4;
    vec4.reserve(100000);
    std::cout << timeFuncInvocation(f, vec3).count() << std::endl;
    std::cout << timeFuncInvocation(f2, vec4).count() << std::endl;
    return 0;
}

EDIT: Ofcourse you always need to remember that your compiler can optimize something out or not. Tools like perf can be useful in such cases.

Auto-expanding layout with Qt-Designer

After creating your QVBoxLayout in Qt Designer, right-click on the background of your widget/dialog/window (not the QVBoxLayout, but the parent widget) and select Lay Out -> Lay Out in a Grid from the bottom of the context-menu. The QVBoxLayout should now stretch to fit the window and will resize automatically when the entire window is resized.

How to print a string at a fixed width?

format is definitely the most elegant way, but afaik you can't use that with python's logging module, so here's how you can do it using the % formatting:

formatter = logging.Formatter(
    fmt='%(asctime)s | %(name)-20s | %(levelname)-10s | %(message)s',
)

Here, the - indicates left-alignment, and the number before s indicates the fixed width.

Some sample output:

2017-03-14 14:43:42,581 | this-app             | INFO       | running main
2017-03-14 14:43:42,581 | this-app.aux         | DEBUG      | 5 is an int!
2017-03-14 14:43:42,581 | this-app.aux         | INFO       | hello
2017-03-14 14:43:42,581 | this-app             | ERROR      | failed running main

More info at the docs here: https://docs.python.org/2/library/stdtypes.html#string-formatting-operations

Get last dirname/filename in a file path argument in Bash

The following approach can be used to get any path of a pathname:

some_path=a/b/c
echo $(basename $some_path)
echo $(basename $(dirname $some_path))
echo $(basename $(dirname $(dirname $some_path)))

Output:

c
b
a

How to set the 'selected option' of a select dropdown list with jquery

The match between .val('Bruce jones') and value="Bruce Jones" is case-sensitive. It looks like you're capitalizing Jones in one but not the other. Either track down where the difference comes from, use id's instead of the name, or call .toLowerCase() on both.

An unhandled exception occurred during the execution of the current web request. ASP.NET

  1. If you are facing this problem (Enter windows + R) an delete temp(%temp%)and windows temp.
  2. Some file is not deleted that time stop IIS(Internet information service) and delete that all remaining files .

Check your problem is solved.

Resize image in the wiki of GitHub using Markdown

This addresses the different question, how to get images in gist (as opposed to github) markdown in the first place ?


In December 2015, it seems that only links to files on github.com or cloud.githubusercontent.com or the like work. Steps that worked for me in a gist:

  1. Make a gist, say Mygist.md (and optionally more files)
  2. Go to the "Write Comment" box at the end
  3. Click "Attach files ... by selecting them"; select your local image file
  4. GitHub echos a long long string where it put the image, e.g. ![khan-lasso-squared](https://cloud.githubusercontent.com/assets/1280390/12011119/596fdca4-acc2-11e5-84d0-4878164e04bb.png)
  5. Cut-paste that by hand into your Mygist.md.

But: GitHub people may change this behavior tomorrow, without documenting it.

Pass parameter from a batch file to a PowerShell script

Assuming your script is something like the below snippet and named testargs.ps1

param ([string]$w)
Write-Output $w

You can call this at the commandline as:

PowerShell.Exe -File C:\scripts\testargs.ps1 "Test String"

This will print "Test String" (w/o quotes) at the console. "Test String" becomes the value of $w in the script.

numpy: most efficient frequency counts for unique values in an array

Update: The method mentioned in the original answer is deprecated, we should use the new way instead:

>>> import numpy as np
>>> x = [1,1,1,2,2,2,5,25,1,1]
>>> np.array(np.unique(x, return_counts=True)).T
    array([[ 1,  5],
           [ 2,  3],
           [ 5,  1],
           [25,  1]])

Original answer:

you can use scipy.stats.itemfreq

>>> from scipy.stats import itemfreq
>>> x = [1,1,1,2,2,2,5,25,1,1]
>>> itemfreq(x)
/usr/local/bin/python:1: DeprecationWarning: `itemfreq` is deprecated! `itemfreq` is deprecated and will be removed in a future version. Use instead `np.unique(..., return_counts=True)`
array([[  1.,   5.],
       [  2.,   3.],
       [  5.,   1.],
       [ 25.,   1.]])

Send auto email programmatically

It might be an easiest way-

    String recipientList = mEditTextTo.getText().toString();
    String[] recipients = recipientList.split(",");

    String subject = mEditTextSubject.getText().toString();
    String message = mEditTextMessage.getText().toString();

    Intent intent = new Intent(Intent.ACTION_SEND);
    intent.putExtra(Intent.EXTRA_EMAIL, recipients);
    intent.putExtra(Intent.EXTRA_SUBJECT, subject);
    intent.putExtra(Intent.EXTRA_TEXT, message);

    intent.setType("message/rfc822");
    startActivity(Intent.createChooser(intent, "Choose an email client"));

Go back button in a page

onclick="history.go(-1)" Simply

Why cannot cast Integer to String in java?

Use .toString instead like below:

String myString = myIntegerObject.toString();

Is it possible to declare a public variable in vba and assign a default value?

As told above, To declare global accessible variables you can do it outside functions preceded with the public keyword.

And, since the affectation is NOT PERMITTED outside the procedures, you can, for example, create a sub called InitGlobals that initializes your public variables, then you just call this subroutine at the beginning of your statements

Here is an example of it:

Public Coordinates(3) as Double
Public Heat as double
Public Weight as double

Sub InitGlobals()
    Coordinates(1)=10.5
    Coordinates(2)=22.54
    Coordinates(3)=-100.5
    Heat=25.5
    Weight=70
End Sub

Sub MyWorkSGoesHere()
    Call InitGlobals
    'Now you can do your work using your global variables initialized as you wanted them to be.
End Sub

How do you overcome the svn 'out of date' error?

I've found that this works for me:

svn update
svn resolved <dir>
svn commit

How to set selected value from Combobox?

Try this one.

cmbEmployeeStatus.SelectedIndex = cmbEmployeeStatus.FindString(employee.employmentstatus);

Hope that helps. :)

OnItemCLickListener not working in listview

Use android:descendantFocusability

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="80dip"
    android:background="@color/light_green"
    android:descendantFocusability="blocksDescendants" >

Add above in root layout

[Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified

Got this error because I had the Data Source Name in User DSN instead of System DSN enter image description here

How do I get the name of a Ruby class?

Both result.class.to_s and result.class.name work.

mongodb group values by multiple fields

Below query will provide exactly the same result as given in the desired response:

db.books.aggregate([
    {
        $group: {
            _id: { addresses: "$addr", books: "$book" },
            num: { $sum :1 }
        }
    },
    {
        $group: {
            _id: "$_id.addresses",
            bookCounts: { $push: { bookName: "$_id.books",count: "$num" } }
        }
    },
    {
        $project: {
            _id: 1,
            bookCounts:1,
            "totalBookAtAddress": {
                "$sum": "$bookCounts.count"
            }
        }
    }

]) 

The response will be looking like below:

/* 1 */
{
    "_id" : "address4",
    "bookCounts" : [
        {
            "bookName" : "book3",
            "count" : 1
        }
    ],
    "totalBookAtAddress" : 1
},

/* 2 */
{
    "_id" : "address90",
    "bookCounts" : [
        {
            "bookName" : "book33",
            "count" : 1
        }
    ],
    "totalBookAtAddress" : 1
},

/* 3 */
{
    "_id" : "address15",
    "bookCounts" : [
        {
            "bookName" : "book1",
            "count" : 1
        }
    ],
    "totalBookAtAddress" : 1
},

/* 4 */
{
    "_id" : "address3",
    "bookCounts" : [
        {
            "bookName" : "book9",
            "count" : 1
        }
    ],
    "totalBookAtAddress" : 1
},

/* 5 */
{
    "_id" : "address5",
    "bookCounts" : [
        {
            "bookName" : "book1",
            "count" : 1
        }
    ],
    "totalBookAtAddress" : 1
},

/* 6 */
{
    "_id" : "address1",
    "bookCounts" : [
        {
            "bookName" : "book1",
            "count" : 3
        },
        {
            "bookName" : "book5",
            "count" : 1
        }
    ],
    "totalBookAtAddress" : 4
},

/* 7 */
{
    "_id" : "address2",
    "bookCounts" : [
        {
            "bookName" : "book1",
            "count" : 2
        },
        {
            "bookName" : "book5",
            "count" : 1
        }
    ],
    "totalBookAtAddress" : 3
},

/* 8 */
{
    "_id" : "address77",
    "bookCounts" : [
        {
            "bookName" : "book11",
            "count" : 1
        }
    ],
    "totalBookAtAddress" : 1
},

/* 9 */
{
    "_id" : "address9",
    "bookCounts" : [
        {
            "bookName" : "book99",
            "count" : 1
        }
    ],
    "totalBookAtAddress" : 1
}

Access is denied when attaching a database

For what it's worth to anyone having the particular variation of this problem that I had:

  • SQL Express 2008
  • Visual Studio 2010 Premium

Through the context menu of the App_data folder I had created a SQL Express database for debugging purposes. The connection string (used by NHibernate) was as follows:

Server=.\SQLExpress;
AttachDbFilename=|DataDirectory|DebugDatabase.mdf;
Database=DebugDatabase;
Trusted_Connection=Yes;

This gave me the same "Access denied" error on the database file. I tried giving various users Full Control to the folder and files, at one point even to "Everyone". Nothing helped, so I removed the added permissions again.

What finally solved it was to open the Server Explorer in Visual Studio, then connect to the MDF, and detach it again. After I'd done that my web app could access the database just fine.

PS. Credits go to this blog post I found while googling this particular problem, triggering the idea to attach/detach the database to solve the issue.

Failed to fetch URL https://dl-ssl.google.com/android/repository/addons_list-1.xml, reason: Connection to https://dl-ssl.google.com refused

I got the solution for the Android Studio installation after trying everything that I could find on the Internet. If you're using Android Studio and getting this error:

Find [Path_to_Android_SDK]\sdk\tools\android.bat. In my case, it was in C:\Users\Nathan\AppData\Local\Android\android-studio\sdk\tools\android.bat.

Right-click it, hit Edit, and scroll all the way down to the bottom.

Find where it says: call %java_exe% %REMOTE_DEBUG% ...

Replace that with call %java_exe% -Djava.net.preferIPv4Stack=true %REMOTE_DEBUG% ...

Restart Android Studio/SDK and everything works. This fixed many issues for me, including being unable to fetch XML files or create new projects.

Can I add a custom attribute to an HTML tag?

Yes, you can do it!

Having the next HTML tag:

<tag key="value"/>

We can access their attributes with JavaScript:

element.getAttribute('key'); // Getter
element.setAttribute('key', 'value'); // Setter

Element.setAttribute() put the attribute in the HTML tag if not exist. So, you dont need to declare it in the HTML code if you are going to set it with JavaScript.

key: could be any name you desire for the attribute, while is not already used for the current tag. value: it's always a string containing what you need.

inserting characters at the start and end of a string

Adding to C2H5OH's answer, in Python 3.6+ you can use format strings to make it a bit cleaner:

s = "something about cupcakes"
print(f"L{s}LL")

How do I free my port 80 on localhost Windows?

Use TcpView to find the process that listens to the port and close the process.

Are string.Equals() and == operator really same?

The Header property of the TreeViewItem is statically typed to be of type object.

Therefore the == yields false. You can reproduce this with the following simple snippet:

object s1 = "Hallo";

// don't use a string literal to avoid interning
string s2 = new string(new char[] { 'H', 'a', 'l', 'l', 'o' });

bool equals = s1 == s2;         // equals is false
equals = string.Equals(s1, s2); // equals is true

complex if statement in python

if
  ...
  # several checks
  ...
elif not (1024<=var<=65535 or var == 80 or var == 443)
  # fail
else
  ...

Margin while printing html page

Updated, Simple Solution

@media print {
   body {
       display: table;
       table-layout: fixed;
       padding-top: 2.5cm;
       padding-bottom: 2.5cm;
       height: auto;
   }
}

Old Solution

Create section with each page, and use the below code to adjust margins, height and width.

If you are printing A4 size.

Then user

Size : 8.27in and 11.69 inches

@page Section1 {
    size: 8.27in 11.69in; 
    margin: .5in .5in .5in .5in; 
    mso-header-margin: .5in; 
    mso-footer-margin: .5in; 
    mso-paper-source: 0;
}



div.Section1 {
    page: Section1;
} 

then create a div with all your content in it.

<div class="Section1"> 
    type your content here... 
</div>

R : how to simply repeat a command?

It's not clear whether you're asking this because you are new to programming, but if that's the case then you should probably read this article on loops and indeed read some basic materials on programming.

If you already know about control structures and you want the R-specific implementation details then there are dozens of tutorials around, such as this one. The other answer uses replicate and colMeans, which is idiomatic when writing in R and probably blazing fast as well, which is important if you want 10,000 iterations.

However, one more general and (for beginners) straightforward way to approach problems of this sort would be to use a for loop.

> for (ii in 1:5) { + print(ii) + } [1] 1 [1] 2 [1] 3 [1] 4 [1] 5 > 

So in your case, if you just wanted to print the mean of your Tandem object 5 times:

for (ii in 1:5) {     Tandem <- sample(OUT, size = 815, replace = TRUE, prob = NULL)     TandemMean <- mean(Tandem)     print(TandemMean) } 

As mentioned above, replicate is a more natural way to deal with this specific problem using R. Either way, if you want to store the results - which is surely the case - you'll need to start thinking about data structures like vectors and lists. Once you store something you'll need to be able to access it to use it in future, so a little knowledge is vital.

set.seed(1234) OUT <- runif(100000, 1, 2) tandem <- list() for (ii in 1:10000) {     tandem[[ii]] <- mean(sample(OUT, size = 815, replace = TRUE, prob = NULL)) }  tandem[1] tandem[100] tandem[20:25] 

...creates this output:

> set.seed(1234) > OUT <- runif(100000, 1, 2) > tandem <- list() > for (ii in 1:10000) { +     tandem[[ii]] <- mean(sample(OUT, size = 815, replace = TRUE, prob = NULL)) + } >  > tandem[1] [[1]] [1] 1.511923  > tandem[100] [[1]] [1] 1.496777  > tandem[20:25] [[1]] [1] 1.500669  [[2]] [1] 1.487552  [[3]] [1] 1.503409  [[4]] [1] 1.501362  [[5]] [1] 1.499728  [[6]] [1] 1.492798  >  

How to type ":" ("colon") in regexp?

Be careful, - has a special meaning with regexp. In a [], you can put it without problem if it is placed at the end. In your case, ,-: is taken as from , to :.

What does the construct x = x || y mean?

Whilst Cletus' answer is correct, I feel more detail should be added in regards to "evaluates to false" in JavaScript.

var title = title || 'Error';
var msg   = msg || 'Error on Request';

Is not just checking if title/msg has been provided, but also if either of them are falsy. i.e. one of the following:

  • false.
  • 0 (zero)
  • "" (empty string)
  • null.
  • undefined.
  • NaN (a special Number value meaning Not-a-Number!)

So in the line

var title = title || 'Error';

If title is truthy (i.e., not falsy, so title = "titleMessage" etc.) then the Boolean OR (||) operator has found one 'true' value, which means it evaluates to true, so it short-circuits and returns the true value (title).

If title is falsy (i.e. one of the list above), then the Boolean OR (||) operator has found a 'false' value, and now needs to evaluate the other part of the operator, 'Error', which evaluates to true, and is hence returned.

It would also seem (after some quick firebug console experimentation) if both sides of the operator evaluate to false, it returns the second 'falsy' operator.

i.e.

return ("" || undefined)

returns undefined, this is probably to allow you to use the behavior asked about in this question when trying to default title/message to "". i.e. after running

var foo = undefined
foo = foo || ""

foo would be set to ""

COLLATION 'utf8_general_ci' is not valid for CHARACTER SET 'latin1'

Firstly run this query

SHOW VARIABLES LIKE '%char%';

You have character_set_server='latin1'

for eg if CHARSET=utf8mb4 COLLATE=utf8mb4_0900_ai_ci replace it to CHARSET=latin1 and remove the collate

You are good to go

How to get current available GPUs in tensorflow?

Apart from the excellent explanation by Mrry, where he suggested to use device_lib.list_local_devices() I can show you how you can check for GPU related information from the command line.

Because currently only Nvidia's gpus work for NN frameworks, the answer covers only them. Nvidia has a page where they document how you can use the /proc filesystem interface to obtain run-time information about the driver, any installed NVIDIA graphics cards, and the AGP status.

/proc/driver/nvidia/gpus/0..N/information

Provide information about each of the installed NVIDIA graphics adapters (model name, IRQ, BIOS version, Bus Type). Note that the BIOS version is only available while X is running.

So you can run this from command line cat /proc/driver/nvidia/gpus/0/information and see information about your first GPU. It is easy to run this from python and also you can check second, third, fourth GPU till it will fail.

Definitely Mrry's answer is more robust and I am not sure whether my answer will work on non-linux machine, but that Nvidia's page provide other interesting information, which not many people know about.

Refreshing page on click of a button

I'd suggest <a href='page1.jsp'>Refresh</a>.

Detecting iOS / Android Operating system

Using the cordova-device-plugin, you can detect

device.platform

will be "Android" for android, and "windows" for windows. Works on device, and when simulating on browser. Here is a toast that will display the device values:

    window.plugins.toast.showLongTop(
    'Cordova:     ' + device.cordova + '\n' +
    'Model:       ' + device.model + '\n' +
    'Platform:    ' + device.platform + '\n' +
    'UUID:        ' + '\n' +
                      device.uuid + '\n' +
    'Version:     ' + device.version + '\n' +
    'Manufacturer ' + device.manufacturer + '\n' +
    'isVirtual    ' + device.isVirtual + '\n' +
    'Serial       ' + device.serial);

Get to UIViewController from UIView?

I think there is a case when the observed needs to inform the observer.

I see a similar problem where the UIView in a UIViewController is responding to a situation and it needs to first tell its parent view controller to hide the back button and then upon completion tell the parent view controller that it needs to pop itself off the stack.

I have been trying this with delegates with no success.

I don't understand why this should be a bad idea?

What does "make oldconfig" do exactly in the Linux kernel makefile?

Summary

As mentioned by Ignacio, it updates your .config for you after you update the kernel source, e.g. with git pull.

It tries to keep your existing options.

Having a script for that is helpful because:

  • new options may have been added, or old ones removed

  • the kernel's Kconfig configuration format has options that:

    • imply one another via select
    • depend on another via depends

    Those option relationships make manual config resolution even harder.

Let's modify .config manually to understand how it resolves configurations

First generate a default configuration with:

make defconfig

Now edit the generated .config file manually to emulate a kernel update and run:

make oldconfig

to see what happens. Some conclusions:

  1. Lines of type:

    # CONFIG_XXX is not set
    

    are not mere comments, but actually indicate that the parameter is not set.

    For example, if we remove the line:

    # CONFIG_DEBUG_INFO is not set
    

    and run make oldconfig, it will ask us:

    Compile the kernel with debug info (DEBUG_INFO) [N/y/?] (NEW)
    

    When it is over, the .config file will be updated.

    If you change any character of the line, e.g. to # CONFIG_DEBUG_INFO, it does not count.

  2. Lines of type:

    # CONFIG_XXX is not set
    

    are always used for the negation of a property, although:

    CONFIG_XXX=n
    

    is also understood as the negation.

    For example, if you remove # CONFIG_DEBUG_INFO is not set and answer:

    Compile the kernel with debug info (DEBUG_INFO) [N/y/?] (NEW)
    

    with N, then the output file contains:

    # CONFIG_DEBUG_INFO is not set
    

    and not:

    CONFIG_DEBUG_INFO=n
    

    Also, if we manually modify the line to:

    CONFIG_DEBUG_INFO=n
    

    and run make oldconfig, then the line gets modified to:

    # CONFIG_DEBUG_INFO is not set
    

    without oldconfig asking us.

  3. Configs whose dependencies are not met, do not appear on the .config. All others do.

    For example, set:

    CONFIG_DEBUG_INFO=y
    

    and run make oldconfig. It will now ask us for: DEBUG_INFO_REDUCED, DEBUG_INFO_SPLIT, etc. configs.

    Those properties did not appear on the defconfig before.

    If we look under lib/Kconfig.debug where they are defined, we see that they depend on DEBUG_INFO:

    config DEBUG_INFO_REDUCED
        bool "Reduce debugging information"
        depends on DEBUG_INFO
    

    So when DEBUG_INFO was off, they did not show up at all.

  4. Configs which are selected by turned on configs are automatically set without asking the user.

    For example, if CONFIG_X86=y and we remove the line:

    CONFIG_ARCH_MIGHT_HAVE_PC_PARPORT=y
    

    and run make oldconfig, the line gets recreated without asking us, unlike DEBUG_INFO.

    This happens because arch/x86/Kconfig contains:

    config X86
        def_bool y
        [...]
        select ARCH_MIGHT_HAVE_PC_PARPORT
    

    and select forces that option to be true. See also: https://unix.stackexchange.com/questions/117521/select-vs-depends-in-kernel-kconfig

  5. Configs whose constraints are not met are asked for.

    For example, defconfig had set:

    CONFIG_64BIT=y
    CONFIG_RCU_FANOUT=64
    

    If we edit:

    CONFIG_64BIT=n
    

    and run make oldconfig, it will ask us:

    Tree-based hierarchical RCU fanout value (RCU_FANOUT) [32] (NEW)
    

    This is because RCU_FANOUT is defined at init/Kconfig as:

    config RCU_FANOUT
        int "Tree-based hierarchical RCU fanout value"
        range 2 64 if 64BIT
        range 2 32 if !64BIT
    

    Therefore, without 64BIT, the maximum value is 32, but we had 64 set on the .config, which would make it inconsistent.

Bonuses

make olddefconfig sets every option to their default value without asking interactively. It gets run automatically on make to ensure that the .config is consistent in case you've modified it manually like we did. See also: https://serverfault.com/questions/116299/automatically-answer-defaults-when-doing-make-oldconfig-on-a-kernel-tree

make alldefconfig is like make olddefconfig, but it also accepts a config fragment to merge. This target is used by the merge_config.sh script: https://stackoverflow.com/a/39440863/895245

And if you want to automate the .config modification, that is not too simple: How do you non-interactively turn on features in a Linux kernel .config file?

exec failed because the name not a valid identifier?

Try this instead in the end:

exec (@query)

If you do not have the brackets, SQL Server assumes the value of the variable to be a stored procedure name.

OR

EXECUTE sp_executesql @query

And it should not be because of FULL JOIN.
But I hope you have already created the temp tables: #TrafficFinal, #TrafficFinal2, #TrafficFinal3 before this.


Please note that there are performance considerations between using EXEC and sp_executesql. Because sp_executesql uses forced statement caching like an sp.
More details here.


On another note, is there a reason why you are using dynamic sql for this case, when you can use the query as is, considering you are not doing any query manipulations and executing it the way it is?

How to make Bootstrap 4 cards the same height in card-columns?

wrap the cards inside

<div class="card-group"></div>

or

<div class="card-deck"></div>

Quick-and-dirty way to ensure only one instance of a shell script is running at a time

The semaphoric utility uses flock (as discussed above, e.g. by presto8) to implement a counting semaphore. It enables any specific number of concurrent processes you want. We use it to limit the level of concurrency of various queue worker processes.

It's like sem but much lighter-weight. (Full disclosure: I wrote it after finding the sem was way too heavy for our needs and there wasn't a simple counting semaphore utility available.)

Java parsing XML document gives "Content not allowed in prolog." error

You are not providing the correct address for the file. You need to provide an address such as C:/Users/xyz/Desktop/myfile.xml

How to get names of enum entries?

Quite a few answers here and considering I looked it up despite this being 7 years old question, I surmise many more will come here. Here's my solution, which is a bit simpler than other ones, it handles numeric-only/text-only/mixed value enums, all the same.

enum funky {
    yum , tum='tum', gum = 'jump', plum = 4
}

const list1 = Object.keys(funky)
  .filter(k => (Number(k).toString() === Number.NaN.toString()));
console.log(JSON.stringify(list1)); // ["yum","tum","gum","plum"]" 

 // for the numeric enum vals (like yum = 0, plum = 4), typescript adds val = key implicitly (0 = yum, 4 = plum)
 // hence we need to filter out such numeric keys (0 or 4)
 

What is the reason for a red exclamation mark next to my project in Eclipse?

It means the jar files are missing from the path that you have given while configuring Build Path/adding jars to the project.

Just once again configure the jars.

How to use __DATE__ and __TIME__ predefined macros in as two integers, then stringify?

You could always write a simple program in Python or something to create an include file that has simple #define statements with a build number, time, and date. You would then need to run this program before doing a build.

If you like I'll write one and post source here.

If you are lucky, your build tool (IDE or whatever) might have the ability to run an external command, and then you could have the external tool rewrite the include file automatically with each build.

EDIT: Here's a Python program. This writes a file called build_num.h and has an integer build number that starts at 1 and increments each time this program is run; it also writes #define values for the year, month, date, hours, minutes and seconds of the time this program is run. It also has a #define for major and minor parts of the version number, plus the full VERSION and COMPLETE_VERSION that you wanted. (I wasn't sure what you wanted for the date and time numbers, so I went for just concatenated digits from the date and time. You can change this easily.)

Each time you run it, it reads in the build_num.h file, and parses it for the build number; if the build_num.h file does not exist, it starts the build number at 1. Likewise it parses out major and minor version numbers, and if the file does not exist defaults those to version 0.1.

import time

FNAME = "build_num.h"

build_num = None
version_major = None
version_minor = None

DEF_BUILD_NUM = "#define BUILD_NUM "
DEF_VERSION_MAJOR = "#define VERSION_MAJOR "
DEF_VERSION_MINOR = "#define VERSION_MINOR "

def get_int(s_marker, line):
    _, _, s = line.partition(s_marker) # we want the part after the marker
    return int(s)

try:
    with open(FNAME) as f:
        for line in f:
            if DEF_BUILD_NUM in line:
                build_num = get_int(DEF_BUILD_NUM, line)
                build_num += 1
            elif DEF_VERSION_MAJOR in line:
                version_major = get_int(DEF_VERSION_MAJOR, line)
            elif DEF_VERSION_MINOR in line:
                version_minor = get_int(DEF_VERSION_MINOR, line)
except IOError:
    build_num = 1
    version_major = 0
    version_minor = 1

assert None not in (build_num, version_major, version_minor)


with open(FNAME, 'w') as f:
    f.write("#ifndef BUILD_NUM_H\n")
    f.write("#define BUILD_NUM_H\n")
    f.write("\n")
    f.write(DEF_BUILD_NUM + "%d\n" % build_num)
    f.write("\n")
    t = time.localtime()
    f.write("#define BUILD_YEAR %d\n" % t.tm_year)
    f.write("#define BUILD_MONTH %d\n" % t.tm_mon)
    f.write("#define BUILD_DATE %d\n" % t.tm_mday)
    f.write("#define BUILD_HOUR %d\n" % t.tm_hour)
    f.write("#define BUILD_MIN %d\n" % t.tm_min)
    f.write("#define BUILD_SEC %d\n" % t.tm_sec)
    f.write("\n")
    f.write("#define VERSION_MAJOR %d\n" % version_major)
    f.write("#define VERSION_MINOR %d\n" % version_minor)
    f.write("\n")
    f.write("#define VERSION \"%d.%d\"\n" % (version_major, version_minor))
    s = "%d.%d.%04d%02d%02d.%02d%02d%02d" % (version_major, version_minor,
            t.tm_year, t.tm_mon, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec)
    f.write("#define COMPLETE_VERSION \"%s\"\n" % s)
    f.write("\n")
    f.write("#endif // BUILD_NUM_H\n")

I made all the defines just be integers, but since they are simple integers you can use the standard stringizing tricks to build a string out of them if you like. Also you can trivially extend it to build additional pre-defined strings.

This program should run fine under Python 2.6 or later, including any Python 3.x version. You could run it under an old Python with a few changes, like not using .partition() to parse the string.

How to change current working directory using a batch file

Try this

chdir /d D:\Work\Root

Enjoy rooting ;)

destination path already exists and is not an empty directory

Explanation

This is pretty vague but I'll do what I can to help.

First, while it may seem daunting at first, I suggest you learn how to do things from the command line (called terminal on OSX). This is a great way to make sure you're putting things where you really want to.

You should definitely google 'unix commands' to learn more, but here are a few important commands to help in this situation:

ls - list all files and directories (folders) in current directory

cd <input directory here without these brackets> - change directory, or change the folder you're looking in

mkdir <input directory name without brackets> - Makes a new directory (be careful, you will have to cd into the directory after you make it)

rm -r <input directory name without brackets> - Removes a directory and everything inside it

git clone <link to repo without brackets> - Clones the repository into the directory you are currently browsing.

Answer

So, on my computer, I would run the following commands to create a directory (folder) called projects within my documents folder and clone a repo there.

  1. Open terminal
  2. cd documents (Not case sensitive on mac)
  3. mkdir projects
  4. cd projects
  5. git clone https://github.com/seanbecker15/wherecanifindit.git
  6. cd wherecanifindit (if I want to go into the directory)

p.s. wherecanifindit is just the name of my git repository, not a command!

How to assign the output of a Bash command to a variable?

Here's your script...

DIR=$(pwd)
echo $DIR
while [ "$DIR" != "/" ]; do
    cd ..
    DIR=$(pwd)
    echo $DIR
done

Note the spaces, use of quotes, and $ signs.

How to execute a remote command over ssh with arguments?

I'm using the following to execute commands on the remote from my local computer:

ssh -i ~/.ssh/$GIT_PRIVKEY user@$IP "bash -s" < localpath/script.sh $arg1 $arg2

What do <o:p> elements do anyway?

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

The relevant paragraph:

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

This makes lots of sense.

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

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

Real world use of JMS/message queues?

JMS (ActiveMQ is a JMS broker implementation) can be used as a mechanism to allow asynchronous request processing. You may wish to do this because the request take a long time to complete or because several parties may be interested in the actual request. Another reason for using it is to allow multiple clients (potentially written in different languages) to access information via JMS. ActiveMQ is a good example here because you can use the STOMP protocol to allow access from a C#/Java/Ruby client.

A real world example is that of a web application that is used to place an order for a particular customer. As part of placing that order (and storing it in a database) you may wish to carry a number of additional tasks:

  • Store the order in some sort of third party back-end system (such as SAP)
  • Send an email to the customer to inform them their order has been placed

To do this your application code would publish a message onto a JMS queue which includes an order id. One part of your application listening to the queue may respond to the event by taking the orderId, looking the order up in the database and then place that order with another third party system. Another part of your application may be responsible for taking the orderId and sending a confirmation email to the customer.

Creating Accordion Table with Bootstrap

In the accepted answer you get annoying spacing between the visible rows when the expandable row is hidden. You can get rid of that by adding this to css:

.collapse-row.collapsed + tr {
     display: none;
}

'+' is adjacent sibling selector, so if you want your expandable row to be the next row, this selects the next tr following tr named collapse-row.

Here is updated fiddle: http://jsfiddle.net/Nb7wy/2372/

how to find 2d array size in c++

The other answers above have answered your first question. As for your second question, how to detect an error of getting a value that is not set, I am not sure which of the following situation you mean:

  1. Accessing an array element using an invalid index:
    If you use std::vector, you can use vector::at function instead of [] operator to get the value, if the index is invalid, an out_of_range exception will be thrown.

  2. Accessing a valid index, but the element has not been set yet: As far as I know, there is no direct way of it. However, the following common practices can probably solve you problem: (1) Initializes all elements to a value that you are certain that is impossible to have. For example, if you are dealing with positive integers, set all elements to -1, so you know the value is not set yet when you find it being -1. (2). Simply use a bool array of the same size to indicate whether the element of the same index is set or not, this applies when all values are "possible".

Select distinct values from a large DataTable column

This will retrun you distinct Ids

 var distinctIds = datatable.AsEnumerable()
                    .Select(s=> new {
                        id = s.Field<string>("id"),                           
                     })
                    .Distinct().ToList();

Android Completely transparent Status Bar?

Simple and crisp and works with almost all use cases (for API level 16 and above):

  1. Use the following tag in your app theme to make the status bar transparent:

    <item name="android:statusBarColor">@android:color/transparent</item>

  2. And then use this code in your activity's onCreate method.

    View decorView = getWindow().getDecorView();
    decorView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_STABLE
            | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN);
    

That's all you need to do ;)

You can learn more from the developer documentation. I'd also recommend reading this blog post.

KOTLIN CODE:

    val decorView = window.decorView
    decorView.systemUiVisibility = (View.SYSTEM_UI_FLAG_LAYOUT_STABLE
            or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN)

Check my another answer here

How to provide a mysql database connection in single file in nodejs

From the node.js documentation, "To have a module execute code multiple times, export a function, and call that function", you could use node.js module.export and have a single file to manage the db connections.You can find more at Node.js documentation. Let's say db.js file be like:

    const mysql = require('mysql');

    var connection;

    module.exports = {

    dbConnection: function () {

        connection = mysql.createConnection({
            host: "127.0.0.1",
            user: "Your_user",
            password: "Your_password",
            database: 'Your_bd'
        });
        connection.connect();
        return connection;
    }

    };

Then, the file where you are going to use the connection could be like useDb.js:

const dbConnection = require('./db');

var connection;

function callDb() {

    try {

        connection = dbConnectionManager.dbConnection();

        connection.query('SELECT 1 + 1 AS solution', function (error, results, fields) {
            if (!error) {

                let response = "The solution is: " + results[0].solution;
                console.log(response);

            } else {
                console.log(error);
            }
        });
        connection.end();


    } catch (err) {
        console.log(err);
    }
}

How to import large sql file in phpmyadmin

One solution is to use the command line;

mysql -h yourhostname -u username -p databasename < yoursqlfile.sql

Just ensure the path to the SQL file to import is stated explicitly.

In my case, I used this;

mysql -h localhost -u root -p databasename < /home/ejalee/dumps/mysqlfile.sql

Voila! you are good to go.

Remove final character from string

What you are trying to do is an extension of string slicing in Python:

Say all strings are of length 10, last char to be removed:

>>> st[:9]
'abcdefghi'

To remove last N characters:

>>> N = 3
>>> st[:-N]
'abcdefg'

Reordering Chart Data Series

Select a series and look in the formula bar. The last argument is the plot order of the series. You can edit this formula just like any other, right in the formula bar.

For example, select series 4, then change the 4 to a 3.

Conditional operator in Python?

simple is the best and works in every version.

if a>10: 
    value="b"
else: 
    value="c"

How to create threads in nodejs

The nodejs 10.5.0 release has announced multithreading in Node.js. The feature is still experimental. There is a new worker_threads module available now.

You can start using worker threads if you run Node.js v10.5.0 or higher, but this is an experimental API. It is not available by default: you need to enable it by using --experimental-worker when invoking Node.js.

Here is an example with ES6 and worker_threads enabled, tested on version 12.3.1

//package.json

  "scripts": {
  "start": "node  --experimental-modules --experimental- worker index.mjs"
  },

Now, you need to import Worker from worker_threads. Note: You need to declare you js files with '.mjs' extension for ES6 support.

//index.mjs
import { Worker } from 'worker_threads';

const spawnWorker = workerData => {
    return new Promise((resolve, reject) => {
        const worker = new Worker('./workerService.mjs', { workerData });
        worker.on('message', resolve);
        worker.on('error', reject);
        worker.on('exit', code => code !== 0 && reject(new Error(`Worker stopped with 
        exit code ${code}`)));
    })
}

const spawnWorkers = () => {
    for (let t = 1; t <= 5; t++)
        spawnWorker('Hello').then(data => console.log(data));
}

spawnWorkers();

Finally, we create a workerService.mjs

//workerService.mjs
import { workerData, parentPort, threadId } from 'worker_threads';

// You can do any cpu intensive tasks here, in a synchronous way
// without blocking the "main thread"
parentPort.postMessage(`${workerData} from worker ${threadId}`);

Output:

npm run start

Hello from worker 4
Hello from worker 3
Hello from worker 1
Hello from worker 2
Hello from worker 5

How to write to a file, using the logging Python module?

here's a simpler way to go about it. this solution doesn't use a config dictionary and uses a rotation file handler, like so:

import logging
from logging.handlers import RotatingFileHandler

logging.basicConfig(handlers=[RotatingFileHandler(filename=logpath+filename,
                     mode='w', maxBytes=512000, backupCount=4)], level=debug_level,
                     format='%(levelname)s %(asctime)s %(message)s', 
                    datefmt='%m/%d/%Y%I:%M:%S %p')

logger = logging.getLogger('my_logger')

or like so:

import logging
from logging.handlers import RotatingFileHandler

handlers = [
            RotatingFileHandler(filename=logpath+filename, mode='w', maxBytes=512000, 
                                backupCount=4)
           ]
logging.basicConfig(handlers=handlers, level=debug_level, 
                    format='%(levelname)s %(asctime)s %(message)s', 
                    datefmt='%m/%d/%Y%I:%M:%S %p')

logger = logging.getLogger('my_logger')

the handlers variable needs to be an iterable. logpath+filename and debug_level are just variables holding the respective info. of course, the values for the function params are up to you.

the first time i was using the logging module i made the mistake of writing the following, which generates an OS file lock error (the above is the solution to that):

import logging
from logging.handlers import RotatingFileHandler

logging.basicConfig(filename=logpath+filename, level=debug_level, format='%(levelname)s %(asctime)s %(message)s', datefmt='%m/%d/%Y
 %I:%M:%S %p')

logger = logging.getLogger('my_logger')
logger.addHandler(RotatingFileHandler(filename=logpath+filename, mode='w', 
                  maxBytes=512000, backupCount=4))

and Bob's your uncle!

Why SQL Server throws Arithmetic overflow error converting int to data type numeric?

NUMERIC(3,2) means: 3 digits in total, 2 after the decimal point. So you only have a single decimal before the decimal point.

Try NUMERIC(5,2) - three before, two after the decimal point.

What are the JavaScript KeyCodes?

Here are some useful links:

The 2nd column is the keyCode and the html column shows how it will displayed. You can test it here.

Django return redirect() with parameters

urls.py:

#...    
url(r'element/update/(?P<pk>\d+)/$', 'element.views.element_update', name='element_update'),

views.py:

from django.shortcuts import redirect
from .models import Element


def element_info(request):
    # ...
    element = Element.object.get(pk=1)
    return redirect('element_update', pk=element.id)

def element_update(request, pk)
    # ...

Access-control-allow-origin with multiple domains

There can only be one Access-Control-Allow-Origin response header, and that header can only have one origin value. Therefore, in order to get this to work, you need to have some code that:

  1. Grabs the Origin request header.
  2. Checks if the origin value is one of the whitelisted values.
  3. If it is valid, sets the Access-Control-Allow-Origin header with that value.

I don't think there's any way to do this solely through the web.config.

if (ValidateRequest()) {
    Response.Headers.Remove("Access-Control-Allow-Origin");
    Response.AddHeader("Access-Control-Allow-Origin", Request.UrlReferrer.GetLeftPart(UriPartial.Authority));

    Response.Headers.Remove("Access-Control-Allow-Credentials");
    Response.AddHeader("Access-Control-Allow-Credentials", "true");

    Response.Headers.Remove("Access-Control-Allow-Methods");
    Response.AddHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
}

Copy table from one database to another

SELECT ... INTO :

select * into <destination table> from <source table>

How to do "If Clicked Else .."

Maybe you're looking for something like this:

$(document).click(function(e)
   {
       if($(e.srcElement).attr('id')=='id')
       {
           alert('click on #id');
       }
       else
       {
            alert('click on something else'); 
       }
   });

jsfiddle

You may retrieve a pointer to the clicked element using event.srcElement .

So all you have to do is to check the id-attribute of the clicked element.

How to make spring inject value into a static field

As these answers are old, I found this alternative. It is very clean and works with just java annotations:

To fix it, create a “none static setter” to assign the injected value for the static variable. For example :

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

@Component
public class GlobalValue {

public static String DATABASE;

@Value("${mongodb.db}")
public void setDatabase(String db) {
    DATABASE = db;
}
}

https://www.mkyong.com/spring/spring-inject-a-value-into-static-variables/

How do I find the parent directory in C#?

string parent = System.IO.Directory.GetParent(str_directory).FullName;

See BOL

Can't use Swift classes inside Objective-C

The file is created automatically (talking about Xcode 6.3.2 here). But you won't see it, since it's in your Derived Data folder. After marking your swift class with @objc, compile, then search for Swift.h in your Derived Data folder. You should find the Swift header there.

I had the problem, that Xcode renamed my my-Project-Swift.h to my_Project-Swift.h Xcode doesn't like "." "-" etc. symbols. With the method above you can find the filename and import it to a Objective-C class.

Select statement to find duplicates on certain fields

To get the list of fields for which there are multiple records, you can use..

select field1,field2,field3, count(*)
  from table_name
  group by field1,field2,field3
  having count(*) > 1

Check this link for more information on how to delete the rows.

http://support.microsoft.com/kb/139444

There should be a criterion for deciding how you define "first rows" before you use the approach in the link above. Based on that you'll need to use an order by clause and a sub query if needed. If you can post some sample data, it would really help.

How to check queue length in Python

it is simple just use .qsize() example:

a=Queue()
a.put("abcdef")
print a.qsize() #prints 1 which is the size of queue

The above snippet applies for Queue() class of python. Thanks @rayryeng for the update.

for deque from collections we can use len() as stated here by K Z.

Placing Unicode character in CSS content value

Why don't you just save/serve the CSS file as UTF-8?

nav a:hover:after {
    content: "?";
}

If that's not good enough, and you want to keep it all-ASCII:

nav a:hover:after {
    content: "\2193";
}

The general format for a Unicode character inside a string is \000000 to \FFFFFF – a backslash followed by six hexadecimal digits. You can leave out leading 0 digits when the Unicode character is the last character in the string or when you add a space after the Unicode character. See the spec below for full details.


Relevant part of the CSS2 spec:

Third, backslash escapes allow authors to refer to characters they cannot easily put in a document. In this case, the backslash is followed by at most six hexadecimal digits (0..9A..F), which stand for the ISO 10646 ([ISO10646]) character with that number, which must not be zero. (It is undefined in CSS 2.1 what happens if a style sheet does contain a character with Unicode codepoint zero.) If a character in the range [0-9a-fA-F] follows the hexadecimal number, the end of the number needs to be made clear. There are two ways to do that:

  1. with a space (or other white space character): "\26 B" ("&B"). In this case, user agents should treat a "CR/LF" pair (U+000D/U+000A) as a single white space character.
  2. by providing exactly 6 hexadecimal digits: "\000026B" ("&B")

In fact, these two methods may be combined. Only one white space character is ignored after a hexadecimal escape. Note that this means that a "real" space after the escape sequence must be doubled.

If the number is outside the range allowed by Unicode (e.g., "\110000" is above the maximum 10FFFF allowed in current Unicode), the UA may replace the escape with the "replacement character" (U+FFFD). If the character is to be displayed, the UA should show a visible symbol, such as a "missing character" glyph (cf. 15.2, point 5).

  • Note: Backslash escapes are always considered to be part of an identifier or a string (i.e., "\7B" is not punctuation, even though "{" is, and "\32" is allowed at the start of a class name, even though "2" is not).
    The identifier "te\st" is exactly the same identifier as "test".

Comprehensive list: Unicode Character 'DOWNWARDS ARROW' (U+2193).

Google maps Marker Label with multiple characters

You can change easy marker label css without use any extra plugin.

var marker = new google.maps.Marker({
        position: this.overlay_text,
        draggable: true,
        icon: '',
        label: {
          text: this.overlay_field_text,
          color: '#fff',
          fontSize: '20px',
          fontWeight: 'bold',
          fontFamily: 'custom-label'
        },
        map:map
      });
      marker.setMap(map);

$("[style*='custom-label']").css({'text-shadow': '2px 2px #000'})

How do I make a request using HTTP basic authentication with PHP curl?

CURLOPT_USERPWD basically sends the base64 of the user:password string with http header like below:

Authorization: Basic dXNlcjpwYXNzd29yZA==

So apart from the CURLOPT_USERPWD you can also use the HTTP-Request header option as well like below with other headers:

$headers = array(
    'Content-Type:application/json',
    'Authorization: Basic '. base64_encode("user:password") // <---
);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

How to check currently internet connection is available or not in android

This will tell if you're connected to a network:

boolean connected = false;
ConnectivityManager connectivityManager = (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);
    if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED || 
            connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
        //we are connected to a network
        connected = true;
    }
    else
        connected = false;

Warning: If you are connected to a WiFi network that doesn't include internet access or requires browser-based authentication, connected will still be true.

You will need this permission in your manifest:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Css Move element from left to right animated

You should try doing it with css3 animation. Check the code bellow:

<!DOCTYPE html>
<html>
<head>
<style> 
div {
    width: 100px;
    height: 100px;
    background: red;
    position: relative;
    -webkit-animation: myfirst 5s infinite; /* Chrome, Safari, Opera */
    -webkit-animation-direction: alternate; /* Chrome, Safari, Opera */
    animation: myfirst 5s infinite;
    animation-direction: alternate;
}

/* Chrome, Safari, Opera */
@-webkit-keyframes myfirst {
    0%   {background: red; left: 0px; top: 0px;}
    25%  {background: yellow; left: 200px; top: 0px;}
    50%  {background: blue; left: 200px; top: 200px;}
    75%  {background: green; left: 0px; top: 200px;}
    100% {background: red; left: 0px; top: 0px;}
}

@keyframes myfirst {
    0%   {background: red; left: 0px; top: 0px;}
    25%  {background: yellow; left: 200px; top: 0px;}
    50%  {background: blue; left: 200px; top: 200px;}
    75%  {background: green; left: 0px; top: 200px;}
    100% {background: red; left: 0px; top: 0px;}
}
</style>
</head>
<body>

<p><strong>Note:</strong> The animation-direction property is not supported in Internet Explorer 9 and earlier versions.</p>
<div></div>

</body>
</html>

Where 'div' is your animated object.

I hope you find this useful.

Thanks.

Convert double to string C++?

Use std::stringstream. Its operator << is overloaded for all built-in types.

#include <sstream>    

std::stringstream s;
s << "(" << c1 << "," << c2 << ")";
storedCorrect[count] = s.str();

This works like you'd expect - the same way you print to the screen with std::cout. You're simply "printing" to a string instead. The internals of operator << take care of making sure there's enough space and doing any necessary conversions (e.g., double to string).

Also, if you have the Boost library available, you might consider looking into lexical_cast. The syntax looks much like the normal C++-style casts:

#include <string>
#include <boost/lexical_cast.hpp>
using namespace boost;

storedCorrect[count] = "(" + lexical_cast<std::string>(c1) +
                       "," + lexical_cast<std::string>(c2) + ")";

Under the hood, boost::lexical_cast is basically doing the same thing we did with std::stringstream. A key advantage to using the Boost library is you can go the other way (e.g., string to double) just as easily. No more messing with atof() or strtod() and raw C-style strings.

Laravel 4: Redirect to a given url

Both Redirect::to() and Redirect::away() should work.

Difference

Redirect::to() does additional URL checks and generations. Those additional steps are done in Illuminate\Routing\UrlGenerator and do the following, if the passed URL is not a fully valid URL (even with protocol):

Determines if URL is secure
rawurlencode() the URL
trim() URL

src : https://medium.com/@zwacky/laravel-redirect-to-vs-redirect-away-dd875579951f

To switch from vertical split to horizontal split fast in Vim

In VIM, take a look at the following to see different alternatives for what you might have done:

:help opening-window

For instance:

Ctrl-W s
Ctrl-W o
Ctrl-W v
Ctrl-W o
Ctrl-W s
...

div with dynamic min-height based on browser window height

You propably have to write some JavaScript, because there is no way to estimate the height of all the users of the page.

What is the simplest way to write the contents of a StringBuilder to a text file in .NET 1.1?

If you need to write line by line from string builder

StringBuilder sb = new StringBuilder();
sb.AppendLine("New Line!");

using (var sw = new StreamWriter(@"C:\MyDir\MyNewTextFile.txt", true))
{
   sw.Write(sb.ToString());
}

If you need to write all text as single line from string builder

StringBuilder sb = new StringBuilder();
sb.Append("New Text line!");

using (var sw = new StreamWriter(@"C:\MyDir\MyNewTextFile.txt", true))
{
   sw.Write(sb.ToString());
}

How to split a file into equal parts, without breaking individual lines?

var dict = File.ReadLines("test.txt")
               .Where(line => !string.IsNullOrWhitespace(line))
               .Select(line => line.Split(new char[] { '=' }, 2, 0))
               .ToDictionary(parts => parts[0], parts => parts[1]);


or 

    enter code here

line="[email protected][email protected]";
string[] tokens = line.Split(new char[] { '=' }, 2, 0);

ans:
tokens[0]=to
token[1][email protected][email protected]"

How can JavaScript save to a local file?

It is not possible to save file locally without involving the local client (browser machine) as I could be a great threat to client machine. You can use link to download that file. If you want to store something like Json data on local machine you can use LocalStorage provided by the browsers, Web Storage

WebView and Cookies on Android

If you are using Android Lollipop i.e. SDK 21, then:

CookieManager.getInstance().setAcceptCookie(true);

won't work. You need to use:

CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true);

I ran into same issue and the above line worked as a charm.

Spring MVC - How to return simple String as JSON in Rest Controller

I know that this question is old but i would like to contribute too:

The main difference between others responses is the hashmap return.

@GetMapping("...")
@ResponseBody
public Map<String, Object> endPointExample(...) {

    Map<String, Object> rtn = new LinkedHashMap<>();

    rtn.put("pic", image);
    rtn.put("potato", "King Potato");

    return rtn;

}

This will return:

{"pic":"a17fefab83517fb...beb8ac5a2ae8f0449","potato":"King Potato"}

$(this).val() not working to get text from span using jquery

Instead of .val() use .text(), like this:

$(".ui-datepicker-month").live("click", function () {
    var monthname =  $(this).text();
    alert(monthname);
});

Or in jQuery 1.7+ use on() as live is deprecated:

$(document).on('click', '.ui-datepicker-month', function () {
    var monthname =  $(this).text();
    alert(monthname);
});

.val() is for input type elements (including textareas and dropdowns), since you're dealing with an element with text content, use .text() here.

Convert base class to derived class

No, there's no built-in way to convert a class like you say. The simplest way to do this would be to do what you suggested: create a DerivedClass(BaseClass) constructor. Other options would basically come out to automate the copying of properties from the base to the derived instance, e.g. using reflection.

The code you posted using as will compile, as I'm sure you've seen, but will throw a null reference exception when you run it, because myBaseObject as DerivedClass will evaluate to null, since it's not an instance of DerivedClass.

How to fix the "java.security.cert.CertificateException: No subject alternative names present" error?

public class RESTfulClientSSL {

    static TrustManager[] trustAllCerts = new TrustManager[]{new X509TrustManager() {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            // TODO Auto-generated method stub
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) throws CertificateException {
            // TODO Auto-generated method stub
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            // TODO Auto-generated method stub
            return null;
        }
    }};

    public class NullHostNameVerifier implements HostnameVerifier {
        /*
         * (non-Javadoc)
         *
         * @see javax.net.ssl.HostnameVerifier#verify(java.lang.String,
         * javax.net.ssl.SSLSession)
         */
        @Override
        public boolean verify(String arg0, SSLSession arg1) {
            // TODO Auto-generated method stub
            return true;
        }
    }

    public static void main(String[] args) {

        HttpURLConnection connection = null;
        try {

            HttpsURLConnection.setDefaultHostnameVerifier(new RESTfulwalkthroughCer().new NullHostNameVerifier());
            SSLContext sc = SSLContext.getInstance("SSL");
            sc.init(null, trustAllCerts, new SecureRandom());
            HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());


            String uriString = "https://172.20.20.12:9443/rest/hr/exposed/service";
            URL url = new URL(uriString);
            connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("GET");
            //connection.setRequestMethod("POST");

            BASE64Encoder encoder = new BASE64Encoder();
            String username = "admin";
            String password = "admin";
            String encodedCredential = encoder.encode((username + ":" + password).getBytes());
            connection.setRequestProperty("Authorization", "Basic " + encodedCredential);

            connection.connect();
            BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            int responseCode = connection.getResponseCode();
            if (responseCode == HttpURLConnection.HTTP_OK) {
                StringBuffer stringBuffer = new StringBuffer();
                String line = "";
                while ((line = reader.readLine()) != null) {
                    stringBuffer.append(line);
                }
                String content = stringBuffer.toString();
                System.out.println(content);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (connection != null) {
                connection.disconnect();
            }
        }
    }
}

Set cursor position on contentEditable <div>

In Firefox you might have the text of the div in a child node (o_div.childNodes[0])

var range = document.createRange();

range.setStart(o_div.childNodes[0],last_caret_pos);
range.setEnd(o_div.childNodes[0],last_caret_pos);
range.collapse(false);

var sel = window.getSelection(); 
sel.removeAllRanges();
sel.addRange(range);

jQuery hide and show toggle div with plus and minus icon

Here is a quick edit of Enve's answer. I do like roXor's solution, but background images are not necessary. And everbody seems to forgot a preventDefault as well.

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $(".slidingDiv").hide();_x000D_
_x000D_
  $('.show_hide').click(function(e) {_x000D_
    $(".slidingDiv").slideToggle("fast");_x000D_
    var val = $(this).text() == "-" ? "+" : "-";_x000D_
    $(this).hide().text(val).fadeIn("fast");_x000D_
    e.preventDefault();_x000D_
  });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<a href="#" class="show_hide">+</a>_x000D_
_x000D_
<div class="slidingDiv">_x000D_
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi. Nulla quis sem at nibh elementum imperdiet. Duis sagittis ipsum. Praesent mauris. Fusce nec tellus sed augue semper porta._x000D_
    Mauris massa. Vestibulum lacinia arcu eget nulla. </p>_x000D_
_x000D_
  <p>Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Curabitur sodales ligula in libero. Sed dignissim lacinia nunc. Curabitur tortor. Pellentesque nibh. Aenean quam. In scelerisque sem at dolor. Maecenas mattis._x000D_
    Sed convallis tristique sem. Proin ut ligula vel nunc egestas porttitor. Morbi lectus risus, iaculis vel, suscipit quis, luctus non, massa. Fusce ac turpis quis ligula lacinia aliquet. Mauris ipsum. </p>_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to pass a parameter to Vue @click event handler

When you are using Vue directives, the expressions are evaluated in the context of Vue, so you don't need to wrap things in {}.

@click is just shorthand for v-on:click directive so the same rules apply.

In your case, simply use @click="addToCount(item.contactID)"

Session variables not working php

I had similar issue and with the cookie domain:

    ini_set('session.cookie_domain', '.domain.com');

the domain was setup wrong so all sessions were ignored because the user cookie was never set right hope this will help someone.

Npm install failed with "cannot run in wd"

I fixed this by changing the ownership of /usr/local and ~/Users/user-name like so:

sudo chown -R my_name /usr/local

This allowed me to do everything without sudo

How to convert array to a string using methods other than JSON?

Use the implode() function:

$array = array('lastname', 'email', 'phone');
$comma_separated = implode(",", $array);
echo $comma_separated; // lastname,email,phone

How do I scroll to an element using JavaScript?

For Chrome and Firefox

I've been looking a bit into this and I figured this one out which somehow feels like the most natural way to do it. Of course, this is my personal favorite scroll now. :)

const y = element.getBoundingClientRect().top + window.scrollY;
window.scroll({
  top: y,
  behavior: 'smooth'
});

For IE, Edge and Safari supporters

Note that window.scroll({ ...options }) is not supported on IE, Edge and Safari. In that case it's most likely best to use element.scrollIntoView(). (Supported on IE 6). You can most likely (read: untested) pass in options without any side effects.

These can of course be wrapped in a function that behaves according to which browser is being used.

How to create a static library with g++?

Can someone please tell me how to create a static library from a .cpp and a .hpp file? Do I need to create the .o and the the .a?

Yes.

Create the .o (as per normal):

g++ -c header.cpp

Create the archive:

ar rvs header.a header.o

Test:

g++ test.cpp header.a -o executable_name

Note that it seems a bit pointless to make an archive with just one module in it. You could just as easily have written:

g++ test.cpp header.cpp -o executable_name

Still, I'll give you the benefit of the doubt that your actual use case is a bit more complex, with more modules.

Hope this helps!

How to convert a SVG to a PNG with ImageMagick?

In order to rescale the image, the option -density should be used. As far as I know the standard density is 72 and maps the size 1:1. If you want the output png to be twice as big as the original svg, set the density to 72*2=144:

convert -density 144 source.svg target.png

Extract images from PDF without resampling, in python?

PikePDF can do this with very little code:

from pikepdf import Pdf, PdfImage

filename = "sample-in.pdf"
example = Pdf.open(filename)

for i, page in enumerate(example.pages):
    for j, (name, raw_image) in enumerate(page.images.items()):
        image = PdfImage(raw_image)
        out = image.extract_to(fileprefix=f"{filename}-page{i:03}-img{j:03}")

extract_to will automatically pick the file extension based on how the image is encoded in the PDF.

If you want, you could also print some detail about the images as they get extracted:

        # Optional: print info about image
        w = raw_image.stream_dict.Width
        h = raw_image.stream_dict.Height
        f = raw_image.stream_dict.Filter
        size = raw_image.stream_dict.Length

        print(f"Wrote {name} {w}x{h} {f} {size:,}B {image.colorspace} to {out}")

which can print something like

Wrote /Im1 150x150 /DCTDecode 5,952B /ICCBased to sample2.pdf-page000-img000.jpg
Wrote /Im10 32x32 /FlateDecode 36B /ICCBased to sample2.pdf-page000-img001.png
...

See the docs for more that you can do with images, including replacing them in the PDF file.

Understanding typedefs for function pointers in C

Use typedefs to define more complicated types i.e function pointers

I will take the example of defining a state-machine in C

    typedef  int (*action_handler_t)(void *ctx, void *data);

now we have defined a type called action_handler that takes two pointers and returns a int

define your state-machine

    typedef struct
    {
      state_t curr_state;   /* Enum for the Current state */
      event_t event;  /* Enum for the event */
      state_t next_state;   /* Enum for the next state */
      action_handler_t event_handler; /* Function-pointer to the action */

     }state_element;

The function pointer to the action looks like a simple type and typedef primarily serves this purpose.

All my event handlers now should adhere to the type defined by action_handler

    int handle_event_a(void *fsm_ctx, void *in_msg );

    int handle_event_b(void *fsm_ctx, void *in_msg );

References:

Expert C programming by Linden

Converting <br /> into a new line for use in a text area

The answer by @Mobilpadde is nice. But this is my solution with regex using preg_replace which might be faster according to my tests.

echo preg_replace('/<br\s?\/?>/i', "\r\n", "testing<br/><br /><BR><br>");

function function_one() {
    preg_replace('/<br\s?\/?>/i', "\r\n", "testing<br/><br /><BR><br>");
}

function function_two() {
    str_ireplace(['<br />','<br>','<br/>'], "\r\n", "testing<br/><br /><BR><br>");
}

function benchmark() {
    $count = 10000000;
    $before = microtime(true);

    for ($i=0 ; $i<$count; $i++) {
        function_one();
    }

    $after = microtime(true);
    echo ($after-$before)/$i . " sec/function one\n";



    $before = microtime(true);

    for ($i=0 ; $i<$count; $i++) {
        function_two();
    }

    $after = microtime(true);
    echo ($after-$before)/$i . " sec/function two\n";
}
benchmark();

Results:

1.1471637010574E-6 sec/function one (preg_replace)
1.6027762889862E-6 sec/function two (str_ireplace)

@ variables in Ruby on Rails

@variables are called instance variables in ruby. Which means you can access these variables in ANY METHOD inside the class. [Across all methods in the class]

Variables without the @ symbol are called local variables, which means you can access these local variables within THAT DECLARED METHOD only. Limited to the local scope.

Example of Instance Variables:

class Customer
  def initialize(id, name, addr)
    @cust_id = id
    @cust_name = name
    @cust_addr = addr
  end

  def display_details
    puts "Customer id #{@cust_id}"
    puts "Customer name #{@cust_name}"
    puts "Customer address #{@cust_addr}"
  end
end

In the above example @cust_id, @cust_name, @cust_addr are accessed in another method within the class. But the same thing would not be accessible with local variables.

Search all tables, all columns for a specific value SQL Server

I've just updated my blog post to correct the error in the script that you were having Jeff, you can see the updated script here: Search all fields in SQL Server Database

As requested, here's the script in case you want it but I'd recommend reviewing the blog post as I do update it from time to time

DECLARE @SearchStr nvarchar(100)
SET @SearchStr = '## YOUR STRING HERE ##'
 
 
-- Copyright © 2002 Narayana Vyas Kondreddi. All rights reserved.
-- Purpose: To search all columns of all tables for a given search string
-- Written by: Narayana Vyas Kondreddi
-- Site: http://vyaskn.tripod.com
-- Updated and tested by Tim Gaunt
-- http://www.thesitedoctor.co.uk
-- http://blogs.thesitedoctor.co.uk/tim/2010/02/19/Search+Every+Table+And+Field+In+A+SQL+Server+Database+Updated.aspx
-- Tested on: SQL Server 7.0, SQL Server 2000, SQL Server 2005 and SQL Server 2010
-- Date modified: 03rd March 2011 19:00 GMT
CREATE TABLE #Results (ColumnName nvarchar(370), ColumnValue nvarchar(3630))
 
SET NOCOUNT ON
 
DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110)
SET  @TableName = ''
SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')
 
WHILE @TableName IS NOT NULL
 
BEGIN
    SET @ColumnName = ''
    SET @TableName = 
    (
        SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
        FROM     INFORMATION_SCHEMA.TABLES
        WHERE         TABLE_TYPE = 'BASE TABLE'
            AND    QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
            AND    OBJECTPROPERTY(
                    OBJECT_ID(
                        QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
                         ), 'IsMSShipped'
                           ) = 0
    )
 
    WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
         
    BEGIN
        SET @ColumnName =
        (
            SELECT MIN(QUOTENAME(COLUMN_NAME))
            FROM     INFORMATION_SCHEMA.COLUMNS
            WHERE         TABLE_SCHEMA    = PARSENAME(@TableName, 2)
                AND    TABLE_NAME    = PARSENAME(@TableName, 1)
                AND    DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar', 'int', 'decimal')
                AND    QUOTENAME(COLUMN_NAME) > @ColumnName
        )
 
        IF @ColumnName IS NOT NULL
         
        BEGIN
            INSERT INTO #Results
            EXEC
            (
                'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630) FROM ' + @TableName + ' (NOLOCK) ' +
                ' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
            )
        END
    END   
END
 
SELECT ColumnName, ColumnValue FROM #Results
 
DROP TABLE #Results

Algorithm for solving Sudoku

I know I'm late, but this is my version:

from time import perf_counter

board = [
    [8, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 3, 6, 0, 0, 0, 0, 0],
    [0, 7, 0, 0, 9, 0, 2, 0, 0],
    [0, 5, 0, 0, 0, 7, 0, 0, 0],
    [0, 0, 0, 0, 4, 5, 7, 0, 0],
    [0, 0, 0, 1, 0, 0, 0, 3, 0],
    [0, 0, 1, 0, 0, 0, 0, 6, 8],
    [0, 0, 8, 5, 0, 0, 0, 1, 0],
    [0, 9, 0, 0, 0, 0, 4, 0, 0]
]


def solve(bo):
    find = find_empty(bo)
    if not find:  # if find is None or False
        return True
    else:
        row, col = find

    for num in range(1, 10):
        if valid(bo, num, (row, col)):
            bo[row][col] = num

            if solve(bo):
                return True

            bo[row][col] = 0

    return False


def valid(bo, num, pos):

    # Check row
    for i in range(len(bo[0])):
        if bo[pos[0]][i] == num and pos[1] != i:
            return False

    # Check column
    for i in range(len(bo)):
        if bo[i][pos[1]] == num and pos[0] != i:
            return False

    # Check box
    box_x = pos[1] // 3
    box_y = pos[0] // 3

    for i in range(box_y*3, box_y*3 + 3):
        for j in range(box_x*3, box_x*3 + 3):
            if bo[i][j] == num and (i, j) != pos:
                return False

    return True


def print_board(bo):
    for i in range(len(bo)):
        if i % 3 == 0:
            if i == 0:
                print(" ?-------------------------?")
            else:
                print(" ?-------------------------?")

        for j in range(len(bo[0])):
            if j % 3 == 0:
                print(" ? ", end=" ")

            if j == 8:
                print(bo[i][j], " ?")
            else:
                print(bo[i][j], end=" ")

    print(" ?-------------------------?")


def find_empty(bo):
    for i in range(len(bo)):
        for j in range(len(bo[0])):
            if bo[i][j] == 0:
                return i, j  # row, column

    return None

print('\n--------------------------------------\n')

print('× Unsolved Suduku :-')
print_board(board)

print('\n--------------------------------------\n')

t1 = perf_counter()
solve(board)
t2 = perf_counter()
print('× Solved Suduku :-')
print_board(board)

print('\n--------------------------------------\n')

print(f' TIME TAKEN = {round(t2-t1,3)} SECONDS')

print('\n--------------------------------------\n')

It uses backtracking. But is not coded by me, it's Tech With Tim's. That list contains the world hardest sudoku, and by implementing the timing function, the time is:

===========================
[Finished in 2.838 seconds]
===========================

But with a simple sudoku puzzle like:

board = [
    [7, 8, 0, 4, 0, 0, 1, 2, 0],
    [6, 0, 0, 0, 7, 5, 0, 0, 9],
    [0, 0, 0, 6, 0, 1, 0, 7, 8],
    [0, 0, 7, 0, 4, 0, 2, 6, 0],
    [0, 0, 1, 0, 5, 0, 9, 3, 0],
    [9, 0, 4, 0, 6, 0, 0, 0, 5],
    [0, 7, 0, 3, 0, 0, 0, 1, 2],
    [1, 2, 0, 0, 0, 7, 4, 0, 0],
    [0, 4, 9, 2, 0, 6, 0, 0, 7]
]

The result is :

===========================
[Finished in 0.011 seconds]
===========================

Pretty fast I can say.

Blocking device rotation on mobile web pages

Simple Javascript code to make mobile browser display either in portrait or landscape..

(Even though you have to enter html code twice in the two DIVs (one for each mode), arguably this will load faster than using javascript to change the stylesheet...

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Mobile Device</title>
<script type="text/javascript">
// Detect whether device supports orientationchange event, otherwise fall back to
// the resize event.
var supportsOrientationChange = "onorientationchange" in window,
    orientationEvent = supportsOrientationChange ? "orientationchange" : "resize";

window.addEventListener(orientationEvent, function() {
    if(window.orientation==0)
    {
      document.getElementById('portrait').style.display = '';
      document.getElementById('landscape').style.display = 'none';
    }
    else if(window.orientation==90)
    {
      document.getElementById('portrait').style.display = 'none';
      document.getElementById('landscape').style.display = '';
    }
}, false);
</script>
<meta name="HandheldFriendly" content="true" />
<meta name="viewport" content="width=device-width, height=device-height, user-scalable=no" />
</head>
<body>
<div id="portrait" style="width:100%;height:100%;font-size:20px;">Portrait</div>
<div id="landscape" style="width:100%;height:100%;font-size:20px;">Landscape</div>

<script type="text/javascript">
if(window.orientation==0)
{
  document.getElementById('portrait').style.display = '';
  document.getElementById('landscape').style.display = 'none';
}
else if(window.orientation==90)
{
  document.getElementById('portrait').style.display = 'none';
  document.getElementById('landscape').style.display = '';
}
</script>
</body>
</html>

Tested and works on Android HTC Sense and Apple iPad.

how to release localhost from Error: listen EADDRINUSE

I have solved this issue by adding below in my package.json for killing active PORT - 4000 (in my case) Running on WSL2/Linux/Mac

"scripts": {
    "dev": "nodemon app.js",
    "predev":"fuser -k 4000/tcp && echo 'Terminated' || echo 'Nothing was running on the PORT'",
  }

Source

How can I convert string to datetime with format specification in JavaScript?

Moment.js will handle this:

var momentDate = moment('23.11.2009 12:34:56', 'DD.MM.YYYY HH:mm:ss');
var date = momentDate.;

What is the purpose for using OPTION(MAXDOP 1) in SQL Server?

There are a couple of parallization bugs in SQL server with abnormal input. OPTION(MAXDOP 1) will sidestep them.

EDIT: Old. My testing was done largely on SQL 2005. Most of these seem to not exist anymore, but every once in awhile we question the assumption when SQL 2014 does something dumb and we go back to the old way and it works. We never managed to demonstrate that it wasn't just a bad plan generation on more recent cases though since SQL server can be relied on to get the old way right in newer versions. Since all cases were IO bound queries MAXDOP 1 doesn't hurt.

Remove blank values from array using C#

I prefer to use two options, white spaces and empty:

test = test.Where(x => !string.IsNullOrEmpty(x)).ToArray();
test = test.Where(x => !string.IsNullOrWhiteSpace(x)).ToArray();

ImportError: No module named _ssl

Either install the supplementary packages for python-ssl using your package manager or recompile Python using -with-ssl (requires OpenSSL headers/libs installed).

How is a CRC32 checksum calculated?

In addition to the Wikipedia Cyclic redundancy check and Computation of CRC articles, I found a paper entitled Reversing CRC - Theory and Practice* to be a good reference.

There are essentially three approaches for computing a CRC: an algebraic approach, a bit-oriented approach, and a table-driven approach. In Reversing CRC - Theory and Practice*, each of these three algorithms/approaches is explained in theory accompanied in the APPENDIX by an implementation for the CRC32 in the C programming language.

* PDF Link
Reversing CRC – Theory and Practice.
HU Berlin Public Report
SAR-PR-2006-05
May 2006
Authors:
Martin Stigge, Henryk Plötz, Wolf Müller, Jens-Peter Redlich

python 2 instead of python 3 as the (temporary) default python?

If you have some problems with virtualenv,

You can use it:

sudo ln -sf python2 /usr/bin/python

and

sudo ln -sf python3 /usr/bin/python

About catching ANY exception

Very simple example, similar to the one found here:

http://docs.python.org/tutorial/errors.html#defining-clean-up-actions

If you're attempting to catch ALL exceptions, then put all your code within the "try:" statement, in place of 'print "Performing an action which may throw an exception."'.

try:
    print "Performing an action which may throw an exception."
except Exception, error:
    print "An exception was thrown!"
    print str(error)
else:
    print "Everything looks great!"
finally:
    print "Finally is called directly after executing the try statement whether an exception is thrown or not."

In the above example, you'd see output in this order:

1) Performing an action which may throw an exception.

2) Finally is called directly after executing the try statement whether an exception is thrown or not.

3) "An exception was thrown!" or "Everything looks great!" depending on whether an exception was thrown.

Hope this helps!

Java ByteBuffer to String

the root of this question is how to decode bytes to string?

this can be done with the JAVA NIO CharSet:

public final CharBuffer decode(ByteBuffer bb)

FileChannel channel = FileChannel.open(
  Paths.get("files/text-latin1.txt", StandardOpenOption.READ);
ByteBuffer buffer = ByteBuffer.allocate(1024);
channel.read(buffer);

CharSet latin1 = StandardCharsets.ISO_8859_1;
CharBuffer latin1Buffer = latin1.decode(buffer);

String result = new String(latin1Buffer.array());
  • First we create a channel and read it in a buffer
  • Then decode method decodes a Latin1 buffer to a char buffer
  • We can then put the result, for instance, in a String

How to automatically convert strongly typed enum into int?

Hope this helps you or someone else

enum class EnumClass : int //set size for enum
{
    Zero, One, Two, Three, Four
};

union Union //This will allow us to convert
{
    EnumClass ec;
    int i;
};

int main()
{
using namespace std;

//convert from strongly typed enum to int

Union un2;
un2.ec = EnumClass::Three;

cout << "un2.i = " << un2.i << endl;

//convert from int to strongly typed enum
Union un;
un.i = 0; 

if(un.ec == EnumClass::Zero) cout << "True" << endl;

return 0;
}

Finding the id of a parent div using Jquery

find() and closest() seems slightly slower than:

$(this).parent().attr("id");

pyplot scatter plot marker size

I also attempted to use 'scatter' initially for this purpose. After quite a bit of wasted time - I settled on the following solution.

import matplotlib.pyplot as plt
input_list = [{'x':100,'y':200,'radius':50, 'color':(0.1,0.2,0.3)}]    
output_list = []   
for point in input_list:
    output_list.append(plt.Circle((point['x'], point['y']), point['radius'], color=point['color'], fill=False))
ax = plt.gca(aspect='equal')
ax.cla()
ax.set_xlim((0, 1000))
ax.set_ylim((0, 1000))
for circle in output_list:    
   ax.add_artist(circle)

enter image description here

This is based on an answer to this question

Replace a value in a data frame based on a conditional (`if`) statement

Short answer is:

junk$nm[junk$nm %in% "B"] <- "b"

Take a look at Index vectors in R Introduction (if you don't read it yet).


EDIT. As noticed in comments this solution works for character vectors so fail on your data.

For factor best way is to change level:

levels(junk$nm)[levels(junk$nm)=="B"] <- "b"

How do I import a sql data file into SQL Server?

If your file is a large file, 50MB+, then I recommend you use sqlcmd, the command line utility that comes bundled with SQL Server. It is easy to use and it handles large files well. I tried it yesterday with a 22GB file using the following command:

sqlcmd -S SERVERNAME\INSTANCE_NAME -i C:\path\mysqlfile.sql -o C:\path\output_file.txt

The command above assumes that your server name is SERVERNAME, that you SQL Server installation uses the instance name INSTANCE_NAME, and that windows auth is the default auth method. After execution output.txt will contain something like the following:

...
(1 rows affected)
Processed 100 total records

(1 rows affected)
Processed 200 total records

(1 rows affected)
Processed 300 total records
...

use readfileonline.com if you need to see the contents of huge files.

UPDATE

This link provides more command line options and details such as username and password:

https://dba.stackexchange.com/questions/44101/importing-sql-server-database-from-a-sql-file

How do I pass a command line argument while starting up GDB in Linux?

Try

gdb --args InsertionSortWithErrors arg1toinsort arg2toinsort

Remove Select arrow on IE

I would suggest mine solution that you can find in this GitHub repo. This works also for IE8 and IE9 with a custom arrow that comes from an icon font.

Examples of Custom Cross Browser Drop-down in action: check them with all your browsers to see the cross-browser feature.

Anyway, let's start with the modern browsers and then we will see the solution for the older ones.

Drop-down Arrow for Chrome, Firefox, Opera, Internet Explorer 10+

For these browser, it is easy to set the same background image for the drop-down in order to have the same arrow.

To do so, you have to reset the browser's default style for the select tag and set new background rules (like suggested before).

select {
    /* you should keep these firsts rules in place to maintain cross-browser behaviour */
    -webkit-appearance: none;
    -moz-appearance: none;
    -o-appearance: none;
    appearance: none;
    background-image: url('<custom_arrow_image_url_here>');
    background-position: 98% center;
    background-repeat: no-repeat;
    outline: none;
    ...
}

The appearance rules are set to none to reset browsers default ones, if you want to have the same aspect for each arrow, you should keep them in place.

The background rules in the examples are set with SVG inline images that represent different arrows. They are positioned 98% from left to keep some margin to the right border (you can easily modify the position as you wish).

In order to maintain the correct cross-browser behavior, the only other rule that have to be left in place is the outline. This rule resets the default border that appears (in some browsers) when the element is clicked. All the others rules can be easily modified if needed.

Drop-down Arrow for Internet Explorer 8 (IE8) and Internet Explorer 9 (IE9) using Icon Font

This is the harder part... Or maybe not.

There is no standard rule to hide the default arrows for these browsers (like the select::-ms-expand for IE10+). The solution is to hide the part of the drop-down that contains the default arrow and insert an arrow icon font (or a SVG, if you prefer) similar to the SVG that is used in the other browsers (see the select CSS rule for more details about the inline SVG used).

The very first step is to set a class that can recognize the browser: this is the reason why I have used the conditional IE IFs at the beginning of the code. These IFs are used to attach specific classes to the html tag to recognize the older IE browser.

After that, every select in the HTML have to be wrapped by a div (or whatever tag that can wraps an element). At this wrapper just add the class that contains the icon font.

<div class="selectTagWrapper prefix-icon-arrow-down-fill">
    ...
</div>

In easy words, this wrapper is used to simulate the select tag.

To act like a drop-down, the wrapper must have a border, because we hide the one that comes from the select.

Notice that we cannot use the select border because we have to hide the default arrow lengthening it 25% more than the wrapper. Consequently its right border should not be visible because we hide this 25% more by the overflow: hidden rule applied to the select itself.

The custom arrow icon-font is placed in the pseudo class :before where the rule content contains the reference for the arrow (in this case it is a right parenthesis).

We also place this arrow in an absolute position to center it as much as possible (if you use different icon fonts, remember to adjust them opportunely by changing top and left values and the font size).

.ie8 .prefix-icon-arrow-down-fill:before,
.ie9 .prefix-icon-arrow-down-fill:before {
    content: ")";
    position: absolute;
    top: 43%;
    left: 93%;
    font-size: 6px;
    ...
}

You can easily create and substitute the background arrow or the icon font arrow, with every one that you want simply changing it in the background-image rule or making a new icon font file by yourself.

How should I multiple insert multiple records?

If I were you I would not use either of them.

The disadvantage of the first one is that the parameter names might collide if there are same values in the list.

The disadvantage of the second one is that you are creating command and parameters for each entity.

The best way is to have the command text and parameters constructed once (use Parameters.Add to add the parameters) change their values in the loop and execute the command. That way the statement will be prepared only once. You should also open the connection before you start the loop and close it after it.

How to See the Contents of Windows library (*.lib)

DUMPBIN /EXPORTS Will get most of that information and hitting MSDN will get the rest.

Get one of the Visual Studio packages; C++

How to view unallocated free space on a hard disk through terminal

If you need to see your partitions and/or filers with available space, mentioned utilities are what you need. You just need to use options.

For instance: df -h will print you those information in "human-readable" form. If you need information only about free space, you could use: df -h | awk '{print $1" "$4}'.

Troubleshooting misplaced .git directory (nothing to commit)

if .git is already there in your dir, then follow:

  1. rm -rf .git/
  2. git init
  3. git remote add origin http://xyzremotedir/xyzgitproject.git
  4. git commit -m "do commit"
  5. git push origin master

Programmatically navigate using react router V4

I think that @rgommezz covers most of the cases minus one that I think it's quite important.

// history is already a dependency or React Router, but if don't have it then try npm install save-dev history

import createHistory from "history/createBrowserHistory"

// in your function then call add the below 
const history = createHistory();
// Use push, replace, and go to navigate around.
history.push("/home");

This allows me to write a simple service with actions/calls that I can call to do the navigation from any component I want without doing a lot HoC on my components...

It is not clear why nobody has provided this solution before. I hope it helps, and if you see any issue with it please let me know.

How to use Microsoft.Office.Interop.Excel on a machine without installed MS Office?

You can't use Microsoft.Office.Interop.Excel without having ms office installed.

Just search in google for some libraries, which allows to modify xls or xlsx:

How to redirect a page using onclick event in php?

Please try this

    <input type="button" value="Home" class="homebutton" id="btnHome" onClick="Javascript:window.location.href = 'http://www.website.com/index.php';" />

window.location.href example:

 window.location.href = 'http://www.google.com'; //Will take you to Google.

window.open() example:

     window.open('http://www.google.com'); //This will open Google in a new window.

How to enable assembly bind failure logging (Fusion) in .NET

Instead of using a ugly log file, you can also activate Fusion log via ETW/xperf by turning on the DotnetRuntime Private provider (Microsoft-Windows-DotNETRuntimePrivate) with GUID 763FD754-7086-4DFE-95EB-C01A46FAF4CA and the FusionKeyword keyword (0x4) on.

@echo off
echo Press a key when ready to start...
pause
echo .
echo ...Capturing...
echo .

"C:\Program Files (x86)\Windows Kits\8.1\Windows Performance Toolkit\xperf.exe" -on PROC_THREAD+LOADER+PROFILE -stackwalk Profile -buffersize 1024 -MaxFile 2048 -FileMode Circular -f Kernel.etl
"C:\Program Files (x86)\Windows Kits\8.1\Windows Performance Toolkit\xperf.exe" -start ClrSession -on Microsoft-Windows-DotNETRuntime:0x8118:0x5:'stack'+763FD754-7086-4DFE-95EB-C01A46FAF4CA:0x4:0x5 -f clr.etl -buffersize 1024

echo Press a key when you want to stop...
pause
pause
echo .
echo ...Stopping...
echo .

"C:\Program Files (x86)\Windows Kits\8.1\Windows Performance Toolkit\xperf.exe" -start ClrRundownSession -on Microsoft-Windows-DotNETRuntime:0x8118:0x5:'stack'+Microsoft-Windows-DotNETRuntimeRundown:0x118:0x5:'stack' -f clr_DCend.etl -buffersize 1024 

timeout /t 15

set XPERF_CreateNGenPdbs=1

"C:\Program Files (x86)\Windows Kits\8.1\Windows Performance Toolkit\xperf.exe" -stop ClrSession ClrRundownSession 
"C:\Program Files (x86)\Windows Kits\8.1\Windows Performance Toolkit\xperf.exe" -stop
"C:\Program Files (x86)\Windows Kits\8.1\Windows Performance Toolkit\xperf.exe" -merge kernel.etl clr.etl clr_DCend.etl Result.etl -compress
del kernel.etl
del clr.etl
del clr_DCend.etl

When you now open the ETL file in PerfView and look under the Events table, you can find the Fusion data:

Fusion events in PerfView