Programs & Examples On #Tf idf

“Term-frequency ⨉ Inverse Document Frequency”, or “tf-idf”, measures how important a word is to a document in a collection or corpus.

Python: tf-idf-cosine: to find document similarity

Here is a function that compares your test data against the training data, with the Tf-Idf transformer fitted with the training data. Advantage is that you can quickly pivot or group by to find the n closest elements, and that the calculations are down matrix-wise.

def create_tokenizer_score(new_series, train_series, tokenizer):
    """
    return the tf idf score of each possible pairs of documents
    Args:
        new_series (pd.Series): new data (To compare against train data)
        train_series (pd.Series): train data (To fit the tf-idf transformer)
    Returns:
        pd.DataFrame
    """

    train_tfidf = tokenizer.fit_transform(train_series)
    new_tfidf = tokenizer.transform(new_series)
    X = pd.DataFrame(cosine_similarity(new_tfidf, train_tfidf), columns=train_series.index)
    X['ix_new'] = new_series.index
    score = pd.melt(
        X,
        id_vars='ix_new',
        var_name='ix_train',
        value_name='score'
    )
    return score

train_set = pd.Series(["The sky is blue.", "The sun is bright."])
test_set = pd.Series(["The sun in the sky is bright."])
tokenizer = TfidfVectorizer() # initiate here your own tokenizer (TfidfVectorizer, CountVectorizer, with stopwords...)
score = create_tokenizer_score(train_series=train_set, new_series=test_set, tokenizer=tokenizer)
score

   ix_new   ix_train    score
0   0       0       0.617034
1   0       1       0.862012

Disable Input fields in reactive form

setTimeout(() => { emailGroup.disable(); });

Is there a SELECT ... INTO OUTFILE equivalent in SQL Server Management Studio?

In SSMS, "Query" menu item... "Results to"... "Results to File"

Shortcut = CTRL+shift+F

You can set it globally too

"Tools"... "Options"... "Query Results"... "SQL Server".. "Default destination" drop down

Edit: after comment

In SSMS, "Query" menu item... "SQLCMD" mode

This allows you to run "command line" like actions.

A quick test in my SSMS 2008

:OUT c:\foo.txt
SELECT * FROM sys.objects

Edit, Sep 2012

:OUT c:\foo.txt
SET NOCOUNT ON;SELECT * FROM sys.objects

Angularjs loading screen on ajax request

I use ngProgress for this.

Add 'ngProgress' to your dependencies once you've included the script/css files in your HTML. Once you do that you can set up something like this, which will trigger when a route change was detected.

angular.module('app').run(function($rootScope, ngProgress) {
  $rootScope.$on('$routeChangeStart', function(ev,data) {
    ngProgress.start();
  });
  $rootScope.$on('$routeChangeSuccess', function(ev,data) {
    ngProgress.complete();
  });
});

For AJAX requests you can do something like this:

$scope.getLatest = function () {
    ngProgress.start();

    $http.get('/latest-goodies')
         .success(function(data,status) {
             $scope.latest = data;
             ngProgress.complete();
         })
         .error(function(data,status) {
             ngProgress.complete();
         });
};

Just remember to add 'ngProgress' to the controllers dependencies before doing so. And if you are doing multiple AJAX requests use an incremental variable in the main app scope to keep track when your AJAX requests have finished before calling 'ngProgress.complete();'.

How do I capture SIGINT in Python?

And as a context manager:

import signal

class GracefulInterruptHandler(object):

    def __init__(self, sig=signal.SIGINT):
        self.sig = sig

    def __enter__(self):

        self.interrupted = False
        self.released = False

        self.original_handler = signal.getsignal(self.sig)

        def handler(signum, frame):
            self.release()
            self.interrupted = True

        signal.signal(self.sig, handler)

        return self

    def __exit__(self, type, value, tb):
        self.release()

    def release(self):

        if self.released:
            return False

        signal.signal(self.sig, self.original_handler)

        self.released = True

        return True

To use:

with GracefulInterruptHandler() as h:
    for i in xrange(1000):
        print "..."
        time.sleep(1)
        if h.interrupted:
            print "interrupted!"
            time.sleep(2)
            break

Nested handlers:

with GracefulInterruptHandler() as h1:
    while True:
        print "(1)..."
        time.sleep(1)
        with GracefulInterruptHandler() as h2:
            while True:
                print "\t(2)..."
                time.sleep(1)
                if h2.interrupted:
                    print "\t(2) interrupted!"
                    time.sleep(2)
                    break
        if h1.interrupted:
            print "(1) interrupted!"
            time.sleep(2)
            break

From here: https://gist.github.com/2907502

How do I get a reference to the app delegate in Swift?

SWIFT < 3

Create a method in AppDelegate Class for ex

func sharedInstance() -> AppDelegate{
        return UIApplication.sharedApplication().delegate as! AppDelegate
    }

and call it some where else for ex

let appDelegate : AppDelegate = AppDelegate().sharedInstance()

SWIFT >= 3.0

func sharedInstance() -> AppDelegate{
    return UIApplication.shared.delegate as! AppDelegate
}

How to add subject alernative name to ssl certs?

Both IP and DNS can be specified with the keytool additional argument -ext SAN=dns:abc.com,ip:1.1.1.1

Example:

keytool -genkeypair -keystore <keystore> -dname "CN=test, OU=Unknown, O=Unknown, L=Unknown, ST=Unknown, C=Unknown" -keypass <keypwd> -storepass <storepass> -keyalg RSA -alias unknown -ext SAN=dns:test.abc.com,ip:1.1.1.1

How to disable JavaScript in Chrome Developer Tools?

chrome://settings/content Javascript/Manage Exceptions

How can foreign key constraints be temporarily disabled using T-SQL?

WITH CHECK CHECK is almost certainly required!

This point was raised in some of the answers and comments but I feel that it is important enough to call it out again.

Re-enabling a constraint using the following command (no WITH CHECK) will have some serious drawbacks.

ALTER TABLE MyTable CHECK CONSTRAINT MyConstraint;

WITH CHECK | WITH NOCHECK

Specifies whether the data in the table is or is not validated against a newly added or re-enabled FOREIGN KEY or CHECK constraint. If not specified, WITH CHECK is assumed for new constraints, and WITH NOCHECK is assumed for re-enabled constraints.

If you do not want to verify new CHECK or FOREIGN KEY constraints against existing data, use WITH NOCHECK. We do not recommend doing this, except in rare cases. The new constraint will be evaluated in all later data updates. Any constraint violations that are suppressed by WITH NOCHECK when the constraint is added may cause future updates to fail if they update rows with data that does not comply with the constraint.

The query optimizer does not consider constraints that are defined WITH NOCHECK. Such constraints are ignored until they are re-enabled by using ALTER TABLE table WITH CHECK CHECK CONSTRAINT ALL.

Note: WITH NOCHECK is the default for re-enabling constraints. I have to wonder why...

  1. No existing data in the table will be evaluated during the execution of this command - successful completion is no guarantee that the data in the table is valid according to the constraint.
  2. During the next update of the invalid records, the constraint will be evaluated and will fail - resulting in errors that may be unrelated to the actual update that is made.
  3. Application logic that relies on the constraint to ensure that data is valid may fail.
  4. The query optimizer will not make use of any constraint that is enabled in this way.

The sys.foreign_keys system view provides some visibility into the issue. Note that it has both an is_disabled and an is_not_trusted column. is_disabled indicates whether future data manipulation operations will be validated against the constraint. is_not_trusted indicates whether all of the data currently in the table has been validated against the constraint.

ALTER TABLE MyTable WITH CHECK CHECK CONSTRAINT MyConstraint;

Are your constraints to be trusted? Find out...

SELECT * FROM sys.foreign_keys WHERE is_not_trusted = 1;

Create an Oracle function that returns a table

I think you want a pipelined table function.

Something like this:

CREATE OR REPLACE PACKAGE test AS

    TYPE measure_record IS RECORD(
       l4_id VARCHAR2(50), 
       l6_id VARCHAR2(50), 
       l8_id VARCHAR2(50), 
       year NUMBER, 
       period NUMBER,
       VALUE NUMBER);

    TYPE measure_table IS TABLE OF measure_record;

    FUNCTION get_ups(foo NUMBER)
        RETURN measure_table
        PIPELINED;
END;

CREATE OR REPLACE PACKAGE BODY test AS

    FUNCTION get_ups(foo number)
        RETURN measure_table
        PIPELINED IS

        rec            measure_record;

    BEGIN
        SELECT 'foo', 'bar', 'baz', 2010, 5, 13
          INTO rec
          FROM DUAL;

        -- you would usually have a cursor and a loop here   
        PIPE ROW (rec);

        RETURN;
    END get_ups;
END;

For simplicity I removed your parameters and didn't implement a loop in the function, but you can see the principle.

Usage:

SELECT *
  FROM table(test.get_ups(0));



L4_ID L6_ID L8_ID       YEAR     PERIOD      VALUE
----- ----- ----- ---------- ---------- ----------
foo   bar   baz         2010          5         13
1 row selected.

How do I find the authoritative name-server for a domain name?

You'll want the SOA (Start of Authority) record for a given domain name, and this is how you accomplish it using the universally available nslookup command line tool:

command line> nslookup
> set querytype=soa
> stackoverflow.com
Server:         217.30.180.230
Address:        217.30.180.230#53

Non-authoritative answer:
stackoverflow.com
        origin = ns51.domaincontrol.com # ("primary name server" on Windows)
        mail addr = dns.jomax.net       # ("responsible mail addr" on Windows)
        serial = 2008041300
        refresh = 28800
        retry = 7200
        expire = 604800
        minimum = 86400
Authoritative answers can be found from:
stackoverflow.com       nameserver = ns52.domaincontrol.com.
stackoverflow.com       nameserver = ns51.domaincontrol.com.

The origin (or primary name server on Windows) line tells you that ns51.domaincontrol is the main name server for stackoverflow.com.

At the end of output all authoritative servers, including backup servers for the given domain, are listed.

How to disable the ability to select in a DataGridView?

Use the DataGridView.ReadOnly property

The code in the MSDN example illustrates the use of this property in a DataGridView control intended primarily for display. In this example, the visual appearance of the control is customized in several ways and the control is configured for limited interactivity.

Observe these settings in the sample code:

// Set property values appropriate for read-only
// display and limited interactivity
dataGridView1.AllowUserToAddRows = false;
dataGridView1.AllowUserToDeleteRows = false;
dataGridView1.AllowUserToOrderColumns = true;
dataGridView1.ReadOnly = true;
dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
dataGridView1.MultiSelect = false;
dataGridView1.AutoSizeRowsMode = DataGridViewAutoSizeRowsMode.None;
dataGridView1.AllowUserToResizeColumns = false;
dataGridView1.ColumnHeadersHeightSizeMode = 
DataGridViewColumnHeadersHeightSizeMode.DisableResizing;
dataGridView1.AllowUserToResizeRows = false;
dataGridView1.RowHeadersWidthSizeMode = 
DataGridViewRowHeadersWidthSizeMode.DisableResizing;

Is there a developers api for craigslist.org

The closest I have been able to find is called 3taps. 3taps was sued by Craigslist with the result that "access to public data on a public website can be selectively censored by blacklisting certain viewers (i.e. competitors)", and thus states that "3taps will therefore access the very same data exclusively from public sources that retain open and equal access rights to public data".

How to convert datatype:object to float64 in python?

convert_objects is deprecated.

For pandas >= 0.17.0, use pd.to_numeric

df["2nd"] = pd.to_numeric(df["2nd"])

CSS to line break before/after a particular `inline-block` item

I've been able to make it work on inline LI elements. Unfortunately, it does not work if the LI elements are inline-block:

Live demo: http://jsfiddle.net/dWkdp/

Or the cliff notes version:

li { 
     display: inline; 
}
li:nth-child(3):after { 
     content: "\A";
     white-space: pre; 
}

Deleting all records in a database table

If you are looking for a way to it without SQL you should be able to use delete_all.

Post.delete_all

or with a criteria

Post.delete_all "person_id = 5 AND (category = 'Something' OR category = 'Else')"

See here for more information.

The records are deleted without loading them first which makes it very fast but will break functionality like counter cache that depends on rails code to be executed upon deletion.

How can I remove non-ASCII characters but leave periods and spaces using Python?

You may use the following code to remove non-English letters:

import re
str = "123456790 ABC#%? .(???)"
result = re.sub(r'[^\x00-\x7f]',r'', str)
print(result)

This will return

123456790 ABC#%? .()

What are the main performance differences between varchar and nvarchar SQL Server data types?

Disk space is not the issue... but memory and performance will be. Double the page reads, double index size, strange LIKE and = constant behaviour etc

Do you need to store Chinese etc script? Yes or no...

And from MS BOL "Storage and Performance Effects of Unicode"

Edit:

Recent SO question highlighting how bad nvarchar performance can be...

SQL Server uses high CPU when searching inside nvarchar strings

android TextView: setting the background color dynamically doesn't work

tv.setTextColor(getResources().getColor(R.color.solid_red));

Selenium Webdriver: Entering text into text field

Use this code.

driver.FindElement(By.XPath(".//[@id='header']/div/div[3]/div/form/input[1]")).SendKeys("25025");

Is there a constraint that restricts my generic method to numeric types?

I was wondering the same as samjudson, why only to integers? and if that is the case, you might want to create a helper class or something like that to hold all the types you want.

If all you want are integers, don't use a generic, that is not generic; or better yet, reject any other type by checking its type.

SQL: Alias Column Name for Use in CASE Statement

SELECT
    a AS [blabla a],
    b [blabla b],
    CASE c
        WHEN 1 THEN 'aaa'
        WHEN 2 THEN 'bbb'
        ELSE 'unknown' 
    END AS [my alias], 
    d AS [blabla d]
FROM mytable

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

Previous answers don't account for the fact that you've overloaded the equals operator and are using that to test for the sought element. In that case, your code would look like this:

list.Find(x => x == objectToFind);

Or, if you don't like lambda syntax, and have overriden object.Equals(object) or have implemented IEquatable<T>, you could do this:

list.Find(objectToFind.Equals);

Changing width property of a :before css selector using JQuery

You may try to inherit property from the base class:

_x000D_
_x000D_
var width = 2;_x000D_
var interval = setInterval(function () {_x000D_
    var element = document.getElementById('box');_x000D_
    width += 0.0625;_x000D_
    element.style.width = width + 'em';_x000D_
    if (width >= 7) clearInterval(interval);_x000D_
}, 50);
_x000D_
.box {_x000D_
    /* Set property */_x000D_
    width:4em;_x000D_
    height:2em;_x000D_
    background-color:#d42;_x000D_
    position:relative;_x000D_
}_x000D_
.box:after {_x000D_
    /* Inherit property */_x000D_
    width:inherit;_x000D_
    content:"";_x000D_
    height:1em;_x000D_
    background-color:#2b4;_x000D_
    position:absolute;_x000D_
    top:100%;_x000D_
}
_x000D_
<div id="box" class="box"></div>
_x000D_
_x000D_
_x000D_

How to display div after click the button in Javascript?

<script type="text/javascript">
function showDiv(toggle){
document.getElementById(toggle).style.display = 'block';
}
</script>

<input type="button" name="answer" onclick="showDiv('toggle')">Show</input>

<div id="toggle" style="display:none">Hello</div>

Could not resolve all dependencies for configuration ':classpath'

Find and Replace:

jcenter()
maven {
    url "https://maven.google.com"
}

to:

maven {
    url "https://maven.google.com"
}
jcenter()

how to call javascript function in html.actionlink in asp.net mvc?

For calling javascript in your action link you simply need to write actionlink like this:

@Html.ActionLink("Delete", "Your-Action", new { id = item.id },
                 new { onclick="return confirm('Are you sure?');"})

Don't get confused between route values and the html attributes.

