Programs & Examples On #Path manipulation

Given a filesystem path, is there a shorter way to extract the filename without its extension?

string filepath = "C:\\Program Files\\example.txt";
FileVersionInfo myFileVersionInfo = FileVersionInfo.GetVersionInfo(filepath);
FileInfo fi = new FileInfo(filepath);
Console.WriteLine(fi.Name);

//input to the "fi" is a full path to the file from "filepath"
//This code will return the fileName from the given path

//output
//example.txt

How to get only the last part of a path in Python?

Use os.path.normpath, then os.path.basename:

>>> os.path.basename(os.path.normpath('/folderA/folderB/folderC/folderD/'))
'folderD'

The first strips off any trailing slashes, the second gives you the last part of the path. Using only basename gives everything after the last slash, which in this case is ''.

Python os.path.join on Windows

To be pedantic, it's probably not good to hardcode either / or \ as the path separator. Maybe this would be best?

mypath = os.path.join('c:%s' % os.sep, 'sourcedir')

or

mypath = os.path.join('c:' + os.sep, 'sourcedir')

C/C++ line number

You should use the preprocessor macro __LINE__ and __FILE__. They are predefined macros and part of the C/C++ standard. During preprocessing, they are replaced respectively by a constant string holding an integer representing the current line number and by the current file name.

Others preprocessor variables :

  • __func__ : function name (this is part of C99, not all C++ compilers support it)
  • __DATE__ : a string of form "Mmm dd yyyy"
  • __TIME__ : a string of form "hh:mm:ss"

Your code will be :

if(!Logical)
  printf("Not logical value at line number %d in file %s\n", __LINE__, __FILE__);

How do I delete unpushed git commits?

Delete the most recent commit, keeping the work you've done:

git reset --soft HEAD~1

Delete the most recent commit, destroying the work you've done:

git reset --hard HEAD~1

How to connect to a MySQL Data Source in Visual Studio

  1. Download MySQL Connector .NET (6.9.4 on this date) from here and install it CUSTOM!
  2. Remove the ASP.NET WEB providers option or the installer will write in machine.config!
  3. Download MySQL for Visual Studio from here and install it CUSTOM. Be sure to check the integration options. You need this step because after Connector .NET 6.7 the installer will no longer integrate the connector with Visual Studio. This installer can take longer then expected. This is it.

You can install it from alternate download here which should have integrated with VS correctly but it did not and I got a strange error and after the reinstall it is ok.

MySQL check if a table exists without throwing an exception

If the reason for wanting to do this is is conditional table creation, then 'CREATE TABLE IF NOT EXISTS' seems ideal for the job. Until I discovered this, I used the 'DESCRIBE' method above. More info here: MySQL "CREATE TABLE IF NOT EXISTS" -> Error 1050

jQuery - Add ID instead of Class

$('selector').attr( 'id', 'yourId' );

Setting the selected attribute on a select list using jQuery

$('#select_id option:eq(0)').prop('selected', 'selected');

its good

How to add anything in <head> through jquery/javascript?

You can select it and add to it as normal:

$('head').append('<link />');

Could not find the main class, program will exit

Is Java installed on your computer? Is the path to its bin directory set properly (in other words if you type 'java' from the command line do you get back a list of instructions or do you get something like "java is not recognized as a .....")?

You could try try running squirrel-sql.jar from the command line (from the squirrel sql directory), using:

java -jar squirrel-sql.jar

Gem Command not found

try

$ /usr/bin/pd-gem

or

$ pd-gem

Deserializing JSON array into strongly typed .NET object

try

List<TheUser> friends = jsonSerializer.Deserialize<List<TheUser>>(response);

How to write a SQL DELETE statement with a SELECT statement in the WHERE clause?

Did something like that once:

CREATE TABLE exclusions(excl VARCHAR(250));
INSERT INTO exclusions(excl)
VALUES
       ('%timeline%'),
       ('%Placeholders%'),
       ('%Stages%'),
       ('%master_stage_1205x465%'),
       ('%Accessories%'),
       ('%chosen-sprite.png'),
('%WebResource.axd');
GO
CREATE VIEW ToBeDeleted AS 
SELECT * FROM chunks
       WHERE chunks.file_id IN
       (
       SELECT DISTINCT
             lf.file_id
       FROM LargeFiles lf
       WHERE lf.file_id NOT IN
             (
             SELECT DISTINCT
                    lf.file_id
             FROM LargeFiles lf
                LEFT JOIN exclusions e ON(lf.URL LIKE e.excl)
                WHERE e.excl IS NULL
             )
       );
GO
CHECKPOINT
GO
SET NOCOUNT ON;
DECLARE @r INT;
SET @r = 1;
WHILE @r>0

BEGIN
    DELETE TOP (10000) FROM ToBeDeleted;
    SET @r = @@ROWCOUNT  
END
GO

Get filename from input [type='file'] using jQuery

There is no jQuery function for this. You have to access the DOM element and check the files property.

document.getElementById("image_file").files[0];

Or

$('#image_file')[0].files[0]

How to call JavaScript function instead of href in HTML

If you only have as "click event handler", use a <button> instead. A link has a specific semantic meaning.

E.g.:

<button onclick="ShowOld(2367,146986,2)">
    <img title="next page" alt="next page" src="/themes/me/img/arrn.png">
</button>

Why compile Python code?

There is a performance increase in running compiled python. However when you run a .py file as an imported module, python will compile and store it, and as long as the .py file does not change it will always use the compiled version.

With any interpeted language when the file is used the process looks something like this:
1. File is processed by the interpeter.
2. File is compiled
3. Compiled code is executed.

obviously by using pre-compiled code you can eliminate step 2, this applies python, PHP and others.

Heres an interesting blog post explaining the differences http://julipedia.blogspot.com/2004/07/compiled-vs-interpreted-languages.html
And here's an entry that explains the Python compile process http://effbot.org/zone/python-compile.htm

laravel 5 : Class 'input' not found

Miscall of Class it should be Input not input

Oracle PL/SQL - How to create a simple array variable?

Sample programs as follows and provided on link also https://oracle-concepts-learning.blogspot.com/

plsql table or associated array.

        DECLARE 
            TYPE salary IS TABLE OF NUMBER INDEX BY VARCHAR2(20); 
            salary_list salary; 
            name VARCHAR2(20); 
        BEGIN 
           -- adding elements to the table 
           salary_list('Rajnish') := 62000; salary_list('Minakshi') := 75000; 
           salary_list('Martin') := 100000; salary_list('James') := 78000; 
           -- printing the table name := salary_list.FIRST; WHILE name IS NOT null 
            LOOP 
               dbms_output.put_line ('Salary of ' || name || ' is ' || 
               TO_CHAR(salary_list(name))); 
               name := salary_list.NEXT(name); 
            END LOOP; 
        END; 
        /

How can I get the error message for the mail() function?

There is no error message associated with the mail() function. There is only a true or false returned on whether the email was accepted for delivery. Not whether it ultimately gets delivered, but basically whether the domain exists and the address is a validly formatted email address.

How to extract a single value from JSON response?

using json.loads will turn your data into a python dictionary.

Dictionaries values are accessed using ['key']

resp_str = {
  "name" : "ns1:timeSeriesResponseType",
  "declaredType" : "org.cuahsi.waterml.TimeSeriesResponseType",
  "scope" : "javax.xml.bind.JAXBElement$GlobalScope",
  "value" : {
    "queryInfo" : {
      "creationTime" : 1349724919000,
      "queryURL" : "http://waterservices.usgs.gov/nwis/iv/",
      "criteria" : {
        "locationParam" : "[ALL:103232434]",
        "variableParam" : "[00060, 00065]"
      },
      "note" : [ {
        "value" : "[ALL:103232434]",
        "title" : "filter:sites"
      }, {
        "value" : "[mode=LATEST, modifiedSince=null]",
        "title" : "filter:timeRange"
      }, {
        "value" : "sdas01",
        "title" : "server"
      } ]
    }
  },
  "nil" : false,
  "globalScope" : true,
  "typeSubstituted" : false
}

would translate into a python diction

resp_dict = json.loads(resp_str)

resp_dict['name'] # "ns1:timeSeriesResponseType"

resp_dict['value']['queryInfo']['creationTime'] # 1349724919000

What is a "cache-friendly" code?

Just piling on: the classic example of cache-unfriendly versus cache-friendly code is the "cache blocking" of matrix multiply.

Naive matrix multiply looks like:

for(i=0;i<N;i++) {
   for(j=0;j<N;j++) {
      dest[i][j] = 0;
      for( k=0;k<N;k++) {
         dest[i][j] += src1[i][k] * src2[k][j];
      }
   }
}

If N is large, e.g. if N * sizeof(elemType) is greater than the cache size, then every single access to src2[k][j] will be a cache miss.

There are many different ways of optimizing this for a cache. Here's a very simple example: instead of reading one item per cache line in the inner loop, use all of the items:

int itemsPerCacheLine = CacheLineSize / sizeof(elemType);

for(i=0;i<N;i++) {
   for(j=0;j<N;j += itemsPerCacheLine ) {
      for(jj=0;jj<itemsPerCacheLine; jj+) {
         dest[i][j+jj] = 0;
      }
      for( k=0;k<N;k++) {
         for(jj=0;jj<itemsPerCacheLine; jj+) {
            dest[i][j+jj] += src1[i][k] * src2[k][j+jj];
         }
      }
   }
}

If the cache line size is 64 bytes, and we are operating on 32 bit (4 byte) floats, then there are 16 items per cache line. And the number of cache misses via just this simple transformation is reduced approximately 16-fold.

Fancier transformations operate on 2D tiles, optimize for multiple caches (L1, L2, TLB), and so on.

Some results of googling "cache blocking":

http://stumptown.cc.gt.atl.ga.us/cse6230-hpcta-fa11/slides/11a-matmul-goto.pdf

http://software.intel.com/en-us/articles/cache-blocking-techniques

A nice video animation of an optimized cache blocking algorithm.

http://www.youtube.com/watch?v=IFWgwGMMrh0

Loop tiling is very closely related:

http://en.wikipedia.org/wiki/Loop_tiling

Git Push Error: insufficient permission for adding an object to repository database

Solved for me... just this:

sudo chmod 777 -R .git/objects

Load local javascript file in chrome for testing?

The easiest way I found was to copy your file contents into you browser console and hit enter. The disadvantage of this approach is that you can only debug with console.log statements.

Changing the row height of a datagridview

You can change the row height of the Datagridview in the .cs [Design].

Then click the datagridview Properties.

Look for RowTemplate and expand it,

then type the value in the Height.

How can I stop the browser back button using JavaScript?

In a modern browser this seems to work:

// https://developer.mozilla.org/en-US/docs/Web/API/History_API
let popHandler = () => {
  if (confirm('Go back?')) {
    window.history.back() 
  } else {
    window.history.forward()
    setTimeout(() => {
      window.addEventListener('popstate', popHandler, {once: true})
    }, 50) // delay needed since the above is an async operation for some reason
  }
}
window.addEventListener('popstate', popHandler, {once: true})
window.history.pushState(null,null,null)

How to change a single value in a NumPy array?

Is this what you are after? Just index the element and assign a new value.

A[2,1]=150

A
Out[345]: 
array([[ 1,  2,  3,  4],
       [ 5,  6,  7,  8],
       [ 9, 150, 11, 12],
       [13, 14, 15, 16]])

Radio button checked event handling

$(document).on('change','.radio-button', function(){

    const radio = $(this);

    if (radio.is(':checked')) {
      console.log(radio)
    }

});

How to compile C programming in Windows 7?

If you are familiar with gcc, as you indicated in the question, you can install MinGW, which will set a linux-like compile environment in Win7. Otherwise, Visual Studio 2010 Express is the best choice.

Span inside anchor or anchor inside span or doesn't matter?

3 - It doesn't matter.

BUT, I tend to only use a <span> inside an <a> if it's only for a part of the contents of the tag i.e.

<a href="#">some <span class="red">text</span></a>

Rather than:

<a href="#"><span class="red">some text</span></a>

Which should obviously just be:

<a href="#" class="red">some text</a>

Conditional WHERE clause in SQL Server

Try this one -

WHERE DateDropped = 0
    AND (
        (ISNULL(@JobsOnHold, 0) = 1 AND DateAppr >= 0) 
        OR 
        (ISNULL(@JobsOnHold, 0) != 1 AND DateAppr != 0)
    )

How can I programmatically freeze the top row of an Excel worksheet in Excel 2007 VBA?

Tomalak already gave you a correct answer, but I would like to add that most of the times when you would like to know the VBA code needed to do a certain action in the user interface it is a good idea to record a macro.

In this case click Record Macro on the developer tab of the Ribbon, freeze the top row and then stop recording. Excel will have the following macro recorded for you which also does the job:

With ActiveWindow
    .SplitColumn = 0
    .SplitRow = 1
End With
ActiveWindow.FreezePanes = True

How to customize the background/border colors of a grouped table view cell?

One thing I ran into with the above CustomCellBackgroundView code from Mike Akers which might be useful to others:

cell.backgroundView doesn't get automatically redrawn when cells are reused, and changes to the backgroundView's position var don't affect reused cells. That means long tables will have incorrectly drawn cell.backgroundViews given their positions.

To fix this without having to create a new backgroundView every time a row is displayed, call [cell.backgroundView setNeedsDisplay] at the end of your -[UITableViewController tableView:cellForRowAtIndexPath:]. Or for a more reusable solution, override CustomCellBackgroundView's position setter to include a [self setNeedsDisplay].

How can I convert radians to degrees with Python?

Python includes two functions in the math package; radians converts degrees to radians, and degrees converts radians to degrees.

To match the output of your calculator you need:

>>> math.cos(math.radians(1))
0.9998476951563913

Note that all of the trig functions convert between an angle and the ratio of two sides of a triangle. cos, sin, and tan take an angle in radians as input and return the ratio; acos, asin, and atan take a ratio as input and return an angle in radians. You only convert the angles, never the ratios.

Java constructor/method with optional parameters?

You can use varargs for optional parameters:

public class Booyah {
    public static void main(String[] args) {
        woohoo(1);
        woohoo(2, 3);
    }
    static void woohoo(int required, Integer... optional) {
        Integer lala;
        if (optional.length == 1) {
            lala = optional[0];
        } else {
            lala = 2;
        }
        System.out.println(required + lala);
    }
}

Also it's important to note the use of Integer over int. Integer is a wrapper around the primitive int, which allows one to make comparisons with null as necessary.

How do I get the position selected in a RecyclerView?

Set your onClickListeners on onBindViewHolder() and you can access the position from there. If you set them in your ViewHolder you won't know what position was clicked unless you also pass the position into the ViewHolder

EDIT

As pskink pointed out ViewHolder has a getPosition() so the way you were originally doing it was correct.

When the view is clicked you can use getPosition() in your ViewHolder and it returns the position

Update

getPosition() is now deprecated and replaced with getAdapterPosition()

Update 2020

getAdapterPosition() is now deprecated and replaced with getAbsoluteAdapterPosition() or getBindingAdapterPosition()

Kotlin code:

override fun onBindViewHolder(holder: MyHolder, position: Int) {
        // - get element from your dataset at this position
        val item = myDataset.get(holder.absoluteAdapterPosition)
    }

Return first N key:value pairs from dict

This depends on what is 'most efficient' in your case.

If you just want a semi-random sample of a huge dictionary foo, use foo.iteritems() and take as many values from it as you need, it's a lazy operation that avoids creation of an explicit list of keys or items.

If you need to sort keys first, there's no way around using something like keys = foo.keys(); keys.sort() or sorted(foo.iterkeys()), you'll have to build an explicit list of keys. Then slice or iterate through first N keys.

BTW why do you care about the 'efficient' way? Did you profile your program? If you did not, use the obvious and easy to understand way first. Chances are it will do pretty well without becoming a bottleneck.

SQL Query - Concatenating Results into One String

If you're on SQL Server 2005 or up, you can use this FOR XML PATH & STUFF trick:

DECLARE @CodeNameString varchar(100)

SELECT 
   @CodeNameString = STUFF( (SELECT ',' + CodeName 
                             FROM dbo.AccountCodes 
                             ORDER BY Sort
                             FOR XML PATH('')), 
                            1, 1, '')

The FOR XML PATH('') basically concatenates your strings together into one, long XML result (something like ,code1,code2,code3 etc.) and the STUFF puts a "nothing" character at the first character, e.g. wipes out the "superfluous" first comma, to give you the result you're probably looking for.

UPDATE: OK - I understand the comments - if your text in the database table already contains characters like <, > or &, then my current solution will in fact encode those into &lt;, &gt;, and &amp;.

If you have a problem with that XML encoding - then yes, you must look at the solution proposed by @KM which works for those characters, too. One word of warning from me: this approach is a lot more resource and processing intensive - just so you know.

how to check confirm password field in form without reloading page

The code proposed by #Chandrahasa Rai works almost perfectly good, with one exception!

When triggering function checkPass(), i changed onkeypress to onkeyup so the last key pressed can be processed too. Otherwise when You type a password, for example: "1234", when You type the last key "4", the script triggers checkPass() before processing "4", so it actually checks "123" instead of "1234". You have to give it a chance by letting key go up :) Now everything should be working fine!

#Chandrahasa Rai, HTML code:

<input type="text" onkeypress="checkPass();" name="password" class="form-control" id="password" placeholder="Password" required>

<input type="text" onkeypress="checkPass();" name="rpassword" class="form-control" id="rpassword" placeholder="Retype Password" required>

#my modification:

<input type="text" onkeyup="checkPass();" name="password" class="form-control" id="password" placeholder="Password" required>

<input type="text" onkeyup="checkPass();" name="rpassword" class="form-control" id="rpassword" placeholder="Retype Password" required>

Add a new column to existing table in a migration

First you have to create a migration, you can use the migrate:make command on the laravel artisan CLI.Old laravel version like laravel 4 you may use this command for Laravel 4:

php artisan migrate:make add_paid_to_users

And for laravel 5 version

for Laravel 5+:

php artisan make:migration add_paid_to_users_table --table=users

Then you need to use the Schema::table() . And you have to add the column:

public function up()

{

    Schema::table('users', function($table) {

        $table->integer('paid');

    });

}

further you can check this

Android-java- How to sort a list of objects by a certain value within the object

You can compare two String by using this.

Collections.sort(contactsList, new Comparator<ContactsData>() {

                    @Override
                    public int compare(ContactsData lhs, ContactsData rhs) {

                        char l = Character.toUpperCase(lhs.name.charAt(0));

                        if (l < 'A' || l > 'Z')

                            l += 'Z';

                        char r = Character.toUpperCase(rhs.name.charAt(0));

                        if (r < 'A' || r > 'Z')

                            r += 'Z';

                        String s1 = l + lhs.name.substring(1);

                        String s2 = r + rhs.name.substring(1);

                        return s1.compareTo(s2);

                    }

                });

And Now make a ContactData Class.

public class ContactsData {

public String name;
public String id;
public String email;
public String avatar; 
public String connection_type;
public String thumb;
public String small;
public String first_name;
public String last_name;
public String no_of_user;
public int grpIndex;

public ContactsData(String name, String id, String email, String avatar, String connection_type)
{
    this.name = name;
    this.id = id;
    this.email = email;
    this.avatar = avatar;
    this.connection_type = connection_type;

}
}

Here contactsList is :

public static ArrayList<ContactsData> contactsList = new ArrayList<ContactsData>();

EditorFor() and html properties

None of the answers in this or any other thread on setting HTML attributes for @Html.EditorFor were much help to me. However, I did find a great answer at

Styling an @Html.EditorFor helper

I used the same approach and it worked beautifully without writing a lot of extra code. Note that the id attribute of the html output of Html.EditorFor is set. The view code

<style type="text/css">
#dob
{
   width:6em;
}
</style>

@using (Html.BeginForm())
{
   Enter date: 
   @Html.EditorFor(m => m.DateOfBirth, null, "dob", null)
}

The model property with data annotation and date formatting as "dd MMM yyyy"

[Required(ErrorMessage= "Date of birth is required")]
[DisplayFormat(ApplyFormatInEditMode = true, DataFormatString = "{0:dd MMM yyyy}")]
public DateTime DateOfBirth { get; set; }

Worked like a charm without writing a whole lot of extra code. This answer uses ASP.NET MVC 3 Razor C#.

How can I change or remove HTML5 form validation default error messages?

To prevent the browser validation message from appearing in your document, with jQuery:

$('input, select, textarea').on("invalid", function(e) {
    e.preventDefault();
});

What's the difference between Perl's backticks, system, and exec?

Let me quote the manuals first:

perldoc exec():

The exec function executes a system command and never returns-- use system instead of exec if you want it to return

perldoc system():

Does exactly the same thing as exec LIST , except that a fork is done first, and the parent process waits for the child process to complete.

In contrast to exec and system, backticks don't give you the return value but the collected STDOUT.

perldoc `String`:

A string which is (possibly) interpolated and then executed as a system command with /bin/sh or its equivalent. Shell wildcards, pipes, and redirections will be honored. The collected standard output of the command is returned; standard error is unaffected.


Alternatives:

In more complex scenarios, where you want to fetch STDOUT, STDERR or the return code, you can use well known standard modules like IPC::Open2 and IPC::Open3.

Example:

use IPC::Open2;
my $pid = open2(\*CHLD_OUT, \*CHLD_IN, 'some', 'cmd', 'and', 'args');
waitpid( $pid, 0 );
my $child_exit_status = $? >> 8;

Finally, IPC::Run from the CPAN is also worth looking at…

Fit image to table cell [Pure HTML]

Inline content leaves space at the bottom for characters that descend (j, y, q):

https://developer.mozilla.org/en-US/docs/Images,_Tables,_and_Mysterious_Gaps

There are a couple fixes:

Use display: block;

<img style="display:block;" width="100%" height="100%" src="http://dummyimage.com/68x68/000/fff" />

or use vertical-align: bottom;

<img style="vertical-align: bottom;" width="100%" height="100%" src="http://dummyimage.com/68x68/000/fff" />

how to File.listFiles in alphabetical order?

I think the previous answer is the best way to do it here is another simple way. just to print the sorted results.

 String path="/tmp";
 String[] dirListing = null;
 File dir = new File(path);
 dirListing = dir.list();
 Arrays.sort(dirListing);
 System.out.println(Arrays.deepToString(dirListing));

VB6 IDE cannot load MSCOMCTL.OCX after update KB 2687323

I use win7 and has same problem. Today I solved this problem, through loading with many error with my project just give order to continue after that goto Project=> Component => Microsoft Windows Common Controls 6.0 (SP6) then save the project (file use was c:\windows\syswow64\mscomctl.ocx)

Greater than and less than in one statement

Please just write a static method somewhere and write:

if( isSizeBetween(orderBean.getFiles(), 0, 5) ){
    // do your stuff 
}

How do I debug Windows services in Visual Studio?