Is there Unicode glyph Symbol to represent "Search"

You can simply add this CSS to your header

<link href='http://netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css' rel='stylesheet' type='text/css'>

next add this code in place where you want to display a glyph symbol.

<div class="fa fa-search"></div> <!-- smaller -->
<div class="fa fa-search fa-2x"></div> <!-- bigger -->

Have fun.

java - path to trustStore - set property doesn't work?

Looks like you have a typo -- "trustStrore" should be "trustStore", i.e.

System.setProperty("javax.net.ssl.trustStrore", "cacerts.jks");

should be:

System.setProperty("javax.net.ssl.trustStore", "cacerts.jks");

Kotlin Android start new Activity

To start a new Activity ,

startActivity(Intent(this@CurrentClassName,RequiredClassName::class.java)

So change your code to :

class MainActivity : AppCompatActivity() {

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

    fun buTestUpdateText2 (view: View) {
        startActivity(Intent(this@MainActivity,ClassName::class.java))

        // Also like this 

        val intent = Intent(this@MainActivity,ClassName::class.java)
        startActivity(intent)
    }

Run an exe from C# code

using System.Diagnostics;

class Program
{
    static void Main()
    {
        Process.Start("C:\\");
    }
}

If your application needs cmd arguments, use something like this:

using System.Diagnostics;

class Program
{
    static void Main()
    {
        LaunchCommandLineApp();
    }

    /// <summary>
    /// Launch the application with some options set.
    /// </summary>
    static void LaunchCommandLineApp()
    {
        // For the example
        const string ex1 = "C:\\";
        const string ex2 = "C:\\Dir";

        // Use ProcessStartInfo class
        ProcessStartInfo startInfo = new ProcessStartInfo();
        startInfo.CreateNoWindow = false;
        startInfo.UseShellExecute = false;
        startInfo.FileName = "dcm2jpg.exe";
        startInfo.WindowStyle = ProcessWindowStyle.Hidden;
        startInfo.Arguments = "-f j -o \"" + ex1 + "\" -z 1.0 -s y " + ex2;

        try
        {
            // Start the process with the info we specified.
            // Call WaitForExit and then the using statement will close.
            using (Process exeProcess = Process.Start(startInfo))
            {
                exeProcess.WaitForExit();
            }
        }
        catch
        {
             // Log error.
        }
    }
}

How do I disable a jquery-ui draggable?

In the case of a dialog, it has a property called draggable, set it to false.

$("#yourDialog").dialog({
    draggable: false
});

Eventhough the question is old, i tried the proposed solution and it did not work for the dialog. Hope this may help others like me.

How do I toggle an ng-show in AngularJS based on a boolean?

If you have multiple Menus with Submenus, then you can go with the below solution.

HTML

          <ul class="sidebar-menu" id="nav-accordion">
             <li class="sub-menu">
                  <a href="" ng-click="hasSubMenu('dashboard')">
                      <i class="fa fa-book"></i>
                      <span>Dashboard</span>
                      <i class="fa fa-angle-right pull-right"></i>
                  </a>
                  <ul class="sub" ng-show="showDash">
                      <li><a ng-class="{ active: isActive('/dashboard/loan')}" href="#/dashboard/loan">Loan</a></li>
                      <li><a ng-class="{ active: isActive('/dashboard/recovery')}" href="#/dashboard/recovery">Recovery</a></li>
                  </ul>
              </li>
              <li class="sub-menu">
                  <a href="" ng-click="hasSubMenu('customerCare')">
                      <i class="fa fa-book"></i>
                      <span>Customer Care</span>
                      <i class="fa fa-angle-right pull-right"></i>
                  </a>
                  <ul class="sub" ng-show="showCC">
                      <li><a ng-class="{ active: isActive('/customerCare/eligibility')}" href="#/CC/eligibility">Eligibility</a></li>
                      <li><a ng-class="{ active: isActive('/customerCare/transaction')}" href="#/CC/transaction">Transaction</a></li>
                  </ul>
              </li>
          </ul>

There are two functions i have called first is ng-click = hasSubMenu('dashboard'). This function will be used to toggle the menu and it is explained in the code below. The ng-class="{ active: isActive('/customerCare/transaction')} it will add a class active to the current menu item.

Now i have defined some functions in my app:

First, add a dependency $rootScope which is used to declare variables and functions. To learn more about $roootScope refer to the link : https://docs.angularjs.org/api/ng/service/$rootScope

Here is my app file:

 $rootScope.isActive = function (viewLocation) { 
                return viewLocation === $location.path();
        };

The above function is used to add active class to the current menu item.

        $rootScope.showDash = false;
        $rootScope.showCC = false;

        var location = $location.url().split('/');

        if(location[1] == 'customerCare'){
            $rootScope.showCC = true;
        }
        else if(location[1]=='dashboard'){
            $rootScope.showDash = true;
        }

        $rootScope.hasSubMenu = function(menuType){
            if(menuType=='dashboard'){
                $rootScope.showCC = false;
                $rootScope.showDash = $rootScope.showDash === false ? true: false;
            }
            else if(menuType=='customerCare'){
                $rootScope.showDash = false;
                $rootScope.showCC = $rootScope.showCC === false ? true: false;
            }
        }

By default $rootScope.showDash and $rootScope.showCC are set to false. It will set the menus to closed when page is initially loaded. If you have more than two submenus add accordingly.

hasSubMenu() function will work for toggling between the menus. I have added a small condition

if(location[1] == 'customerCare'){
                $rootScope.showCC = true;
            }
            else if(location[1]=='dashboard'){
                $rootScope.showDash = true;
            }

it will remain the submenu open after reloading the page according to selected menu item.

I have defined my pages like:

$routeProvider
        .when('/dasboard/loan', {
            controller: 'LoanController',
            templateUrl: './views/loan/view.html',
            controllerAs: 'vm'
        })

You can use isActive() function only if you have a single menu without submenu. You can modify the code according to your requirement. Hope this will help. Have a great day :)

Is there a "not equal" operator in Python?

There are two operators in Python for the "not equal" condition -

a.) != If values of the two operands are not equal, then the condition becomes true. (a != b) is true.

b.) <> If values of the two operands are not equal, then the condition becomes true. (a <> b) is true. This is similar to the != operator.

Find and replace entire mysql database

Simple Soltion

UPDATE `table_name`
 SET `field_name` = replace(same_field_name, 'unwanted_text', 'wanted_text')

HttpContext.Current.Request.Url.Host what it returns?

Yes, as long as the url you type into the browser www.someshopping.com and you aren't using url rewriting then

string currentURL = HttpContext.Current.Request.Url.Host;

will return www.someshopping.com

Note the difference between a local debugging environment and a production environment

How to set Linux environment variables with Ansible

I did not have enough reputation to comment and hence am adding a new answer.
Gasek answer is quite correct. Just one thing: if you are updating the .bash_profile file or the /etc/profile, those changes would be reflected only after you do a new login. In case you want to set the env variable and then use it in subsequent tasks in the same playbook, consider adding those environment variables in the .bashrc file.
I guess the reason behind this is the login and the non-login shells.
Ansible, while executing different tasks, reads the parameters from a .bashrc file instead of the .bash_profile or the /etc/profile.

As an example, if I updated my path variable to include the custom binary in the .bash_profile file of the respective user and then did a source of the file. The next subsequent tasks won't recognize my command. However if you update in the .bashrc file, the command would work.

 - name: Adding the path in the bashrc files
   lineinfile: dest=/root/.bashrc line='export PATH=$PATH:path-to-mysql/bin' insertafter='EOF' regexp='export PATH=\$PATH:path-to-mysql/bin' state=present
 
-  - name: Source the bashrc file
   shell: source /root/.bashrc

 - name: Start the mysql client
   shell: mysql -e "show databases";

This would work, but had I done it using profile files the mysql -e "show databases" would have given an error.

- name: Adding the path in the Profile files
   lineinfile: dest=/root/.bash_profile line='export PATH=$PATH:{{install_path}}/{{mysql_folder_name}}/bin' insertafter='EOF' regexp='export PATH=\$PATH:{{install_path}}/{{mysql_folder_name}}/bin' state=present

 - name: Source the bash_profile file
   shell: source /root/.bash_profile

 - name: Start the mysql client
   shell: mysql -e "show databases";

This one won't work, if we have all these tasks in the same playbook.

Pandas conditional creation of a series/dataframe column

Here's yet another way to skin this cat, using a dictionary to map new values onto the keys in the list:

def map_values(row, values_dict):
    return values_dict[row]

values_dict = {'A': 1, 'B': 2, 'C': 3, 'D': 4}

df = pd.DataFrame({'INDICATOR': ['A', 'B', 'C', 'D'], 'VALUE': [10, 9, 8, 7]})

df['NEW_VALUE'] = df['INDICATOR'].apply(map_values, args = (values_dict,))

What's it look like:

df
Out[2]: 
  INDICATOR  VALUE  NEW_VALUE
0         A     10          1
1         B      9          2
2         C      8          3
3         D      7          4

This approach can be very powerful when you have many ifelse-type statements to make (i.e. many unique values to replace).

And of course you could always do this:

df['NEW_VALUE'] = df['INDICATOR'].map(values_dict)

But that approach is more than three times as slow as the apply approach from above, on my machine.

And you could also do this, using dict.get:

df['NEW_VALUE'] = [values_dict.get(v, None) for v in df['INDICATOR']]

How can I remove "\r\n" from a string in C#? Can I use a regular expression?

This splits the string on any combo of new line characters and joins them with a space, assuming you actually do want the space where the new lines would have been.

var oldString = "the quick brown\rfox jumped over\nthe box\r\nand landed on some rocks.";
var newString = string.Join(" ", Regex.Split(oldString, @"(?:\r\n|\n|\r)"));
Console.Write(newString);

// prints:
// the quick brown fox jumped over the box and landed on some rocks.

Correct redirect URI for Google API and OAuth 2.0

There's no problem with using a localhost url for Dev work - obviously it needs to be changed when it comes to production.

You need to go here: https://developers.google.com/accounts/docs/OAuth2 and then follow the link for the API Console - link's in the Basic Steps section. When you've filled out the new application form you'll be asked to provide a redirect Url. Put in the page you want to go to once access has been granted.

When forming the Google oAuth Url - you need to include the redirect url - it has to be an exact match or you'll have problems. It also needs to be UrlEncoded.

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

If you are trying to load a cert from a .pfx file in IIS the solution may be as simple as enabling this option for the Application Pool.

Right click on the App Pool and select Advanced Settings.

Then enable Load User Profile


enter image description here

Open a folder using Process.Start

Does it open correctly when you run "explorer.exe c:\teste" from your start menu? How long have you been trying this? I see a similar behavior when my machine has a lot of processes and when I open a new process(sets say IE)..it starts in the task manager but does not show up in the front end. Have you tried a restart?

The following code should open a new explorer instance

class sample{

static void Main()
{
  System.Diagnostics.Process.Start("explorer.exe",@"c:\teste");
}
}

How can I escape latex code received through user input?

Python’s raw strings are just a way to tell the Python interpreter that it should interpret backslashes as literal slashes. If you read strings entered by the user, they are already past the point where they could have been raw. Also, user input is most likely read in literally, i.e. “raw”.

This means the interpreting happens somewhere else. But if you know that it happens, why not escape the backslashes for whatever is interpreting it?

s = s.replace("\\", "\\\\")

(Note that you can't do r"\" as “a raw string cannot end in a single backslash”, but I could have used r"\\" as well for the second argument.)

If that doesn’t work, your user input is for some arcane reason interpreting the backslashes, so you’ll need a way to tell it to stop that.

Reset Windows Activation/Remove license key

On Windows XP -

  1. Reboot into "Safe mode with Command Prompt"
  2. Type "explorer" in the command prompt that comes up and push [Enter]
  3. Click on Start>Run, and type the following :

    rundll32.exe syssetup,SetupOobeBnk

Reboot, and login as normal.

This will reset the 30 day timer for activation back to 30 days so you can enter in the key normally.

Safely turning a JSON string into an object

You also can use reviver function to filter.

var data = JSON.parse(jsonString, function reviver(key, value) {
   //your code here to filter
});

For more information read JSON.parse.

OpenSSL: PEM routines:PEM_read_bio:no start line:pem_lib.c:703:Expecting: TRUSTED CERTIFICATE

Another possible cause of this is trying to use the ;x509; module on something that is not X.509.

The server certificate is X.509 format, but the private key is RSA.

So:

openssl rsa -noout -text -in privkey.pem
openssl x509 -noout -text -in servercert.pem

Cannot install Aptana Studio 3.6 on Windows

It seems having msysgit (Git for Windows) installed is causing the problem.

In most cases you'll have a pretty recent version of Git for Windows installed. Cited from https://code.google.com/p/tortoisegit/:

There was a security issue in Git, see here. Git for Windows < 1.9.5 is affected - so you should update, TortoiseGit itself is not affected (using the default configuration; only if libgit2 is manually enabled for checkout/fetching). TortoiseGit 1.8.13.0 includes all fixes.

But it seems Aptana Studio Installer won't accept any pre-installed version of Git for Windows!

What you need to do:

  1. Uninstall Git for Windows.
  2. Install Aptana Studio.
    Apanta Studio 3.6.1 will install Git for Windows 1.8.4-preview20130916.
  3. Download latest version of Git for Windows from http://msysgit.github.io/.
  4. Install latest version of Git for Windows.
    The outdated Git for Windows 1.8.4-preview20130916 will be updated to recent version.

That's it !!!

How to delete all rows from all tables in a SQL Server database?

--Load tables to delete from
SELECT 
DISTINCT
' Delete top 1000000 from <DBName>.<schema>.' + c.TABLE_NAME + ' WHERE <Filter Clause Here>' AS query,c.TABLE_NAME AS TableName, IsDeleted=0, '<InsertSomeDescriptorHere>' AS [Source]--,t.TABLE_TYPE, c.*
            INTO dbo.AllTablesToDeleteFrom
            FROM INFORMATION_SCHEMA.TABLES AS t
            INNER JOIN information_schema.columns c ON c.TABLE_NAME = t.TABLE_NAME 
    WHERE c.COLUMN_NAME = '<column name>'
           AND c.TABLE_SCHEMA = 'dbo'
           AND c.TABLE_CATALOG = '<DB Name here>'
           AND t.TABLE_TYPE='Base table'
           --AND t.TABLE_NAME LIKE '<put filter here>'

            DECLARE @TableSelect NVARCHAR(1000)= '';
            DECLARE @Table NVARCHAR(1000)= '';
            DECLARE @IsDeleted INT= 0;
            DECLARE @NumRows INT = 1000000;
            DECLARE @Source NVARCHAR(50)='';


            WHILE ( @IsDeleted = 0 )
                BEGIN
                --This grabs one table at a time to be deleted from. @TableSelect has the sql to execute. it is important to order by IsDeleted ASC
                --because it will pull tables to delete from by those that have a 0=IsDeleted first. Once the loop grabs a table with IsDeleted=1 then this will pop out of loop

                    SELECT TOP 1
                            @TableSelect = query,
                            @IsDeleted = IsDeleted,
                            @Table = TableName,
                            @Source=[a].[Source]
                    FROM    dbo.AllTablesToDeleteFrom a
                    WHERE a.[Source]='SomeDescriptorHere'--use only if needed
                    ORDER BY a.IsDeleted ASC;--this is required because only those records returned with IsDeleted=0 will run through loop

                    --SELECT  @Table; can add this in to  monitor what table is being deleted from

                    WHILE ( @NumRows = 1000000 )--only delete a million rows at a time?

                    BEGIN 
                    EXEC sp_executesql @TableSelect;
                    SET @NumRows = @@ROWCOUNT;
                    --IF @NumRows = 1000000 --can do something here if needed
                    --One wants this loop to continue as long as a million rows is deleted. Once < 1 million rows is deleted it pops out of loop
                    --and grabs next table to delete
                    --    BEGIN
                    --SELECT  @NumRows;--can add this in to see current number of deleted records for table
                            INSERT  INTO dbo.DeleteFromAllTables
                                    ( tableName,
                                      query,
                                      cnt,
                                      [Source]
                                    )
                            SELECT  @Table,
                                    @TableSelect,
                                    @NumRows,
                                    @Source;
                     --   END; 
                END; 



SET @NumRows = 1000000;

UPDATE  a
SET     a.IsDeleted = 1
FROM    dbo.AllTablesToDeleteFrom a
WHERE   a.TableName = @Table;
--flag this as deleted so you can move on to the next table to delete from

END; 

How can I make my match non greedy in vim?

If you're more comfortable PCRE regex syntax, which

  1. supports the non-greedy operator ?, as you asked in OP; and
  2. doesn't require backwhacking grouping and cardinality operators (an utterly counterintuitive vim syntax requirement since you're not matching literal characters but specifying operators); and
  3. you have [g]vim compiled with perl feature, test using

    :ver and inspect features; if +perl is there you're good to go)

try search/replace using

:perldo s///

Example. Swap src and alt attributes in img tag:

<p class="logo"><a href="/"><img src="/caminoglobal_en/includes/themes/camino/images/header_logo.png" alt=""></a></p>

:perldo s/(src=".*?")\s+(alt=".*?")/$2 $1/

<p class="logo"><a href="/"><img alt="" src="/caminoglobal_en/includes/themes/camino/images/header_logo.png"></a></p>

Find integer index of rows with NaN in pandas dataframe

Another simple solution is list(np.where(df['b'].isnull())[0])

How to make Scrollable Table with fixed headers using CSS

What you want to do is separate the content of the table from the header of the table. You want only the <th> elements to be scrolled. You can easily define this separation in HTML with the <tbody> and the <thead> elements.
Now the header and the body of the table are still connected to each other, they will still have the same width (and same scroll properties). Now to let them not 'work' as a table anymore you can set the display: block. This way <thead> and <tbody> are separated.

table tbody, table thead
{
    display: block;
}

Now you can set the scroll to the body of the table:

table tbody 
{
   overflow: auto;
   height: 100px;
}

And last, because the <thead> doesn't share the same width as the body anymore, you should set a static width to the header of the table:

th
{
    width: 72px;
}

You should also set a static width for <td>. This solves the issue of the unaligned columns.

td
{
    width: 72px;
}


Note that you are also missing some HTML elements. Every row should be in a <tr> element, that includes the header row:

<tr>
     <th>head1</th>
     <th>head2</th>
     <th>head3</th>
     <th>head4</th>
</tr>

I hope this is what you meant.

jsFiddle

Addendum

If you would like to have more control over the column widths, have them to vary in width between each other, and course keep the header and body columns aligned, you can use the following example:

    table th:nth-child(1), td:nth-child(1) { min-width: 50px;  max-width: 50px; }
    table th:nth-child(2), td:nth-child(2) { min-width: 100px; max-width: 100px; }
    table th:nth-child(3), td:nth-child(3) { min-width: 150px; max-width: 150px; }
    table th:nth-child(4), td:nth-child(4) { min-width: 200px; max-width: 200px; }

Error 500: Premature end of script headers

I tried all of the above but found out it was a missing windows compiler.

Downloading and installing this fixed the issue. To see if this is your problem, try to run PHP from command line.

msvcr110.dll is missing from computer error while installing PHP

How to prevent sticky hover effects for buttons on touch devices

Add this JS code to your page:

document.body.className = 'ontouchstart' in document.documentElement ? '' : 'hover';

now in your CSS before every hover add the hover class like this:

.hover .foo:hover {}

If the device is touch, the body class will be empty, otherwise its class will be hover and the rules are applied!

"for loop" with two variables?

For your use case, it may be easier to utilize a while loop.

t1 = [137, 42]
t2 = ["Hello", "world"]

i = 0
j = 0
while i < len(t1) and j < len(t2):
    print t1[i], t2[j]
    i += 1
    j += 1

# 137 Hello
# 42 world

As a caveat, this approach will truncate to the length of your shortest list.

Cassandra "no viable alternative at input"

Wrong syntax. Here you are:

insert into user_by_category (game_category,customer_id) VALUES ('Goku','12');

or:

insert into user_by_category ("game_category","customer_id") VALUES ('Kakarot','12');

The second one is normally used for case-sensitive column names.

Paging with Oracle

Try the following:

SELECT *
FROM
  (SELECT FIELDA,
    FIELDB,
    FIELDC,
    ROW_NUMBER() OVER (ORDER BY FIELDC) R
  FROM TABLE_NAME
  WHERE FIELDA = 10
  )
WHERE R >= 10
AND R   <= 15;

via [tecnicume]

How to split a long array into smaller arrays, with JavaScript

You can take a look at this code . Simple and Effective .

function chunkArrayInGroups(array, unit) {
var results = [],
length = Math.ceil(array.length / unit);

for (var i = 0; i < length; i++) {
    results.push(array.slice(i * unit, (i + 1) * unit));
}
 return results;
}

chunkArrayInGroups(["a", "b", "c", "d"], 2);

How to remove all non-alpha numeric characters from a string in MySQL?

I tried a few solutions but at the end used replace. My data set is part numbers and I fairly know what to expect. But just for sanity, I used PHP to build the long query:

$dirty = array(' ', '-', '.', ',', ':', '?', '/', '!', '&', '@');
$query = 'part_no';
foreach ($dirty as $dirt) {
    $query = "replace($query,'$dirt','')";
}
echo $query;

This outputs something I used to get a headache from:

replace(replace(replace(replace(replace(replace(replace(replace(replace(replace(part_no,' ',''),'-',''),'.',''),',',''),':',''),'?',''),'/',''),'!',''),'&',''),'@','')

How to press/click the button using Selenium if the button does not have the Id?

    You can achieve this by using cssSelector 
    // Use of List web elements:
    String cssSelectorOfLoginButton="input[type='button'][id='login']"; 
    //****Add cssSelector of your 1st webelement
    //List<WebElement> button 
    =driver.findElements(By.cssSelector(cssSelectorOfLoginButton));
    button.get(0).click();

    I hope this work for you

Class 'ViewController' has no initializers in swift

if you lost a "!" in your code ,like this code below, you'll also get this error.

import UIKit

class MemeDetailViewController : UIViewController {

    @IBOutlet weak var memeImage: UIImageView!

    var meme:Meme! // lost"!"

    override func viewWillAppear(animated: Bool) {

        super.viewWillAppear(animated)
        self.memeImage!.image = meme.memedImage
    }

    override func viewDidDisappear(animated: Bool) {
        super.viewDidDisappear(animated)
    }

}

Do copyright dates need to be updated?

There is no reason at all for an individual to update the copyright year, because in the U.S. and Europe the life of copyright is the life of the author plus 70 years (50 years in some other countries like Canada and Australia). Extending the date does not extend the copyright. This also applies when a page has multiple contributors none of which are corporations.

As for corporations, Google doesn't update their copyright dates because they don't care whether some page they started in 1999 and updated this year falls into the public domain in 2094 or 2109. And if they don't, why should you? (As a Googler, now an ex-Googler, I was told this was the policy for internal source code as well.)

SQL Server using wildcard within IN

I think I have a solution to what the originator of this inquiry wanted in simple form. It works for me and actually it is the reason I came on here to begin with. I believe just using parentheses around the column like '%text%' in combination with ORs will do it.

select * from tableName
where (sameColumnName like '%findThis%' or sameColumnName like '%andThis%' or 
sameColumnName like '%thisToo%' or sameColumnName like '%andOneMore%') 

Convert java.util.date default format to Timestamp in Java

Best one

String str_date=month+"-"+day+"-"+yr;
DateFormat formatter = new SimpleDateFormat("MM-dd-yyyy");
Date date = (Date)formatter.parse(str_date); 
long output=date.getTime()/1000L;
String str=Long.toString(output);
long timestamp = Long.parseLong(str) * 1000;

How do I serialize a C# anonymous type to a JSON string?

Assuming you are using this for a web service, you can just apply the following attribute to the class:

[System.Web.Script.Services.ScriptService]

Then the following attribute to each method that should return Json:

[ScriptMethod(ResponseFormat = ResponseFormat.Json)]

And set the return type for the methods to be "object"

How can I compare strings in C using a `switch` statement?

This is how you do it. No, not really.

#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <stdint.h>


 #define p_ntohl(u) ({const uint32_t Q=0xFF000000;       \
                     uint32_t S=(uint32_t)(u);           \
                   (*(uint8_t*)&Q)?S:                    \
                   ( (S<<24)|                            \
                     ((S<<8)&0x00FF0000)|                \
                     ((S>>8)&0x0000FF00)|                \
                     ((S>>24)&0xFF) );  })

main (void)
{
    uint32_t s[0x40]; 
    assert((unsigned char)1 == (unsigned char)(257));
    memset(s, 0, sizeof(s));
    fgets((char*)s, sizeof(s), stdin);

    switch (p_ntohl(s[0])) {
        case 'open':
        case 'read':
        case 'seek':
            puts("ok");
            break;
        case 'rm\n\0':
            puts("not authorized");
            break;
        default:
            puts("unrecognized command");  
    }
    return 0;
}

Why won't my PHP app send a 404 error?

Your code is technically correct. If you looked at the headers of that blank page, you'd see a 404 header, and other computers/programs would be able to correctly identify the response as file not found.

Of course, your users are still SOL. Normally, 404s are handled by the web server.

  • User: Hey, do you have anything for me at this URI webserver?
  • Webserver: No, I don't, 404! Here's a page to display for 404s.

The problem is, once the web server starts processing the PHP page, it's already passed the point where it would handle a 404

  • User: Hey, do you have anything for me at this URI webserver?
  • Webserver: Yes, I do, it's a PHP page. It'll tell you what the response code is
  • PHP: Hey, OMG 404!!!!!!!
  • Webserver: Well crap, the 404 page people have already gone home, so I'll just send along whatever PHP gave me

In addition to providing a 404 header, PHP is now responsible for outputting the actual 404 page.

Simple excel find and replace for formulas

It turns out that the solution was to switch to R1C1 Cell Reference. My worksheet was structured in such a way that every formula had the same structure just different references. Luck though, they were always positioned the same way

=((E9-E8)/E8) 

became

=((R[-1]C-R[-2]C)/R[-2]C)

and

(EXP((LN(E9/E8)/14.32))-1)

became

=(EXP((LN(R[-1]C/R[-2]C)/14.32))-1)

In R1C1 Reference, every formula was identical so the find and replace required no wildcards. Thank you to those who answered!

better way to drop nan rows in pandas

To remove rows based on Nan value of particular column:

d= pd.DataFrame([[2,3],[4,None]])   #creating data frame
d
Output:
    0   1
0   2   3.0
1   4   NaN
d = d[np.isfinite(d[1])]  #Select rows where value of 1st column is not nan
d

Output:
    0   1
0   2   3.0

How to declare an ArrayList with values?

In Java 9+ you can do:

var x = List.of("xyz", "abc");
// 'var' works only for local variables

Java 8 using Stream:

Stream.of("xyz", "abc").collect(Collectors.toList());

And of course, you can create a new object using the constructor that accepts a Collection:

List<String> x = new ArrayList<>(Arrays.asList("xyz", "abc"));

Tip: The docs contains very useful information that usually contains the answer you're looking for. For example, here are the constructors of the ArrayList class:

What does bundle exec rake mean?

You're running bundle exec on a program. The program's creators wrote it when certain versions of gems were available. The program Gemfile specifies the versions of the gems the creators decided to use. That is, the script was made to run correctly against these gem versions.

Your system-wide Gemfile may differ from this Gemfile. You may have newer or older gems with which this script doesn't play nice. This difference in versions can give you weird errors.

bundle exec helps you avoid these errors. It executes the script using the gems specified in the script's Gemfile rather than the systemwide Gemfile. It executes the certain gem versions with the magic of shell aliases.

See more on the man page.

Here's an example Gemfile:

source 'http://rubygems.org'

gem 'rails', '2.8.3'

Here, bundle exec would execute the script using rails version 2.8.3 and not some other version you may have installed system-wide.

Why I get 411 Length required error?

When you're using HttpWebRequest and POST method, you have to set a content (or a body if you prefer) via the RequestStream. But, according to your code, using authRequest.Method = "GET" should be enough.

In case you're wondering about POST format, here's what you have to do :

ASCIIEncoding encoder = new ASCIIEncoding();
byte[] data = encoder.GetBytes(serializedObject); // a json object, or xml, whatever...

HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
request.Method = "POST";
request.ContentType = "application/json";
request.ContentLength = data.Length;
request.Expect = "application/json";

request.GetRequestStream().Write(data, 0, data.Length);

HttpWebResponse response = request.GetResponse() as HttpWebResponse;

When is del useful in Python?

As an example of what del can be used for, I find it useful i situations like this:

def f(a, b, c=3):
    return '{} {} {}'.format(a, b, c)

def g(**kwargs):
    if 'c' in kwargs and kwargs['c'] is None:
        del kwargs['c']

    return f(**kwargs)

# g(a=1, b=2, c=None) === '1 2 3'
# g(a=1, b=2) === '1 2 3'
# g(a=1, b=2, c=4) === '1 2 4'

These two functions can be in different packages/modules and the programmer doesn't need to know what default value argument c in f actually have. So by using kwargs in combination with del you can say "I want the default value on c" by setting it to None (or in this case also leave it).

You could do the same thing with something like:

def g(a, b, c=None):
    kwargs = {'a': a,
              'b': b}
    if c is not None:
        kwargs['c'] = c

    return f(**kwargs)

However I find the previous example more DRY and elegant.

How to bind WPF button to a command in ViewModelBase?

 <Grid >
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <Button Command="{Binding ClickCommand}" Width="100" Height="100" Content="wefwfwef"/>
</Grid>

the code behind for the window:

public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
        DataContext = new ViewModelBase();
    }
}

The ViewModel:

public class ViewModelBase
{
    private ICommand _clickCommand;
    public ICommand ClickCommand
    {
        get
        {
            return _clickCommand ?? (_clickCommand = new CommandHandler(() => MyAction(), ()=> CanExecute));
        }
    }
     public bool CanExecute
     {
        get
        {
            // check if executing is allowed, i.e., validate, check if a process is running, etc. 
            return true/false;
        }
     }

    public void MyAction()
    {

    }
}

Command Handler:

 public class CommandHandler : ICommand
{
    private Action _action;
    private Func<bool> _canExecute;

    /// <summary>
    /// Creates instance of the command handler
    /// </summary>
    /// <param name="action">Action to be executed by the command</param>
    /// <param name="canExecute">A bolean property to containing current permissions to execute the command</param>
    public CommandHandler(Action action, Func<bool> canExecute)
    {
        _action = action;
        _canExecute = canExecute;
    }

    /// <summary>
    /// Wires CanExecuteChanged event 
    /// </summary>
    public event EventHandler CanExecuteChanged
    {
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }
    }

    /// <summary>
    /// Forcess checking if execute is allowed
    /// </summary>
    /// <param name="parameter"></param>
    /// <returns></returns>
    public bool CanExecute(object parameter)
    {
        return _canExecute.Invoke();
    }

    public void Execute(object parameter)
    {
        _action();
    }
}

I hope this will give you the idea.

favicon.png vs favicon.ico - why should I use PNG instead of ICO?

Some social tools like Google+ use a simple method to get a favicon for external links, fetching http://your.domainname.com/favicon.ico

Since they don't prefetch the HTML content, the <link> tag will not work. In this case, you might want to use a mod_rewrite rule or just place the file in the default location.

Difference between Date(dateString) and new Date(dateString)