Just add a contructor to your service class (if you don't have it already). Below, you can check and example for visual basic .net.

Public Sub New()
   OnStart(Nothing) 
End Sub

After, that, right-click on project and select "Debug -> Start a new instance".

ReactJS lifecycle method inside a function Component

You can make use of create-react-class module. Official documentation

Of course you must first install it

npm install create-react-class

Here is a working example

import React from "react";
import ReactDOM from "react-dom"
let createReactClass = require('create-react-class')


let Clock = createReactClass({
    getInitialState:function(){
        return {date:new Date()}
    },

    render:function(){
        return (
            <h1>{this.state.date.toLocaleTimeString()}</h1>
        )
    },

    componentDidMount:function(){
        this.timerId = setInterval(()=>this.setState({date:new Date()}),1000)
    },

    componentWillUnmount:function(){
        clearInterval(this.timerId)
    }

})

ReactDOM.render(
    <Clock/>,
    document.getElementById('root')
)

Failed to connect to mailserver at "localhost" port 25

PHP mail function can send email in 2 scenarios:

a. Try to send email via unix sendmail program At linux it will exec program "sendmail", put all params to sendmail and that all.

OR

b. Connect to mail server (using smtp protocol and host/port/username/pass from php.ini) and try to send email.

If php unable to connect to email server it will give warning (and you see such workning in your logs) To solve it, install smtp server on your local machine or use any available server. How to setup / configure smtp you can find on php.net

Is it possible to change the package name of an Android app on Google Play?

Complete guide : https://developer.android.com/studio/build/application-id.html

As per Android official Blogs : https://android-developers.googleblog.com/2011/06/things-that-cannot-change.html

We can say that:

  • If the manifest package name has changed, the new application will be installed alongside the old application, so they both co-exist on the user’s device at the same time.

  • If the signing certificate changes, trying to install the new application on to the device will fail until the old version is uninstalled.

As per Google App Update check list : https://support.google.com/googleplay/android-developer/answer/113476?hl=en

Update your apps

Prepare your APK

When you're ready to make changes to your APK, make sure to update your app’s version code as well so that existing users will receive your update.

Use the following checklist to make sure your new APK is ready to update your existing users:

  • The package name of the updated APK needs to be the same as the current version.
  • The version code needs to be greater than that current version. Learn more about versioning your applications.
  • The updated APK needs to be signed with the same signature as the current version.

To verify that your APK is using the same certification as the previous version, you can run the following command on both APKs and compare the results:

$ jarsigner -verify -verbose -certs my_application.apk

If the results are identical, you’re using the same key and are ready to continue. If the results are different, you will need to re-sign the APK with the correct key.

Learn more about signing your applications

Upload your APK Once your APK is ready, you can create a new release.

Use Robocopy to copy only changed files?

To answer all your questions:

Can I use ROBOCOPY for this?

Yes, RC should fit your requirements (simplicity, only copy what needed)


What exactly does it mean to exclude?

It will exclude copying - RC calls it skipping


Would the /XO option copy only newer files, not files of the same age?

Yes, RC will only copy newer files. Files of the same age will be skipped.

(the correct command would be robocopy C:\SourceFolder D:\DestinationFolder ABC.dll /XO)


Maybe in your case using the /MIR option could be useful. In general RC is rather targeted at directories and directory trees than single files.

Plotting in a non-blocking way with Matplotlib

You can avoid blocking execution by writing the plot to an array, then displaying the array in a different thread. Here is an example of generating and displaying plots simultaneously using pf.screen from pyformulas 0.2.8:

import pyformulas as pf
import matplotlib.pyplot as plt
import numpy as np
import time

fig = plt.figure()

canvas = np.zeros((480,640))
screen = pf.screen(canvas, 'Sinusoid')

start = time.time()
while True:
    now = time.time() - start

    x = np.linspace(now-2, now, 100)
    y = np.sin(2*np.pi*x) + np.sin(3*np.pi*x)
    plt.xlim(now-2,now+1)
    plt.ylim(-3,3)
    plt.plot(x, y, c='black')

    # If we haven't already shown or saved the plot, then we need to draw the figure first...
    fig.canvas.draw()

    image = np.fromstring(fig.canvas.tostring_rgb(), dtype=np.uint8, sep='')
    image = image.reshape(fig.canvas.get_width_height()[::-1] + (3,))

    screen.update(image)

#screen.close()

Result:

Sine animation

Disclaimer: I'm the maintainer for pyformulas.

Reference: Matplotlib: save plot to numpy array

How to use the onClick event for Hyperlink using C# code?

The onclick attribute on your anchor tag is going to call a client-side function. (This is what you would use if you wanted to call a javascript function when the link is clicked.)

What you want is a server-side control, like the LinkButton:

<asp:LinkButton ID="lnkTutorial" runat="server" Text="Tutorial" OnClick="displayTutorial_Click"/>

This has an OnClick attribute that will call the method in your code behind.

Looking further into your code, it looks like you're just trying to open a different tutorial based on access level of the user. You don't need an event handler for this at all. A far better approach would be to just set the end point of your LinkButton control in the code behind.

protected void Page_Load(object sender, EventArgs e)
{
    userinfo = (UserInfo)Session["UserInfo"];

    if (userinfo.user == "Admin")
    {
        lnkTutorial.PostBackUrl = "help/AdminTutorial.html";
    }
    else
    {
        lnkTutorial.PostBackUrl = "help/UserTutorial.html";
    }
}

Really, it would be best to check that you actually have a user first.

protected void Page_Load(object sender, EventArgs e)
{
    if (Session["UserInfo"] != null && ((UserInfo)Session["UserInfo"]).user == "Admin")
    {
        lnkTutorial.PostBackUrl = "help/AdminTutorial.html";
    }
    else
    {
        lnkTutorial.PostBackUrl = "help/UserTutorial.html";
    }
}

what does the __file__ variable mean/do?

When a module is loaded from a file in Python, __file__ is set to its path. You can then use that with other functions to find the directory that the file is located in.

Taking your examples one at a time:

A = os.path.join(os.path.dirname(__file__), '..')
# A is the parent directory of the directory where program resides.

B = os.path.dirname(os.path.realpath(__file__))
# B is the canonicalised (?) directory where the program resides.

C = os.path.abspath(os.path.dirname(__file__))
# C is the absolute path of the directory where the program resides.

You can see the various values returned from these here:

import os
print(__file__)
print(os.path.join(os.path.dirname(__file__), '..'))
print(os.path.dirname(os.path.realpath(__file__)))
print(os.path.abspath(os.path.dirname(__file__)))

and make sure you run it from different locations (such as ./text.py, ~/python/text.py and so forth) to see what difference that makes.


I just want to address some confusion first. __file__ is not a wildcard it is an attribute. Double underscore attributes and methods are considered to be "special" by convention and serve a special purpose.

http://docs.python.org/reference/datamodel.html shows many of the special methods and attributes, if not all of them.

In this case __file__ is an attribute of a module (a module object). In Python a .py file is a module. So import amodule will have an attribute of __file__ which means different things under difference circumstances.

Taken from the docs:

__file__ is the pathname of the file from which the module was loaded, if it was loaded from a file. The __file__ attribute is not present for C modules that are statically linked into the interpreter; for extension modules loaded dynamically from a shared library, it is the pathname of the shared library file.

In your case the module is accessing it's own __file__ attribute in the global namespace.

To see this in action try:

# file: test.py

print globals()
print __file__

And run:

python test.py

{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__file__':
 'test_print__file__.py', '__doc__': None, '__package__': None}
test_print__file__.py

Go doing a GET request and building the Querystring

As a commenter mentioned you can get Values from net/url which has an Encode method. You could do something like this (req.URL.Query() returns the existing url.Values)

package main

import (
    "fmt"
    "log"
    "net/http"
    "os"
)

func main() {
    req, err := http.NewRequest("GET", "http://api.themoviedb.org/3/tv/popular", nil)
    if err != nil {
        log.Print(err)
        os.Exit(1)
    }

    q := req.URL.Query()
    q.Add("api_key", "key_from_environment_or_flag")
    q.Add("another_thing", "foo & bar")
    req.URL.RawQuery = q.Encode()

    fmt.Println(req.URL.String())
    // Output:
    // http://api.themoviedb.org/3/tv/popular?another_thing=foo+%26+bar&api_key=key_from_environment_or_flag
}

http://play.golang.org/p/L5XCrw9VIG

How to get mouse position in jQuery without mouse-events?

You can't read mouse position in jQuery without using an event. Note firstly that the event.pageX and event.pageY properties exists on any event, so you could do:

$('#myEl').click(function(e) {
    console.log(e.pageX);
});

Your other option is to use a closure to give your whole code access to a variable that is updated by a mousemove handler:

var mouseX, mouseY;
$(document).mousemove(function(e) {
    mouseX = e.pageX;
    mouseY = e.pageY;
}).mouseover(); // call the handler immediately

// do something with mouseX and mouseY

How do I do an insert with DATETIME now inside of SQL server mgmt studioÜ

Just use GETDATE() or GETUTCDATE() (if you want to get the "universal" UTC time, instead of your local server's time-zone related time).

INSERT INTO [Business]
           ([IsDeleted]
           ,[FirstName]
           ,[LastName]
           ,[LastUpdated]
           ,[LastUpdatedBy])
     VALUES
           (0, 'Joe', 'Thomas', 
           GETDATE(),  <LastUpdatedBy, nvarchar(50),>)

How to filter an array of objects based on values in an inner array with jq?

Very close! In your select expression, you have to use a pipe (|) before contains.

This filter produces the expected output.

. - map(select(.Names[] | contains ("data"))) | .[] .Id

The jq Cookbook has an example of the syntax.

Filter objects based on the contents of a key

E.g., I only want objects whose genre key contains "house".

$ json='[{"genre":"deep house"}, {"genre": "progressive house"}, {"genre": "dubstep"}]'
$ echo "$json" | jq -c '.[] | select(.genre | contains("house"))'
{"genre":"deep house"}
{"genre":"progressive house"}

Colin D asks how to preserve the JSON structure of the array, so that the final output is a single JSON array rather than a stream of JSON objects.

The simplest way is to wrap the whole expression in an array constructor:

$ echo "$json" | jq -c '[ .[] | select( .genre | contains("house")) ]'
[{"genre":"deep house"},{"genre":"progressive house"}]

You can also use the map function:

$ echo "$json" | jq -c 'map(select(.genre | contains("house")))'
[{"genre":"deep house"},{"genre":"progressive house"}]

map unpacks the input array, applies the filter to every element, and creates a new array. In other words, map(f) is equivalent to [.[]|f].

Pandas convert string to int

You need add parameter errors='coerce' to function to_numeric:

ID = pd.to_numeric(ID, errors='coerce')

If ID is column:

df.ID = pd.to_numeric(df.ID, errors='coerce')

but non numeric are converted to NaN, so all values are float.

For int need convert NaN to some value e.g. 0 and then cast to int:

df.ID = pd.to_numeric(df.ID, errors='coerce').fillna(0).astype(np.int64)

Sample:

df = pd.DataFrame({'ID':['4806105017087','4806105017087','CN414149']})
print (df)
              ID
0  4806105017087
1  4806105017087
2       CN414149

print (pd.to_numeric(df.ID, errors='coerce'))
0    4.806105e+12
1    4.806105e+12
2             NaN
Name: ID, dtype: float64

df.ID = pd.to_numeric(df.ID, errors='coerce').fillna(0).astype(np.int64)
print (df)
              ID
0  4806105017087
1  4806105017087
2              0

EDIT: If use pandas 0.25+ then is possible use integer_na:

df.ID = pd.to_numeric(df.ID, errors='coerce').astype('Int64')
print (df)
              ID
0  4806105017087
1  4806105017087
2            NaN

Using PowerShell to remove lines from a text file if it contains a string

The pipe character | has a special meaning in regular expressions. a|b means "match either a or b". If you want to match a literal | character, you need to escape it:

... | Select-String -Pattern 'H\|159' -NotMatch | ...

Sorting Directory.GetFiles()

A more succinct VB.Net version, if anyone is interested

Dim filePaths As Linq.IOrderedEnumerable(Of IO.FileInfo) = _
  New DirectoryInfo("c:\temp").GetFiles() _
   .OrderBy(Function(f As FileInfo) f.CreationTime)
For Each fi As IO.FileInfo In filePaths
  ' Do whatever you wish here
Next

Selenium 2.53 not working on Firefox 47

If you're on OSX using Homebrew, you can install old Firefox versions via brew cask:

brew tap goldcaddy77/firefox
brew cask install firefox-46 # or whatever version you want

After installing, you'll just need to rename your FF executable in the Applications directory to "Firefox".

More info can be found at the git repo homebrew-firefox. Props to smclernon for creating the original cask.

Output Django queryset as JSON

To return the queryset you retrieved with queryset = Users.objects.all(), you first need to serialize them.

Serialization is the process of converting one data structure to another. Using Class-Based Views, you could return JSON like this.

from django.core.serializers import serialize
from django.http import JsonResponse
from django.views.generic import View

class JSONListView(View):
    def get(self, request, *args, **kwargs):
        qs = User.objects.all()
        data = serialize("json", qs)
        return JsonResponse(data)

This will output a list of JSON. For more detail on how this works, check out my blog article How to return a JSON Response with Django. It goes into more detail on how you would go about this.

Java Read Large Text File With 70million line of text

In Java 8, for anyone looking now to read file large files line by line,

Stream<String> lines = Files.lines(Paths.get("c:\myfile.txt"));
lines.forEach(l -> {
  // Do anything line by line   
});

Check folder size in Bash

Use a summary (-s) and bytes (-b). You can cut the first field of the summary with cut. Putting it all together:

CHECK=$(du -sb /data/sflow_log | cut -f1)

Looping through a Scripting.Dictionary using index/item number

Using d.Keys()(i) method is a very bad idea, because on each call it will re-create a new array (you will have significant speed reduction).

Here is an analogue of Scripting.Dictionary called "Hash Table" class from @TheTrick, that support such enumerator: http://www.cyberforum.ru/blogs/354370/blog2905.html

Dim oDict As clsTrickHashTable

Sub aaa()
    Set oDict = New clsTrickHashTable

    oDict.Add "a", "aaa"
    oDict.Add "b", "bbb"

    For i = 0 To oDict.Count - 1
        Debug.Print oDict.Keys(i) & " - " & oDict.Items(i)
    Next
End Sub

powershell - extract file name and extension

If the file is coming off the disk and as others have stated, use the BaseName and Extension properties:

PS C:\> dir *.xlsx | select BaseName,Extension

BaseName                                Extension
--------                                ---------
StackOverflow.com Test Config           .xlsx  

If you are given the file name as part of string (say coming from a text file), I would use the GetFileNameWithoutExtension and GetExtension static methods from the System.IO.Path class:

PS C:\> [System.IO.Path]::GetFileNameWithoutExtension("Test Config.xlsx")
Test Config
PS H:\> [System.IO.Path]::GetExtension("Test Config.xlsx")
.xlsx

Replacing a fragment with another fragment inside activity group

Please see this Question

You can only replace a "dynamically added fragment".

So, if you want to add a dynamic fragment, see this example.

How to switch between python 2.7 to python 3 from command line?

For Windows 7, I just rename the python.exe from the Python 3 folder to python3.exe and add the path into the environment variables. Using that, I can execute python test_script.py and the script runs with Python 2.7 and when I do python3 test_script.py, it runs the script in Python 3.

To add Python 3 to the environment variables, follow these steps -

  1. Right Click on My Computer and go to Properties.
  2. Go to Advanced System Settings.
  3. Click on Environment Variables and edit PATH and add the path to your Python 3 installation directory.

For example,

enter image description here

Fix footer to bottom of page

A very simple example that shows how to fix the footer at the bottom in your application's layout.

_x000D_
_x000D_
/* Styles go here */_x000D_
html{ height: 100%;}_x000D_
body{ min-height: 100%; background: #fff;}_x000D_
.page-layout{ border: none; width: 100%; height: 100vh; }_x000D_
.page-layout td{ vertical-align: top; }_x000D_
.page-layout .header{ background: #aaa; }_x000D_
.page-layout .main-content{ height: 100%; background: #f1f1f1; text-align: center; padding-top: 50px; }_x000D_
.page-layout .main-content .container{ text-align: center; padding-top: 50px; }_x000D_
.page-layout .footer{ background: #333; color: #fff; } 
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
  <head>_x000D_
    <link data-require="bootstrap@*" data-semver="4.0.5" rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-alpha.6/css/bootstrap.min.css" />_x000D_
    <link rel="stylesheet" href="style.css" />_x000D_
    <script src="script.js"></script>_x000D_
  </head>_x000D_
_x000D_
  <body>_x000D_
    <table class="page-layout">_x000D_
      <tr>_x000D_
        <td class="header">_x000D_
          <div>_x000D_
            This is the site header._x000D_
          </div>_x000D_
        </td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td class="main-content">_x000D_
          <div>_x000D_
            <h1>Fix footer always to the bottom</h1>_x000D_
            <div>_x000D_
              This is how you can simply fix the footer to the bottom._x000D_
            </div>_x000D_
            <div>_x000D_
              The footer will always stick to the bottom until the main-content doesn't grow till footer._x000D_
            </div>_x000D_
            <div>_x000D_
              Even if the content grows, the footer will start to move down naturally as like the normal behavior of page._x000D_
            </div>_x000D_
          </div>_x000D_
        </td>_x000D_
      </tr>_x000D_
      <tr>_x000D_
        <td class="footer">_x000D_
          <div>_x000D_
            This is the site footer._x000D_
          </div>_x000D_
        </td>_x000D_
      </tr>_x000D_
    </table>_x000D_
  </body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Onclick on bootstrap button

Just like any other click event, you can use jQuery to register an element, set an id to the element and listen to events like so:

$('#myButton').on('click', function(event) {
  event.preventDefault(); // To prevent following the link (optional)
  ...
});

You can also use inline javascript in the onclick attribute:

<a ... onclick="myFunc();">..</a>

how to get last insert id after insert query in codeigniter active record

Just to complete this topic: If you set up your table with primary key and auto increment you can omit the process of manually incrementing the id.

Check out this example

if (!$CI->db->table_exists(db_prefix() . 'my_table_name')) {
    $CI->db->query('CREATE TABLE `' . db_prefix() . "my_table_name` (
  `serviceid` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT,
  `name` varchar(64) NOT NULL,
  `hash` varchar(32) NOT NULL,
  `url` varchar(120) NOT NULL,
  `datecreated` datetime NOT NULL,
  `active` tinyint(1) NOT NULL DEFAULT '1'
) ENGINE=InnoDB DEFAULT CHARSET=" . $CI->db->char_set . ';');

Now you can insert rows

$this->db->insert(db_prefix(). 'my_table_name', [
            'name'         => $data['name'],
            'hash'            => app_generate_hash(),
            'url'     => $data['url'],
            'datecreated'     => date('Y-m-d H:i:s'),
            'active'          => $data['active']
        ]);

Continuous Integration vs. Continuous Delivery vs. Continuous Deployment

Continuous Integration: The practice of merging the development work with the main branch constantly so that the code has been tested as often as possible to catch issues early.

Continuous Delivery: Continuous delivery of code to an environment once the code is ready to ship. This could be staging or production. The idea is the product is delivered to a user base, which can be QA's or customers for review and inspection.

Unit test during the Continuous Integration phase can not catch all the bugs and business logic, particularly design issues that is why we need QA, or staging environment for testing.

Continuous Deployment: The deployment or release of code as soon as it's ready. Continuous Deployment requires Continuous Integration and Continuous Delivery otherwise the code quality won't be guarantee in a release.

Continuous Deployment ~~ Continuous Integration + Continuous Delivery

What is a Java String's default initial value?

Any object if it is initailised , its defeault value is null, until unless we explicitly provide a default value.

What is the difference between an Instance and an Object?

If we see the Definition of Object and Instance object -

Memory allocated for the member of class at run time is called object or object is the instance of Class.

Let us see the Definition of instance -

Memory allocated For Any at run time is called as instance variable.

Now understand the meaning of any run time memory allocation happen in C also through Malloc, Calloc, Realloc such:

struct p
{

}
p *t1
t1=(p) malloc(sizeof(p))

So here also we are allocating run time memory allocation but here we call as instance so t1 is instance here we can not say t1 as object so Every object is the instance of Class but every Instance is not Object.

jQuery .each() with input elements

You can use:

$(formId).serializeArray();

How do I convert a column of text URLs into active hyperlinks in Excel?

I shocked Excel didn't do this automatically so here is my solution I hope would be useful for others,

  1. Copy the whole column to clipboard
  2. Open this on your Chrome or Firefox

data:text/html,<button onclick="document.write(document.body.querySelector('textarea').value.split('\n').map(x => '<a href=\'' + x + '\'>' + x + '</a>').join('<br>'))">Linkify</button><br><textarea></textarea>

  1. Paste the column on the page you just opened on the browser and press "Linkify"
  2. Copy the result from the tab to the the column on Excel

Instead step two, you can use the below page, first, click on "Run code snippet" then paste the column on it

_x000D_
_x000D_
<button onclick="document.write(document.body.querySelector('textarea').value.split('\n').map(x => '<a href=\'' + x + '\'>' + x + '</a>').join('<br>'))">Linkify</button><br><textarea></textarea>
_x000D_
_x000D_
_x000D_

Provide password to ssh command inside bash script, Without the usage of public keys and Expect

For security reasons you must avoid providing password on a command line otherwise anyone running ps command can see your password. Better to use sshpass utility like this:

#!/bin/bash

export SSHPASS="your-password"
sshpass -e ssh -oBatchMode=no sshUser@remoteHost

You might be interested in How to run the sftp command with a password from Bash script?

INSERT IF NOT EXISTS ELSE UPDATE?

You should use the INSERT OR IGNORE command followed by an UPDATE command: In the following example name is a primary key:

INSERT OR IGNORE INTO my_table (name, age) VALUES ('Karen', 34)
UPDATE my_table SET age = 34 WHERE name='Karen'

The first command will insert the record. If the record exists, it will ignore the error caused by the conflict with an existing primary key.

The second command will update the record (which now definitely exists)

Get distance between two points in canvas

You can do it with pythagoras theorem

If you have two points (x1, y1) and (x2, y2) then you can calculate the difference in x and difference in y, lets call them a and b.

enter image description here

var a = x1 - x2;
var b = y1 - y2;

var c = Math.sqrt( a*a + b*b );

// c is the distance

How to convert a char array back to a string?

package naresh.java;

public class TestDoubleString {

    public static void main(String args[]){
        String str="abbcccddef";    
        char charArray[]=str.toCharArray();
        int len=charArray.length;

        for(int i=0;i<len;i++){
            //if i th one and i+1 th character are same then update the charArray
            try{
                if(charArray[i]==charArray[i+1]){
                    charArray[i]='0';                   
                }}
                catch(Exception e){
                    System.out.println("Exception");
                }
        }//finally printing final character string
        for(int k=0;k<charArray.length;k++){
            if(charArray[k]!='0'){
                System.out.println(charArray[k]);
            }       }
    }
}

How to get the number of columns in a matrix?

When want to get row size with size() function, below code can be used:

size(A,1)

Another usage for it:

[height, width] = size(A)

So, you can get 2 dimension of your matrix.

How do I make a splash screen?

public class SplashActivity extends Activity {

  Context ctx;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      ctx = this;
      setContentView(R.layout.activity_splash);

      Thread thread = new Thread(){
          public void run(){
              try {
                  sleep(3000);
              } catch (InterruptedException e) {
                  e.printStackTrace();
              }

              Intent in = new Intent(ctx,MainActivity.class);
              startActivity(in);
              finish();
          }
      };
      thread.start();
  }
}

How do I use extern to share variables between source files?

In C a variable inside a file say example.c is given local scope. The compiler expects that the variable would have its definition inside the same file example.c and when it does not find the same , it would throw an error.A function on the other hand has by default global scope . Thus you do not have to explicitly mention to the compiler "look dude...you might find the definition of this function here". For a function including the file which contains its declaration is enough.(The file which you actually call a header file). For example consider the following 2 files :
example.c

#include<stdio.h>
extern int a;
main(){
       printf("The value of a is <%d>\n",a);
}

example1.c

int a = 5;

Now when you compile the two files together, using the following commands :

step 1)cc -o ex example.c example1.c step 2)./ex

You get the following output : The value of a is <5>

How to set lifetime of session

As long as the User does not delete their cookies or close their browser, the session should stay in existence.

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

Generally speaking; Start out with the most expensive datatype that has the least constraints. Put it in production. If performance starts to be an issue, find out what's actually being stored in those nvarchar columns. Is there any characters in there that wouldn't fit into varchar? If not, switch to varchar. Don't try to pre-optimize before you know where the pain is. My guess is that the choice between nvarchar/varchar is not what's going to slow down your application in the foreseable future. There will be other parts of the application where performance tuning will give you much more bang for the bucks.

Why do I need to do `--set-upstream` all the time?

For those looking for an alias that works with git pull, this is what I use:

alias up="git branch | awk '/^\\* / { print \$2 }' | xargs -I {} git branch --set-upstream-to=origin/{} {}"

Now whenever you get:

$ git pull
There is no tracking information for the current branch.
...

Just run:

$ up
Branch my_branch set up to track remote branch my_branch from origin.
$ git pull

And you're good to go

Refresh Page C# ASP.NET

Depending on what exactly you require, a Server.Transfer might be a resource-cheaper alternative to Response.Redirect. More information is in Server.Transfer Vs. Response.Redirect.

What is the copy-and-swap idiom?

There are some good answers already. I'll focus mainly on what I think they lack - an explanation of the "cons" with the copy-and-swap idiom....

What is the copy-and-swap idiom?

A way of implementing the assignment operator in terms of a swap function:

X& operator=(X rhs)
{
    swap(rhs);
    return *this;
}

The fundamental idea is that:

  • the most error-prone part of assigning to an object is ensuring any resources the new state needs are acquired (e.g. memory, descriptors)

  • that acquisition can be attempted before modifying the current state of the object (i.e. *this) if a copy of the new value is made, which is why rhs is accepted by value (i.e. copied) rather than by reference

  • swapping the state of the local copy rhs and *this is usually relatively easy to do without potential failure/exceptions, given the local copy doesn't need any particular state afterwards (just needs state fit for the destructor to run, much as for an object being moved from in >= C++11)

When should it be used? (Which problems does it solve [/create]?)

  • When you want the assigned-to objected unaffected by an assignment that throws an exception, assuming you have or can write a swap with strong exception guarantee, and ideally one that can't fail/throw..†

  • When you want a clean, easy to understand, robust way to define the assignment operator in terms of (simpler) copy constructor, swap and destructor functions.

    • Self-assignment done as a copy-and-swap avoids oft-overlooked edge cases.‡

  • When any performance penalty or momentarily higher resource usage created by having an extra temporary object during the assignment is not important to your application. ?

swap throwing: it's generally possible to reliably swap data members that the objects track by pointer, but non-pointer data members that don't have a throw-free swap, or for which swapping has to be implemented as X tmp = lhs; lhs = rhs; rhs = tmp; and copy-construction or assignment may throw, still have the potential to fail leaving some data members swapped and others not. This potential applies even to C++03 std::string's as James comments on another answer:

@wilhelmtell: In C++03, there is no mention of exceptions potentially thrown by std::string::swap (which is called by std::swap). In C++0x, std::string::swap is noexcept and must not throw exceptions. – James McNellis Dec 22 '10 at 15:24


‡ assignment operator implementation that seems sane when assigning from a distinct object can easily fail for self-assignment. While it might seem unimaginable that client code would even attempt self-assignment, it can happen relatively easily during algo operations on containers, with x = f(x); code where f is (perhaps only for some #ifdef branches) a macro ala #define f(x) x or a function returning a reference to x, or even (likely inefficient but concise) code like x = c1 ? x * 2 : c2 ? x / 2 : x;). For example:

struct X
{
    T* p_;
    size_t size_;
    X& operator=(const X& rhs)
    {
        delete[] p_;  // OUCH!
        p_ = new T[size_ = rhs.size_];
        std::copy(p_, rhs.p_, rhs.p_ + rhs.size_);
    }
    ...
};

On self-assignment, the above code delete's x.p_;, points p_ at a newly allocated heap region, then attempts to read the uninitialised data therein (Undefined Behaviour), if that doesn't do anything too weird, copy attempts a self-assignment to every just-destructed 'T'!


? The copy-and-swap idiom can introduce inefficiencies or limitations due to the use of an extra temporary (when the operator's parameter is copy-constructed):

struct Client
{
    IP_Address ip_address_;
    int socket_;
    X(const X& rhs)
      : ip_address_(rhs.ip_address_), socket_(connect(rhs.ip_address_))
    { }
};

Here, a hand-written Client::operator= might check if *this is already connected to the same server as rhs (perhaps sending a "reset" code if useful), whereas the copy-and-swap approach would invoke the copy-constructor which would likely be written to open a distinct socket connection then close the original one. Not only could that mean a remote network interaction instead of a simple in-process variable copy, it could run afoul of client or server limits on socket resources or connections. (Of course this class has a pretty horrid interface, but that's another matter ;-P).

How to Empty Caches and Clean All Targets Xcode 4 and later

You have to be careful about the xib file. I tried all the above and nothing worked for me. I was using custom UIButtons defined in the xib, and realized it might be related to the fact that I had assigned attributes there which were not changing programmatically. If you've defined images or text there, remove them. When I did, my programmatic changes began to take effect.

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/tmp/mysql.sock'

Solutions revolve around:

  • changing MySQL's permissions

    sudo chown -R _mysql:mysql /usr/local/var/mysql
    
  • Starting a MySQL process

    sudo mysql.server start
    

Just to add on a lot of great and useful answers that have been provided here and from many different posts, try specifying the host if the above commands did not resolve this issue for you, i.e

mysql -u root -p h127.0.0.1

Do you get charged for a 'stopped' instance on EC2?

When you stop an instance, it is 'deleted'. As such there's nothing to be charged for. If you have an Elastic IP or EBS, then you'll be charged for those - but nothing related to the instance itself.

How to delete from a text file, all lines that contain a specific string?

You may consider using ex (which is a standard Unix command-based editor):

ex +g/match/d -cwq file

where:

  • + executes given Ex command (man ex), same as -c which executes wq (write and quit)
  • g/match/d - Ex command to delete lines with given match, see: Power of g

The above example is a POSIX-compliant method for in-place editing a file as per this post at Unix.SE and POSIX specifications for ex.


The difference with sed is that:

sed is a Stream EDitor, not a file editor.BashFAQ

Unless you enjoy unportable code, I/O overhead and some other bad side effects. So basically some parameters (such as in-place/-i) are non-standard FreeBSD extensions and may not be available on other operating systems.

Evaluating string "3*(4+2)" yield int 18

Try this:

static double Evaluate(string expression) {
  var loDataTable = new DataTable();
  var loDataColumn = new DataColumn("Eval", typeof (double), expression);
  loDataTable.Columns.Add(loDataColumn);
  loDataTable.Rows.Add(0);
  return (double) (loDataTable.Rows[0]["Eval"]);
}

Type converting slices of interfaces

Here is the official explanation: https://github.com/golang/go/wiki/InterfaceSlice

var dataSlice []int = foo()
var interfaceSlice []interface{} = make([]interface{}, len(dataSlice))
for i, d := range dataSlice {
    interfaceSlice[i] = d
}

How do I rename a local Git branch?

git branch -m [old-branch] [new-branch]

-m means move all from [old-branch] to [new-branch] and remember you can use -M for other file systems.

How can I list ALL DNS records?

There is no easy way to get all DNS records for a domain in one instance. You can only view certain records for example, if you wanna see an A record for a certain domain you can use the command: dig a(type of record) domain.com. This is the same for all the other type of records you wanna see for that domain.

If your not familiar with the command line interface, you can also use a site like mxtoolbox.com. Wich is very handy tool for getting records of a domain.

I hope this answers your question.

How to use the toString method in Java?

From the Object.toString docs:

Returns a string representation of the object. In general, the toString method returns a string that "textually represents" this object. The result should be a concise but informative representation that is easy for a person to read. It is recommended that all subclasses override this method.

The toString method for class Object returns a string consisting of the name of the class of which the object is an instance, the at-sign character `@', and the unsigned hexadecimal representation of the hash code of the object. In other words, this method returns a string equal to the value of:

getClass().getName() + '@' + Integer.toHexString(hashCode())

Example:

String[] mystr ={"a","b","c"};
System.out.println("mystr.toString: " + mystr.toString());

output:- mystr.toString: [Ljava.lang.String;@13aaa14a

receiver type *** for instance message is a forward declaration

I was trying to use @class "Myclass.h".

When I changed it to #import "Myclass.h", it worked fine.

Laravel blank white screen

In addition to Permission problems in storage and cache folder and php version issues, there could be another reasons to display blank page without any error message.

For example, I had a redeclare error message without any log and with blank white page. There was a conflict between my own helper function and a vendor function.

I suggest as a starting point, run artisan commands. for example:

php artisan cache:clear

If there was a problem, it will prompted in terminal and you've got a Clue and you can google for the solution.

Setting up Eclipse with JRE Path

I have several version of JDK (not JRE) instaled and I launch Eclipse with:

C:\eclipse\eclipse.exe -vm "%JAVA_HOME%\bin\javaw.exe" -data f:\dev\java\2013

As you can see, I set JAVA_HOME to point to the version of JDK I want to use.

I NEVER add javaw.exe in the PATH.

-data is used to choose a workspace for a particular job/client/context.

How to use ES6 Fat Arrow to .filter() an array of objects

You can't implicitly return with an if, you would need the braces:

let adults = family.filter(person => { if (person.age > 18) return person} );

It can be simplified though:

let adults = family.filter(person => person.age > 18);

Retrieving JSON Object Literal from HttpServletRequest

There is another way to do it, using org.apache.commons.io.IOUtils to extract the String from the request

String jsonString = IOUtils.toString(request.getInputStream());

Then you can do whatever you want, convert it to JSON or other object with Gson, etc.

JSONObject json = new JSONObject(jsonString);
MyObject myObject = new Gson().fromJson(jsonString, MyObject.class);

Maximum call stack size exceeded on npm install

echo 65536 | sudo tee -a /proc/sys/fs/inotify/max_user_watches

works for me on Ubuntu.

When using Trusted_Connection=true and SQL Server authentication, will this affect performance?

Not 100% sure what you mean:

Trusted_Connection=True;

IS using Windows credentials and is 100% equivalent to:

Integrated Security=SSPI;

or

Integrated Security=true;

If you don't want to use integrated security / trusted connection, you need to specify user id and password explicitly in the connection string (and leave out any reference to Trusted_Connection or Integrated Security)

server=yourservername;database=yourdatabase;user id=YourUser;pwd=TopSecret

Only in this case, the SQL Server authentication mode is used.

If any of these two settings is present (Trusted_Connection=true or Integrated Security=true/SSPI), then the Windows credentials of the current user are used to authenticate against SQL Server and any user iD= setting will be ignored and not used.

For reference, see the Connection Strings site for SQL Server 2005 with lots of samples and explanations.

Using Windows Authentication is the preferred and recommended way of doing things, but it might incur a slight delay since SQL Server would have to authenticate your credentials against Active Directory (typically). I have no idea how much that slight delay might be, and I haven't found any references for that.


Summing up:

If you specify either Trusted_Connection=True; or Integrated Security=SSPI; or Integrated Security=true; in your connection string

==> THEN (and only then) you have Windows Authentication happening. Any user id= setting in the connection string will be ignored.


If you DO NOT specify either of those settings,

==> then you DO NOT have Windows Authentication happening (SQL Authentication mode will be used)


How to get first and last day of the current week in JavaScript

Nice suggestion but you got a small problem in lastday. You should change it to:

lastday = new Date(firstday.getTime() + 60 * 60 *24 * 6 * 1000);

How to return dictionary keys as a list in Python?

Converting to a list without using the keys method makes it more readable:

list(newdict)

and, when looping through dictionaries, there's no need for keys():

for key in newdict:
    print key

unless you are modifying it within the loop which would require a list of keys created beforehand:

for key in list(newdict):
    del newdict[key]

On Python 2 there is a marginal performance gain using keys().

Making a PowerShell POST request if a body param starts with '@'

Use Invoke-RestMethod to consume REST-APIs. Save the JSON to a string and use that as the body, ex:

$JSON = @'
{"@type":"login",
 "username":"[email protected]",
 "password":"yyy"
}
'@

$response = Invoke-RestMethod -Uri "http://somesite.com/oneendpoint" -Method Post -Body $JSON -ContentType "application/json"

If you use Powershell 3, I know there have been some issues with Invoke-RestMethod, but you should be able to use Invoke-WebRequest as a replacement:

$response = Invoke-WebRequest -Uri "http://somesite.com/oneendpoint" -Method Post -Body $JSON -ContentType "application/json"

If you don't want to write your own JSON every time, you can use a hashtable and use PowerShell to convert it to JSON before posting it. Ex.

$JSON = @{
    "@type" = "login"
    "username" = "[email protected]"
    "password" = "yyy"
} | ConvertTo-Json

How to do case insensitive search in Vim

As well as the suggestions for \c and ignorecase, I find the smartcase very useful. If you search for something containing uppercase characters, it will do a case sensitive search; if you search for something purely lowercase, it will do a case insensitive search. You can use \c and \C to override this:

:set ignorecase
:set smartcase
/copyright      " Case insensitive
/Copyright      " Case sensitive
/copyright\C    " Case sensitive
/Copyright\c    " Case insensitive

See:

:help /\c
:help /\C
:help 'smartcase'

Is it possible to write to the console in colour in .NET?

Yes. See this article. Here's an example from there:

Console.BackgroundColor = ConsoleColor.Blue;
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("White on blue.");

enter image description here

Open multiple Eclipse workspaces on the Mac

To make this you need to navigate to the Eclipse.app directory and use the following command:

open -n Eclipse.app

How to HTML encode/escape a string? Is there a built-in?

The h helper method:

<%=h "<p> will be preserved" %>

Skip a submodule during a Maven build

Maven version 3.2.1 added this feature, you can use the -pl switch (shortcut for --projects list) with ! or - (source) to exclude certain submodules.

mvn -pl '!submodule-to-exclude' install
mvn -pl -submodule-to-exclude install

Be careful in bash the character ! is a special character, so you either have to single quote it (like I did) or escape it with the backslash character.

The syntax to exclude multiple module is the same as the inclusion

mvn -pl '!submodule1,!submodule2' install
mvn -pl -submodule1,-submodule2 install

EDIT Windows does not seem to like the single quotes, but it is necessary in bash ; in Windows, use double quotes (thanks @awilkinson)

mvn -pl "!submodule1,!submodule2" install

How do I generate a random int number?

 int n = new Random().Next();

You can also give minimum and maximum value to Next() function. Like:

 int n = new Random().Next(5, 10);

Running Facebook application on localhost

So I got this to work today. My URL is http://localhost:8888. The domain I gave facebook is localhost. I thought that it was not working because I was trying to pull data using the FB.api method. I kept on getting an "undefined" name and an image without a source, so definitely didn't have access to the Graph.

Later I realized that my problem was really that I was only passing a first argument of /me to FB.api, and I didn't have a token. So you'll need to use the FB.getLoginStatus function to get a token, which should be added to the /me argument.

What is the regular expression to allow uppercase/lowercase (alphabetical characters), periods, spaces and dashes only?

Check out the basics of regular expressions in a tutorial. All it requires is two anchors and a repeated character class:

^[a-zA-Z ._-]*$

If you use the case-insensitive modifier, you can shorten this to

^[a-z ._-]*$

Note that the space is significant (it is just a character like any other).

C#: How to access an Excel cell?

How I work to automate Office / Excel:

  1. Record a macro, this will generate a VBA template
  2. Edit the VBA template so it will match my needs
  3. Convert to VB.Net (A small step for men)
  4. Leave it in VB.Net, Much more easy as doing it using C#

How to create custom spinner like border around the spinner with down triangle on the right side?

Spinner

<Spinner
    android:id="@+id/To_Units"
    style="@style/spinner_style" />

style.xml

    <style name="spinner_style">
          <item name="android:layout_width">match_parent</item>
          <item name="android:layout_height">wrap_content</item>
          <item name="android:background">@drawable/gradient_spinner</item>
          <item name="android:layout_margin">10dp</item>
          <item name="android:paddingLeft">8dp</item>
          <item name="android:paddingRight">20dp</item>
          <item name="android:paddingTop">5dp</item>
          <item name="android:paddingBottom">5dp</item>
          <item name="android:popupBackground">#DFFFFFFF</item>
     </style>

gradient_spinner.xml (in drawable folder)

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item><layer-list>
            <item><shape>
                    <gradient android:angle="90" android:endColor="#B3BBCC" android:startColor="#E8EBEF" android:type="linear" />

                    <stroke android:width="1dp" android:color="#000000" />

                    <corners android:radius="4dp" />

                    <padding android:bottom="3dp" android:left="3dp" android:right="3dp" android:top="3dp" />
                </shape></item>
            <item ><bitmap android:gravity="bottom|right" android:src="@drawable/spinner_arrow" />
            </item>
        </layer-list></item>

</selector>  

@drawable/spinner_arrow is your bottom right corner image

css padding is not working in outlook

I had the same problem and ended up actually using border instead of padding.

Moving Average Pandas

To get the moving average in pandas we can use cum_sum and then divide by count.

Here is the working example:

import pandas as pd
import numpy as np

df = pd.DataFrame({'id': range(5),
                   'value': range(100,600,100)})

# some other similar statistics
df['cum_sum'] = df['value'].cumsum()
df['count'] = range(1,len(df['value'])+1)
df['mov_avg'] = df['cum_sum'] / df['count']

# other statistics
df['rolling_mean2'] = df['value'].rolling(window=2).mean()

print(df)

output

   id  value  cum_sum  count  mov_avg     rolling_mean2
0   0    100      100      1    100.0           NaN
1   1    200      300      2    150.0           150.0
2   2    300      600      3    200.0           250.0
3   3    400     1000      4    250.0           350.0
4   4    500     1500      5    300.0           450.0

Internet Explorer 11 detection

To detect MSIE (from version 6 to 11) quickly:

if(navigator.userAgent.indexOf('MSIE')!==-1
|| navigator.appVersion.indexOf('Trident/') > -1){
   /* Microsoft Internet Explorer detected in. */
}

How to reload the current route with the angular 2 router

subscribe to route parameter changes

    // parent param listener ie: "/:id"
    this.route.params.subscribe(params => {
        // do something on parent param change
        let parent_id = params['id']; // set slug
    });

    // child param listener ie: "/:id/:id"
    this.route.firstChild.params.subscribe(params => {
        // do something on child param change
        let child_id = params['id'];
    });

rsync: how can I configure it to create target directory on server?

This answer uses bits of other answers, but hopefully it'll be a bit clearer as to the circumstances. You never specified what you were rsyncing - a single directory entry or multiple files.

So let's assume you are moving a source directory entry across, and not just moving the files contained in it.

Let's say you have a directory locally called data/myappdata/ and you have a load of subdirectories underneath this. You have data/ on your target machine but no data/myappdata/ - this is easy enough:

rsync -rvv /path/to/data/myappdata/ user@host:/remote/path/to/data/myappdata

You can even use a different name for the remote directory:

rsync -rvv --recursive /path/to/data/myappdata user@host:/remote/path/to/data/newdirname

If you're just moving some files and not moving the directory entry that contains them then you would do:

rsync -rvv /path/to/data/myappdata/*.txt user@host:/remote/path/to/data/myappdata/

and it will create the myappdata directory for you on the remote machine to place your files in. Again, the data/ directory must exist on the remote machine.

Incidentally, my use of -rvv flag is to get doubly verbose output so it is clear about what it does, as well as the necessary recursive behaviour.

Just to show you what I get when using rsync (3.0.9 on Ubuntu 12.04)

$ rsync -rvv *.txt [email protected]:/tmp/newdir/
opening connection using: ssh -l user remote.machine rsync --server -vvre.iLsf . /tmp/newdir/
[email protected]'s password:
sending incremental file list
created directory /tmp/newdir
delta-transmission enabled
bar.txt
foo.txt
total: matches=0  hash_hits=0  false_alarms=0 data=0

Hope this clears this up a little bit.

error: ORA-65096: invalid common user or role name in oracle

Create user dependency upon the database connect tools

sql plus
SQL> connect as sysdba;
Enter user-name: sysdba
Enter password:
Connected.
SQL> ALTER USER hr account unlock identified by hr;
User altered
 then create user on sql plus and sql developer

How to convert hex string to Java string?

byte[] bytes = javax.xml.bind.DatatypeConverter.parseHexBinary(hexString);
String result= new String(bytes, encoding);

How to get the HTML for a DOM element in javascript

You'll want something like this for it to be cross browser.

function OuterHTML(element) {
    var container = document.createElement("div");
    container.appendChild(element.cloneNode(true));

    return container.innerHTML;
}

How to select all checkboxes with jQuery?

 $(document).ready(function(){
    $("#select_all").click(function(){
      var checked_status = this.checked;
      $("input[name='select[]']").each(function(){
        this.checked = checked_status;
      });
    });
  });

Why is JsonRequestBehavior needed?

Improving upon the answer of @Arjen de Mooij a bit by making the AllowJsonGetAttribute applicable to mvc-controllers (not just individual action-methods):

using System.Web.Mvc;
public sealed class AllowJsonGetAttribute : ActionFilterAttribute, IActionFilter
{
    void IActionFilter.OnActionExecuted(ActionExecutedContext context)
    {
        var jsonResult = context.Result as JsonResult;
        if (jsonResult == null) return;

        jsonResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
    }

    public override void OnResultExecuting(ResultExecutingContext filterContext)
    {
        var jsonResult = filterContext.Result as JsonResult;
        if (jsonResult == null) return;

        jsonResult.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
        base.OnResultExecuting(filterContext);
    }
}

SQL "between" not inclusive

cast(created_at as date)

That will work only in 2008 and newer versions of SQL Server

If you are using older version then use

convert(varchar, created_at, 101)

How to set x axis values in matplotlib python?

The scaling on your example figure is a bit strange but you can force it by plotting the index of each x-value and then setting the ticks to the data points:

import matplotlib.pyplot as plt
x = [0.00001,0.001,0.01,0.1,0.5,1,5]
# create an index for each tick position
xi = list(range(len(x)))
y = [0.945,0.885,0.893,0.9,0.996,1.25,1.19]
plt.ylim(0.8,1.4)
# plot the index for the x-values
plt.plot(xi, y, marker='o', linestyle='--', color='r', label='Square') 
plt.xlabel('x')
plt.ylabel('y') 
plt.xticks(xi, x)
plt.title('compare')
plt.legend() 
plt.show()

How to set JAVA_HOME in Mac permanently?

Besides the settings for bash/ zsh terminal which are well covered by the other answers, if you want a permanent system environment variable for terminal + GUI applications (works for macOS Sierra; should work for El Capitan too):

launchctl setenv JAVA_HOME $(/usr/libexec/java_home -v 1.8)

(this will set JAVA_HOME to the latest 1.8 JDK, chances are you have gone through serveral updates e.g. javac 1.8.0_101, javac 1.8.0_131)

Of course, change 1.8 to 1.7 or 1.6 (really?) to suit your need and your system

Spring Boot without the web server

Spring boot will not include embedded tomcat if you don't have Tomcat dependencies on the classpath. You can view this fact yourself at the class EmbeddedServletContainerAutoConfiguration whose source you can find here.

The meat of the code is the use of the @ConditionalOnClass annotation on the class EmbeddedTomcat


Also, for more information check out this and this guide and this part of the documentation

Limit the height of a responsive image with css

I set the below 3 styles to my img tag

max-height: 500px;
height: 70%;
width: auto;

What it does that for desktop screen img doesn't grow beyond 500px but for small mobile screens, it will shrink to 70% of the outer container. Works like a charm.

It also works width property.

Matching exact string with JavaScript

Either modify the pattern beforehand so that it only matches the entire string:

var r = /^a$/

or check afterward whether the pattern matched the whole string:

function matchExact(r, str) {
   var match = str.match(r);
   return match && str === match[0];
}

Finding row index containing maximum value using R

How about the following, where y is the name of your matrix and you are looking for the maximum in the entire matrix:

row(y)[y==max(y)]

if you want to extract the row:

y[row(y)[y==max(y)],] # this returns unsorted rows.

To return sorted rows use:

y[sort(row(y)[y==max(y)]),]

The advantage of this approach is that you can change the conditional inside to anything you need. Also, using col(y) and location of the hanging comma you can also extract columns.

y[,col(y)[y==max(y)]]

To find just the row for the max in a particular column, say column 2 you could use:

seq(along=y[,2])[y[,2]==max(y[,2])]

again the conditional is flexible to look for different requirements.

See Phil Spector's excellent "An introduction to S and S-Plus" Chapter 5 for additional ideas.

Replacing accented characters php

To remove the diacritics, use iconv:

$val = iconv('ISO-8859-1','ASCII//TRANSLIT',$val);

or

$val = iconv('UTF-8','ASCII//TRANSLIT',$val);

note that php has some weird bug in that it (sometimes?) needs to have a locale set to make these conversions work, using setlocale().

edit tested, it gets all of your diacritics out of the box:

$val = "á|â|à|å|ä ð|é|ê|è|ë í|î|ì|ï ó|ô|ò|ø|õ|ö ú|û|ù|ü æ ç ß abc ABC 123";
echo iconv('UTF-8','ASCII//TRANSLIT',$val); 

output (updated 2019-12-30)

a|a|a|a|a d|e|e|e|e i|i|i|i o|o|o|o|o|o u|u|u|u ae c ss abc ABC 123

Note that ð is correctly transliterated to d instead of o, as in the accepted answer.

JQuery - Call the jquery button click event based on name property

You can use normal CSS selectors to select an element by name using jquery. Like this:

Button Code
<button type="button" name="mybutton">Click Me!</button>

Selector & Event Bind Code
$("button[name='mybutton']").click(function() {});

Why does modulus division (%) only work with integers?

You're looking for fmod().

I guess to more specifically answer your question, in older languages the % operator was just defined as integer modular division and in newer languages they decided to expand the definition of the operator.

EDIT: If I were to wager a guess why, I would say it's because the idea of modular arithmetic originates in number theory and deals specifically with integers.

'mvn' is not recognized as an internal or external command,

On my Windows 7 machine I have the following environment variables:

  • JAVA_HOME=C:\Program Files\Java\jdk1.7.0_07

  • M2_HOME=C:\apache-maven-3.0.3

On my PATH variable, I have (among others) the following:

  • %JAVA_HOME%\bin;%M2_HOME%\bin

I tried doing what you've done with %M2% having the nested %M2_HOME% and it also works.

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

Easier to convert nm to characters and then make the change:

junk$nm <- as.character(junk$nm)
junk$nm[junk$nm == "B"] <- "b"

EDIT: And if indeed you need to maintain nm as factors, add this in the end:

junk$nm <- as.factor(junk$nm)

Find IP address of directly connected device

You can also get information from directly connected networking devices, such as network switches with LDWin, a portable and free Windows program published on github:

http://www.sysadmit.com/2016/11/windows-como-saber-la-ip-del-switch-al-que-estoy-conectado.html

LDWin supports the following methods of link discovery: CDP (Cisco Discovery Protocol) and LLDP (Link Layer Discovery Protocol).

You can obtain the model, management IP, VLAN identifier, Port identifier, firmware version, etc.

Extract substring in Bash

Here's how i'd do it:

FN=someletters_12345_moreleters.ext
[[ ${FN} =~ _([[:digit:]]{5})_ ]] && NUM=${BASH_REMATCH[1]}

Explanation:

Bash-specific:

Regular Expressions (RE): _([[:digit:]]{5})_

  • _ are literals to demarcate/anchor matching boundaries for the string being matched
  • () create a capture group
  • [[:digit:]] is a character class, i think it speaks for itself
  • {5} means exactly five of the prior character, class (as in this example), or group must match

In english, you can think of it behaving like this: the FN string is iterated character by character until we see an _ at which point the capture group is opened and we attempt to match five digits. If that matching is successful to this point, the capture group saves the five digits traversed. If the next character is an _, the condition is successful, the capture group is made available in BASH_REMATCH, and the next NUM= statement can execute. If any part of the matching fails, saved details are disposed of and character by character processing continues after the _. e.g. if FN where _1 _12 _123 _1234 _12345_, there would be four false starts before it found a match.

How to make a jquery function call after "X" seconds

You can just use the normal setTimeout method in JavaScript.

ie...

setTimeout( function(){ 
    // Do something after 1 second 
  }  , 1000 );

In your example, you might want to use showStickySuccessToast directly.

Find duplicate records in MongoDB

db.getCollection('orders').aggregate([  
    {$group: { 
            _id: {name: "$name"},
            uniqueIds: {$addToSet: "$_id"},
            count: {$sum: 1}
        } 
    },
    {$match: { 
        count: {"$gt": 1}
        }
    }
])

First Group Query the group according to the fields.

Then we check the unique Id and count it, If count is greater then 1 then the field is duplicate in the entire collection so that thing is to be handle by $match query.

How to map with index in Ruby?

If you're using ruby 1.8.7 or 1.9, you can use the fact that iterator methods like each_with_index, when called without a block, return an Enumerator object, which you can call Enumerable methods like map on. So you can do:

arr.each_with_index.map { |x,i| [x, i+2] }

In 1.8.6 you can do:

require 'enumerator'
arr.enum_for(:each_with_index).map { |x,i| [x, i+2] }

How to write JUnit test with Spring Autowire?

In Spring 2.1.5 at least, the XML file can be conveniently replaced by annotations. Piggy backing on @Sembrano's answer, I have this. "Look ma, no XML".

It appears I to had list all the classes I need @Autowired in the @ComponentScan

@RunWith(SpringJUnit4ClassRunner.class)
@ComponentScan(
    basePackageClasses = {
            OwnerService.class
            })
@EnableAutoConfiguration
public class OwnerIntegrationTest {
    
    @Autowired
    OwnerService ownerService;
    
    @Test
    public void testOwnerService() {
       Assert.assertNotNull(ownerService);
    }
}

Where do I call the BatchNormalization function in Keras?

It is another type of layer, so you should add it as a layer in an appropriate place of your model

model.add(keras.layers.normalization.BatchNormalization())

See an example here: https://github.com/fchollet/keras/blob/master/examples/kaggle_otto_nn.py

How to cast the size_t to double or int C++

Assuming that the program cannot be redesigned to avoid the cast (ref. Keith Thomson's answer):

To cast from size_t to int you need to ensure that the size_t does not exceed the maximum value of the int. This can be done using std::numeric_limits:

int SizeTToInt(size_t data)
{
    if (data > std::numeric_limits<int>::max())
        throw std::exception("Invalid cast.");
    return std::static_cast<int>(data);
}

If you need to cast from size_t to double, and you need to ensure that you don't lose precision, I think you can use a narrow cast (ref. Stroustrup: The C++ Programming Language, Fourth Edition):

template<class Target, class Source>
Target NarrowCast(Source v)
{
    auto r = static_cast<Target>(v);
    if (static_cast<Source>(r) != v)
        throw RuntimeError("Narrow cast failed.");
    return r;
}

I tested using the narrow cast for size_t-to-double conversions by inspecting the limits of the maximum integers floating-point-representable integers (code uses googletest):

EXPECT_EQ(static_cast<size_t>(NarrowCast<double>(size_t{ IntegerRepresentableBoundary() - 2 })), size_t{ IntegerRepresentableBoundary() - 2 });
EXPECT_EQ(static_cast<size_t>(NarrowCast<double>(size_t{ IntegerRepresentableBoundary() - 1 })), size_t{ IntegerRepresentableBoundary() - 1 });
EXPECT_EQ(static_cast<size_t>(NarrowCast<double>(size_t{ IntegerRepresentableBoundary() })), size_t{ IntegerRepresentableBoundary() });
EXPECT_THROW(NarrowCast<double>(size_t{ IntegerRepresentableBoundary() + 1 }), std::exception);
EXPECT_EQ(static_cast<size_t>(NarrowCast<double>(size_t{ IntegerRepresentableBoundary() + 2 })), size_t{ IntegerRepresentableBoundary() + 2 });
EXPECT_THROW(NarrowCast<double>(size_t{ IntegerRepresentableBoundary() + 3 }), std::exception);
EXPECT_EQ(static_cast<size_t>(NarrowCast<double>(size_t{ IntegerRepresentableBoundary() + 4 })), size_t{ IntegerRepresentableBoundary() + 4 });
EXPECT_THROW(NarrowCast<double>(size_t{ IntegerRepresentableBoundary() + 5 }), std::exception);

where

constexpr size_t IntegerRepresentableBoundary()
{
    static_assert(std::numeric_limits<double>::radix == 2, "Method only valid for binary floating point format.");
    return size_t{2} << (std::numeric_limits<double>::digits - 1);
}

That is, if N is the number of digits in the mantissa, for doubles smaller than or equal to 2^N, integers can be exactly represented. For doubles between 2^N and 2^(N+1), every other integer can be exactly represented. For doubles between 2^(N+1) and 2^(N+2) every fourth integer can be exactly represented, and so on.

How to pass multiple arguments in processStartInfo?

startInfo.Arguments = "/c \"netsh http add sslcert ipport=127.0.0.1:8085 certhash=0000000000003ed9cd0c315bbb6dc1c08da5e6 appid={00112233-4455-6677-8899-AABBCCDDEEFF} clientcertnegotiation=enable\"";

and...

startInfo.Arguments = "/c \"makecert -sk server -sky exchange -pe -n CN=localhost -ir LocalMachine -is Root -ic MyCA.cer -sr LocalMachine -ss My MyAdHocTestCert.cer\"";

The /c tells cmd to quit once the command has completed. Everything after /c is the command you want to run (within cmd), including all of the arguments.

Manually install Gradle and use it in Android Studio

Android Studio will automatically use the Gradle wrapper and pull the correct version of Gradle rather than use a locally installed version. If you wish to use a new version of Gradle, you can change the version used by studio. Beneath your Android Studio's project tree, open the file gradle/wrapper/gradle-wrapper.properties. Change this entry:

distributionUrl=http\://services.gradle.org/distributions/gradle-2.1-all.zip

Xcode5 "No matching provisioning profiles found issue" (but good at xcode4)

Don't forget to change profile in Provision Profile sections: enter image description here

Ideally you should see Automatic in Code Signing Identity after you choose provision profile you need. If you don't see any option that's mean you don't have private key for current provision profile.

JavaScript require() on client side

I asked myself the very same questions. When I looked into it I found the choices overwhelming.

Fortunately I found this excellent spreadsheet that helps you choice the best loader based on your requirements:

https://spreadsheets.google.com/lv?key=tDdcrv9wNQRCNCRCflWxhYQ

How to clear input buffer in C?

But I cannot explain myself how it works? Because in the while statement, we use getchar() != '\n', that means read any single character except '\n'?? if so, in the input buffer still remains the '\n' character??? Am I misunderstanding something??

The thing you may not realize is that the comparison happens after getchar() removes the character from the input buffer. So when you reach the '\n', it is consumed and then you break out of the loop.

Create a new cmd.exe window from within another cmd.exe prompt

start cmd.exe 

opens a separate window

start file.cmd 

opens the batch file and executes it in another command prompt

svn: E155004: ..(path of resource).. is already locked

For me worked, in Eclipse:

Team -> Cleanup

Java 8 Stream API to find Unique Object matching a property value

findAny & orElse

By using findAny() and orElse():

Person matchingObject = objects.stream().
filter(p -> p.email().equals("testemail")).
findAny().orElse(null);

Stops looking after finding an occurrence.

findAny

Optional<T> findAny()

Returns an Optional describing some element of the stream, or an empty Optional if the stream is empty. This is a short-circuiting terminal operation. The behavior of this operation is explicitly nondeterministic; it is free to select any element in the stream. This is to allow for maximal performance in parallel operations; the cost is that multiple invocations on the same source may not return the same result. (If a stable result is desired, use findFirst() instead.)

Background thread with QThread in PyQt

I created a little example that shows 3 different and simple ways of dealing with threads. I hope it will help you find the right approach to your problem.

import sys
import time

from PyQt5.QtCore import (QCoreApplication, QObject, QRunnable, QThread,
                          QThreadPool, pyqtSignal)


# Subclassing QThread
# http://qt-project.org/doc/latest/qthread.html
class AThread(QThread):

    def run(self):
        count = 0
        while count < 5:
            time.sleep(1)
            print("A Increasing")
            count += 1

# Subclassing QObject and using moveToThread
# http://blog.qt.digia.com/blog/2007/07/05/qthreads-no-longer-abstract
class SomeObject(QObject):

    finished = pyqtSignal()

    def long_running(self):
        count = 0
        while count < 5:
            time.sleep(1)
            print("B Increasing")
            count += 1
        self.finished.emit()

# Using a QRunnable
# http://qt-project.org/doc/latest/qthreadpool.html
# Note that a QRunnable isn't a subclass of QObject and therefore does
# not provide signals and slots.
class Runnable(QRunnable):

    def run(self):
        count = 0
        app = QCoreApplication.instance()
        while count < 5:
            print("C Increasing")
            time.sleep(1)
            count += 1
        app.quit()


def using_q_thread():
    app = QCoreApplication([])
    thread = AThread()
    thread.finished.connect(app.exit)
    thread.start()
    sys.exit(app.exec_())

def using_move_to_thread():
    app = QCoreApplication([])
    objThread = QThread()
    obj = SomeObject()
    obj.moveToThread(objThread)
    obj.finished.connect(objThread.quit)
    objThread.started.connect(obj.long_running)
    objThread.finished.connect(app.exit)
    objThread.start()
    sys.exit(app.exec_())

def using_q_runnable():
    app = QCoreApplication([])
    runnable = Runnable()
    QThreadPool.globalInstance().start(runnable)
    sys.exit(app.exec_())

if __name__ == "__main__":
    #using_q_thread()
    #using_move_to_thread()
    using_q_runnable()

Angular 2 Unit Tests: Cannot find name 'describe'

With [email protected] or later you can install types with npm install

npm install --save-dev @types/jasmine

then import the types automatically using the typeRoots option in tsconfig.json.

"typeRoots": [
      "node_modules/@types"
    ],

This solution does not require import {} from 'jasmine'; in each spec file.

Convert char* to string C++

char *charPtr = "test string";
cout << charPtr << endl;

string str = charPtr;
cout << str << endl;

How to fill Matrix with zeros in OpenCV?

Mat img;

img=Mat::zeros(size of image,CV_8UC3);

if you want it to be of an image img1

img=Mat::zeros(img1.size,CV_8UC3);

Access VBA | How to replace parts of a string with another string

Use Access's VBA function Replace(text, find, replacement):

Dim result As String

result = Replace("Some sentence containing Avenue in it.", "Avenue", "Ave")

creating triggers for After Insert, After Update and After Delete in SQL

(Update: overlooked a fault in the matter, I have corrected)

(Update2: I wrote from memory the code screwed up, repaired it)

(Update3: check on SQLFiddle)

create table Derived_Values
  (
    BusinessUnit nvarchar(100) not null
    ,Questions nvarchar(100) not null
    ,Answer nvarchar(100)
    )

go

ALTER TABLE Derived_Values ADD CONSTRAINT PK_Derived_Values
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);

create table Derived_Values_Test
  (
    BusinessUnit nvarchar(150)
    ,Questions nvarchar(100)
    ,Answer nvarchar(100)
    )

go

CREATE TRIGGER trgAfterUpdate ON  [Derived_Values]
FOR UPDATE
AS  
begin
    declare @BusinessUnit nvarchar(50)
    set @BusinessUnit = 'Updated Record -- After Update Trigger.'

    insert into 
        [Derived_Values_Test]
        --(BusinessUnit,Questions, Answer) 
    SELECT 
        @BusinessUnit + i.BusinessUnit, i.Questions, i.Answer
    FROM 
        inserted i
        inner join deleted d on i.BusinessUnit = d.BusinessUnit
end

go

CREATE TRIGGER trgAfterDelete ON  [Derived_Values]
FOR UPDATE
AS  
begin
    declare @BusinessUnit nvarchar(50)
    set @BusinessUnit = 'Deleted Record -- After Delete Trigger.'

    insert into 
        [Derived_Values_Test]
        --(BusinessUnit,Questions, Answer) 
    SELECT 
        @BusinessUnit + d.BusinessUnit, d.Questions, d.Answer
    FROM 
        deleted d
end

go

insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q11', 'A11')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q12', 'A12')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q21', 'A21')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q22', 'A22')

UPDATE Derived_Values SET Answer='Updated Answers A11' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q11');
UPDATE Derived_Values SET Answer='Updated Answers A12' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q12');
UPDATE Derived_Values SET Answer='Updated Answers A21' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q21');
UPDATE Derived_Values SET Answer='Updated Answers A22' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q22');

delete Derived_Values;

and then:

SELECT * FROM Derived_Values;
go

select * from Derived_Values_Test;


Record Count: 0;

BUSINESSUNIT    QUESTIONS   ANSWER
Updated Record -- After Update Trigger.BU1  Q11 Updated Answers A11
Deleted Record -- After Delete Trigger.BU1  Q11 A11
Updated Record -- After Update Trigger.BU1  Q12 Updated Answers A12
Deleted Record -- After Delete Trigger.BU1  Q12 A12
Updated Record -- After Update Trigger.BU2  Q21 Updated Answers A21
Deleted Record -- After Delete Trigger.BU2  Q21 A21
Updated Record -- After Update Trigger.BU2  Q22 Updated Answers A22
Deleted Record -- After Delete Trigger.BU2  Q22 A22

(Update4: If you want to sync: SQLFiddle)

create table Derived_Values
  (
    BusinessUnit nvarchar(100) not null
    ,Questions nvarchar(100) not null
    ,Answer nvarchar(100)
    )

go

ALTER TABLE Derived_Values ADD CONSTRAINT PK_Derived_Values
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);

create table Derived_Values_Test
  (
    BusinessUnit nvarchar(150) not null
    ,Questions nvarchar(100) not null
    ,Answer nvarchar(100)
    )

go

ALTER TABLE Derived_Values_Test ADD CONSTRAINT PK_Derived_Values_Test
PRIMARY KEY CLUSTERED (BusinessUnit, Questions);

CREATE TRIGGER trgAfterInsert ON  [Derived_Values]
FOR INSERT
AS  
begin
    insert
        [Derived_Values_Test]
        (BusinessUnit,Questions,Answer)
    SELECT 
        i.BusinessUnit, i.Questions, i.Answer
    FROM 
        inserted i
end

go


CREATE TRIGGER trgAfterUpdate ON  [Derived_Values]
FOR UPDATE
AS  
begin
    declare @BusinessUnit nvarchar(50)
    set @BusinessUnit = 'Updated Record -- After Update Trigger.'

    update
        [Derived_Values_Test]
    set
        --BusinessUnit = i.BusinessUnit
        --,Questions = i.Questions
        Answer = i.Answer
    from
        [Derived_Values]
        inner join inserted i 
    on
        [Derived_Values].BusinessUnit = i.BusinessUnit
        and
        [Derived_Values].Questions = i.Questions
end

go

CREATE TRIGGER trgAfterDelete ON  [Derived_Values]
FOR DELETE
AS  
begin
    delete 
        [Derived_Values_Test]
    from
        [Derived_Values_Test]
        inner join deleted d 
    on
        [Derived_Values_Test].BusinessUnit = d.BusinessUnit
        and
        [Derived_Values_Test].Questions = d.Questions
end

go

insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q11', 'A11')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU1', 'Q12', 'A12')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q21', 'A21')
insert Derived_Values (BusinessUnit,Questions, Answer) values ('BU2', 'Q22', 'A22')

UPDATE Derived_Values SET Answer='Updated Answers A11' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q11');
UPDATE Derived_Values SET Answer='Updated Answers A12' from Derived_Values WHERE (BusinessUnit = 'BU1') AND (Questions = 'Q12');
UPDATE Derived_Values SET Answer='Updated Answers A21' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q21');
UPDATE Derived_Values SET Answer='Updated Answers A22' from Derived_Values WHERE (BusinessUnit = 'BU2') AND (Questions = 'Q22');

--delete Derived_Values;

And then:

SELECT * FROM Derived_Values;
go

select * from Derived_Values_Test;


BUSINESSUNIT    QUESTIONS   ANSWER
BU1 Q11 Updated Answers A11
BU1 Q12 Updated Answers A12
BU2 Q21 Updated Answers A21
BU2 Q22 Updated Answers A22

BUSINESSUNIT    QUESTIONS   ANSWER
BU1 Q11 Updated Answers A11
BU1 Q12 Updated Answers A12
BU2 Q21 Updated Answers A21
BU2 Q22 Updated Answers A22

Difference between Ctrl+Shift+F and Ctrl+I in Eclipse

Ctrl+Shift+F formats the selected line(s) or the whole source code if you haven't selected any line(s) as per the format specified in your Eclipse, while Ctrl+I gives proper indent to the selected line(s) or the current line if you haven't selected any line(s). try this. or more precisely

The Ant editor that ships with Eclipse can be used to reformat

XML/XHTML/HTML code (with a few configuration options in Window > Preferences > Ant > Editor).

You can right-click a file then

Open With... > Other... > Internal Editors > Ant Editor

Or add a file association between .html (or .xhtml) and that editor with

Window > Preferences > General > Editors > File Associations

Once open in the editor, hit ESC then CTRL-F to reformat.

How to write text in ipython notebook?

As it is written in the documentation you have to change the cell type to a markdown.

enter image description here

How can I pass a Bitmap object from one activity to another

All of the above solutions doesn't work for me, Sending bitmap as parceableByteArray also generates error android.os.TransactionTooLargeException: data parcel size.

Solution

  1. Saved the bitmap in internal storage as:
public String saveBitmap(Bitmap bitmap) {
        String fileName = "ImageName";//no .png or .jpg needed
        try {
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
            FileOutputStream fo = openFileOutput(fileName, Context.MODE_PRIVATE);
            fo.write(bytes.toByteArray());
            // remember close file output
            fo.close();
        } catch (Exception e) {
            e.printStackTrace();
            fileName = null;
        }
        return fileName;
    }
  1. and send in putExtra(String) as
Intent intent = new Intent(ActivitySketcher.this,ActivityEditor.class);
intent.putExtra("KEY", saveBitmap(bmp));
startActivity(intent);
  1. and Receive it in other activity as:
if(getIntent() != null){
  try {
           src = BitmapFactory.decodeStream(openFileInput("myImage"));
       } catch (FileNotFoundException e) {
            e.printStackTrace();
      }

 }


PHP write file from input to txt

A possible solution:

<?php
$txt = "data.txt"; 
if (isset($_POST['field1']) && isset($_POST['field2'])) { // check if both fields are set
    $fh = fopen($txt, 'a'); 
    $txt=$_POST['field1'].' - '.$_POST['field2']; 
    fwrite($fh,$txt); // Write information to the file
    fclose($fh); // Close the file
}
?>

You were closing the script before close de file.

How to prevent 'query timeout expired'? (SQLNCLI11 error '80040e31')

Turns out that the post (or rather the whole table) was locked by the very same connection that I tried to update the post with.

I had a opened record set of the post that was created by:

Set RecSet = Conn.Execute()

This type of recordset is supposed to be read-only and when I was using MS Access as database it did not lock anything. But apparently this type of record set did lock something on MS SQL Server 2012 because when I added these lines of code before executing the UPDATE SQL statement...

RecSet.Close
Set RecSet = Nothing

...everything worked just fine.

So bottom line is to be careful with opened record sets - even if they are read-only they could lock your table from updates.

Angular 4: no component factory found,did you add it to @NgModule.entryComponents?

TL;DR: A service in ng6 with providedIn: "root" cannot find the ComponentFactory when the Component is not added in the entryComponents of app.module.

This problem can also occur if you are using angular 6 in combination with dynamically creating a Component in a service!

For example, creating an Overlay:

@Injectable({
  providedIn: "root"
})
export class OverlayService {

  constructor(private _overlay: Overlay) {}

  openOverlay() {
    const overlayRef = this._createOverlay();
    const portal = new ComponentPortal(OverlayExampleComponent);

    overlayRef.attach(portal).instance;
  }
}

The Problem is the

providedIn: "root"

definition, which provides this service in app.module.

So if your service is located in, for example, the "OverlayModule", where you also declared the OverlayExampleComponent and added it to the entryComponents, the service cannot find the ComponentFactory for OverlayExampleComponent.

What is the convention in JSON for empty vs. null?

It is good programming practice to return an empty array [] if the expected return type is an array. This makes sure that the receiver of the json can treat the value as an array immediately without having to first check for null. It's the same way with empty objects using open-closed braces {}.

Strings, Booleans and integers do not have an 'empty' form, so there it is okay to use null values.

This is also addressed in Joshua Blochs excellent book "Effective Java". There he describes some very good generic programming practices (often applicable to other programming langages as well). Returning empty collections instead of nulls is one of them.

Here's a link to that part of his book:

http://jtechies.blogspot.nl/2012/07/item-43-return-empty-arrays-or.html

Pycharm: run only part of my Python file

Pycharm shortcut for running "Selection" in the console is ALT + SHIFT + e

For this to work properly, you'll have to run everything this way.

enter image description here

Get difference between 2 dates in JavaScript?

This is the code to subtract one date from another. This example converts the dates to objects as the getTime() function won't work unless it's an Date object.

    var dat1 = document.getElementById('inputDate').value;
                var date1 = new Date(dat1)//converts string to date object
                alert(date1);
                var dat2 = document.getElementById('inputFinishDate').value;
                var date2 = new Date(dat2)
                alert(date2);

                var oneDay = 24 * 60 * 60 * 1000; // hours*minutes*seconds*milliseconds
                var diffDays = Math.abs((date1.getTime() - date2.getTime()) / (oneDay));
                alert(diffDays);

how to access parent window object using jquery?

Here is a more literal answer (parent window as opposed to opener) to the original question that can be used within an iframe, assuming the domain name in the iframe matches that of the parent window:

window.parent.$("#serverMsg")

What is content-type and datatype in an AJAX request?

From the jQuery documentation - http://api.jquery.com/jQuery.ajax/

contentType When sending data to the server, use this content type.

dataType The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response

"text": A plain text string.

So you want contentType to be application/json and dataType to be text:

$.ajax({
    type : "POST",
    url : /v1/user,
    dataType : "text",
    contentType: "application/json",
    data : dataAttribute,
    success : function() {

    },
    error : function(error) {

    }
});

how to get rid of notification circle in right side of the screen?

This stuff comes from ES file explorer

Just go into this app > settings

Then there is an option that says logging floating window, you just need to disable that and you will get rid of this infernal bubble for good

Android Studio - ADB Error - "...device unauthorized. Please check the confirmation dialog on your device."

This might help - Just Download and install the Android SDK version(same as your mobile's android version), then run.

You don't have write permissions for the /var/lib/gems/2.3.0 directory

Rather than changing owners, which might lock out other local users, or –some day– your own ruby server/deployment-things... running under a different user...

I would rather simply extend rights of that particular folder to... well, everybody:

cd /var/lib
sudo chmod -R a+w gems/

(I did encounter your error as well. So this is fairly verified.)

How can I get the actual video URL of a YouTube live stream?

You need to get the HLS m3u8 playlist files from the video's manifest. There are ways to do this by hand, but for simplicity I'll be using the youtube-dl tool to get this information. I'll be using this live stream as an example: https://www.youtube.com/watch?v=_Gtc-GtLlTk

First, get the formats of the video:

?  ~ youtube-dl --list-formats https://www.youtube.com/watch\?v\=_Gtc-GtLlTk
[youtube] _Gtc-GtLlTk: Downloading webpage
[youtube] _Gtc-GtLlTk: Downloading video info webpage
[youtube] Downloading multifeed video (_Gtc-GtLlTk, aflWCT1tYL0) - add --no-playlist to just download video _Gtc-GtLlTk
[download] Downloading playlist: Southwest Florida Eagle Cam
[youtube] playlist Southwest Florida Eagle Cam: Collected 2 video ids (downloading 2 of them)
[download] Downloading video 1 of 2
[youtube] _Gtc-GtLlTk: Downloading webpage
[youtube] _Gtc-GtLlTk: Downloading video info webpage
[youtube] _Gtc-GtLlTk: Extracting video information
[youtube] _Gtc-GtLlTk: Downloading formats manifest
[youtube] _Gtc-GtLlTk: Downloading DASH manifest
[info] Available formats for _Gtc-GtLlTk:
format code  extension  resolution note
140          m4a        audio only DASH audio  144k , m4a_dash container, mp4a.40.2@128k (48000Hz)
160          mp4        256x144    DASH video  124k , avc1.42c00b, 30fps, video only
133          mp4        426x240    DASH video  258k , avc1.4d4015, 30fps, video only
134          mp4        640x360    DASH video  646k , avc1.4d401e, 30fps, video only
135          mp4        854x480    DASH video 1171k , avc1.4d401f, 30fps, video only
136          mp4        1280x720   DASH video 2326k , avc1.4d401f, 30fps, video only
137          mp4        1920x1080  DASH video 4347k , avc1.640028, 30fps, video only
151          mp4        72p        HLS , h264, aac  @ 24k
132          mp4        240p       HLS , h264, aac  @ 48k
92           mp4        240p       HLS , h264, aac  @ 48k
93           mp4        360p       HLS , h264, aac  @128k
94           mp4        480p       HLS , h264, aac  @128k
95           mp4        720p       HLS , h264, aac  @256k
96           mp4        1080p      HLS , h264, aac  @256k (best)
[download] Downloading video 2 of 2
[youtube] aflWCT1tYL0: Downloading webpage
[youtube] aflWCT1tYL0: Downloading video info webpage
[youtube] aflWCT1tYL0: Extracting video information
[youtube] aflWCT1tYL0: Downloading formats manifest
[youtube] aflWCT1tYL0: Downloading DASH manifest
[info] Available formats for aflWCT1tYL0:
format code  extension  resolution note
140          m4a        audio only DASH audio  144k , m4a_dash container, mp4a.40.2@128k (48000Hz)
160          mp4        256x144    DASH video  124k , avc1.42c00b, 30fps, video only
133          mp4        426x240    DASH video  258k , avc1.4d4015, 30fps, video only
134          mp4        640x360    DASH video  646k , avc1.4d401e, 30fps, video only
135          mp4        854x480    DASH video 1171k , avc1.4d401f, 30fps, video only
136          mp4        1280x720   DASH video 2326k , avc1.4d401f, 30fps, video only
151          mp4        72p        HLS , h264, aac  @ 24k
132          mp4        240p       HLS , h264, aac  @ 48k
92           mp4        240p       HLS , h264, aac  @ 48k
93           mp4        360p       HLS , h264, aac  @128k
94           mp4        480p       HLS , h264, aac  @128k
95           mp4        720p       HLS , h264, aac  @256k (best)
[download] Finished downloading playlist: Southwest Florida Eagle Cam

In this case, there are two videos because the live stream contains two cameras. From here, we need to get the HLS URL for a specific stream. Use -f to pass in the format you would like to watch, and -g to get that stream's URL:

?  ~ youtube-dl -f 95 -g https://www.youtube.com/watch\?v\=_Gtc-GtLlTk
https://manifest.googlevideo.com/api/manifest/hls_playlist/id/_Gtc-GtLlTk.2/itag/95/source/yt_live_broadcast/requiressl/yes/ratebypass/yes/live/1/cmbypass/yes/gir/yes/dg_shard/X0d0Yy1HdExsVGsuMg.95/hls_chunk_host/r1---sn-ab5l6ne6.googlevideo.com/playlist_type/LIVE/gcr/us/pmbypass/yes/mm/32/mn/sn-ab5l6ne6/ms/lv/mv/m/pl/20/dover/3/sver/3/fexp/9408495,9410706,9416126,9418581,9420452,9422596,9422780,9423059,9423661,9423662,9425349,9425959,9426661,9426720,9427325,9428422,9429306/upn/xmL7zNht848/mt/1456412649/ip/64.125.177.124/ipbits/0/expire/1456434315/sparams/ip,ipbits,expire,id,itag,source,requiressl,ratebypass,live,cmbypass,gir,dg_shard,hls_chunk_host,playlist_type,gcr,pmbypass,mm,mn,ms,mv,pl/signature/7E48A727654105FF82E158154FCBA7569D52521B.1FA117183C664F00B7508DDB81274644F520C27F/key/dg_yt0/playlist/index.m3u8
https://manifest.googlevideo.com/api/manifest/hls_playlist/id/aflWCT1tYL0.2/itag/95/source/yt_live_broadcast/requiressl/yes/ratebypass/yes/live/1/cmbypass/yes/gir/yes/dg_shard/YWZsV0NUMXRZTDAuMg.95/hls_chunk_host/r13---sn-ab5l6n7y.googlevideo.com/pmbypass/yes/playlist_type/LIVE/gcr/us/mm/32/mn/sn-ab5l6n7y/ms/lv/mv/m/pl/20/dover/3/sver/3/upn/vdBkD9lrq8Q/fexp/9408495,9410706,9416126,9418581,9420452,9422596,9422780,9423059,9423661,9423662,9425349,9425959,9426661,9426720,9427325,9428422,9429306/mt/1456412649/ip/64.125.177.124/ipbits/0/expire/1456434316/sparams/ip,ipbits,expire,id,itag,source,requiressl,ratebypass,live,cmbypass,gir,dg_shard,hls_chunk_host,pmbypass,playlist_type,gcr,mm,mn,ms,mv,pl/signature/4E83CD2DB23C2331CE349CE9AFE806C8293A01ED.880FD2E253FAC8FA56FAA304C78BD1D62F9D22B4/key/dg_yt0/playlist/index.m3u8

These are your HLS m3u8 playlists, one for each camera associated with the live stream.

Without youtube-dl, your flow might look like this:

Take your video id and make a GET request to the get_video_info endpoint:

HTTP GET: https://www.youtube.com/get_video_info?&video_id=_Gtc-GtLlTk&el=info&ps=default&eurl=&gl=US&hl=en

In the response, the hlsvp value will be the link to the m3u8 HLS playlist:

https://manifest.googlevideo.com/api/manifest/hls_variant/maudio/1/ipbits/0/key/yt6/ip/64.125.177.124/gcr/us/source/yt_live_broadcast/upn/BYS1YGuQtYI/id/_Gtc-GtLlTk.2/fexp/9416126%2C9416984%2C9417367%2C9420452%2C9422596%2C9423039%2C9423661%2C9423662%2C9423923%2C9425346%2C9427672%2C9428946%2C9429162/sparams/gcr%2Cid%2Cip%2Cipbits%2Citag%2Cmaudio%2Cplaylist_type%2Cpmbypass%2Csource%2Cexpire/sver/3/expire/1456449859/pmbypass/yes/playlist_type/LIVE/itag/0/signature/1E6874232CCAC397B601051699A03DC5A32F66D9.1CABCD9BFC87A2A886A29B86CF877077DD1AEEAA/file/index.m3u8

NodeJS: How to get the server's port?

The easier way is just to call app.get('url'), which gives you the protocol, sub domain, domain, and port.

Asp.net - Add blank item at top of dropdownlist

Do your databinding and then add the following:

Dim liFirst As New ListItem("", "")
drpList.Items.Insert(0, liFirst)

How to add Class in <li> using wp_nav_menu() in Wordpress?

No need to create custom walker. Just use additional argument and set filter for nav_menu_css_class.

For example:

$args = array(
    'container'     => '',
    'theme_location'=> 'your-theme-loc',
    'depth'         => 1,
    'fallback_cb'   => false,
    'add_li_class'  => 'your-class-name1 your-class-name-2'
    );
wp_nav_menu($args);

Notice the new 'add_li_class' argument.

And set the filter on functions.php

function add_additional_class_on_li($classes, $item, $args) {
    if(isset($args->add_li_class)) {
        $classes[] = $args->add_li_class;
    }
    return $classes;
}
add_filter('nav_menu_css_class', 'add_additional_class_on_li', 1, 3);

Questions every good .NET developer should be able to answer?

A few more:

What are the limitations of garbage collection.

Know about finalizers and IDisposable.

Be aware of the thread pool and when to use it.

If you're doing GUI applications - be aware that Windows GUI is single threaded.

Use foreach (I see a lot of people doing MoveNext etc.)

How do I exit the Vim editor?

I got Vim by installing a Git client on Windows. :q wouldn't exit Vim for me. :exit did however...

Check if a value is within a range of numbers

If you must use a regexp (and really, you shouldn't!) this will work:

/^0\.00([1-8]\d*|90*)$/

should work, i.e.

  • ^ nothing before,
  • followed by 0.00 (nb: backslash escape for the . character)
  • followed by 1 through 8, and any number of additional digits
  • or 9, followed by any number of zeroes
  • $: followed by nothing else

UINavigationBar custom back button without title

I found an easy way to make my back button with iOS single arrow.

Let's supouse that you have a navigation controller going to ViewA from ViewB. In IB, select ViewA's navigation bar, you should see these options: Title, Prompt and Back Button.

ViewA navigate bar options

ViewA navigate bar options

The trick is choose your destiny view controller back button title (ViewB) in the options of previous view controller (View A). If you don't fill the option "Back Button", iOS will put the title "Back" automatically, with previous view controller's title. So, you need to fill this option with a single space.

Fill space in "Back Button" option

Fill space in "Back Button" option

The Result:

The Result:

Contains case insensitive

From ES2016 you can also use slightly better / easier / more elegant method (case-sensitive):

if (referrer.includes("Ral")) { ... }

or (case-insensitive):

if (referrer.toLowerCase().includes(someString.toLowerCase())) { ... }

Here is some comparison of .indexOf() and .includes(): https://dev.to/adroitcoder/includes-vs-indexof-in-javascript

How to get the Touch position in android?

@Override
    public boolean onTouch(View v, MotionEvent event) {
       float x = event.getX();
       float y = event.getY();
       return true;
    }

How can I do width = 100% - 100px in CSS?

my code, and it works for IE6:

<style>
#container {margin:0 auto; width:100%;}
#header { height:100px; background:#9c6; margin-bottom:5px;}
#mainContent { height:500px; margin-bottom:5px;}
#sidebar { float:left; width:100px; height:500px; background:#cf9;}
#content { margin-left:100px; height:500px; background:#ffa;}

</style>

<div id="container">
  <div id="header">header</div>
  <div id="mainContent">
    <div id="sidebar">left</div>
    <div id="content">right 100% - 100px</div>
  <span style="display:none"></span></div>
</div>

enter image description here

Equivalent of LIMIT and OFFSET for SQL Server?

select top {LIMIT HERE} * from (
      select *, ROW_NUMBER() over (order by {ORDER FIELD}) as r_n_n 
      from {YOUR TABLES} where {OTHER OPTIONAL FILTERS}
) xx where r_n_n >={OFFSET HERE}

A note: This solution will only work in SQL Server 2005 or above, since this was when ROW_NUMBER() was implemented.

phpmailer - The following SMTP Error: Data not accepted

Try to set the port on 26, this has fixed my problem with the message "data not accepted".

Dynamic SQL results into temp table in SQL Stored procedure

INSERT INTO #TempTable
EXEC(@SelectStatement)

Check if a file exists or not in Windows PowerShell?

Use Test-Path:

if (!(Test-Path $exactadminfile) -and !(Test-Path $userfile)) {
  Write-Warning "$userFile absent from both locations"
}

Placing the above code in your ForEach loop should do what you want

LogisticRegression: Unknown label type: 'continuous' using sklearn in python

LogisticRegression is not for regression but classification !

The Y variable must be the classification class,

(for example 0 or 1)

And not a continuous variable,

that would be a regression problem.

A method to count occurrences in a list

How about something like this ...

var l1 = new List<int>() { 1,2,3,4,5,2,2,2,4,4,4,1 };

var g = l1.GroupBy( i => i );

foreach( var grp in g )
{
  Console.WriteLine( "{0} {1}", grp.Key, grp.Count() );
}

Edit per comment: I will try and do this justice. :)

In my example, it's a Func<int, TKey> because my list is ints. So, I'm telling GroupBy how to group my items. The Func takes a int and returns the the key for my grouping. In this case, I will get an IGrouping<int,int> (a grouping of ints keyed by an int). If I changed it to (i => i.ToString() ) for example, I would be keying my grouping by a string. You can imagine a less trivial example than keying by "1", "2", "3" ... maybe I make a function that returns "one", "two", "three" to be my keys ...

private string SampleMethod( int i )
{
  // magically return "One" if i == 1, "Two" if i == 2, etc.
}

So, that's a Func that would take an int and return a string, just like ...

i =>  // magically return "One" if i == 1, "Two" if i == 2, etc. 

But, since the original question called for knowing the original list value and it's count, I just used an integer to key my integer grouping to make my example simpler.

Purge Kafka Topic

To clean up all the messages from a particular topic using your application group (GroupName should be same as application kafka group name).

./kafka-path/bin/kafka-console-consumer.sh --zookeeper localhost:2181 --topic topicName --from-beginning --group application-group

How to hide the border for specified rows of a table?

Add programatically noborder class to specific row to hide it

<style>
     .noborder
      {
        border:none;
      }
    </style>

<table>

    <tr>
       <th>heading1</th>
       <th>heading2</th>
    </tr>


    <tr>
       <td>content1</td>
       <td>content2</td>
    </tr>
    /*no border for this row */
    <tr class="noborder">
       <td>content1</td>
       <td>content2</td>
    </tr>

</table>

Set the Value of a Hidden field using JQuery

If you have a hidden field like this

  <asp:HiddenField ID="HiddenField1" runat="server" Value='<%# Eval("VertragNr") %>'/>

Now you can use your value like this

$(this).parent().find('input[type=hidden]').val()

How to add a single item to a Pandas Series

TLDR: do not append items to a series one by one, better extend with an ordered collection

I think the question in its current form is a bit tricky. And the accepted answer does answer the question. But the more I use pandas, the more I understand that it's a bad idea to append items to a Series one by one. I'll try to explain why for pandas beginners.

You might think that appending data to a given Series might allow you to reuse some resources, but in reality a Series is just a container that stores a relation between an index and a values array. Each is a numpy.array under the hood, and the index is immutable. When you add to Series an item with a label that is missing in the index, a new index with size n+1 is created, and a new values values array of the same size. That means that when you append items one by one, you create two more arrays of the n+1 size on each step.

By the way, you can not append a new item by position (you will get an IndexError) and the label in an index does not have to be unique, that is when you assign a value with a label, you assign the value to all existing items with the the label, and a new row is not appended in this case. This might lead to subtle bugs.

The moral of the story is that you should not append data one by one, you should better extend with an ordered collection. The problem is that you can not extend a Series inplace. That is why it is better to organize your code so that you don't need to update a specific instance of a Series by reference.

If you create labels yourself and they are increasing, the easiest way is to add new items to a dictionary, then create a new Series from the dictionary (it sorts the keys) and append the Series to an old one. If the keys are not increasing, then you will need to create two separate lists for the new labels and the new values.

Below are some code samples:

In [1]: import pandas as pd
In [2]: import numpy as np

In [3]: s = pd.Series(np.arange(4)**2, index=np.arange(4))

In [4]: s
Out[4]:
0    0
1    1
2    4
3    9
dtype: int64

In [6]: id(s.index), id(s.values)
Out[6]: (4470549648, 4470593296)

When we update an existing item, the index and the values array stay the same (if you do not change the type of the value)

In [7]: s[2] = 14  

In [8]: id(s.index), id(s.values)
Out[8]: (4470549648, 4470593296)

But when you add a new item, a new index and a new values array is generated:

In [9]: s[4] = 16

In [10]: s
Out[10]:
0     0
1     1
2    14
3     9
4    16
dtype: int64

In [11]: id(s.index), id(s.values)
Out[11]: (4470548560, 4470595056)

That is if you are going to append several items, collect them in a dictionary, create a Series, append it to the old one and save the result:

In [13]: new_items = {item: item**2 for item in range(5, 7)}

In [14]: s2 = pd.Series(new_items)

In [15]: s2  # keys are guaranteed to be sorted!
Out[15]:
5    25
6    36
dtype: int64

In [16]: s = s.append(s2); s
Out[16]:
0     0
1     1
2    14
3     9
4    16
5    25
6    36
dtype: int64

How do files get into the External Dependencies in Visual Studio C++?

The External Dependencies folder is populated by IntelliSense: the contents of the folder do not affect the build at all (you can in fact disable the folder in the UI).

You need to actually include the header (using a #include directive) to use it. Depending on what that header is, you may also need to add its containing folder to the "Additional Include Directories" property and you may need to add additional libraries and library folders to the linker options; you can set all of these in the project properties (right click the project, select Properties). You should compare the properties with those of the project that does build to determine what you need to add.