I was having the same issue using an API call which responded in ISO 8601 format. Working in Chrome this worked: `

// date variable from an api all in ISO 8601 format yyyy-mm-dd hh:mm:ss
  var date = oDate['events']['event'][0]['start_time'];
  var eventDate = new Date();
  var outputDate = eventDate.toDateString();

`

but this didn't work with firefox.

Above answer helped me format it correctly for firefox:

 // date variable from an api all in ISO 8601 format yyyy-mm-dd hh:mm:ss
 var date = oDate['events']['event'][0]['start_time'];
 var eventDate = new Date(date.replace(/-/g,"/");
 var outputDate = eventDate.toDateString();

Overlay a background-image with an rgba background-color

Ideally the background property would allow us to layer various backgrounds similar to the background image layering detailed at http://www.css3.info/preview/multiple-backgrounds/. Unfortunately, at least in Chrome (40.0.2214.115), adding an rgba background alongside a url() image background seems to break the property.

The solution I've found is to render the rgba layer as a 1px*1px Base64 encoded image and inline it.

.the-div:hover {
  background-image:url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNgkAQAABwAGkn5GOoAAAAASUVORK5CYII=), url("the-image.png");
}

for base64 encoded 1*1 pixel images I used http://px64.net/

Here is your jsfiddle with these changes made. http://jsfiddle.net/325Ft/49/ (I also swapped the image to one that still exists on the internet)

How can I do GUI programming in C?

C is more of a hardware programming language, there are easy GUI builders for C, GTK, Glade, etc. The problem is making a program in C that is the easy part, making a GUI that is a easy part, the hard part is to combine both, to interface between your program and the GUI is a headache, and different GUI use different ways, some threw global variables, some use slots. It would be nice to have a GUI builder that would bind easily your C program variables, and outputs. CLI programming is easy when you overcome memory allocation and pointers, GUI you can use a IDE that uses drag and drop. But all around I think it could be simpler.

Convert string to BigDecimal in java

Hi Guys you cant convert directly string to bigdecimal

you need to first convert it into long after that u will convert big decimal

String currency = "135.69"; 
Long rate1=Long.valueOf((currency ));            
System.out.println(BigDecimal.valueOf(rate1));

How do you move a file?

If you are moving folders via Repository Browser, then there is no Move option on right-click; the only way is to drag and drop.

Android Studio installation on Windows 7 fails, no JDK found

Today I found another situation when this problem occures - when you have several JDK, defined in JAVA_PATH. I have:

JAVA_HOME = C:\JAVA\JDK\jdk1.6.0_38;C:\JAVA\JDK\jdk1.7.0_10

So I received this problem with Android Studio setup

But when I've removed one of JDK - problem has been solved:

JAVA_HOME = C:\JAVA\JDK\jdk1.7.0_10

Installation wisard found my jdk and i had a nice night to study studio.

But unfortunatelly even installed studio doesn't work with several jdk. Does anybody know how to fix it?

I hope I've helped someone

Angular 4/5/6 Global Variables

I use environment for that. It works automatically and you don't have to create new injectable service and most usefull for me, don't need to import via constructor.

1) Create environment variable in your environment.ts

export const environment = {
    ...
    // runtime variables
    isContentLoading: false,
    isDeployNeeded: false
}

2) Import environment.ts in *.ts file and create public variable (i.e. "env") to be able to use in html template

import { environment } from 'environments/environment';

@Component(...)
export class TestComponent {
    ...
    env = environment;
}

3) Use it in template...

<app-spinner *ngIf='env.isContentLoading'></app-spinner>

in *.ts ...

env.isContentLoading = false 

(or just environment.isContentLoading in case you don't need it for template)


You can create your own set of globals within environment.ts like so:

export const globals = {
    isContentLoading: false,
    isDeployNeeded: false
}

and import directly these variables (y)

Split value from one field to two

mysql 5.4 provides a native split function:

SPLIT_STR(<column>, '<delimiter>', <index>)

How do I get a background location update every n minutes in my iOS application?

On iOS 8/9/10 to make background location update every 5 minutes do the following:

  1. Go to Project -> Capabilities -> Background Modes -> select Location updates

  2. Go to Project -> Info -> add a key NSLocationAlwaysUsageDescription with empty value (or optionally any text)

  3. To make location working when your app is in the background and send coordinates to web service or do anything with them every 5 minutes implement it like in the code below.

I'm not using any background tasks or timers. I've tested this code with my device with iOS 8.1 which was lying on my desk for few hours with my app running in the background. Device was locked and the code was running properly all the time.

@interface LocationManager () <CLLocationManagerDelegate>
@property (strong, nonatomic) CLLocationManager *locationManager;
@property (strong, nonatomic) NSDate *lastTimestamp;

@end

@implementation LocationManager

+ (instancetype)sharedInstance
{
    static id sharedInstance = nil;

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
        LocationManager *instance = sharedInstance;
        instance.locationManager = [CLLocationManager new];
        instance.locationManager.delegate = instance;
        instance.locationManager.desiredAccuracy = kCLLocationAccuracyBest; // you can use kCLLocationAccuracyHundredMeters to get better battery life
        instance.locationManager.pausesLocationUpdatesAutomatically = NO; // this is important
    });

    return sharedInstance;
}

- (void)startUpdatingLocation
{
    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];

    if (status == kCLAuthorizationStatusDenied)
    {
        NSLog(@"Location services are disabled in settings.");
    }
    else
    {
        // for iOS 8
        if ([self.locationManager respondsToSelector:@selector(requestAlwaysAuthorization)])
        {
            [self.locationManager requestAlwaysAuthorization];
        }
        // for iOS 9
        if ([self.locationManager respondsToSelector:@selector(setAllowsBackgroundLocationUpdates:)])
        {
            [self.locationManager setAllowsBackgroundLocationUpdates:YES];
        }

        [self.locationManager startUpdatingLocation];
    }
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations
{
    CLLocation *mostRecentLocation = locations.lastObject;
    NSLog(@"Current location: %@ %@", @(mostRecentLocation.coordinate.latitude), @(mostRecentLocation.coordinate.longitude));

    NSDate *now = [NSDate date];
    NSTimeInterval interval = self.lastTimestamp ? [now timeIntervalSinceDate:self.lastTimestamp] : 0;

    if (!self.lastTimestamp || interval >= 5 * 60)
    {
        self.lastTimestamp = now;
        NSLog(@"Sending current location to web service.");
    }
}

@end

How to import module when module name has a '-' dash or hyphen in it?

Starting from Python 3.1, you can use importlib :

import importlib  
foobar = importlib.import_module("foo-bar")

( https://docs.python.org/3/library/importlib.html )

Bootstrap 4 - Responsive cards in card-columns

Bootstrap 4 (4.0.0-alpha.2) uses the css property column-count in the card-columns class to define how many columns of cards would be displayed inside the div element.
But this property has only two values:

  • The default value 1 for small screens (max-width: 34em)
  • The value 3 for all other sizes (min-width: 34em)

Here's how it is implemented in bootstrap.min.css :

@media (min-width: 34em) {
    .card-columns {
        -webkit-column-count:3;
        -moz-column-count:3;
        column-count:3;
        ?
    }
    ?
}

To make the card stacking responsive, you can add the following media queries to your css file and modify the values for min-width as per your requirements :

@media (min-width: 34em) {
    .card-columns {
        -webkit-column-count: 2;
        -moz-column-count: 2;
        column-count: 2;
    }
}

@media (min-width: 48em) {
    .card-columns {
        -webkit-column-count: 3;
        -moz-column-count: 3;
        column-count: 3;
    }
}

@media (min-width: 62em) {
    .card-columns {
        -webkit-column-count: 4;
        -moz-column-count: 4;
        column-count: 4;
    }
}

@media (min-width: 75em) {
    .card-columns {
        -webkit-column-count: 5;
        -moz-column-count: 5;
        column-count: 5;
    }
}

Java: how to initialize String[]?

String[] errorSoon = new String[n];

With n being how many strings it needs to hold.

You can do that in the declaration, or do it without the String[] later on, so long as it's before you try use them.

How do I create 7-Zip archives with .NET?

These easiest way is to work with .zip files instead of .7z and use Dot Net Zip

When spinning off 7zip commands to shell there are other issues like user privileges, I had issue with SevenZipSharp.

Private Function CompressFile(filename As String) As Boolean
Using zip As New ZipFile()
    zip.AddFile(filename & ".txt", "")
    zip.Save(filename & ".zip")
End Using

Return File.Exists(filename & ".zip")
End Function

Save the plots into a PDF

Never mind got the way to do it.

def plotGraph(X,Y):
     fignum = random.randint(0,sys.maxint)
     fig = plt.figure(fignum)
     ### Plotting arrangements ###
     return fig

------ plotting module ------

----- mainModule ----

 import matplotlib.pyplot as plt
 ### tempDLStats, tempDLlabels are the argument
 plot1 = plotGraph(tempDLstats, tempDLlabels)
 plot2 = plotGraph(tempDLstats_1, tempDLlabels_1)
 plot3 = plotGraph(tempDLstats_2, tempDLlabels_2)
 plt.show()
 plot1.savefig('plot1.png')
 plot2.savefig('plot2.png')
 plot3.savefig('plot3.png')

----- mainModule -----

Regex to check whether a string contains only numbers

This is extreme overkill for your purpose, but here's what I use:

var numberReSnippet = "(?:NaN|-?(?:(?:\\d+|\\d*\\.\\d+)(?:[E|e][+|-]?\\d+)?|Infinity))";
var matchOnlyNumberRe = new RegExp("^("+ numberReSnippet + ")$");

To my knowledge, this matches all the variations on numbers that Java and JavaScript will ever throw at you, including "-Infinity", "1e-24" and "NaN". It also matches numbers you might type, such as "-.5".

As written, reSnippet is designed to be dropped into other regular expressions, so you can extract (or avoid) numbers. Despite all the parentheses, it contains no capturing groups. Thus "matchOnlyNumberRe" matches only strings that are numbers, and has a capturing group for the entire string.

Here are the Jasmine tests, so you can see what it does and doesn't handle:

describe("Number Regex", function() {
    var re = new RegExp("^("+ numberReSnippet + ")$");
    it("Matches Java and JavaScript numbers", function() {
        expect(re.test(         "1")).toBe(true);
        expect(re.test(       "0.2")).toBe(true);
        expect(re.test(     "0.4E4")).toBe(true);  // Java-style
        expect(re.test(       "-55")).toBe(true);
        expect(re.test(      "-0.6")).toBe(true);
        expect(re.test(  "-0.77E77")).toBe(true);
        expect(re.test(      "88E8")).toBe(true);
        expect(re.test(       "NaN")).toBe(true);
        expect(re.test(  "Infinity")).toBe(true);
        expect(re.test( "-Infinity")).toBe(true);
        expect(re.test(     "1e+24")).toBe(true);  // JavaScript-style
    });
    it("Matches fractions with a leading decimal point", function() {
        expect(re.test(        ".3")).toBe(true);
        expect(re.test(       "-.3")).toBe(true);
        expect(re.test(     ".3e-4")).toBe(true);
    });
    it("Doesn't match non-numbers", function() {
        expect(re.test(         ".")).toBe(false);
        expect(re.test(        "9.")).toBe(false);
        expect(re.test(          "")).toBe(false);
        expect(re.test(         "E")).toBe(false);
        expect(re.test(       "e24")).toBe(false);
        expect(re.test(   "1e+24.5")).toBe(false);
        expect(re.test("-.Infinity")).toBe(false);
    });
});

A transport-level error has occurred when receiving results from the server

It happened to me when I was trying to restore a SQL database and checked following Check Box in Options tab,

enter image description here

As it's a stand alone database server just closing down SSMS and reopening it solved the issue for me.

After installation of Gulp: “no command 'gulp' found”

I solved the issue without reinstalling node using the commands below:

$ npm uninstall --global gulp gulp-cli
$ rm /usr/local/share/man/man1/gulp.1
$ npm install --global gulp-cli

How to set up a cron job to run an executable every hour?

You can also use @hourly instant of 0 * * * *

How to Find App Pool Recycles in Event Log

As it seems impossible to filter the XPath message data (it isn't in the XML to filter), you can also use powershell to search:

Get-WinEvent -LogName System | Where-Object {$_.Message -like "*recycle*"}

From this, I can see that the event Id for recycling seems to be 5074, so you can filter on this as well. I hope this helps someone as this information seemed to take a lot longer than expected to work out.

This along with @BlackHawkDesign comment should help you find what you need.

I had the same issue. Maybe interesting to mention is that you have to configure in which cases the app pool recycle event is logged. By default it's in a couple of cases, not all of them. You can do that in IIS > app pools > select the app pool > advanced settings > expand generate recycle event log entry – BlackHawkDesign Jan 14 '15 at 10:00

Return value of x = os.system(..)

os.system() returns the (encoded) process exit value. 0 means success:

On Unix, the return value is the exit status of the process encoded in the format specified for wait(). Note that POSIX does not specify the meaning of the return value of the C system() function, so the return value of the Python function is system-dependent.

The output you see is written to stdout, so your console or terminal, and not returned to the Python caller.

If you wanted to capture stdout, use subprocess.check_output() instead:

x = subprocess.check_output(['whoami'])

How to save a plot as image on the disk?

There are two closely-related questions, and an answer for each.


1. An image will be generated in future in my script, how do I save it to disk?

To save a plot, you need to do the following:

  1. Open a device, using png(), bmp(), pdf() or similar
  2. Plot your model
  3. Close the device using dev.off()

Some example code for saving the plot to a png file:

fit <- lm(some ~ model)

png(filename="your/file/location/name.png")
plot(fit)
dev.off()

This is described in the (combined) help page for the graphical formats ?png, ?bmp, ?jpeg and ?tiff as well as in the separate help page for ?pdf.

Note however that the image might look different on disk to the same plot directly plotted to your screen, for example if you have resized the on-screen window.


Note that if your plot is made by either lattice or ggplot2 you have to explicitly print the plot. See this answer that explains this in more detail and also links to the R FAQ: ggplot's qplot does not execute on sourcing


2. I'm currently looking at a plot on my screen and I want to copy it 'as-is' to disk.

dev.print(pdf, 'filename.pdf')

This should copy the image perfectly, respecting any resizing you have done to the interactive window. You can, as in the first part of this answer, replace pdf with other filetypes such as png.

Add centered text to the middle of a <hr/>-like line

Responsive, transparent background, variable height and style of divider, variable position of text, adjustable distance between divider and text. Can also be applied multiple times with different selectors for multiple divider styles in same project.
SCSS below.

Markup (HTML):

<div class="divider" text-position="right">Divider</div>

CSS:

.divider {
  display: flex;
  align-items: center;
  padding: 0 1rem;
}

.divider:before,
.divider:after {
  content: '';
  flex: 0 1 100%;
  border-bottom: 5px dotted #ccc;
  margin: 0 1rem;
}

.divider:before {
  margin-left: 0;
}

.divider:after {
  margin-right: 0;
}

.divider[text-position="right"]:after,
.divider[text-position="left"]:before {
  content: none;
}

Without text-position it defaults to center.

Demo:

_x000D_
_x000D_
.divider {_x000D_
  display: flex;_x000D_
  align-items: center;_x000D_
  padding: 0 1rem;_x000D_
}_x000D_
_x000D_
.divider:before,_x000D_
.divider:after {_x000D_
  content: '';_x000D_
  flex: 0 1 100%;_x000D_
  border-bottom: 5px dotted #ccc;_x000D_
  margin: 0 1rem;_x000D_
}_x000D_
_x000D_
.divider:before {_x000D_
  margin-left: 0;_x000D_
}_x000D_
_x000D_
.divider:after {_x000D_
  margin-right: 0;_x000D_
}_x000D_
_x000D_
.divider[text-position="right"]:after,_x000D_
.divider[text-position="left"]:before {_x000D_
  content: none;_x000D_
}
_x000D_
<span class="divider" text-position="left">Divider</span>_x000D_
<h2 class="divider">Divider</h2>_x000D_
<div class="divider" text-position="right">Divider</div>
_x000D_
_x000D_
_x000D_

And SCSS, to modify it quickly:

$divider-selector    : ".divider";
$divider-border-color: rgba(0,0,0,.21);
$divider-padding     : 1rem;
$divider-border-width: 1px;
$divider-border-style: solid;
$divider-max-width   : 100%;

#{$divider-selector} {
    display: flex;
    align-items: center;
    padding: 0 $divider-padding;
    max-width: $divider-max-width;
    margin-left: auto;
    margin-right: auto;

    &:before,
    &:after {
        content: '';
        flex: 0 1 100%;
        border-bottom: $divider-border-width $divider-border-style $divider-border-color;
        margin: 0 $divider-padding;
        transform: translateY(#{$divider-border-width} / 2)
    }

    &:before {
        margin-left: 0;
    }

    &:after {
        margin-right: 0;
    }

    &[text-position="right"]:after,
    &[text-position="left"]:before {
        content: none;
    }
}

fiddle here.

ERROR: Sonar server 'http://localhost:9000' can not be reached

For others who ran into this issue in a project that is not using a sonar-runners.property file, you may find (as I did) that you need to tweak your pom.xml file, adding a sonar.host.url property.

For example, I needed to add the following line under the 'properties' element:

<sonar.host.url>https://sonar.my-internal-company-domain.net</sonar.host.url>

Where the url points to our internal sonar deployment.

How do you setLayoutParams() for an ImageView?

Old thread but I had the same problem now. If anyone encounters this he'll probably find this answer:

LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(30, 30);
yourImageView.setLayoutParams(layoutParams);

This will work only if you add the ImageView as a subView to a LinearLayout. If you add it to a RelativeLayout you will need to call:

RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(30, 30);
yourImageView.setLayoutParams(layoutParams);

How to secure database passwords in PHP?

Your choices are kind of limited as as you say you need the password to access the database. One general approach is to store the username and password in a seperate configuration file rather than the main script. Then be sure to store that outside the main web tree. That was if there is a web configuration problem that leaves your php files being simply displayed as text rather than being executed you haven't exposed the password.

Other than that you are on the right lines with minimal access for the account being used. Add to that

  • Don't use the combination of username/password for anything else
  • Configure the database server to only accept connections from the web host for that user (localhost is even better if the DB is on the same machine) That way even if the credentials are exposed they are no use to anyone unless they have other access to the machine.
  • Obfuscate the password (even ROT13 will do) it won't put up much defense if some does get access to the file, but at least it will prevent casual viewing of it.

Peter

Creating files in C++

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

string filename = "/tmp/filename.txt";

int main() {
  std::ofstream o(filename.c_str());

  o << "Hello, World\n" << std::endl;

  return 0;
}

This is what I had to do in order to use a variable for the filename instead of a regular string.

SQL : BETWEEN vs <= and >=

In this scenario col BETWEEN ... AND ... and col <= ... and col >= ... are equivalent.


SQL Standard defines also T461 Symmetric BETWEEN predicate:

 <between predicate part 2> ::=
 [ NOT ] BETWEEN [ ASYMMETRIC | SYMMETRIC ]
 <row value predicand> AND <row value predicand>

Transact-SQL does not support this feature.

BETWEEN requires that values are sorted. For instance:

SELECT 1 WHERE 3 BETWEEN 10 AND 1
-- no rows

<=>

SELECT 1 WHERE 3 >= 10 AND 3 <= 1
-- no rows

On the other hand:

SELECT 1 WHERE 3 BETWEEN SYMMETRIC 1 AND 10;
-- 1

SELECT 1 WHERE 3 BETWEEN SYMMETRIC 10 AND 1
-- 1

It works exactly as the normal BETWEEN but after sorting the comparison values.

db<>fiddle demo

How can I get LINQ to return the object which has the max value for a given property?

You could use a captured variable.

Item result = items.FirstOrDefault();
items.ForEach(x =>
{
  if(result.ID < x.ID)
    result = x;
});

Get a substring of a char*

Use char* strncpy(char* dest, char* src, int n) from <cstring>. In your case you will need to use the following code:

char* substr = malloc(4);
strncpy(substr, buff+10, 4);

Full documentation on the strncpy function here.

Initializing a struct to 0

If the data is a static or global variable, it is zero-filled by default, so just declare it myStruct _m;

If the data is a local variable or a heap-allocated zone, clear it with memset like:

memset(&m, 0, sizeof(myStruct));

Current compilers (e.g. recent versions of gcc) optimize that quite well in practice. This works only if all zero values (include null pointers and floating point zero) are represented as all zero bits, which is true on all platforms I know about (but the C standard permits implementations where this is false; I know no such implementation).

You could perhaps code myStruct m = {}; or myStruct m = {0}; (even if the first member of myStruct is not a scalar).

My feeling is that using memset for local structures is the best, and it conveys better the fact that at runtime, something has to be done (while usually, global and static data can be understood as initialized at compile time, without any cost at runtime).

ActionBarActivity cannot resolve a symbol

If the same error occurs in ADT/Eclipse

Add Action Bar Sherlock library in your project.

Now, to remove the "import The import android.support.v7 cannot be resolved" error download a jar file named as android-support-v7-appcompat.jar and add it in your project lib folder.

This will surely removes your both errors.

Write string to text file and ensure it always overwrites the existing content.

System.IO.File.WriteAllText (@"D:\path.txt", contents);
  • If the file exists, this overwrites it.
  • If the file does not exist, this creates it.
  • Please make sure you have appropriate privileges to write at the location, otherwise you will get an exception.

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

I've the same problem and solved with this code. I put this code before the first call to my webservices.

javax.net.ssl.HttpsURLConnection.setDefaultHostnameVerifier(
  new javax.net.ssl.HostnameVerifier(){

      public boolean verify(String hostname,
             javax.net.ssl.SSLSession sslSession) {
          return hostname.equals("localhost"); // or return true
      }
  });

It's simple and works fine.

Here is the original source.

How to install a .ipa file into my iPhone?

You need to install the provisioning profile (drag and drop it into iTunes). Then drag and drop the .ipa. Ensure you device is set to sync apps, and try again.

How to print variable addresses in C?

When you intend to print the memory address of any variable or a pointer, using %d won't do the job and will cause some compilation errors, because you're trying to print out a number instead of an address, and even if it does work, you'd have an intent error, because a memory address is not a number. the value 0xbfc0d878 is surely not a number, but an address.

What you should use is %p. e.g.,

#include<stdio.h>

int main(void) {

    int a;
    a = 5;
    printf("The memory address of a is: %p\n", (void*) &a);
    return 0;
}

Good luck!

Python convert set to string and vice versa

If you do not need the serialized text to be human readable, you can use pickle.

import pickle

s = set([1,2,3])

serialized_s = pickle.dumps(s)
print "serialized:"
print serialized_s

deserialized_s = pickle.loads(serialized_s)
print "deserialized:"
print deserialized_s

Result:

serialized:
c__builtin__
set
p0
((lp1
I1
aI2
aI3
atp2
Rp3
.
deserialized:
set([1, 2, 3])

ReadFile in Base64 Nodejs

var fs = require('fs');

function base64Encode(file) {
    var body = fs.readFileSync(file);
    return body.toString('base64');
}


var base64String = base64Encode('test.jpg');
console.log(base64String);

Select columns in PySpark dataframe

First two columns and 5 rows

 df.select(df.columns[:2]).take(5)

git rebase merge conflict

Note: with Git 2.14.x/2.15 (Q3 2017), the git rebase message in case of conflicts will be clearer.

See commit 5fdacc1 (16 Jul 2017) by William Duclot (williamdclt).
(Merged by Junio C Hamano -- gitster -- in commit 076eeec, 11 Aug 2017)

rebase: make resolve message clearer for inexperienced users

Before:

When you have resolved this problem, run "git rebase --continue".
If you prefer to skip this patch, run "git rebase --skip" instead.
To check out the original branch and stop rebasing, run "git rebase --abort"

After:

Resolve all conflicts manually, 
mark them as resolved with git add/rm <conflicted_files>
then run "git rebase --continue".

You can instead skip this commit: run "git rebase --skip".
To abort and get back to the state before "git rebase", run "git rebase --abort".')

The git UI can be improved by addressing the error messages to those they help: inexperienced and casual git users.
To this intent, it is helpful to make sure the terms used in those messages can be understood by this segment of users, and that they guide them to resolve the problem.

In particular, failure to apply a patch during a git rebase is a common problem that can be very destabilizing for the inexperienced user.
It is important to lead them toward the resolution of the conflict (which is a 3-steps process, thus complex) and reassure them that they can escape a situation they can't handle with "--abort".
This commit answer those two points by detailing the resolution process and by avoiding cryptic git linguo.

Get JSON Data from URL Using Android?

My fairly short code to read JSON from an URL. (requires Guava due to usage of CharStreams).

    private static class VersionTask extends AsyncTask<String, String, String> {
        @Override
        protected String doInBackground(String... strings) {
            String result = null;
            URL url;
            HttpURLConnection connection = null;
            try {
                url = new URL("https://api.github.com/repos/user_name/repo_name/releases/latest");
                connection = (HttpURLConnection) url.openConnection();
                connection.connect();
                result = CharStreams.toString(new InputStreamReader(connection.getInputStream(), Charsets.UTF_8));
            } catch (IOException e) {
                Log.d("VersionTask", Log.getStackTraceString(e));
            } finally {
                if (connection != null) {
                    connection.disconnect();
                }
            }
            return result;
        }

        @Override
        protected void onPostExecute(String result) {
            super.onPostExecute(result);
            if (result != null) {
                String version = "";
                try {
                    version = new JSONObject(result).optString("tag_name").trim();
                } catch (JSONException e) {
                    Log.e("VersionTask", Log.getStackTraceString(e));
                }
                if (version.startsWith("v")) {
                    //process version
                }
            }
        }
    }

PS: This code gets the latest release version (based on tag name) for a given GitHub repo.

How do I revert back to an OpenWrt router configuration?

If you installed the SquashFS image you can run the script firstboot. That will return OpenWrt to the defaults of when you flashed the router.

With your serial access just run firstboot and then power cycle the device.

What is an MvcHtmlString and when should I use it?

ASP.NET 4 introduces a new code nugget syntax <%: %>. Essentially, <%: foo %> translates to <%= HttpUtility.HtmlEncode(foo) %>. The team is trying to get developers to use <%: %> instead of <%= %> wherever possible to prevent XSS.

However, this introduces the problem that if a code nugget already encodes its result, the <%: %> syntax will re-encode it. This is solved by the introduction of the IHtmlString interface (new in .NET 4). If the foo() in <%: foo() %> returns an IHtmlString, the <%: %> syntax will not re-encode it.

MVC 2's helpers return MvcHtmlString, which on ASP.NET 4 implements the interface IHtmlString. Therefore when developers use <%: Html.*() %> in ASP.NET 4, the result won't be double-encoded.

Edit:

An immediate benefit of this new syntax is that your views are a little cleaner. For example, you can write <%: ViewData["anything"] %> instead of <%= Html.Encode(ViewData["anything"]) %>.

openssl s_client using a proxy

You can use proxytunnel:

proxytunnel -p yourproxy:8080 -d www.google.com:443 -a 7000

and then you can do this:

openssl s_client -connect localhost:7000 -showcerts

Hope this can help you!

How can I determine browser window size on server side C#

Here's an Ajax, asxh handler and session variables approach:

Handler:

using System;
using System.Web;

public class windowSize : IHttpHandler , System.Web.SessionState.IRequiresSessionState  {

    public void ProcessRequest (HttpContext context) {
        context.Response.ContentType = "application/json";

        var json = new System.Web.Script.Serialization.JavaScriptSerializer();
        var output = json.Serialize(new { isFirst = context.Session["BrowserWidth"] == null });
        context.Response.Write(output);

        context.Session["BrowserWidth"] =  context.Request.QueryString["Width"]; 
        context.Session["BrowserHeight"] = context.Request.QueryString["Height"];
    }

    public bool IsReusable
    {
        get { throw new NotImplementedException(); }
    }
}

Javascript:

window.onresize = function (event) {
    SetWidthHeight();
}
function SetWidthHeight() {
    var height = $(window).height();
    var width = $(window).width();
    $.ajax({
        url: "windowSize.ashx",
        data: {
            'Height': height,
            'Width': width
        },
        contentType: "application/json; charset=utf-8",
        dataType: "json"
    }).done(function (data) {     
        if (data.isFirst) {
            window.location.reload();
        };
    }).fail(function (xhr) {
        alert("Problem to retrieve browser size.");
    });

}
$(function () {
    SetWidthHeight();
});

On aspx file:

...
<script src="Scripts/jquery-1.9.1.min.js"></script>
<script src="Scripts/BrowserWindowSize.js"></script>
...
<asp:Label ID="lblDim" runat="server" Text=""></asp:Label>
...

Code behind:

protected void Page_Load(object sender, EventArgs e)
  {
      if (Session["BrowserWidth"] != null)
      {
          // Do all code here to avoid double execution first time
          // ....
          lblDim.Text = "Width: " + Session["BrowserWidth"] + " Height: " + Session["BrowserHeight"];
      }
  }

Source: https://techbrij.com/browser-height-width-server-responsive-design-asp-net

Installing jdk8 on ubuntu- "unable to locate package" update doesn't fix

I used another repository for oracle java.

sudo add-apt-repository ppa:linuxuprising/java
sudo apt-get update

sudo apt install  oracle-java11-installer

If Browser is Internet Explorer: run an alternative script instead

See this script in Microsoft's developer archives: https://msdn.microsoft.com/en-us/library/ms537509%28v=vs.85%29.aspx

I have used this script in quite a few projects, never had any problems.

PDF files do not open in Internet Explorer with Adobe Reader 10.0 - users get an empty gray screen. How can I fix this for my users?

I realize this is a rather late post but still a possible solution for the OP. I use IE9 on Win 7 and have been having Adobe Reader's grey screen issues for several months when trying to open pdf bank and credit card statements online. I could open everything in Firefox or Opera but not IE. I finally tried PDF-Viewer, set it as the default pdf viewer in its preferences and no more problems. I'm sure there are other free viewers out there, like Foxit, PDF-Xchange, etc., that will give better results than Reader with less headaches. Adobe is like some of the other big companies that develop software on a take it or leave it basis ... so I left it.

Why does DEBUG=False setting make my django Static Files Access fail?

Johnny's answer is great, but still didn't work for me just by adding those lines described there. Based on that answer, the steps that actually worked for me where:

  1. Install WhiteNoise as described:

    pip install WhiteNoise
    
  2. Create the STATIC_ROOT variable and add WhiteNoise to your MIDDLEWARE variable in settings.py:

    #settings.py
    MIDDLEWARE = [
        'django.middleware.security.SecurityMiddleware',
        'whitenoise.middleware.WhiteNoiseMiddleware', #add whitenoise
        'django.contrib.sessions.middleware.SessionMiddleware',
        ...
    ]
    
    #...
    
    STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') ##specify static root
    
  3. Then, modify your wsgi.py file as explained in Johnny's answer:

    #wsgi.py
    from django.core.wsgi import get_wsgi_application
    from whitenoise.django import DjangoWhiteNoise
    
    application = get_wsgi_application()
    application = DjangoWhiteNoise(application)
    
  4. After that, deploy your changes to your server (with git or whatever you use).

  5. Finally, run the collectstatic option from your manage.py on your server. This will copy all files from your static folders into the STATIC_ROOT directory we specified before:

    $ python manage.py collectstatic
    

    You will now see a new folder named staticfiles that contains such elements.

After following these steps you can now run your server and will be able to see your static files while in Production mode.

Update: In case you had version < 4 the changelog indicates that it's no longer necessary to declare the WSGI_APPLICATION = 'projectName.wsgi.application' on your settings.py file.

How to write asynchronous functions for Node.js

If you KNOW that a function returns a promise, i suggest using the new async/await features in JavaScript. It makes the syntax look synchronous but work asynchronously. When you add the async keyword to a function, it allows you to await promises in that scope:

async function ace() {
  var r = await new Promise((resolve, reject) => {
    resolve(true)
  });

  console.log(r); // true
}

if a function does not return a promise, i recommend wrapping it in a new promise that you define, then resolve the data that you want:

function ajax_call(url, method) {
  return new Promise((resolve, reject) => {
    fetch(url, { method })
    .then(resp => resp.json())
    .then(json => { resolve(json); })
  });
}

async function your_function() {
  var json = await ajax_call('www.api-example.com/some_data', 'GET');
  console.log(json); // { status: 200, data: ... }
}

Bottom line: leverage the power of Promises.

Repeat-until or equivalent loop in Python

REPEAT
    ...
UNTIL cond

Is equivalent to

while True:
    ...
    if cond:
        break

How to restart kubernetes nodes?

If a node is so unhealthy that the master can't get status from it -- Kubernetes may not be able to restart the node. And if health checks aren't working, what hope do you have of accessing the node by SSH?

In this case, you may have to hard-reboot -- or, if your hardware is in the cloud, let your provider do it.

For example, the AWS EC2 Dashboard allows you to right-click an instance to pull up an "Instance State" menu -- from which you can reboot/terminate an unresponsive node.

Before doing this, you might choose to kubectl cordon node for good measure. And you may find kubectl delete node to be an important part of the process for getting things back to normal -- if the node doesn't automatically rejoin the cluster after a reboot.


Why would a node become unresponsive? Probably some resource has been exhausted in a way that prevents the host operating system from handling new requests in a timely manner. This could be disk, or network -- but the more insidious case is out-of-memory (OOM), which Linux handles poorly.

To help Kubernetes manage node memory safely, it's a good idea to do both of the following:

  • Reserve some memory for the system.
  • Be very careful with (avoid) opportunistic memory specifications for your pods. In other words, don't allow different values of requests and limits for memory.

The idea here is to avoid the complications associated with memory overcommit, because memory is incompressible, and both Linux and Kubernetes' OOM killers may not trigger before the node has already become unhealthy and unreachable.

How can I use random numbers in groovy?

If you want to generate random numbers in range including '0' , use the following while 'max' is the maximum number in the range.

Random rand = new Random()
random_num = rand.nextInt(max+1)

How to create dictionary and add key–value pairs dynamically?

You can use maps with Map, like this:

var sayings = new Map();
sayings.set('dog', 'woof');
sayings.set('cat', 'meow');

Is it possible to interactively delete matching search pattern in Vim?

The best way is probably to use:

:%s/phrase//gc

c asks for confirmation before each deletion. g allows multiple replacements to occur on the same line.

You can also just search using /phrase, select the next match with gn, and delete it with d.

How can I return the sum and average of an int array?

This is the way you should be doing it, and I say this because you are clearly new to C# and should probably try to understand how some basic stuff works!

public int Sum(params int[] customerssalary)
{
   int result = 0;

   for(int i = 0; i < customerssalary.Length; i++)
   {
      result += customerssalary[i];
   }

   return result;
}

with this Sum function, you can use this to calculate the average too...

public decimal Average(params int[] customerssalary)
{
   int sum = Sum(customerssalary);
   decimal result = (decimal)sum / customerssalary.Length;
   return result;
}

the reason for using a decimal type in the second function is because the division can easily return a non-integer result


Others have provided a Linq alternative which is what I would use myself anyway, but with Linq there is no point in having your own functions anyway. I have made the assumption that you have been asked to implement such functions as a task to demonstrate your understanding of C#, but I could be wrong.

Delegates in swift?

Delegates always confused me until I realized that a delegate is just a class that does some work for another class. It's like having someone else there to do all the dirty work for you that you don't want to do yourself.

I wrote a little story to illustrate this. Read it in a Playground if you like.

Once upon a time...

// MARK: Background to the story

// A protocol is like a list of rules that need to be followed.
protocol OlderSiblingDelegate: class {
    // The following command (ie, method) must be obeyed by any 
    // underling (ie, delegate) of the older sibling.
    func getYourNiceOlderSiblingAGlassOfWater()
}

// MARK: Characters in the story

class BossyBigBrother {
    
    // I can make whichever little sibling is around at 
    // the time be my delegate (ie, slave)
    weak var delegate: OlderSiblingDelegate?
    
    func tellSomebodyToGetMeSomeWater() {
        // The delegate is optional because even though 
        // I'm thirsty, there might not be anyone nearby 
        // that I can boss around.
        delegate?.getYourNiceOlderSiblingAGlassOfWater()
    }
}

// Poor little sisters have to follow (or at least acknowledge) 
// their older sibling's rules (ie, protocol)
class PoorLittleSister: OlderSiblingDelegate {

    func getYourNiceOlderSiblingAGlassOfWater() {
        // Little sis follows the letter of the law (ie, protocol),
        // but no one said exactly how she had to respond.
        print("Go get it yourself!")
    }
}

// MARK: The Story

// Big bro is laying on the couch watching basketball on TV.
let bigBro = BossyBigBrother()

// He has a little sister named Sally.
let sally = PoorLittleSister()

// Sally walks into the room. How convenient! Now big bro 
// has someone there to boss around.
bigBro.delegate = sally

// So he tells her to get him some water.
bigBro.tellSomebodyToGetMeSomeWater()

// Unfortunately no one lived happily ever after...

// The end.

In review, there are three key parts to making and using the delegate pattern.

  1. the protocol that defines what the worker needs to do
  2. the boss class that has a delegate variable, which it uses to tell the worker class what to do
  3. the worker class that adopts the protocol and does what is required

Real life

In comparison to our Bossy Big Brother story above, delegates are often used for the following practical applications:

  1. Communication: one class needs to send some information to another class.
  2. Customization: one class wants to allow another class to customize it.

The great part is that these classes don't need to know anything about each other beforehand except that the delegate class conforms to the required protocol.

I highly recommend reading the following two articles. They helped me understand delegates even better than the documentation did.

One more note

Delegates that reference other classes that they do not own should use the weak keyword to avoid strong reference cycles. See this answer for more details.

How to center the text in PHPExcel merged cell

The solution is to set the cell style through this function:

$sheet->getStyle('A1')->getAlignment()->applyFromArray(
    array('horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,)
);

Full code

<?php
/** Error reporting */
error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);
date_default_timezone_set('Europe/London');

/** Include PHPExcel */
require_once '../Classes/PHPExcel.php';

$objPHPExcel = new PHPExcel();
$sheet = $objPHPExcel->getActiveSheet();
$sheet->setCellValueByColumnAndRow(0, 1, "test");
$sheet->mergeCells('A1:B1');
$sheet->getStyle('A1')->getAlignment()->applyFromArray(
    array('horizontal' => PHPExcel_Style_Alignment::HORIZONTAL_CENTER,)
);
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel2007');
$objWriter->save("test.xlsx");

enter image description here

Android Studio: Gradle: error: cannot find symbol variable

If you are using a String build config field in your project, this might be the case:

buildConfigField "String", "source", "play"

If you declare your String like above it will cause the error to happen. The fix is to change it to:

buildConfigField "String", "source", "\"play\""

Checking if my Windows application is running

Checkout: What is a good pattern for using a Global Mutex in C#?

// unique id for global mutex - Global prefix means it is global to the machine
const string mutex_id = "Global\\{B1E7934A-F688-417f-8FCB-65C3985E9E27}";

static void Main(string[] args)
{
    using (var mutex = new Mutex(false, mutex_id))
    {
        // edited by Jeremy Wiebe to add example of setting up security for multi-user usage
        // edited by 'Marc' to work also on localized systems (don't use just "Everyone") 
        var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
        var securitySettings = new MutexSecurity();
        securitySettings.AddAccessRule(allowEveryoneRule);
        mutex.SetAccessControl(securitySettings);

        //edited by acidzombie24
        var hasHandle = false;
        try
        {
            try
            {
                // note, you may want to time out here instead of waiting forever
                //edited by acidzombie24
                //mutex.WaitOne(Timeout.Infinite, false);
                hasHandle = mutex.WaitOne(5000, false);
                if (hasHandle == false) return;//another instance exist
            }
            catch (AbandonedMutexException)
            {
                // Log the fact the mutex was abandoned in another process, it will still get aquired
            }

            // Perform your work here.
        }
        finally
        {
            //edit by acidzombie24, added if statemnet
            if (hasHandle)
                mutex.ReleaseMutex();
        }
    }
}

The network path was not found

Same problem with me. I solved this by adding @ before connection string (C# has a thing called 'String Literals') like so:

SqlConnection sconnection = new SqlConnection(@"Data Source=(Localdb)\v11.0; Initial Catalog=Mydatabase;Integrated Security=True");

sconnection.Open();

How to select a single column with Entity Framework?

I'm a complete noob on Entity but this is how I would do it in theory...

var name = yourDbContext.MyTable.Find(1).Name;

If It's A Primary Key.

-- OR --

var name = yourDbContext.MyTable.SingleOrDefault(mytable => mytable.UserId == 1).Name;

-- OR --

For whole Column:

var names = yourDbContext.MyTable
.Where(mytable => mytable.UserId == 1)
.Select(column => column.Name); //You can '.ToList();' this....

But "oh Geez Rick, What do I know..."

How do I get the path to the current script with Node.js?

If you want something more like $0 in a shell script, try this:

var path = require('path');

var command = getCurrentScriptPath();

console.log(`Usage: ${command} <foo> <bar>`);

function getCurrentScriptPath () {
    // Relative path from current working directory to the location of this script
    var pathToScript = path.relative(process.cwd(), __filename);

    // Check if current working dir is the same as the script
    if (process.cwd() === __dirname) {
        // E.g. "./foobar.js"
        return '.' + path.sep + pathToScript;
    } else {
        // E.g. "foo/bar/baz.js"
        return pathToScript;
    }
}

Run R script from command line

This does not answer the question directly. But someone may end up here because they want to run a oneliner of R from the terminal. For example, if you just want to install some missing packages and quit, this oneliner can be very convenient. I use it a lot when I suddenly find out that I miss some packages, and I want to install them to where I want.

  • To install to the default location:

    R -e 'install.packages(c("package1", "package2"))'
    
  • To install to a location that requires root privileges:

    R -e 'install.packages(c("package1", "package2"), lib="/usr/local/lib/R/site-library")' 
    

Running conda with proxy

The best way I settled with is to set proxy environment variables right before using conda or pip install/update commands. Simply run:

set HTTP_PROXY=http://username:password@proxy_url:port

For example, your actual command could be like

set HTTP_PROXY=http://yourname:[email protected]_company.com:8080

If your company uses https proxy, then also

set HTTPS_PROXY=https://username:password@proxy_url:port

Once you exit Anaconda prompt then this setting is gone, so your username/password won't be saved after the session.

I didn't choose other methods mentioned in Anaconda documentation or some other sources, because they all require hardcoding of username/password into

  • Windows environment variables (also this requires restart of Anaconda prompt for the first time)
  • Conda .condarc or .netrc configuration files (also this won't work for PIP)
  • A batch/script file loaded while starting Anaconda prompt (also this might require configuring the path)

All of these are unsafe and will require constant update later. And if you forget where to update? More troubleshooting will come your way...

Correct way to quit a Qt program?

If you're using Qt Jambi, this should work:

QApplication.closeAllWindows();

ant build.xml file doesn't exist

There may be two situations.

  1. No build.xml is present in the current directory
  2. Your ant configuration file has diffrent name.

Please see and confim the same. In the case one you have to find where your build file is located and in the case 2, You will have to run command ant -f <your build file name>.

MIT vs GPL license

Can I include GPL licensed code in a MIT licensed product?

You can. GPL is free software as well as MIT is, both licenses do not restrict you to bring together the code where as "include" is always two-way.

In copyright for a combined work (that is two or more works form together a work), it does not make much of a difference if the one work is "larger" than the other or not.

So if you include GPL licensed code in a MIT licensed product you will at the same time include a MIT licensed product in GPL licensed code as well.

As a second opinion, the OSI listed the following criteria (in more detail) for both licenses (MIT and GPL):

  1. Free Redistribution
  2. Source Code
  3. Derived Works
  4. Integrity of The Author's Source Code
  5. No Discrimination Against Persons or Groups
  6. No Discrimination Against Fields of Endeavor
  7. Distribution of License
  8. License Must Not Be Specific to a Product
  9. License Must Not Restrict Other Software
  10. License Must Be Technology-Neutral

Both allow the creation of combined works, which is what you've been asking for.

If combining the two works is considered being a derivate, then this is not restricted as well by both licenses.

And both licenses do not restrict to distribute the software.

It seems to me that the chief difference between the MIT license and GPL is that the MIT doesn't require modifications be open sourced whereas the GPL does.

The GPL doesn't require you to release your modifications only because you made them. That's not precise.

You might mix this with distribiution of software under GPL which is not what you've asked about directly.

Is that correct - is the GPL is more restrictive than the MIT license?

This is how I understand it:

As far as distribution counts, you need to put the whole package under GPL. MIT code inside of the package will still be available under MIT whereas the GPL applies to the package as a whole if not limited by higher rights.

"Restrictive" or "more restrictive" / "less restrictive" depends a lot on the point of view. For a software-user the MIT might result in software that is more restricted than the one available under GPL even some call the GPL more restrictive nowadays. That user in specific will call the MIT more restrictive. It's just subjective to say so and different people will give you different answers to that.

As it's just subjective to talk about restrictions of different licenses, you should think about what you would like to achieve instead:

  • If you want to restrict the use of your modifications, then MIT is able to be more restrictive than the GPL for distribution and that might be what you're looking for.
  • In case you want to ensure that the freedom of your software does not get restricted that much by the users you distribute it to, then you might want to release under GPL instead of MIT.

As long as you're the author it's you who can decide.

So the most restrictive person ever is the author, regardless of which license anybody is opting for ;)

Make Https call using HttpClient

Simply specify HTTPS in the URI.

new Uri("https://foobar.com/");

Foobar.com will need to have a trusted SSL cert or your calls will fail with untrusted error.

EDIT Answer: ClientCertificates with HttpClient

WebRequestHandler handler = new WebRequestHandler();
X509Certificate2 certificate = GetMyX509Certificate();
handler.ClientCertificates.Add(certificate);
HttpClient client = new HttpClient(handler);

EDIT Answer2: If the server you are connecting to has disabled SSL, TLS 1.0, and 1.1 and you are still running .NET framework 4.5(or below) you need to make a choice

  1. Upgrade to .Net 4.6+ (Supports TLS 1.2 by default)
  2. Add registry changes to instruct 4.5 to connect over TLS1.2 ( See: salesforce writeup for compat and keys to change OR checkout IISCrypto see Ronald Ramos answer comments)
  3. Add application code to manually configure .NET to connect over TLS1.2 (see Ronald Ramos answer)

"The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine" Error in importing process of xlsx to a sql server

I had no luck until I installed the 2010 version link here: https://www.microsoft.com/en-us/download/details.aspx?id=13255

I tried installing the 32 bit version, it still errored, so I uninstalled it and installed the 64 bit version and it started working.

tkinter: Open a new window with a button prompt

Here's the nearly shortest possible solution to your question. The solution works in python 3.x. For python 2.x change the import to Tkinter rather than tkinter (the difference being the capitalization):

import tkinter as tk
#import Tkinter as tk  # for python 2
    
def create_window():
    window = tk.Toplevel(root)

root = tk.Tk()
b = tk.Button(root, text="Create new window", command=create_window)
b.pack()

root.mainloop()

This is definitely not what I recommend as an example of good coding style, but it illustrates the basic concepts: a button with a command, and a function that creates a window.

ArrayList filter

In , they introduced the method removeIf which takes a Predicate as parameter.

So it will be easy as:

List<String> list = new ArrayList<>(Arrays.asList("How are you",
                                                  "How you doing",
                                                  "Joe",
                                                  "Mike"));
list.removeIf(s -> !s.contains("How"));

How do I create a message box with "Yes", "No" choices and a DialogResult?

The MessageBox does produce a DialogResults

DialogResult r = MessageBox.Show("Some question here");

You can also specify the buttons easily enough. More documentation can be found at http://msdn.microsoft.com/en-us/library/ba2a6d06.aspx

How to map atan2() to degrees 0-360

Here's some javascript. Just input x and y values.

var angle = (Math.atan2(x,y) * (180/Math.PI) + 360) % 360;

Find all files with a filename beginning with a specified string?

ls | grep "^abc"  

will give you all files beginning (which is what the OP specifically required) with the substringabc.
It operates only on the current directory whereas find operates recursively into sub folders.

To use find for only files starting with your string try

find . -name 'abc'*

How to SFTP with PHP?

I performed a full-on cop-out and wrote a class which creates a batch file and then calls sftp via a system call. Not the nicest (or fastest) way of doing it but it works for what I need and it didn't require any installation of extra libraries or extensions in PHP.

Could be the way to go if you don't want to use the ssh2 extensions

Home does not contain an export named Home

I just ran into this error message (after upgrading to nextjs 9 some transpiled imports started giving this error). I managed to fix them using syntax like this:

import * as Home from './layouts/Home';

How to check if $? is not equal to zero in unix shell scripting?

Try this after execution of your script :

if [ $? -ne 0 ];
then
//statements//
fi

Sort objects in ArrayList by date?

With introduction of Java 1.8, streams are very useful in solving this kind of problems:

Comparator <DateTime> myComparator = (arg1, arg2) 
                -> {
                    if(arg1.lt(arg2)) 
                       return -1;
                    else if (arg1.lteq(arg2))
                       return 0;
                    else
                       return 1;
                   };

ArrayList<DateTime> sortedList = myList
                   .stream()
                   .sorted(myComparator)
                   .collect(Collectors.toCollection(ArrayList::new));

How to Deserialize XML document

Here's a working version. I changed the XmlElementAttribute labels to XmlElement because in the xml the StockNumber, Make and Model values are elements, not attributes. Also I removed the reader.ReadToEnd(); (that function reads the whole stream and returns a string, so the Deserialize() function couldn't use the reader anymore...the position was at the end of the stream). I also took a few liberties with the naming :).

Here are the classes:

[Serializable()]
public class Car
{
    [System.Xml.Serialization.XmlElement("StockNumber")]
    public string StockNumber { get; set; }

    [System.Xml.Serialization.XmlElement("Make")]
    public string Make { get; set; }

    [System.Xml.Serialization.XmlElement("Model")]
    public string Model { get; set; }
}


[Serializable()]
[System.Xml.Serialization.XmlRoot("CarCollection")]
public class CarCollection
{
    [XmlArray("Cars")]
    [XmlArrayItem("Car", typeof(Car))]
    public Car[] Car { get; set; }
}

The Deserialize function:

CarCollection cars = null;
string path = "cars.xml";

XmlSerializer serializer = new XmlSerializer(typeof(CarCollection));

StreamReader reader = new StreamReader(path);
cars = (CarCollection)serializer.Deserialize(reader);
reader.Close();

And the slightly tweaked xml (I needed to add a new element to wrap <Cars>...Net is picky about deserializing arrays):

<?xml version="1.0" encoding="utf-8"?>
<CarCollection>
<Cars>
  <Car>
    <StockNumber>1020</StockNumber>
    <Make>Nissan</Make>
    <Model>Sentra</Model>
  </Car>
  <Car>
    <StockNumber>1010</StockNumber>
    <Make>Toyota</Make>
    <Model>Corolla</Model>
  </Car>
  <Car>
    <StockNumber>1111</StockNumber>
    <Make>Honda</Make>
    <Model>Accord</Model>
  </Car>
</Cars>
</CarCollection>

How to invoke the super constructor in Python?

Just to add an example with parameters:

class B(A):
    def __init__(self, x, y, z):
        A.__init__(self, x, y)

Given a derived class B that requires the variables x, y, z to be defined, and a superclass A that requires x, y to be defined, you can call the static method init of the superclass A with a reference to the current subclass instance (self) and then the list of expected arguments.

How do I restrict an input to only accept numbers?

Easy way, use type="number" if it works for your use case:

<input type="number" ng-model="myText" name="inputName">

Another easy way: ng-pattern can also be used to define a regex that will limit what is allowed in the field. See also the "cookbook" page about forms.

Hackish? way, $watch the ng-model in your controller:

<input type="text"  ng-model="myText" name="inputName">

Controller:

$scope.$watch('myText', function() {
   // put numbersOnly() logic here, e.g.:
   if ($scope.myText  ... regex to look for ... ) {
      // strip out the non-numbers
   }
})

Best way, use a $parser in a directive. I'm not going to repeat the already good answer provided by @pkozlowski.opensource, so here's the link: https://stackoverflow.com/a/14425022/215945

All of the above solutions involve using ng-model, which make finding this unnecessary.

Using ng-change will cause problems. See AngularJS - reset of $scope.value doesn't change value in template (random behavior)

What is the best way to conditionally apply a class?

I faced a similar problem recently and decided to just create a conditional filter:

  angular.module('myFilters', []).
    /**
     * "if" filter
     * Simple filter useful for conditionally applying CSS classes and decouple
     * view from controller 
     */
    filter('if', function() {
      return function(input, value) {
        if (typeof(input) === 'string') {
          input = [input, ''];
        }
        return value? input[0] : input[1];
      };
    });

It takes a single argument, which is either a 2-element array or a string, which gets turned into an array that is appended an empty string as the second element:

<li ng-repeat="item in products | filter:search | orderBy:orderProp |
  page:pageNum:pageLength" ng-class="'opened'|if:isOpen(item)">
  ...
</li>

INSERT VALUES WHERE NOT EXISTS

More of a comment link for suggested further reading...A really good blog article which benchmarks various ways of accomplishing this task can be found here.

They use a few techniques: "Insert Where Not Exists", "Merge" statement, "Insert Except", and your typical "left join" to see which way is the fastest to accomplish this task.

The example code used for each technique is as follows (straight copy/paste from their page) :

INSERT INTO #table1 (Id, guidd, TimeAdded, ExtraData)
SELECT Id, guidd, TimeAdded, ExtraData
FROM #table2
WHERE NOT EXISTS (Select Id, guidd From #table1 WHERE #table1.id = #table2.id)
-----------------------------------
MERGE #table1 as [Target]
USING  (select Id, guidd, TimeAdded, ExtraData from #table2) as [Source]
(id, guidd, TimeAdded, ExtraData)
    on [Target].id =[Source].id
WHEN NOT MATCHED THEN
    INSERT (id, guidd, TimeAdded, ExtraData)
    VALUES ([Source].id, [Source].guidd, [Source].TimeAdded, [Source].ExtraData);
------------------------------
INSERT INTO #table1 (id, guidd, TimeAdded, ExtraData)
SELECT id, guidd, TimeAdded, ExtraData from #table2
EXCEPT
SELECT id, guidd, TimeAdded, ExtraData from #table1
------------------------------
INSERT INTO #table1 (id, guidd, TimeAdded, ExtraData)
SELECT #table2.id, #table2.guidd, #table2.TimeAdded, #table2.ExtraData
FROM #table2
LEFT JOIN #table1 on #table1.id = #table2.id
WHERE #table1.id is null

It's a good read for those who are looking for speed! On SQL 2014, the Insert-Except method turned out to be the fastest for 50 million or more records.

Blurry text after using CSS transform: scale(); in Chrome

My solution was:

display: initial;

Then it was crispy sharp

PostgreSQL error 'Could not connect to server: No such file or directory'

The Cause

Lion comes with a version of postgres already installed and uses those binaries by default. In general you can get around this by using the full path to the homebrew postgres binaries but there may be still issues with other programs.

The Solution

curl http://nextmarvel.net/blog/downloads/fixBrewLionPostgres.sh | sh

Via

http://nextmarvel.net/blog/2011/09/brew-install-postgresql-on-os-x-lion/

What are the best JVM settings for Eclipse?

If you are using Linux + Sun JDK/JRE 32bits, change the "-vm" to:

-vm 
[your_jdk_folder]/jre/lib/i386/client/libjvm.so

If you are using Linux + Sun JDK/JRE 64bits, change the "-vm" to:

-vm
[your_jdk_folder]/jre/lib/amd64/server/libjvm.so

That's working fine for me on Ubuntu 8.10 and 9.04

Add a fragment to the URL without causing a redirect?

window.location.hash = 'something';

That is just plain JavaScript.

Your comment...

Hi, what I really need is to add only the hash... something like this: window.location.hash = '#'; but in this way nothing is added.

Try this...

window.location = '#';

Also, don't forget about the window.location.replace() method.

jQuery same click event for multiple elements

I normally use on instead of click. It allow me to add more events listeners to a specific function.

$(document).on("click touchend", ".class1, .class2, .class3", function () {
     //do stuff
});

Embed ruby within URL : Middleman Blog

<%= link_to "http://www.facebook.com/sharer.php?u=" + article_url(article, :text => article.title), :class => "btn btn-primary" do %>   <i class="fa fa-facebook">     Facebook Share    </i> <%end%> 

I am assuming that current_article_url is http://0.0.0.0:4567/link_to_title

How to show imageView full screen on imageView click?

You can use ImageView below two properties to show image based on your requirement :

  1. android:adjustViewBounds : Set this to true if you want the ImageView to adjust its bounds to preserve the aspect ratio of its drawable.

  2. android:scaleType :Controls how the image should be resized or moved to match the size of this ImageView

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:adjustViewBounds="true"
        android:src="@drawable/ic_launcher"/>
    

Above two properties can be use either xml or java code.

As you need to decide at run time need to show image into full screen or not so will apply above two properties at java code as below :

public class MainActivity extends Activity {

    ImageView imageView;

    boolean isImageFitToScreen;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        imageView = (ImageView) findViewById(R.id.imageView);

        imageView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(isImageFitToScreen) {
                    isImageFitToScreen=false;
                    imageView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
                    imageView.setAdjustViewBounds(true);
                }else{
                    isImageFitToScreen=true;
                    imageView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
                    imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                }
            }
        });

    }
}

How can I convince IE to simply display application/json rather than offer to download it?

Above solution was missing thing, and below code should work in every situation:

Windows Registry Editor Version 5.00
;
; Tell IE to open JSON documents in the browser.  
; 25336920-03F9-11cf-8FD0-00AA00686F13 is the CLSID for the "Browse in place" .
;  

[HKEY_CLASSES_ROOT\MIME\Database\Content Type\application/json]
"CLSID"="{25336920-03F9-11cf-8FD0-00AA00686F13}"
"Encoding"=hex:08,00,00,00

[HKEY_CLASSES_ROOT\MIME\Database\Content Type\application/x-json]
"CLSID"="{25336920-03F9-11cf-8FD0-00AA00686F13}"
"Encoding"=hex:08,00,00,00

[HKEY_CLASSES_ROOT\MIME\Database\Content Type\text/json]
"CLSID"="{25336920-03F9-11cf-8FD0-00AA00686F13}"
"Encoding"=hex:08,00,00,00

Just save it file json.reg, and run to modify your registry.

Pass a string parameter in an onclick function

Multiple parameters:

bounds.extend(marker.position);
bindInfoWindow(marker, map, infowindow,
    '<b>' + response[i].driver_name + '</b><br>' +
    '<b>' + moment(response[i].updated_at).fromNow() + '</b>
     <button onclick="myFunction(\'' + response[i].id + '\',\'' + driversList + '\')">Click me</button>'
);

Getting a UnhandledPromiseRejectionWarning when testing using mocha/chai

I had a similar experience with Chai-Webdriver for Selenium. I added await to the assertion and it fixed the issue:

Example using Cucumberjs:

Then(/I see heading with the text of Tasks/, async function() {
    await chai.expect('h1').dom.to.contain.text('Tasks');
});

MySQL Alter Table Add Field Before or After a field already present

$query = "ALTER TABLE `" . $table_prefix . "posts_to_bookmark` 
          ADD COLUMN `ping_status` INT(1) NOT NULL 
          AFTER `<TABLE COLUMN BEFORE THIS COLUMN>`";

I believe you need to have ADD COLUMN and use AFTER, not BEFORE.

In case you want to place column at the beginning of a table, use the FIRST statement:

$query = "ALTER TABLE `" . $table_prefix . "posts_to_bookmark`
          ADD COLUMN `ping_status` INT(1) NOT NULL 
          FIRST";

http://dev.mysql.com/doc/refman/5.1/en/alter-table.html

Logging best practices

As far as aspect oriented logging is concerned I was recommended PostSharp on another SO question -

Aspect Oriented Logging with Unity\T4\anything else

The link provided in the answer is worth visiting if you are evaluating logging frameworks.

Disable eslint rules for folder

YAML version :

overrides:
  - files: *-tests.js
    rules:
      no-param-reassign: 0

Example of specific rules for mocha tests :

You can also set a specific env for a folder, like this :

overrides:
  - files: test/*-tests.js
    env:
      mocha: true

This configuration will fix error message about describe and it not defined, only for your test folder:

/myproject/test/init-tests.js
6:1 error 'describe' is not defined no-undef
9:3 error 'it' is not defined no-undef

How to copy a string of std::string type in C++?

strcpy is only for C strings. For std::string you copy it like any C++ object.

std::string a = "text";
std::string b = a; // copy a into b

If you want to concatenate strings you can use the + operator:

std::string a = "text";
std::string b = "image";
a = a + b; // or a += b;

You can even do many at once:

std::string c = a + " " + b + "hello";

Although "hello" + " world" doesn't work as you might expect. You need an explicit std::string to be in there: std::string("Hello") + "world"

End of File (EOF) in C

That's a lot of questions.

  1. Why EOF is -1: usually -1 in POSIX system calls is returned on error, so i guess the idea is "EOF is kind of error"

  2. any boolean operation (including !=) returns 1 in case it's TRUE, and 0 in case it's FALSE, so getchar() != EOF is 0 when it's FALSE, meaning getchar() returned EOF.

  3. in order to emulate EOF when reading from stdin press Ctrl+D

How to handle AssertionError in Python and find out which line or statement it occurred on?

The traceback module and sys.exc_info are overkill for tracking down the source of an exception. That's all in the default traceback. So instead of calling exit(1) just re-raise:

try:
    assert "birthday cake" == "ice cream cake", "Should've asked for pie"
except AssertionError:
    print 'Houston, we have a problem.'
    raise

Which gives the following output that includes the offending statement and line number:

Houston, we have a problem.
Traceback (most recent call last):
  File "/tmp/poop.py", line 2, in <module>
    assert "birthday cake" == "ice cream cake", "Should've asked for pie"
AssertionError: Should've asked for pie

Similarly the logging module makes it easy to log a traceback for any exception (including those which are caught and never re-raised):

import logging

try:
    assert False == True 
except AssertionError:
    logging.error("Nothing is real but I can't quit...", exc_info=True)

React-Native: Module AppRegistry is not a registered callable module

I got this error in Expo because I had exported the wrong component name, e.g.

const Wonk = props => (
  <Text>Hi!</Text>
)

export default Stack;

Python initializing a list of lists

The problem is that they're all the same exact list in memory. When you use the [x]*n syntax, what you get is a list of n many x objects, but they're all references to the same object. They're not distinct instances, rather, just n references to the same instance.

To make a list of 3 different lists, do this:

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

This gives you 3 separate instances of [], which is what you want

[[]]*n is similar to

l = []
x = []
for i in range(n):
    x.append(l)

While [[] for i in range(3)] is similar to:

x = []
for i in range(n):
    x.append([])   # appending a new list!

In [20]: x = [[]] * 4

In [21]: [id(i) for i in x]
Out[21]: [164363948, 164363948, 164363948, 164363948] # same id()'s for each list,i.e same object


In [22]: x=[[] for i in range(4)]

In [23]: [id(i) for i in x]
Out[23]: [164382060, 164364140, 164363628, 164381292] #different id(), i.e unique objects this time

Android: How to turn screen on and off programmatically?

Hi I hope this will help:

 private PowerManager mPowerManager;
 private PowerManager.WakeLock mWakeLock;

 public void turnOnScreen(){
     // turn on screen
     Log.v("ProximityActivity", "ON!");
     mWakeLock = mPowerManager.newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP, "tag");
     mWakeLock.acquire();
}

 @TargetApi(21) //Suppress lint error for PROXIMITY_SCREEN_OFF_WAKE_LOCK
 public void turnOffScreen(){
     // turn off screen
     Log.v("ProximityActivity", "OFF!");
     mWakeLock = mPowerManager.newWakeLock(PowerManager.PROXIMITY_SCREEN_OFF_WAKE_LOCK, "tag");
     mWakeLock.acquire();
}

How to update and delete a cookie?

check this out A little framework: a complete cookies reader/writer with full Unicode support

/*\
|*|
|*|  :: cookies.js ::
|*|
|*|  A complete cookies reader/writer framework with full unicode support.
|*|
|*|  Revision #1 - September 4, 2014
|*|
|*|  https://developer.mozilla.org/en-US/docs/Web/API/document.cookie
|*|  https://developer.mozilla.org/User:fusionchess
|*|  https://github.com/madmurphy/cookies.js
|*|
|*|  This framework is released under the GNU Public License, version 3 or later.
|*|  http://www.gnu.org/licenses/gpl-3.0-standalone.html
|*|
|*|  Syntaxes:
|*|
|*|  * docCookies.setItem(name, value[, end[, path[, domain[, secure]]]])
|*|  * docCookies.getItem(name)
|*|  * docCookies.removeItem(name[, path[, domain]])
|*|  * docCookies.hasItem(name)
|*|  * docCookies.keys()
|*|
\*/

var docCookies = {
  getItem: function (sKey) {
    if (!sKey) { return null; }
    return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
  },
  setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
    if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; }
    var sExpires = "";
    if (vEnd) {
      switch (vEnd.constructor) {
        case Number:
          sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
          break;
        case String:
          sExpires = "; expires=" + vEnd;
          break;
        case Date:
          sExpires = "; expires=" + vEnd.toUTCString();
          break;
      }
    }
    document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
    return true;
  },
  removeItem: function (sKey, sPath, sDomain) {
    if (!this.hasItem(sKey)) { return false; }
    document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "");
    return true;
  },
  hasItem: function (sKey) {
    if (!sKey) { return false; }
    return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
  },
  keys: function () {
    var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/);
    for (var nLen = aKeys.length, nIdx = 0; nIdx < nLen; nIdx++) { aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]); }
    return aKeys;
  }
};

How to compare arrays in C#?

Array.Equals() appears to only test for the same instance.

There doesn't appear to be a method that compares the values but it would be very easy to write.

Just compare the lengths, if not equal, return false. Otherwise, loop through each value in the array and determine if they match.

Why doesn't list have safe "get" method like dictionary?

Credits to jose.angel.jimenez and Gus Bus.


For the "oneliner" fans…


If you want the first element of a list or if you want a default value if the list is empty try:

liste = ['a', 'b', 'c']
value = (liste[0:1] or ('default',))[0]
print(value)

returns a

and

liste = []
value = (liste[0:1] or ('default',))[0]
print(value)

returns default


Examples for other elements…

liste = ['a', 'b', 'c']
print(liste[0:1])  # returns ['a']
print(liste[1:2])  # returns ['b']
print(liste[2:3])  # returns ['c']
print(liste[3:4])  # returns []

With default fallback…

liste = ['a', 'b', 'c']
print((liste[0:1] or ('default',))[0])  # returns a
print((liste[1:2] or ('default',))[0])  # returns b
print((liste[2:3] or ('default',))[0])  # returns c
print((liste[3:4] or ('default',))[0])  # returns default

Possibly shorter:

liste = ['a', 'b', 'c']
value, = liste[:1] or ('default',)
print(value)  # returns a

It looks like you need the comma before the equal sign, the equal sign and the latter parenthesis.


More general:

liste = ['a', 'b', 'c']
f = lambda l, x, d: l[x:x+1] and l[x] or d
print(f(liste, 0, 'default'))  # returns a
print(f(liste, 1, 'default'))  # returns b
print(f(liste, 2, 'default'))  # returns c
print(f(liste, 3, 'default'))  # returns default

Tested with Python 3.6.0 (v3.6.0:41df79263a11, Dec 22 2016, 17:23:13)

How to create a multiline UITextfield?

This code block is enough. Please don't forget to set delegate in viewDidLoad or by storyboard just before to use the following extension:

extension YOUR_VIEW_CONTROLLER: UITextViewDelegate {

func textViewDidBeginEditing (_ textView: UITextView) {
    if YOUR_TEXT_VIEW.text.isEmpty || YOUR_TEXT_VIEW.text == "YOUR DEFAULT PLACEHOLDER TEXT HERE" {
        YOUR_TEXT_VIEW.text = nil
        YOUR_TEXT_VIEW.textColor = .red // YOUR PREFERED COLOR HERE
    }
}
func textViewDidEndEditing (_ textView: UITextView) {
    if YOUR_TEXT_VIEW.text.isEmpty {
        YOUR_TEXT_VIEW.textColor = UIColor.gray // YOUR PREFERED PLACEHOLDER COLOR HERE
        YOUR_TEXT_VIEW.text =  "YOUR DEFAULT PLACEHOLDER TEXT HERE"
    }
}

}

How to redirect siteA to siteB with A or CNAME records

These days, many site owners are using CDN services which pulls data from CDN server. If that's your case then you are left with two options:

  1. Create a subdomain and edit DNS by Adding a CNAME record

  2. Don't create a subdomain but only create a CNAME record pointing back to your temporary DNS URL.

This solution only implies to pulling code from CDN which will show that it's fetching data from cdn.sitename.com but practically its pulling from your CDN host.

SSRS expression to format two decimal places does not show zeros

Format(Fields!CUL1.Value, "0.00") would work better since @abe suggests they want to show 0.00 , and if the value was 0, "#0.##" would show "0".

How should strace be used?

Strace stands out as a tool for investigating production systems where you can't afford to run these programs under a debugger. In particular, we have used strace in the following two situations:

  • Program foo seems to be in deadlock and has become unresponsive. This could be a target for gdb; however, we haven't always had the source code or sometimes were dealing with scripted languages that weren't straight-forward to run under a debugger. In this case, you run strace on an already running program and you will get the list of system calls being made. This is particularly useful if you are investigating a client/server application or an application that interacts with a database
  • Investigating why a program is slow. In particular, we had just moved to a new distributed file system and the new throughput of the system was very slow. You can specify strace with the '-T' option which will tell you how much time was spent in each system call. This helped to determine why the file system was causing things to slow down.

For an example of analyzing using strace see my answer to this question.

Trying to get the average of a count resultset

You just can put your query as a subquery:

SELECT avg(count)
  FROM 
    (
    SELECT COUNT (*) AS Count
      FROM Table T
     WHERE T.Update_time =
               (SELECT MAX (B.Update_time )
                  FROM Table B
                 WHERE (B.Id = T.Id))
    GROUP BY T.Grouping
    ) as counts

Edit: I think this should be the same:

SELECT count(*) / count(distinct T.Grouping)
  FROM Table T
 WHERE T.Update_time =
           (SELECT MAX (B.Update_time)
              FROM Table B
             WHERE (B.Id = T.Id))

Determine the line of code that causes a segmentation fault?

Also, you can give valgrind a try: if you install valgrind and run

valgrind --leak-check=full <program>

then it will run your program and display stack traces for any segfaults, as well as any invalid memory reads or writes and memory leaks. It's really quite useful.

How to open html file?

import codecs
f=codecs.open("test.html", 'r')
print f.read()

Try something like this.

HTML5: Slider with two inputs possible?

I've been looking for a lightweight, dependency free dual slider for some time (it seemed crazy to import jQuery just for this) and there don't seem to be many out there. I ended up modifying @Wildhoney's code a bit and really like it.

_x000D_
_x000D_
function getVals(){_x000D_
  // Get slider values_x000D_
  var parent = this.parentNode;_x000D_
  var slides = parent.getElementsByTagName("input");_x000D_
    var slide1 = parseFloat( slides[0].value );_x000D_
    var slide2 = parseFloat( slides[1].value );_x000D_
  // Neither slider will clip the other, so make sure we determine which is larger_x000D_
  if( slide1 > slide2 ){ var tmp = slide2; slide2 = slide1; slide1 = tmp; }_x000D_
  _x000D_
  var displayElement = parent.getElementsByClassName("rangeValues")[0];_x000D_
      displayElement.innerHTML = slide1 + " - " + slide2;_x000D_
}_x000D_
_x000D_
window.onload = function(){_x000D_
  // Initialize Sliders_x000D_
  var sliderSections = document.getElementsByClassName("range-slider");_x000D_
      for( var x = 0; x < sliderSections.length; x++ ){_x000D_
        var sliders = sliderSections[x].getElementsByTagName("input");_x000D_
        for( var y = 0; y < sliders.length; y++ ){_x000D_
          if( sliders[y].type ==="range" ){_x000D_
            sliders[y].oninput = getVals;_x000D_
            // Manually trigger event first time to display values_x000D_
            sliders[y].oninput();_x000D_
          }_x000D_
        }_x000D_
      }_x000D_
}
_x000D_
  section.range-slider {_x000D_
    position: relative;_x000D_
    width: 200px;_x000D_
    height: 35px;_x000D_
    text-align: center;_x000D_
}_x000D_
_x000D_
section.range-slider input {_x000D_
    pointer-events: none;_x000D_
    position: absolute;_x000D_
    overflow: hidden;_x000D_
    left: 0;_x000D_
    top: 15px;_x000D_
    width: 200px;_x000D_
    outline: none;_x000D_
    height: 18px;_x000D_
    margin: 0;_x000D_
    padding: 0;_x000D_
}_x000D_
_x000D_
section.range-slider input::-webkit-slider-thumb {_x000D_
    pointer-events: all;_x000D_
    position: relative;_x000D_
    z-index: 1;_x000D_
    outline: 0;_x000D_
}_x000D_
_x000D_
section.range-slider input::-moz-range-thumb {_x000D_
    pointer-events: all;_x000D_
    position: relative;_x000D_
    z-index: 10;_x000D_
    -moz-appearance: none;_x000D_
    width: 9px;_x000D_
}_x000D_
_x000D_
section.range-slider input::-moz-range-track {_x000D_
    position: relative;_x000D_
    z-index: -1;_x000D_
    background-color: rgba(0, 0, 0, 1);_x000D_
    border: 0;_x000D_
}_x000D_
section.range-slider input:last-of-type::-moz-range-track {_x000D_
    -moz-appearance: none;_x000D_
    background: none transparent;_x000D_
    border: 0;_x000D_
}_x000D_
  section.range-slider input[type=range]::-moz-focus-outer {_x000D_
  border: 0;_x000D_
}
_x000D_
<!-- This block can be reused as many times as needed -->_x000D_
<section class="range-slider">_x000D_
  <span class="rangeValues"></span>_x000D_
  <input value="5" min="0" max="15" step="0.5" type="range">_x000D_
  <input value="10" min="0" max="15" step="0.5" type="range">_x000D_
</section>
_x000D_
_x000D_
_x000D_

How do I get video durations with YouTube API version 3?

You can get the duration from the 'contentDetails' field in the json response.

enter image description here

SQL WHERE ID IN (id1, id2, ..., idn)

Try this

SELECT Position_ID , Position_Name
FROM 
position
WHERE Position_ID IN (6 ,7 ,8)
ORDER BY Position_Name

PHP Excel Header

The problem is you typed the wrong file extension for excel file. you used .xsl instead of xls.

I know i came in late but it can help future readers of this post.

in a "using" block is a SqlConnection closed on return or exception?

Yes to both questions. The using statement gets compiled into a try/finally block

using (SqlConnection connection = new SqlConnection(connectionString))
{
}

is the same as

SqlConnection connection = null;
try
{
    connection = new SqlConnection(connectionString);
}
finally
{
   if(connection != null)
        ((IDisposable)connection).Dispose();
}

Edit: Fixing the cast to Disposable http://msdn.microsoft.com/en-us/library/yh598w02.aspx

Comparing strings in Java

In onclik function replace first line with this line u will definitely get right result.

if (passw1.getText().toString().equalsIgnoreCase("1234") && passw2.getText().toString().equalsIgnoreCase("1234")){

In java how to get substring from a string till a character c?

How about using regex?

String firstWord = filename.replaceAll("\\..*","")

This replaces everything from the first dot to the end with "" (ie it clears it, leaving you with what you want)

Here's a test:

System.out.println("abc.def.hij".replaceAll("\\..*", "");

Output:

abc

Debugging iframes with Chrome developer tools

In my fairly complex scenario the accepted answer for how to do this in Chrome doesn't work for me. You may want to try the Firefox debugger instead (part of the Firefox developer tools), which shows all of the 'Sources', including those that are part of an iFrame

Unable to load config info from /usr/local/ssl/openssl.cnf on Windows

On the basic question of why openssl is not found: Short answer:Some installation packages for openssl have a default openssl.cnf pre-included. Other packages do not. In the latter case you will include one from the link shown below; You can enter additional user-specifics --DN name,etc-- as needed.

From https://www.openssl.org/docs/manmaster/man5/config.html,I quote directly:

"OPENSSL LIBRARY CONFIGURATION

Applications can automatically configure certain aspects of OpenSSL using the master OpenSSL configuration file, or optionally an alternative configuration file. The openssl utility includes this functionality: any sub command uses the master OpenSSL configuration file unless an option is used in the sub command to use an alternative configuration file.

To enable library configuration the default section needs to contain an appropriate line which points to the main configuration section. The default name is openssl_conf which is used by the openssl utility. Other applications may use an alternative name such as myapplication_conf. All library configuration lines appear in the default section at the start of the configuration file.

The configuration section should consist of a set of name value pairs which contain specific module configuration information. The name represents the name of the configuration module. The meaning of the value is module specific: it may, for example, represent a further configuration section containing configuration module specific information. E.g.:"

So it appears one must self configure openssl.cnf according to your Distinguished Name (DN), along with other entries specific to your use.

Here is the template file from which you can generate openssl.cnf with your specific entries.

One Application actually has a demo installation that includes a demo .cnf file.

Additionally, if you need to programmatically access .cnf files, you can include appropriate headers --openssl/conf.h-- and parse your .cnf files using

CONF_modules_load_file(const char *filename, const char *appname,
                            unsigned long flags);

Here are docs for "CONF_modules_load_file";

How to convert comma-separated String to List?

I usually use precompiled pattern for the list. And also this is slightly more universal since it can consider brackets which follows some of the listToString expressions.

private static final Pattern listAsString = Pattern.compile("^\\[?([^\\[\\]]*)\\]?$");

private List<String> getList(String value) {
  Matcher matcher = listAsString.matcher((String) value);
  if (matcher.matches()) {
    String[] split = matcher.group(matcher.groupCount()).split("\\s*,\\s*");
    return new ArrayList<>(Arrays.asList(split));
  }
  return Collections.emptyList();