Programs & Examples On #Authorizationmanager

Change jsp on button click

It works using ajax. The jsp then display in iframe returned by controller in response to request.

function openPage() {
  jQuery.ajax({
  type : 'POST',
  data : jQuery(this).serialize(),
  url : '<%=request.getContextPath()%>/post_action',
  success : function(data, textStatus) {
  jQuery('#iframeId').contents().find('body').append(data);
  },
  error : function(XMLHttpRequest, textStatus, errorThrown) {
  }
  });
}

How to downgrade Java from 9 to 8 on a MACOS. Eclipse is not running with Java 9

You don't need to down grade. You can run more than one version of Java on MacOS. You can set the version of your terminal with this command in MacOS.

# List Java versions installed
/usr/libexec/java_home -V

# Java 11
export JAVA_HOME=$(/usr/libexec/java_home -v 11)

# Java 1.8
export JAVA_HOME=$(/usr/libexec/java_home -v 1.8)

# Java 1.7
export JAVA_HOME=$(/usr/libexec/java_home -v 1.7)

# Java 1.6
export JAVA_HOME=$(/usr/libexec/java_home -v 1.6)

You can set the default value in the .bashrc, .profile, or .zprofile

Selecting data frame rows based on partial string match in a column

I notice that you mention a function %like% in your current approach. I don't know if that's a reference to the %like% from "data.table", but if it is, you can definitely use it as follows.

Note that the object does not have to be a data.table (but also remember that subsetting approaches for data.frames and data.tables are not identical):

library(data.table)
mtcars[rownames(mtcars) %like% "Merc", ]
iris[iris$Species %like% "osa", ]

If that is what you had, then perhaps you had just mixed up row and column positions for subsetting data.


If you don't want to load a package, you can try using grep() to search for the string you're matching. Here's an example with the mtcars dataset, where we are matching all rows where the row names includes "Merc":

mtcars[grep("Merc", rownames(mtcars)), ]
             mpg cyl  disp  hp drat   wt qsec vs am gear carb
# Merc 240D   24.4   4 146.7  62 3.69 3.19 20.0  1  0    4    2
# Merc 230    22.8   4 140.8  95 3.92 3.15 22.9  1  0    4    2
# Merc 280    19.2   6 167.6 123 3.92 3.44 18.3  1  0    4    4
# Merc 280C   17.8   6 167.6 123 3.92 3.44 18.9  1  0    4    4
# Merc 450SE  16.4   8 275.8 180 3.07 4.07 17.4  0  0    3    3
# Merc 450SL  17.3   8 275.8 180 3.07 3.73 17.6  0  0    3    3
# Merc 450SLC 15.2   8 275.8 180 3.07 3.78 18.0  0  0    3    3

And, another example, using the iris dataset searching for the string osa:

irisSubset <- iris[grep("osa", iris$Species), ]
head(irisSubset)
#   Sepal.Length Sepal.Width Petal.Length Petal.Width Species
# 1          5.1         3.5          1.4         0.2  setosa
# 2          4.9         3.0          1.4         0.2  setosa
# 3          4.7         3.2          1.3         0.2  setosa
# 4          4.6         3.1          1.5         0.2  setosa
# 5          5.0         3.6          1.4         0.2  setosa
# 6          5.4         3.9          1.7         0.4  setosa

For your problem try:

selectedRows <- conservedData[grep("hsa-", conservedData$miRNA), ]

How to use OpenFileDialog to select a folder?

Take a look at the Ookii Dialogs libraries which has an implementation of a folder browser dialog for Windows Forms and WPF respectively.

enter image description here

Ookii.Dialogs.WinForms

https://github.com/augustoproiete/ookii-dialogs-winforms


Ookii.Dialogs.Wpf

https://github.com/augustoproiete/ookii-dialogs-wpf

MIT vs GPL license

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

True - in general. You don't have to open-source your changes if you're using GPL. You could modify it and use it for your own purpose as long as you're not distributing it. BUT... if you DO distribute it, then your entire project that is using the GPL code also becomes GPL automatically. Which means, it must be open-sourced, and the recipient gets all the same rights as you - meaning, they can turn around and distribute it, modify it, sell it, etc. And that would include your proprietary code which would then no longer be proprietary - it becomes open source.

The difference with MIT is that even if you actually distribute your proprietary code that is using the MIT licensed code, you do not have to make the code open source. You can distribute it as a closed app where the code is encrypted or is a binary. Including the MIT-licensed code can be encrypted, as long as it carries the MIT license notice.

is the GPL is more restrictive than the MIT license?

Yes, very much so.

Import a custom class in Java

First off, avoid using the default package.

Second of all, you don't need to import the class; it's in the same package.

jQuery - find table row containing table cell containing specific text

I know this is an old post but I thought I could share an alternative [not as robust, but simpler] approach to searching for a string in a table.

$("tr:contains(needle)"); //where needle is the text you are searching for.

For example, if you are searching for the text 'box', that would be:

$("tr:contains('box')");

This would return all the elements with this text. Additional criteria could be used to narrow it down if it returns multiple elements

How to make several plots on a single page using matplotlib?

The answer from las3rjock, which somehow is the answer accepted by the OP, is incorrect--the code doesn't run, nor is it valid matplotlib syntax; that answer provides no runnable code and lacks any information or suggestion that the OP might find useful in writing their own code to solve the problem in the OP.

Given that it's the accepted answer and has already received several up-votes, I suppose a little deconstruction is in order.

First, calling subplot does not give you multiple plots; subplot is called to create a single plot, as well as to create multiple plots. In addition, "changing plt.figure(i)" is not correct.

plt.figure() (in which plt or PLT is usually matplotlib's pyplot library imported and rebound as a global variable, plt or sometimes PLT, like so:

from matplotlib import pyplot as PLT

fig = PLT.figure()

the line just above creates a matplotlib figure instance; this object's add_subplot method is then called for every plotting window (informally think of an x & y axis comprising a single subplot). You create (whether just one or for several on a page), like so

fig.add_subplot(111)

this syntax is equivalent to

fig.add_subplot(1,1,1)

choose the one that makes sense to you.

Below I've listed the code to plot two plots on a page, one above the other. The formatting is done via the argument passed to add_subplot. Notice the argument is (211) for the first plot and (212) for the second.

from matplotlib import pyplot as PLT

fig = PLT.figure()

ax1 = fig.add_subplot(211)
ax1.plot([(1, 2), (3, 4)], [(4, 3), (2, 3)])

ax2 = fig.add_subplot(212)
ax2.plot([(7, 2), (5, 3)], [(1, 6), (9, 5)])

PLT.show()

Each of these two arguments is a complete specification for correctly placing the respective plot windows on the page.

211 (which again, could also be written in 3-tuple form as (2,1,1) means two rows and one column of plot windows; the third digit specifies the ordering of that particular subplot window relative to the other subplot windows--in this case, this is the first plot (which places it on row 1) hence plot number 1, row 1 col 1.

The argument passed to the second call to add_subplot, differs from the first only by the trailing digit (a 2 instead of a 1, because this plot is the second plot (row 2, col 1).

An example with more plots: if instead you wanted four plots on a page, in a 2x2 matrix configuration, you would call the add_subplot method four times, passing in these four arguments (221), (222), (223), and (224), to create four plots on a page at 10, 2, 8, and 4 o'clock, respectively and in this order.

Notice that each of the four arguments contains two leadings 2's--that encodes the 2 x 2 configuration, ie, two rows and two columns.

The third (right-most) digit in each of the four arguments encodes the ordering of that particular plot window in the 2 x 2 matrix--ie, row 1 col 1 (1), row 1 col 2 (2), row 2 col 1 (3), row 2 col 2 (4).

Count the items from a IEnumerable<T> without iterating?

I use IEnum<string>.ToArray<string>().Length and it works fine.

How can I check if a Perl module is installed on my system from the command line?

If you want to quickly check if a module is installed (at least on Unix systems, with Bash as shell), add this to your .bashrc file:

alias modver="perl -e\"eval qq{use \\\$ARGV[0];\\\\\\\$v=\\\\\\\$\\\${ARGV[0]}::VERSION;};\ print\\\$@?qq{No module found\\n}:\\\$v?qq{Version \\\$v\\n}:qq{Found.\\n};\"\$1"

Then you can:

=> modver XML::Simple
No module found

=> modver DBI
Version 1.607

Label on the left side instead above an input field

I managed to fix my issue with. Seems to work fine and means I dont have to add widths to all my inputs manually.

.form-inline .form-group input {
 width: auto; 
}

ORA-00904: invalid identifier

DEPARTMENT_CODE is not a column that exists in the table Team. Check the DDL of the table to find the proper column name.

Preventing twitter bootstrap carousel from auto sliding on page load

if you're using bootstrap 3 set data-interval="false" on the HTML structure of carousel

example:

<div id="carousel-example-generic" class="carousel slide" data-ride="carousel" data-interval="false">

How to reset Django admin password?

You may try this:

1.Change Superuser password without console

python manage.py changepassword <username>

2.Change Superuser password through console

enter image description here enter image description here

How do I get a PHP class constructor to call its parent's parent's constructor?

// main class that everything inherits
class Grandpa 
{
    public function __construct()
    {
        $this->___construct();
    }

    protected function ___construct()
    {
        // grandpa's logic
    }

}

class Papa extends Grandpa
{
    public function __construct()
    {
        // call Grandpa's constructor
        parent::__construct();
    }
}

class Kiddo extends Papa
{
    public function __construct()
    {
        parent::___construct();
    }
}

note that "___construct" is not some magic name, you can call it "doGrandpaStuff".

How to get all the values of input array element jquery

By Using map

var values = $("input[name='pname[]']")
              .map(function(){return $(this).val();}).get();

How do I turn off PHP Notices?

I believe commenting out display_errors in php.ini won't work because the default is On. You must set it to 'Off' instead.

Don't forget to restart Apache to apply configuration changes.

Also note that while you can set display_errors at runtime, changing it here does not affect FATAL errors.

As noted by others, ideally during development you should run with error_reporting at the highest level possible and display_errors enabled. While annoying when you first start out, these errors, warnings, notices and strict coding advice all add up and enable you to becoem a better coder.

How to pass parameter to function using in addEventListener?

When you use addEventListener, this will be bound automatically. So if you want a reference to the element on which the event handler is installed, just use this from within your function:

productLineSelect.addEventListener('change',getSelection,false);

function getSelection(){
    var value = sel.options[this.selectedIndex].value;
    alert(value);
}

If you want to pass in some other argument from the context where you call addEventListener, you can use a closure, like this:

productLineSelect.addEventListener('change', function(){ 
    // pass in `this` (the element), and someOtherVar
    getSelection(this, someOtherVar); 
},false);

function getSelection(sel, someOtherVar){
    var value = sel.options[sel.selectedIndex].value;
    alert(value);
    alert(someOtherVar);
}

Postgresql Windows, is there a default password?

Try this:

Open PgAdmin -> Files -> Open pgpass.conf

You would get the path of pgpass.conf at the bottom of the window. Go to that location and open this file, you can find your password there.

Reference

If the above does not work, you may consider trying this:

 1. edit pg_hba.conf to allow trust authorization temporarily
 2. Reload the config file (pg_ctl reload)
 3. Connect and issue ALTER ROLE / PASSWORD to set the new password
 4. edit pg_hba.conf again and restore the previous settings
 5. Reload the config file again

ASP.NET Web Site or ASP.NET Web Application?

In Web Application Projects, Visual Studio needs additional .designer files for pages and user controls. Web Site Projects do not require this overhead. The markup itself is interpreted as the design.

Angular 2 - View not updating after model changes

In my case, I had a very similar problem. I was updating my view inside a function that was being called by a parent component, and in my parent component I forgot to use @ViewChild(NameOfMyChieldComponent). I lost at least 3 hours just for this stupid mistake. i.e: I didn't need to use any of those methods:

  • ChangeDetectorRef.detectChanges()
  • ChangeDetectorRef.markForCheck()
  • ApplicationRef.tick()

String parsing in Java with delimiter tab "\t" using split

I just had the same question and noticed the answer in some kind of tutorial. In general you need to use the second form of the split method, using the

split(regex, limit)

Here is the full tutorial http://www.rgagnon.com/javadetails/java-0438.html

If you set some negative number for the limit parameter you will get empty strings in the array where the actual values are missing. To use this your initial string should have two copies of the delimiter i.e. you should have \t\t where the values are missing.

Hope this helps :)

Express.js req.body undefined

Credit to @spikeyang for the great answer (provided below). After reading the suggested article attached to the post, I decided to share my solution.

When to use?

The solution required you to use the express router in order to enjoy it.. so: If you have you tried to use the accepted answer with no luck, just use copy-and-paste this function:

function bodyParse(req, ready, fail) 
{
    var length = req.header('Content-Length');

    if (!req.readable) return fail('failed to read request');

    if (!length) return fail('request must include a valid `Content-Length` header');

    if (length > 1000) return fail('this request is too big'); // you can replace 1000 with any other value as desired

    var body = ''; // for large payloads - please use an array buffer (see note below)

    req.on('data', function (data) 
    {
        body += data; 
    });

    req.on('end', function () 
    {
        ready(body);
    });
}

and call it like:

bodyParse(req, function success(body)
{

}, function error(message)
{

});

NOTE: For large payloads - please use an array buffer (more @ MDN)

How do I enable php to work with postgresql?

You need to isntall pdo_pgsql package

Can I set variables to undefined or pass undefined as an argument?

You cannot (should not?) define anything as undefined, as the variable would no longer be undefined – you just defined it to something.

You cannot (should not?) pass undefined to a function. If you want to pass an empty value, use null instead.

The statement if(!testvar) checks for boolean true/false values, this particular one tests whether testvar evaluates to false. By definition, null and undefined shouldn't be evaluated neither as true or false, but JavaScript evaluates null as false, and gives an error if you try to evaluate an undefined variable.

To properly test for undefined or null, use these:

if(typeof(testvar) === "undefined") { ... }

if(testvar === null) { ... }

Is it bad to have my virtualenv directory inside my git repository?

I think is that the best is to install the virtual environment in a path inside the repository folder, maybe is better inclusive to use a subdirectory dedicated to the environment (I have deleted accidentally my entire project when force installing a virtual environment in the repository root folder, good that I had the project saved in its latest version in Github).

Either the automated installer, or the documentation should indicate the virtualenv path as a relative path, this way you won't run into problems when sharing the project with other people. About the packages, the packages used should be saved by pip freeze -r requirements.txt.

ASP.NET MVC 5 - Identity. How to get current ApplicationUser

For MVC 5 just look inside the EnableTwoFactorAuthentication method of ManageController in WebApplication template scaffold, its being done there:

        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> EnableTwoFactorAuthentication()
        {
            await UserManager.SetTwoFactorEnabledAsync(User.Identity.GetUserId(), true);
            var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());
            if (user != null)
            {
                await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
            }
            return RedirectToAction("Index", "Manage");
        }

The answer is right there as suggested by Microsoft itself:

var user = await UserManager.FindByIdAsync(User.Identity.GetUserId());

It will have all the additional properties you defined in ApplicationUser class.

Setting up redirect in web.config file

  1. Open web.config in the directory where the old pages reside
  2. Then add code for the old location path and new destination as follows:

    <configuration>
      <location path="services.htm">
        <system.webServer>
          <httpRedirect enabled="true" destination="http://domain.com/services" httpResponseStatus="Permanent" />
        </system.webServer>
      </location>
      <location path="products.htm">
        <system.webServer>
          <httpRedirect enabled="true" destination="http://domain.com/products" httpResponseStatus="Permanent" />
        </system.webServer>
      </location>
    </configuration>
    

You may add as many location paths as necessary.

Several ports (8005, 8080, 8009) required by Tomcat Server at localhost are already in use

Don't need to close your eclipse IDE.Your Tomcat is probably running already. That's why you have got an error.

open tomcat directory >> bin >> from command terminal (in my case is tomcat9)

Enter command

./shutdown.sh

it will close your running tomcat

enter image description here

How do I iterate and modify Java Sets?

I don't like very much iterator's semantic, please consider this as an option. It's also safer as you publish less of your internal state

private Map<String, String> JSONtoMAP(String jsonString) {

    JSONObject json = new JSONObject(jsonString);
    Map<String, String> outMap = new HashMap<String, String>();

    for (String curKey : (Set<String>) json.keySet()) {
        outMap.put(curKey, json.getString(curKey));
    }

    return outMap;

}

Struct memory layout in C

In C, the compiler is allowed to dictate some alignment for every primitive type. Typically the alignment is the size of the type. But it's entirely implementation-specific.

Padding bytes are introduced so every object is properly aligned. Reordering is not allowed.

Possibly every remotely modern compiler implements #pragma pack which allows control over padding and leaves it to the programmer to comply with the ABI. (It is strictly nonstandard, though.)

From C99 §6.7.2.1:

12 Each non-bit-field member of a structure or union object is aligned in an implementation- defined manner appropriate to its type.

13 Within a structure object, the non-bit-field members and the units in which bit-fields reside have addresses that increase in the order in which they are declared. A pointer to a structure object, suitably converted, points to its initial member (or if that member is a bit-field, then to the unit in which it resides), and vice versa. There may be unnamed padding within a structure object, but not at its beginning.

Android device is not connected to USB for debugging (Android studio)

If you're using a USB Type-C cable, check if it has the charging and data transfer capability. Many USB Type-C cables are for charging only, and are not recognized by Android Studio.

How can I solve equations in Python?

Use a different tool. Something like Wolfram Alpha, Maple, R, Octave, Matlab or any other algebra software package.

As a beginner you should probably not attempt to solve such a non-trivial problem.

WHILE LOOP with IF STATEMENT MYSQL

I have discovered that you cannot have conditionals outside of the stored procedure in mysql. This is why the syntax error. As soon as I put the code that I needed between

   BEGIN
   SELECT MONTH(CURDATE()) INTO @curmonth;
   SELECT MONTHNAME(CURDATE()) INTO @curmonthname;
   SELECT DAY(LAST_DAY(CURDATE())) INTO @totaldays;
   SELECT FIRST_DAY(CURDATE()) INTO @checkweekday;
   SELECT DAY(@checkweekday) INTO @checkday;
   SET @daycount = 0;
   SET @workdays = 0;

     WHILE(@daycount < @totaldays) DO
       IF (WEEKDAY(@checkweekday) < 5) THEN
         SET @workdays = @workdays+1;
       END IF;
       SET @daycount = @daycount+1;
       SELECT ADDDATE(@checkweekday, INTERVAL 1 DAY) INTO @checkweekday;
     END WHILE;
   END

Just for others:

If you are not sure how to create a routine in phpmyadmin you can put this in the SQL query

    delimiter ;;
    drop procedure if exists test2;;
    create procedure test2()
    begin
    select ‘Hello World’;
    end
    ;;

Run the query. This will create a stored procedure or stored routine named test2. Now go to the routines tab and edit the stored procedure to be what you want. I also suggest reading http://net.tutsplus.com/tutorials/an-introduction-to-stored-procedures/ if you are beginning with stored procedures.

The first_day function you need is: How to get first day of every corresponding month in mysql?

Showing the Procedure is working Simply add the following line below END WHILE and above END

    SELECT @curmonth,@curmonthname,@totaldays,@daycount,@workdays,@checkweekday,@checkday;

Then use the following code in the SQL Query Window.

    call test2 /* or whatever you changed the name of the stored procedure to */

NOTE: If you use this please keep in mind that this code does not take in to account nationally observed holidays (or any holidays for that matter).

MS Excel showing the formula in a cell instead of the resulting value

I had the same problem and solved with below:

Range("A").Formula = Trim(CStr("the formula"))

Is log(n!) = T(n·log(n))?

Helping you further, where Mick Sharpe left you:

It's deriveration is quite simple: see http://en.wikipedia.org/wiki/Logarithm -> Group Theory

log(n!) = log(n * (n-1) * (n-2) * ... * 2 * 1) = log(n) + log(n-1) + ... + log(2) + log(1)

Think of n as infinitly big. What is infinite minus one? or minus two? etc.

log(inf) + log(inf) + log(inf) + ... = inf * log(inf)

And then think of inf as n.

Replace single quotes in SQL Server

select replace ( colname, '''', '') AS colname FROM .[dbo].[Db Name]

What are the most common font-sizes for H1-H6 tags

Headings are normally bold-faced; that has been turned off for this demonstration of size correspondence. MSIE and Opera interpret these sizes the same, but note that Gecko browsers and Chrome interpret Heading 6 as 11 pixels instead of 10 pixels/font size 1, and Heading 3 as 19 pixels instead of 18 pixels/font size 4 (though it's difficult to tell the difference even in a direct comparison and impossible in use). It seems Gecko also limits text to no smaller than 10 pixels.

Python - TypeError: 'int' object is not iterable

If the case is:

n=int(input())

Instead of -> for i in n: -> gives error- 'int' object is not iterable

Use -> for i in range(0,n): -> works fine..!

When do you use the "this" keyword?

I can't believe all of the people that say using it always is a "best practice" and such.

Use "this" when there is ambiguity, as in Corey's example or when you need to pass the object as a parameter, as in Ryan's example. There is no reason to use it otherwise because being able to resolve a variable based on the scope chain should be clear enough that qualifying variables with it should be unnecessary.

EDIT: The C# documentation on "this" indicates one more use, besides the two I mentioned, for the "this" keyword - for declaring indexers

EDIT: @Juan: Huh, I don't see any inconsistency in my statements - there are 3 instances when I would use the "this" keyword (as documented in the C# documentation), and those are times when you actually need it. Sticking "this" in front of variables in a constructor when there is no shadowing going on is simply a waste of keystrokes and a waste of my time when reading it, it provides no benefit.

In android how to set navigation drawer header image and name programmatically in class file?

EDIT : Works with design library upto 23.0.1 but doesn't work on 23.1.0

In main layout xml you will have NavigationView defined, in that use app:headerLayout to set the header view.

<android.support.design.widget.NavigationView
        android:id="@+id/navigation_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:headerLayout="@layout/nav_drawer_header"
        app:menu="@menu/navigation_drawer_menu" />

And the @layout/nav_drawer_header will be the place holder of the image and texts.

nav_drawer_header.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="170dp"
android:orientation="vertical">

<RelativeLayout
    android:id="@+id/headerRelativeLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scaleType="fitXY"
        android:src="@drawable/background" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="@dimen/action_bar_size"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:background="#40000000"
        android:gravity="center"
        android:orientation="horizontal"
        android:paddingBottom="5dp"
        android:paddingLeft="16dp"
        android:paddingRight="10dp"
        android:paddingTop="5dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginLeft="35dp"
            android:orientation="vertical"
            android:weightSum="2">


            <TextView
                android:id="@+id/navHeaderTitle"
                android:layout_width="wrap_content"
                android:layout_height="0dp"
                android:layout_weight="1"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:textColor="@android:color/white" />

            <TextView
                android:id="@+id/navHeaderSubTitle"
                android:layout_width="wrap_content"
                android:layout_height="0dp"
                android:layout_weight="1"
                android:textAppearance="?android:attr/textAppearanceSmall"
                android:textColor="@android:color/white" />

        </LinearLayout>

    </LinearLayout>
</RelativeLayout>
</LinearLayout>

And in your main class, you can take handle of Imageview and TextView as like normal other views.

TextView navHeaderTitle = (TextView) findViewById(R.id.navHeaderTitle);
navHeaderTitle.setText("Application Name");

TextView navHeaderSubTitle = (TextView) findViewById(R.id.navHeaderSubTitle);
navHeaderSubTitle.setText("Application Caption");

Hope this helps.

Python Remove last 3 characters of a string

I try to avoid regular expressions, but this appears to work:

string = re.sub("\s","",(string.lower()))[:-3]

How can I format decimal property to currency?

A decimal type can not contain formatting information. You can create another property, say FormattedProperty of a string type that does what you want.

Get controller and action name from within controller?

Try this code

add this override method to controller

protected override void OnActionExecuting(ActionExecutingContext actionExecutingContext)
{
   var actionName = actionExecutingContext.ActionDescriptor.ActionName;
   var controllerName = actionExecutingContext.ActionDescriptor.ControllerDescriptor.ControllerName;
   base.OnActionExecuting(actionExecutingContext);
}

Parse XML document in C#

Try this:

XmlDocument doc = new XmlDocument();
doc.Load(@"C:\Path\To\Xml\File.xml");

Or alternatively if you have the XML in a string use the LoadXml method.

Once you have it loaded, you can use SelectNodes and SelectSingleNode to query specific values, for example:

XmlNode node = doc.SelectSingleNode("//Company/Email/text()");
// node.Value contains "[email protected]"

Finally, note that your XML is invalid as it doesn't contain a single root node. It must be something like this:

<Data>
    <Employee>
        <Name>Test</Name>
        <ID>123</ID>
    </Employee>
    <Company>
        <Name>ABC</Name>
        <Email>[email protected]</Email>
    </Company>
</Data>

Javascript: open new page in same window

I'd take that a slightly different way if I were you. Change the text link when the page loads, not on the click. I'll give the example in jQuery, but it could easily be done in vanilla javascript (though, jQuery is nicer)

$(function() {
    $('a[href$="url="]')    // all links whose href ends in "url="
        .each(function(i, el) {
            this.href += escape(document.location.href);
        })
    ;
});

and write your HTML like this:

<a href="http://example.com/submit.php?url=">...</a>

the benefits of this are that people can see what they're clicking on (the href is already set), and it removes the javascript from your HTML.

All this said, it looks like you're using PHP... why not add it in server-side?

Java heap terminology: young, old and permanent generations?

The Java virtual machine is organized into three generations: a young generation, an old generation, and a permanent generation. Most objects are initially allocated in the young generation. The old generation contains objects that have survived some number of young generation collections, as well as some large objects that may be allocated directly in the old generation. The permanent generation holds objects that the JVM finds convenient to have the garbage collector manage, such as objects describing classes and methods, as well as the classes and methods themselves.

In the shell, what does " 2>&1 " mean?

File descriptor 1 is the standard output (stdout).
File descriptor 2 is the standard error (stderr).

Here is one way to remember this construct (although it is not entirely accurate): at first, 2>1 may look like a good way to redirect stderr to stdout. However, it will actually be interpreted as "redirect stderr to a file named 1". & indicates that what follows and precedes is a file descriptor and not a filename. So the construct becomes: 2>&1.

Consider >& as redirect merger operator.

How to programmatically open the Permission Screen for a specific app on Android Marshmallow?

It is not possible to programmatically open the permission screen. Instead, we can open the app settings screen.

Code

Intent i = new Intent(android.provider.Settings.ACTION_APPLICATION_DETAILS_SETTINGS, Uri.parse("package:" + BuildConfig.APPLICATION_ID));
startActivity(i);

Sample Output

enter image description here

Assigning strings to arrays of characters

When initializing an array, C allows you to fill it with values. So

char s[100] = "abcd";

is basically the same as

int s[3] = { 1, 2, 3 };

but it doesn't allow you to do the assignment since s is an array and not a free pointer. The meaning of

s = "abcd" 

is to assign the pointer value of abcd to s but you can't change s since then nothing will be pointing to the array.
This can and does work if s is a char* - a pointer that can point to anything.

If you want to copy the string simple use strcpy.

Prevent direct access to a php include file

The easiest way is to store your includes outside of the web directory. That way the server has access to them but no outside machine. The only down side is you need to be able to access this part of your server. The upside is it requires no set up, configuration, or additional code/server stress.

How to properly add include directories with CMake

This worked for me:

set(SOURCE main.cpp)
add_executable(${PROJECT_NAME} ${SOURCE})

# target_include_directories must be added AFTER add_executable
target_include_directories(${PROJECT_NAME} PUBLIC ${INTERNAL_INCLUDES})

How can I use console logging in Internet Explorer?

There is Firebug Lite which gives a lot of Firebug functionality in IE.

How do you use a variable in a regular expression?

this.replace( new RegExp( replaceThis, 'g' ), withThis );

if var == False

Since Python evaluates also the data type NoneType as False during the check, a more precise answer is:

var = False
if var is False:
    print('learnt stuff')

This prevents potentially unwanted behaviour such as:

var = []  # or None
if not var:
    print('learnt stuff') # is printed what may or may not be wanted

But if you want to check all cases where var will be evaluated to False, then doing it by using logical not keyword is the right thing to do.

What primitive data type is time_t?

You can use the function difftime. It returns the difference between two given time_t values, the output value is double (see difftime documentation).

time_t actual_time;
double actual_time_sec;
actual_time = time(0);
actual_time_sec = difftime(actual_time,0); 
printf("%g",actual_time_sec);

Discard all and get clean copy of latest revision?

To delete untracked on *nix without the purge extension you can use

hg pull
hg update -r MY_BRANCH -C
hg status -un|xargs rm

Which is using

update -r --rev REV revision

update -C --clean discard uncommitted changes (no backup)

status -u --unknown show only unknown (not tracked) files

status -n --no-status hide status prefix

TextView bold via xml file?

Example:

use: android:textStyle="bold"

 <TextView
    android:id="@+id/txtVelocidade"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/txtlatitude"
    android:layout_centerHorizontal="true"
    android:layout_marginBottom="34dp"
    android:textStyle="bold"
    android:text="Aguardando GPS"
    android:textAppearance="?android:attr/textAppearanceLarge" />

Remove gutter space for a specific div only

Okay If you want to change the gutter inside one row, but want those (first and last) inner divs to align with the grid surrounding the .no-gutter row, you could copy-paste-merge most answers into the following snippet:

.row.no-gutter [class*='col-']:first-child:not(:only-child) {
    padding-right: 0;
}
.row.no-gutter [class*='col-']:last-child:not(:only-child) {
    padding-left: 0;
}
.row.no-gutter [class*='col-']:not(:first-child):not(:last-child):not(:only-child) {
    padding-right: 0;
    padding-left: 0;
}

If you like to have a smaller gutter instead of completly none, just change the 0's to what you like... (eg: 5px to get 10px gutter).

jQuery - Fancybox: But I don't want scrollbars!

I know this sounds a bit weird but have any of you tried to set the margin of the form page body tag to 0.

The problem is actually pretty simple, the reason is that the body tag margin by default is set to 8px (depending on browser) and if you just set it to 0 then it fixes the scrollbar.

The js configuration I have is as follows and it works well without changing the css of fancybox.

$(".iframe").fancybox({
    'autoScale'         : false,
    'autoDimensions'    : false,
    'transitionIn'      : 'none',
    'transitionOut'     : 'none',
    'type'              : 'iframe'
});

How to declare string constants in JavaScript?

Use global namespace or global object like Constants.

var Constants = {};

And using defineObject write function which will add all properties to that object and assign value to it.

function createConstant (prop, value) {
    Object.defineProperty(Constants , prop, {
      value: value,
      writable: false
   });
};

How to update-alternatives to Python 3 without breaking apt?

Per Debian policy, python refers to Python 2 and python3 refers to Python 3. Don't try to change this system-wide or you are in for the sort of trouble you already discovered.

Virtual environments allow you to run an isolated Python installation with whatever version of Python and whatever libraries you need without messing with the system Python install.

With recent Python 3, venv is part of the standard library; with older versions, you might need to install python3-venv or a similar package.

$HOME~$ python --version
Python 2.7.11

$HOME~$ python3 -m venv myenv
... stuff happens ...

$HOME~$ . ./myenv/bin/activate

(myenv) $HOME~$ type python   # "type" is preferred over which; see POSIX
python is /home/you/myenv/bin/python

(myenv) $HOME~$ python --version
Python 3.5.1

A common practice is to have a separate environment for each project you work on, anyway; but if you want this to look like it's effectively system-wide for your own login, you could add the activation stanza to your .profile or similar.

How do I find out what License has been applied to my SQL Server installation?

When I run:

   exec sp_readerrorlog @p1 = 0
   ,@p2 = 1
   ,@p3 = N'licensing'

I get:

SQL Server detected 2 sockets with 21 cores per socket and 21 logical processors per socket, 42 total logical processors; using 20 logical processors based on SQL Server licensing. This is an informational message; no user action is required.

also, SELECT @@VERSION shows:

Microsoft SQL Server 2014 (SP1-GDR) (KB4019091) - 12.0.4237.0 (X64) Jul 5 2017 22:03:42 Copyright (c) Microsoft Corporation Enterprise Edition (64-bit) on Windows NT 6.3 (Build 9600: ) (Hypervisor)

This is a VM

What's the main difference between Java SE and Java EE?

Best description i've encounter so far is available on Oracle website.

Java SE's API provides the core functionality of the Java programming language. It defines everything from the basic types and objects of the Java programming language to high-level classes that are used for networking, security, database access, graphical user interface (GUI) development, and XML parsing.

The Java EE platform is built on top of the Java SE platform. The Java EE platform provides an API and runtime environment for developing and running large-scale, multi-tiered, scalable, reliable, and secure network applications.

If you consider developing application using for example Spring Framework you will use both API's and would have to learn key concept of JavaServer Pages and related technologies like for ex.: JSP, JPA, JDBC, Dependency Injection etc.

Export database schema into SQL file

enter image description here

In the picture you can see. In the set script options, choose the last option: Types of data to script you click at the right side and you choose what you want. This is the option you should choose to export a schema and data

Tesseract running error

You can call tesseract API function from C code:

#include <tesseract/baseapi.h>
#include <tesseract/ocrclass.h>; // ETEXT_DESC

using namespace tesseract;

class TessAPI : public TessBaseAPI {
    public:
    void PrintRects(int len);
};

...
TessAPI *api = new TessAPI();
int res = api->Init(NULL, "rus");
api->SetAccuracyVSpeed(AVS_MOST_ACCURATE);
api->SetImage(data, w0, h0, bpp, stride);
api->SetRectangle(x0,y0,w0,h0);

char *text;
ETEXT_DESC monitor;
api->RecognizeForChopTest(&monitor);
text = api->GetUTF8Text();
printf("text: %s\n", text);
printf("m.count: %s\n", monitor.count);
printf("m.progress: %s\n", monitor.progress);

api->RecognizeForChopTest(&monitor);
text = api->GetUTF8Text();
printf("text: %s\n", text);
...
api->End();

And build this code:

g++ -g -I. -I/usr/local/include -o _test test.cpp -ltesseract_api -lfreeimageplus

(i need FreeImage for picture loading)

How can I control Chromedriver open window size?

Python

Drivers

chrome = 57.0.2987.133
chromedriver = 2.27.440174

Code:

from selenium.webdriver.chrome.options import Options

chrome_options = Options()
chrome_options.add_argument("--window-size=1920,1080")
driver = Chrome(chrome_options=chrome_options)

Run text file as commands in Bash

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

./scriptname.sh

Its very simple to write a bash script

Mockup sh file:

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

What's the use of session.flush() in Hibernate

As rightly said in above answers, by calling flush() we force hibernate to execute the SQL commands on Database. But do understand that changes are not "committed" yet. So after doing flush and before doing commit, if you access DB directly (say from SQL prompt) and check the modified rows, you will NOT see the changes.

This is same as opening 2 SQL command sessions. And changes done in 1 session are not visible to others until committed.

assigning column names to a pandas series

You can also use the .to_frame() method.

If it is a Series, I assume 'Gene' is already the index, and will remain the index after converting it to a DataFrame. The name argument of .to_frame() will name the column.

x = x.to_frame('count')

If you want them both as columns, you can reset the index:

x = x.to_frame('count').reset_index()

How to check if a date is in a given range?

$start_date="17/02/2012";
$end_date="21/02/2012";
$date_from_user="19/02/2012";

function geraTimestamp($data)
{
    $partes = explode('/', $data); 
    return mktime(0, 0, 0, $partes[1], $partes[0], $partes[2]);
}


$startDatedt = geraTimestamp($start_date); 
$endDatedt = geraTimestamp($end_date);
$usrDatedt = geraTimestamp($date_from_user);

if (($usrDatedt >= $startDatedt) && ($usrDatedt <= $endDatedt))
{ 
    echo "Dentro";
}    
else
{
    echo "Fora";
}

Where does Vagrant download its .box files to?

To change the Path, you can set a new Path to an Enviroment-Variable named: VAGRANT_HOME

export VAGRANT_HOME=my/new/path/goes/here/

Thats maybe nice if you want to have those vagrant-Images on another HDD.

More Information here in the Documentations: http://docs.vagrantup.com/v2/other/environmental-variables.html

How to concatenate multiple column values into a single column in Panda dataframe

Just wanted to make a time comparison for both solutions (for 30K rows DF):

In [1]: df = DataFrame({'foo':['a','b','c'], 'bar':[1, 2, 3], 'new':['apple', 'banana', 'pear']})

In [2]: big = pd.concat([df] * 10**4, ignore_index=True)

In [3]: big.shape
Out[3]: (30000, 3)

In [4]: %timeit big.apply(lambda x:'%s_%s_%s' % (x['bar'],x['foo'],x['new']),axis=1)
1 loop, best of 3: 881 ms per loop

In [5]: %timeit big['bar'].astype(str)+'_'+big['foo']+'_'+big['new']
10 loops, best of 3: 44.2 ms per loop

a few more options:

In [6]: %timeit big.ix[:, :-1].astype(str).add('_').sum(axis=1).str.cat(big.new)
10 loops, best of 3: 72.2 ms per loop

In [11]: %timeit big.astype(str).add('_').sum(axis=1).str[:-1]
10 loops, best of 3: 82.3 ms per loop

How to mark a method as obsolete or deprecated?

Add an annotation to the method using the keyword Obsolete. Message argument is optional but a good idea to communicate why the item is now obsolete and/or what to use instead.
Example:

[System.Obsolete("use myMethodB instead")]
void myMethodA()

How to join a slice of strings into a single string?

The title of your question is:

How to join a slice of strings into a single string?

but in fact, reg is not a slice, but a length-three array. [...]string is just syntactic sugar for (in this case) [3]string.

To get an actual slice, you should write:

reg := []string {"a","b","c"}

(Try it out: https://play.golang.org/p/vqU5VtDilJ.)

Incidentally, if you ever really do need to join an array of strings into a single string, you can get a slice from the array by adding [:], like so:

fmt.Println(strings.Join(reg[:], ","))

(Try it out: https://play.golang.org/p/zy8KyC8OTuJ.)

How do I declare and initialize an array in Java?

One another full example with a movies class:

public class A {

    public static void main(String[] args) {

        class Movie {

            String movieName;
            String genre;
            String movieType;
            String year;
            String ageRating;
            String rating;

            public Movie(String [] str)
            {
                this.movieName = str[0];
                this.genre = str[1];
                this.movieType = str[2];
                this.year = str[3];
                this.ageRating = str[4];
                this.rating = str[5];
            }
        }

        String [] movieDetailArr = {"Inception", "Thriller", "MovieType", "2010", "13+", "10/10"};

        Movie mv = new Movie(movieDetailArr);

        System.out.println("Movie Name: "+ mv.movieName);
        System.out.println("Movie genre: "+ mv.genre);
        System.out.println("Movie type: "+ mv.movieType);
        System.out.println("Movie year: "+ mv.year);
        System.out.println("Movie age : "+ mv.ageRating);
        System.out.println("Movie  rating: "+ mv.rating);
    }
}

Sending JSON object to Web API

Change:

 data: JSON.stringify({ model: source })

To:

 data: {model: JSON.stringify(source)}

And in your controller you do this:

public void PartSourceAPI(string model)
{
       System.Web.Script.Serialization.JavaScriptSerializer js = new System.Web.Script.Serialization.JavaScriptSerializer();

   var result = js.Deserialize<PartSourceModel>(model);
}

If the url you use in jquery is /api/PartSourceAPI then the controller name must be api and the action(method) should be PartSourceAPI

org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/CollegeWebsite]]

You have a version conflict, please verify whether compiled version and JVM of Tomcat version are same. you can do it by examining tomcat startup .bat , looking for JAVA_HOME

Git clone without .git directory

since you only want the files, you don't need to treat it as a git repo.

rsync -rlp --exclude '.git' user@host:path/to/git/repo/ .

and this only works with local path and remote ssh/rsync path, it may not work if the remote server only provides git:// or https:// access.

Excluding directory when creating a .tar.gz file

The exclude option needs to include the = sign and " are not required.

--exclude=/home/user/public_html/tmp

What is the proper way to test if a parameter is empty in a batch file?

I got in in just under a month old (even though it was asked 8 years ago)... I hope s/he's moved beyond batch files by now. ;-) I used to do this all the time. I'm not sure what the ultimate goal is, though. If s/he's lazy like me, my go.bat works for stuff like that. (See below) But, 1, the command in the OP could be invalid if you are directly using the input as a command. i.e.,

"C:/Users/Me"

is an invalid command (or used to be if you were on a different drive). You need to break it in two parts.

C:
cd /Users/Me

And, 2, what does 'defined' or 'undefined' mean? GIGO. I use the default to catch errors. If the input doesn't get caught, it drops to help (or a default command). So, no input is not an error. You can try to cd to the input and catch the error if there is one. (Ok, using go "downloads (only one paren) is caught by DOS. (Harsh!))

cd "%1"
if %errorlevel% neq 0 goto :error

And, 3, quotes are needed only around the path, not the command. i.e.,

"cd C:\Users" 

was bad (or used to in the old days) unless you were on a different drive.

cd "\Users" 

is functional.

cd "\Users\Dr Whos infinite storage space"

works if you have spaces in your path.

@REM go.bat
@REM The @ sigh prevents echo on the current command
@REM The echo on/off turns on/off the echo command. Turn on for debugging
@REM You can't see this.
@echo off
if "help" == "%1" goto :help

if "c" == "%1" C:
if "c" == "%1" goto :done

if "d" == "%1" D:
if "d" == "%1" goto :done

if "home"=="%1" %homedrive%
if "home"=="%1" cd %homepath%
if "home"=="%1" if %errorlevel% neq 0 goto :error
if "home"=="%1" goto :done

if "docs" == "%1" goto :docs

@REM goto :help
echo Default command
cd %1
if %errorlevel% neq 0 goto :error
goto :done

:help
echo "Type go and a code for a location/directory
echo For example
echo go D
echo will change disks (D:)
echo go home
echo will change directories to the users home directory (%homepath%)
echo go pictures
echo will change directories to %homepath%\pictures
echo Notes
echo @ sigh prevents echo on the current command
echo The echo on/off turns on/off the echo command. Turn on for debugging
echo Paths (only) with folder names with spaces need to be inclosed in         quotes (not the ommand)
goto :done

:docs
echo executing "%homedrive%%homepath%\Documents"
%homedrive%
cd "%homepath%\Documents"\test error\
if %errorlevel% neq 0 goto :error
goto :done

:error
echo Error: Input (%1 %2 %3 %4 %5 %6 %7 %8 %9) or command is invalid
echo go help for help
goto :done

:done

Linux cmd to search for a class file among jars irrespective of jar path

Where are you jar files? Is there a pattern to find where they are?

1. Are they all in one directory?

For example, foo/a/a.jar and foo/b/b.jar are all under the folder foo/, in this case, you could use find with grep:

find foo/ -name "*.jar" | xargs grep Hello.class

Sure, at least you can search them under the root directory /, but it will be slow.

As @loganaayahee said, you could also use the command locate. locate search the files with an index, so it will be faster. But the command should be:

locate "*.jar" | xargs grep Hello.class

Since you want to search the content of the jar files.

2. Are the paths stored in an environment variable?

Typically, Java will store the paths to find jar files in an environment variable like CLASS_PATH, I don't know if this is what you want. But if your variable is just like this:CLASS_PATH=/lib:/usr/lib:/bin, which use a : to separate the paths, then you could use this commend to search the class:

for P in `echo $CLASS_PATH | sed 's/:/ /g'`; do grep Hello.calss $P/*.jar; done

List of all unique characters in a string?

char_seen = []
for char in string:
    if char not in char_seen:
        char_seen.append(char)
print(''.join(char_seen))

This will preserve the order in which alphabets are coming,

output will be

abcd

R - test if first occurrence of string1 is followed by string2

I think it's worth answering the generic question "R - test if string contains string" here.

For that, use the grep function.

# example:
> if(length(grep("ab","aacd"))>0) print("found") else print("Not found")
[1] "Not found"
> if(length(grep("ab","abcd"))>0) print("found") else print("Not found")
[1] "found"

How to shrink temp tablespace in oracle?

Temporary tablespaces are used for database sorting and joining operations and for storing global temporary tables. It may grow in size over a period of time and thus either we need to recreate temporary tablespace or shrink it to release the unused space.

Steps to shrink TEMP Tablespace

Iterate through <select> options

After try several code, and still not working, I go to official documentation of select2.js. here the link: https://select2.org/programmatic-control/add-select-clear-items

from that the way to clear selection select2 js is:

$('#mySelect2').val(null).trigger('change');

Get records with max value for each group of grouped SQL results

You can also try

SELECT * FROM mytable WHERE age IN (SELECT MAX(age) FROM mytable GROUP BY `Group`) ;

Unable to install gem - Failed to build gem native extension - cannot load such file -- mkmf (LoadError)

  1. Make sure ruby-dev is installed
  2. Make sure make is installed
  3. If you still get the error, look for suggested packages. If you are trying to install something like gem install pg you will also need to install the lib libpq-dev (sudo apt-get install libpq-dev).

How can you undo the last git add?

At date git prompts:

  1. use "git rm --cached <file>..." to unstage if files were not in the repo. It unstages the files keeping them there.
  2. use "git reset HEAD <file>..." to unstage if the files were in the repo, and you are adding them as modified. It keeps the files as they are, and unstages them.

At my knowledge you cannot undo the git add -- but you can unstage a list of files as mentioned above.

React Native TextInput that only accepts numeric characters

Using a RegExp to replace any non digit. Take care the next code will give you the first digit he found, so if user paste a paragraph with more than one number (xx.xx) the code will give you the first number. This will help if you want something like price, not a mobile phone.

Use this for your onTextChange handler:

onChanged (text) {
    this.setState({
        number: text.replace(/[^(((\d)+(\.)\d)|((\d)+))]/g,'_').split("_"))[0],
    });
}

Subtracting 2 lists in Python

If this is something you end up doing frequently, and with different operations, you should probably create a class to handle cases like this, or better use some library like Numpy.

Otherwise, look for list comprehensions used with the zip builtin function:

[a_i - b_i for a_i, b_i in zip(a, b)]

What is the largest TCP/IP network port number allowable for IPv4?

It depends on which range you're talking about, but the dynamic range goes up to 65535 or 2^16-1 (16 bits).

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

Enable Hibernate logging

We have a tomcat-8.5 + restlet-2.3.4 + hibernate-4.2.0 + log4j-1.2.14 java 8 app running on AlpineLinux in docker.

On adding these 2 lines to /usr/local/tomcat/webapps/ROOT/WEB-INF/classes/log4j.properties, I started seeing the HQL queries in the logs:

### log just the SQL
log4j.logger.org.hibernate.SQL=debug

### log JDBC bind parameters ###
log4j.logger.org.hibernate.type=debug

However, the JDBC bind parameters are not being logged.

Customizing the template within a Directive

angular.module('formComponents', [])
  .directive('formInput', function() {
    return {
        restrict: 'E',
        compile: function(element, attrs) {
            var type = attrs.type || 'text';
            var required = attrs.hasOwnProperty('required') ? "required='required'" : "";
            var htmlText = '<div class="control-group">' +
                '<label class="control-label" for="' + attrs.formId + '">' + attrs.label + '</label>' +
                    '<div class="controls">' +
                    '<input type="' + type + '" class="input-xlarge" id="' + attrs.formId + '" name="' + attrs.formId + '" ' + required + '>' +
                    '</div>' +
                '</div>';
            element.replaceWith(htmlText);
        }
    };
})

Array vs. Object efficiency in JavaScript

  1. Indexed fields (fields with numerical keys) are stored as a holy array inside the object. Therefore lookup time is O(1)

  2. Same for a lookup array it's O(1)

  3. Iterating through an array of objects and testing their ids against the provided one is a O(n) operation.

How to change shape color dynamically?

    LayerDrawable bgDrawable = (LayerDrawable) button.getBackground();
    final GradientDrawable shape = (GradientDrawable)
            bgDrawable.findDrawableByLayerId(R.id.round_button_shape);
    shape.setColor(Color.BLACK);

Load a Bootstrap popover content with AJAX. Is this possible?

I have updated the most popular answer. But in case my changes will not be approved I put here a separate answer.

Differences are:

  • LOADING text shown while content is loading. Very good for slow connection.
  • Removed flickering which occures when mouse leaves popover first time.

First we should add a data-poload attribute to the elements you would like to add a pop over to. The content of this attribute should be the url to be loaded (absolute or relative):

<a href="#" data-poload="/test.php">HOVER ME</a>

And in JavaScript, preferably in a $(document).ready();

 // On first hover event we will make popover and then AJAX content into it.
$('[data-poload]').hover(
    function (event) {
        var el = $(this);

        // disable this event after first binding 
        el.off(event);

        // add initial popovers with LOADING text
        el.popover({
            content: "loading…", // maybe some loading animation like <img src='loading.gif />
            html: true,
            placement: "auto",
            container: 'body',
            trigger: 'hover'
        });

        // show this LOADING popover
        el.popover('show');

        // requesting data from unsing url from data-poload attribute
        $.get(el.data('poload'), function (d) {
            // set new content to popover
            el.data('bs.popover').options.content = d;

            // reshow popover with new content
            el.popover('show');
        });
    },
    // Without this handler popover flashes on first mouseout
    function() { }
);

off('hover') prevents loading data more than once and popover() binds a new hover event. If you want the data to be refreshed at every hover event, you should remove the off.

Please see the working JSFiddle of the example.

Converting HTML element to string in JavaScript / JQuery

Try a slight different approach:

//set string and append it as object
var myHtmlString = '<iframe id="myFrame" width="854" height="480" src="http://www.youtube.com/embed/gYKqrjq5IjU?feature=oembed" frameborder="0" allowfullscreen></iframe>';
$('body').append(myHtmlString);

//as you noticed you can't just get it back
var myHtmlStringBack = $('#myFrame').html(); 
alert(myHtmlStringBack); // will be empty (a bug in jquery?) but...

//since an id was added to your iframe so you can retrieve its attributes back...
var width = $('#myFrame').attr('width');
var height = $('#myFrame').attr('height');
var src = $('#myFrame').attr('src');
var myReconstructedString = '<iframe id="myFrame" width="'+ width +'" height="'+ height +'" src="'+ src+'" frameborder="0" allowfullscreen></iframe>';
alert(myReconstructedString);

CSS: Change image src on img:hover

Concerning semantics, I do not like any solution given so far. Therefore, I personally use the following solution:

_x000D_
_x000D_
.img-wrapper {_x000D_
  display: inline-block;_x000D_
  background-image: url(https://www.w3schools.com/w3images/fjords.jpg);_x000D_
}_x000D_
_x000D_
.img-wrapper > img {_x000D_
  vertical-align: top;_x000D_
}_x000D_
_x000D_
.img-wrapper > img:hover {_x000D_
  opacity: 0;_x000D_
}
_x000D_
<div class="img-wrapper">_x000D_
  <img src="https://www.w3schools.com/w3css/img_lights.jpg" alt="image" />_x000D_
</div>
_x000D_
_x000D_
_x000D_

This is a CSS only solution with good browser compatibility. It makes use of an image wrapper that has a background which is initially hidden by the image itself. On hover, the image is hidden through the opacity, hence the background image becomes visible. This way, one does not have an empty wrapper but a real image in the markup code.

Could not find method android() for arguments

guys. I had the same problem before when I'm trying import a .aar package into my project, and unfortunately before make the .aar package as a module-dependence of my project, I had two modules (one about ROS-ANDROID-CV-BRIDGE, one is OPENCV-FOR-ANDROID) already. So, I got this error as you guys meet:

Error:Could not find method android() for arguments [org.ros.gradle_plugins.RosAndroidPlugin$_apply_closure2_closure4@7e550e0e] on project ‘:xxx’ of type org.gradle.api.Project.

So, it's the painful gradle-structure caused this problem when you have several modules in your project, and worse, they're imported in different way or have different types (.jar/.aar packages or just a project of Java library). And it's really a headache matter to make the configuration like compile-version, library dependencies etc. in each subproject compatible with the main-project.

I solved my problem just follow this steps:

? Copy .aar package in app/libs.

? Add this in app/build.gradle file:

repositories {
    flatDir {
        dirs 'libs' //this way we can find the .aar file in libs folder
    }
}

? Add this in your add build.gradle file of the module which you want to apply the .aar dependence (in my situation, just add this in my app/build.gradle file):

dependencies {
    compile(name:'package_name', ext:'aar')
}

So, if it's possible, just try export your module-dependence as a .aar package, and then follow this way import it to your main-project. Anyway, I hope this can be a good suggestion and would solve your problem if you have the same situation with me.

Equivalent VB keyword for 'break'

In case you're inside a Sub of Function and you want to exit it, you can use :

Exit Sub

or

Exit Function 

How to Convert Excel Numeric Cell Value into Words

There is no built-in formula in excel, you have to add a vb script and permanently save it with your MS. Excel's installation as Add-In.

  1. press Alt+F11
  2. MENU: (Tool Strip) Insert Module
  3. copy and paste the below code


Option Explicit

Public Numbers As Variant, Tens As Variant

Sub SetNums()
    Numbers = Array("", "One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine", "Ten", "Eleven", "Twelve", "Thirteen", "Fourteen", "Fifteen", "Sixteen", "Seventeen", "Eighteen", "Nineteen")
    Tens = Array("", "", "Twenty", "Thirty", "Forty", "Fifty", "Sixty", "Seventy", "Eighty", "Ninety")
End Sub

Function WordNum(MyNumber As Double) As String
    Dim DecimalPosition As Integer, ValNo As Variant, StrNo As String
    Dim NumStr As String, n As Integer, Temp1 As String, Temp2 As String
    ' This macro was written by Chris Mead - www.MeadInKent.co.uk
    If Abs(MyNumber) > 999999999 Then
        WordNum = "Value too large"
        Exit Function
    End If
    SetNums
    ' String representation of amount (excl decimals)
    NumStr = Right("000000000" & Trim(Str(Int(Abs(MyNumber)))), 9)
    ValNo = Array(0, Val(Mid(NumStr, 1, 3)), Val(Mid(NumStr, 4, 3)), Val(Mid(NumStr, 7, 3)))
    For n = 3 To 1 Step -1    'analyse the absolute number as 3 sets of 3 digits
        StrNo = Format(ValNo(n), "000")
        If ValNo(n) > 0 Then
            Temp1 = GetTens(Val(Right(StrNo, 2)))
            If Left(StrNo, 1) <> "0" Then
                Temp2 = Numbers(Val(Left(StrNo, 1))) & " hundred"
                If Temp1 <> "" Then Temp2 = Temp2 & " and "
            Else
                Temp2 = ""
            End If
            If n = 3 Then
                If Temp2 = "" And ValNo(1) + ValNo(2) > 0 Then Temp2 = "and "
                WordNum = Trim(Temp2 & Temp1)
            End If
            If n = 2 Then WordNum = Trim(Temp2 & Temp1 & " thousand " & WordNum)
            If n = 1 Then WordNum = Trim(Temp2 & Temp1 & " million " & WordNum)
        End If
    Next n
    NumStr = Trim(Str(Abs(MyNumber)))
    ' Values after the decimal place
    DecimalPosition = InStr(NumStr, ".")
    Numbers(0) = "Zero"
    If DecimalPosition > 0 And DecimalPosition < Len(NumStr) Then
        Temp1 = " point"
        For n = DecimalPosition + 1 To Len(NumStr)
            Temp1 = Temp1 & " " & Numbers(Val(Mid(NumStr, n, 1)))
        Next n
        WordNum = WordNum & Temp1
    End If
    If Len(WordNum) = 0 Or Left(WordNum, 2) = " p" Then
        WordNum = "Zero" & WordNum
    End If
End Function

Function GetTens(TensNum As Integer) As String
' Converts a number from 0 to 99 into text.
    If TensNum <= 19 Then
        GetTens = Numbers(TensNum)
    Else
        Dim MyNo As String
        MyNo = Format(TensNum, "00")
        GetTens = Tens(Val(Left(MyNo, 1))) & " " & Numbers(Val(Right(MyNo, 1)))
    End If
End Function

After this, From File Menu select Save Book ,from next menu select "Excel 97-2003 Add-In (*.xla)

It will save as Excel Add-In. that will be available till the Ms.Office Installation to that machine.

Now Open any Excel File in any Cell type =WordNum(<your numeric value or cell reference>)

you will see a Words equivalent of the numeric value.

This Snippet of code is taken from: http://en.kioskea.net/forum/affich-267274-how-to-convert-number-into-text-in-excel

How to create a HashMap with two keys (Key-Pair, Value)?

You could create your key object something like this:

public class MapKey {

public  Object key1;
public Object key2;

public Object getKey1() {
    return key1;
}

public void setKey1(Object key1) {
    this.key1 = key1;
}

public Object getKey2() {
    return key2;
}

public void setKey2(Object key2) {
    this.key2 = key2;
}

public boolean equals(Object keyObject){

    if(keyObject==null)
        return false;

    if (keyObject.getClass()!= MapKey.class)
        return false;

    MapKey key = (MapKey)keyObject;

    if(key.key1!=null && this.key1==null)
        return false;

    if(key.key2 !=null && this.key2==null)
        return false;

    if(this.key1==null && key.key1 !=null)
        return false;

    if(this.key2==null && key.key2 !=null)
        return false;

    if(this.key1==null && key.key1==null && this.key2 !=null && key.key2 !=null)
        return this.key2.equals(key.key2);

    if(this.key2==null && key.key2==null && this.key1 !=null && key.key1 !=null)
        return this.key1.equals(key.key1);

    return (this.key1.equals(key.key1) && this.key2.equals(key2));
}

public int hashCode(){
    int key1HashCode=key1.hashCode();
    int key2HashCode=key2.hashCode();
    return key1HashCode >> 3 + key2HashCode << 5;
}

}

The advantage of this is: It will always make sure you are covering all the scenario's of Equals as well.

NOTE: Your key1 and key2 should be immutable. Only then will you be able to construct a stable key Object.

FFmpeg: How to split video efficiently?

Here's a useful script, it helps you split automatically: A script for splitting videos using ffmpeg

#!/bin/bash
 
# Written by Alexis Bezverkhyy <[email protected]> in 2011
# This is free and unencumbered software released into the public domain.
# For more information, please refer to <http://unlicense.org/>
 
function usage {
        echo "Usage : ffsplit.sh input.file chunk-duration [output-filename-format]"
        echo -e "\t - input file may be any kind of file reconginzed by ffmpeg"
        echo -e "\t - chunk duration must be in seconds"
        echo -e "\t - output filename format must be printf-like, for example myvideo-part-%04d.avi"
        echo -e "\t - if no output filename format is given, it will be computed\
 automatically from input filename"
}
 
IN_FILE="$1"
OUT_FILE_FORMAT="$3"
typeset -i CHUNK_LEN
CHUNK_LEN="$2"
 
DURATION_HMS=$(ffmpeg -i "$IN_FILE" 2>&1 | grep Duration | cut -f 4 -d ' ')
DURATION_H=$(echo "$DURATION_HMS" | cut -d ':' -f 1)
DURATION_M=$(echo "$DURATION_HMS" | cut -d ':' -f 2)
DURATION_S=$(echo "$DURATION_HMS" | cut -d ':' -f 3 | cut -d '.' -f 1)
let "DURATION = ( DURATION_H * 60 + DURATION_M ) * 60 + DURATION_S"
 
if [ "$DURATION" = '0' ] ; then
        echo "Invalid input video"
        usage
        exit 1
fi
 
if [ "$CHUNK_LEN" = "0" ] ; then
        echo "Invalid chunk size"
        usage
        exit 2
fi
 
if [ -z "$OUT_FILE_FORMAT" ] ; then
        FILE_EXT=$(echo "$IN_FILE" | sed 's/^.*\.\([a-zA-Z0-9]\+\)$/\1/')
        FILE_NAME=$(echo "$IN_FILE" | sed 's/^\(.*\)\.[a-zA-Z0-9]\+$/\1/')
        OUT_FILE_FORMAT="${FILE_NAME}-%03d.${FILE_EXT}"
        echo "Using default output file format : $OUT_FILE_FORMAT"
fi
 
N='1'
OFFSET='0'
let 'N_FILES = DURATION / CHUNK_LEN + 1'
 
while [ "$OFFSET" -lt "$DURATION" ] ; do
        OUT_FILE=$(printf "$OUT_FILE_FORMAT" "$N")
        echo "writing $OUT_FILE ($N/$N_FILES)..."
        ffmpeg -i "$IN_FILE" -vcodec copy -acodec copy -ss "$OFFSET" -t "$CHUNK_LEN" "$OUT_FILE"
        let "N = N + 1"
        let "OFFSET = OFFSET + CHUNK_LEN"
done

rails + MySQL on OSX: Library not loaded: libmysqlclient.18.dylib

I was working with the rails g model command and I got this error:

Library not loaded: libmysqlclient.18.dylib

I have tried this and it functioned for me. I was using Mavericks 10.9.5

sudo ln -s /usr/local/mysql-5.6.19-osx10.7-x86_64/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib

Thanks!

Now I'm using Yosemite 10.10.5 and I got the same error, so I just ran this command on the terminal an it was successfully fixed up.

$ sudo ln -s /usr/local/mysql-5.6.26-osx10.8-x86_64/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib

also you can try:

sudo ln -s /usr/local/mysql/lib/libmysqlclient.18.dylib /usr/lib/libmysqlclient.18.dylib

Both of them work fine for me. Hope it could be useful!

How to file split at a line number

file_name=test.log

# set first K lines:
K=1000

# line count (N): 
N=$(wc -l < $file_name)

# length of the bottom file:
L=$(( $N - $K ))

# create the top of file: 
head -n $K $file_name > top_$file_name

# create bottom of file: 
tail -n $L $file_name > bottom_$file_name

Also, on second thought, split will work in your case, since the first split is larger than the second. Split puts the balance of the input into the last split, so

split -l 300000 file_name

will output xaa with 300k lines and xab with 100k lines, for an input with 400k lines.

Is there a decent wait function in C++?

Lots of people have suggested POSIX sleep, Windows Sleep, Windows system("pause"), C++ cin.get()… there's even a DOS getch() in there, from roughly the late 1920s.

Please don't do any of these.

None of these solutions would pass code review in my team. That means, if you submitted this code for inclusion in our products, your commit would be blocked and you would be told to go and find another solution. (One might argue that things aren't so serious when you're just a hobbyist playing around, but I propose that developing good habits in your pet projects is what will make you a valued professional in a business organisation, and keep you hired.)

Keeping the console window open so you can read the output of your program is not the responsibility of your program! When you add a wait/sleep/block to the end of your program, you are violating the single responsibility principle, creating a massive abstraction leak, and obliterating the re-usability/chainability of your program. It no longer takes input and gives output — it blocks for transient usage reasons. This is very non-good.

Instead, you should configure your environment to keep the prompt open after your program has finished its work. Your Batch script wrapper is a good approach! I can see how it would be annoying to have to keep manually updating, and you can't invoke it from your IDE. You could make the script take the path to the program to execute as a parameter, and configure your IDE to invoke it instead of your program directly.

An interim, quick-start approach would be to change your IDE's run command from cmd.exe <myprogram> or <myprogram>, to cmd.exe /K <myprogram>. The /K switch to cmd.exe makes the prompt stay open after the program at the given path has terminated. This is going to be slightly more annoying than your Batch script solution, because now you have to type exit or click on the red 'X' when you're done reading your program's output, rather than just smacking the space bar.


I assume usage of an IDE, because otherwise you're already invoking from a command prompt, and this would not be a problem in the first place. Furthermore, I assume the use of Windows (based on detail given in the question), but this answer applies to any platform… which is, incidentally, half the point.

new Runnable() but no new thread?

You can create a thread just like this:

 Thread thread = new Thread(new Runnable() {
                    public void run() {

                       }
                    });
                thread.start();

Also, you can use Runnable, Asyntask, Timer, TimerTaks and AlarmManager to excecute Threads.

How to play videos in android from assets folder or raw folder?

I found it :

Uri raw_uri = Uri.parse(<package_name>/+R.raw.<video_file_name>);

Personnaly Android found the resource, but can't play it for now. My file is a .m4v

How can I make a div stick to the top of the screen once it's been scrolled to?

And here's how without jquery (UPDATE: see other answers where you can now do this with CSS only)

_x000D_
_x000D_
var startProductBarPos=-1;_x000D_
window.onscroll=function(){_x000D_
  var bar = document.getElementById('nav');_x000D_
  if(startProductBarPos<0)startProductBarPos=findPosY(bar);_x000D_
_x000D_
  if(pageYOffset>startProductBarPos){_x000D_
    bar.style.position='fixed';_x000D_
    bar.style.top=0;_x000D_
  }else{_x000D_
    bar.style.position='relative';_x000D_
  }_x000D_
_x000D_
};_x000D_
_x000D_
function findPosY(obj) {_x000D_
  var curtop = 0;_x000D_
  if (typeof (obj.offsetParent) != 'undefined' && obj.offsetParent) {_x000D_
    while (obj.offsetParent) {_x000D_
      curtop += obj.offsetTop;_x000D_
      obj = obj.offsetParent;_x000D_
    }_x000D_
    curtop += obj.offsetTop;_x000D_
  }_x000D_
  else if (obj.y)_x000D_
    curtop += obj.y;_x000D_
  return curtop;_x000D_
}
_x000D_
* {margin:0;padding:0;}_x000D_
.nav {_x000D_
  border: 1px red dashed;_x000D_
  background: #00ffff;_x000D_
  text-align:center;_x000D_
  padding: 21px 0;_x000D_
_x000D_
  margin: 0 auto;_x000D_
  z-index:10; _x000D_
  width:100%;_x000D_
  left:0;_x000D_
  right:0;_x000D_
}_x000D_
_x000D_
.header {_x000D_
  text-align:center;_x000D_
  padding: 65px 0;_x000D_
  border: 1px red dashed;_x000D_
}_x000D_
_x000D_
.content {_x000D_
  padding: 500px 0;_x000D_
  text-align:center;_x000D_
  border: 1px red dashed;_x000D_
}_x000D_
.footer {_x000D_
  padding: 100px 0;_x000D_
  text-align:center;_x000D_
  background: #777;_x000D_
  border: 1px red dashed;_x000D_
}
_x000D_
<header class="header">This is a Header</header>_x000D_
<div id="nav" class="nav">Main Navigation</div>_x000D_
<div class="content">Hello World!</div>_x000D_
<footer class="footer">This is a Footer</footer>
_x000D_
_x000D_
_x000D_

How to disable copy/paste from/to EditText

If you want to disable ActionMode for copy/pasting, you need to override 2 callbacks. This works for both TextView and EditText (or TextInputEditText)

import android.view.ActionMode

fun TextView.disableCopyPaste() {
  isLongClickable = false
  setTextIsSelectable(false)
  customSelectionActionModeCallback = object : ActionMode.Callback {
    override fun onCreateActionMode(mode: ActionMode?, menu: Menu) = false
    override fun onPrepareActionMode(mode: ActionMode?, menu: Menu) = false
    override fun onActionItemClicked(mode: ActionMode?, item: MenuItem) = false
    override fun onDestroyActionMode(mode: ActionMode?) {}
  }
  //disable action mode when edittext gain focus at first
  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    customInsertionActionModeCallback = object : ActionMode.Callback {
      override fun onCreateActionMode(mode: ActionMode?, menu: Menu) = false
      override fun onPrepareActionMode(mode: ActionMode?, menu: Menu) = false
      override fun onActionItemClicked(mode: ActionMode?, item: MenuItem) = false
      override fun onDestroyActionMode(mode: ActionMode?) {}
    }
  }
}

This extension is based off above @Alexandr solution and worked fine for me.

Checking if output of a command contains a certain string in a shell script

Test the return value of grep:

./somecommand | grep 'string' &> /dev/null
if [ $? == 0 ]; then
   echo "matched"
fi

which is done idiomatically like so:

if ./somecommand | grep -q 'string'; then
   echo "matched"
fi

and also:

./somecommand | grep -q 'string' && echo 'matched'

Does .NET provide an easy way convert bytes to KB, MB, GB, etc.?

Since everyone else is posting their methods, I figured I'd post the extension method I usually use for this:

EDIT: added int/long variants...and fixed a copypasta typo...

public static class Ext
{
    private const long OneKb = 1024;
    private const long OneMb = OneKb * 1024;
    private const long OneGb = OneMb * 1024;
    private const long OneTb = OneGb * 1024;

    public static string ToPrettySize(this int value, int decimalPlaces = 0)
    {
        return ((long)value).ToPrettySize(decimalPlaces);
    }

    public static string ToPrettySize(this long value, int decimalPlaces = 0)
    {
        var asTb = Math.Round((double)value / OneTb, decimalPlaces);
        var asGb = Math.Round((double)value / OneGb, decimalPlaces);
        var asMb = Math.Round((double)value / OneMb, decimalPlaces);
        var asKb = Math.Round((double)value / OneKb, decimalPlaces);
        string chosenValue = asTb > 1 ? string.Format("{0}Tb",asTb)
            : asGb > 1 ? string.Format("{0}Gb",asGb)
            : asMb > 1 ? string.Format("{0}Mb",asMb)
            : asKb > 1 ? string.Format("{0}Kb",asKb)
            : string.Format("{0}B", Math.Round((double)value, decimalPlaces));
        return chosenValue;
    }
}

TypeError [ERR_INVALID_ARG_TYPE]: The "path" argument must be of type string. Received type undefined raised when starting react app

Just need to remove and re-install react-scripts

To Remove yarn remove react-scripts To Add yarn add react-scripts

and then rm -rf node_modules/ yarn.lock && yarn

  • Remember don't update the react-scripts version maually

HTML5 Canvas and Anti-aliasing

Here's a workaround that requires you to draw lines pixel by pixel, but will prevent anti aliasing.

// some helper functions
// finds the distance between points
function DBP(x1,y1,x2,y2) {
    return Math.sqrt((x2-x1)*(x2-x1)+(y2-y1)*(y2-y1));
}
// finds the angle of (x,y) on a plane from the origin
function getAngle(x,y) { return Math.atan(y/(x==0?0.01:x))+(x<0?Math.PI:0); }
// the function
function drawLineNoAliasing(ctx, sx, sy, tx, ty) {
    var dist = DBP(sx,sy,tx,ty); // length of line
    var ang = getAngle(tx-sx,ty-sy); // angle of line
    for(var i=0;i<dist;i++) {
        // for each point along the line
        ctx.fillRect(Math.round(sx + Math.cos(ang)*i), // round for perfect pixels
                     Math.round(sy + Math.sin(ang)*i), // thus no aliasing
                     1,1); // fill in one pixel, 1x1
    }
}

Basically, you find the length of the line, and step by step traverse that line, rounding each position, and filling in a pixel.

Call it with

var context = cv.getContext("2d");
drawLineNoAliasing(context, 20,30,20,50); // line from (20,30) to (20,50)

DLL References in Visual C++

You need to do a couple of things to use the library:

  1. Make sure that you have both the *.lib and the *.dll from the library you want to use. If you don't have the *.lib, skip #2

  2. Put a reference to the *.lib in the project. Right click the project name in the Solution Explorer and then select Configuration Properties->Linker->Input and put the name of the lib in the Additional Dependencies property.

  3. You have to make sure that VS can find the lib you just added so you have to go to the Tools menu and select Options... Then under Projects and Solutions select VC++ Directories,edit Library Directory option. From within here you can set the directory that contains your new lib by selecting the 'Library Files' in the 'Show Directories For:' drop down box. Just add the path to your lib file in the list of directories. If you dont have a lib you can omit this, but while your here you will also need to set the directory which contains your header files as well under the 'Include Files'. Do it the same way you added the lib.

After doing this you should be good to go and can use your library. If you dont have a lib file you can still use the dll by importing it yourself. During your applications startup you can explicitly load the dll by calling LoadLibrary (see: http://msdn.microsoft.com/en-us/library/ms684175(VS.85).aspx for more info)

Cheers!

EDIT

Remember to use #include < Foo.h > as opposed to #include "foo.h". The former searches the include path. The latter uses the local project files.

Compare dates in MySQL

That is SQL Server syntax for converting a date to a string. In MySQL you can use the DATE function to extract the date from a datetime:

SELECT *
FROM players
WHERE DATE(us_reg_date) BETWEEN '2000-07-05' AND '2011-11-10'

But if you want to take advantage of an index on the column us_reg_date you might want to try this instead:

SELECT *
FROM players
WHERE us_reg_date >= '2000-07-05'
  AND us_reg_date < '2011-11-10' + interval 1 day

Is there a way to define a min and max value for EditText in Android?

Of what i've seen of @Patrik's solution and @Zac's addition, the code provided still has a big problem :

If min==3 then it's impossible to type any number starting with 1 or 2 (ex: 15, 23)
If min>=10 then it's impossible to type anything as every number will have to start with 1,2,3...

In my understanding we cannot achieve the min-max limitation of an EditText's value with simple use of the class InputFilterMinMax, at least not for the min Value, because when user is typing a positive number, the value goes growing and we can easily perform an on-the-fly test to check if it's reached the limit or went outside the range and block entries that do not comply. Testing the min value is a different story as we cannot be sure if the user has finished typing or not and therefore cannot decide if we should block or not.

It's not exactly what OP requested but for validation purposes i've combined in my solution an InputFilter to test max values, with an OnFocusChangeListener to re-test for min value when the EditText loses the focus assuming the user's finished typing and it's something like this :

package test;


import android.text.InputFilter;

import android.text.Spanned;

public class InputFilterMax implements InputFilter {

private int max;

public InputFilterMax(int max) {
    this.max = max;
}

public InputFilterMax(String max) {
    this.max = Integer.parseInt(max);
}

@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {   
    try {
        String replacement = source.subSequence(start, end).toString(); 

        String newVal = dest.toString().substring(0, dstart) + replacement +dest.toString().substring(dend, dest.toString().length());

        int input = Integer.parseInt(newVal);

        if (input<=max)
            return null;
    } catch (NumberFormatException nfe) { }   
//Maybe notify user that the value is not good      
return "";
}
}

And OnFocusChangeListenerMin

package test;

import android.text.TextUtils;
import android.view.View;
import android.view.View.OnFocusChangeListener;

public class OnFocusChangeListenerMin implements OnFocusChangeListener {

private int min;

public OnFocusChangeListenerMin(int min) {
    this.min = min;
}

public OnFocusChangeListenerMin(String min) {
    this.min = Integer.parseInt(min);
}


@Override
public void onFocusChange(View v, boolean hasFocus) {
    if(!hasFocus) {
        String val = ((EditText)v).getText().toString();
        if(!TextUtils.isEmpty(val)){
            if(Integer.valueOf(val)<min){
                //Notify user that the value is not good
            }

        }
    }
}
}

Then in Activity set the InputFilterMax and theOnFocusChangeListenerMin to EditText note : You can 2 both min and max in onFocusChangeListener.

mQteEditText.setOnFocusChangeListener( new OnFocusChangeListenerMin('20');
mQteEditText.setFilters(new InputFilter[]{new InputFilterMax(getActivity(),'50')});

UIImageView - How to get the file name of the image assigned?

Or you can use the restoration identifier, like this:

let myImageView = UIImageView()
myImageView.image = UIImage(named: "anyImage")
myImageView.restorationIdentifier = "anyImage" // Same name as image's name!

// Later, in UI Tests:
print(myImageView.restorationIdentifier!) // Prints "anyImage"

Basically in this solution you're using the restoration identifier to hold the image's name, so you can use it later anywhere. If you update the image, you must also update the restoration identifier, like this:

myImageView.restorationIdentifier = "newImageName"

I hope that helps you, good luck!

'Malformed UTF-8 characters, possibly incorrectly encoded' in Laravel

I got this error and i fixed the issue with iconv function like following:

iconv('latin5', 'utf-8', $data['index']);

retrieve data from db and display it in table in php .. see this code whats wrong with it?

<html>
    <head>
        <meta charset="UTF-8">
        <title>LoginDB</title>
    </head>
    <body>

        <?php
        $con=  mysqli_connect("localhost", "root", "", "detail");
<!-- detail is the database in MySqli Database -->
        if(!$con)
       {
           die('not connected');
       }
            $con=  mysqli_query($con, "select * from signup");
<!-- signup is the table in the detail_Database -->
       ?>
        <div>
            <td>Login Page Database</td>
         <table border="1">
            <th> First Name</th>
                    <th>Last Name</th>
                    <th>UserName</th>
                     <th>Password</th>
                    <th>Gender</th>
                    <th>D.O.B.</th>
                    <th>Phone Number</th>
                    <th>Address</th>

            </tr>

        <?php

             while($row=  mysqli_fetch_array($con))
<!-- Fetch each row from signup Table  -->
             {
                 ?>
            <tr>
                <td><?php echo $row['FirstName']; ?></td>
                <td><?php echo $row['LastName']; ?></td>
                <td><?php echo $row['Username']; ?></td>
                <td><?php echo $row['Password'] ;?></td>
                <td><?php echo $row['Gender'] ;?></td>
                <td><?php echo $row['DOB'] ;?></td>
                <td><?php echo $row['PhoneNumber'] ;?></td>
                <td><?php echo $row['Address'] ;?></td>
            </tr>
        <?php
             }
             ?>
             </table>
            </div>
    </body>
</html>

How to make a background 20% transparent on Android

Now Android Studio 3.3 and later version provide an inbuilt feature to change an Alpha value of the color,

Just click on a color in Android studio editor and provide Alpha value in percentage.

For more information see below image

enter image description here

How to sort an ArrayList?

In JAVA 8 its much easy now.

List<String> alphaNumbers = Arrays.asList("one", "two", "three", "four");
List<String> alphaNumbersUpperCase = alphaNumbers.stream()
    .map(String::toUpperCase)
    .sorted()
    .collect(Collectors.toList());
System.out.println(alphaNumbersUpperCase); // [FOUR, ONE, THREE, TWO]

-- For reverse use this

.sorted(Comparator.reverseOrder())

Retrieving a List from a java.util.stream.Stream in Java 8

Updated:

Another approach is to use Collectors.toList:

targetLongList = 
    sourceLongList.stream().
    filter(l -> l > 100).
    collect(Collectors.toList());

Previous Solution:

Another approach is to use Collectors.toCollection:

targetLongList = 
    sourceLongList.stream().
    filter(l -> l > 100).
    collect(Collectors.toCollection(ArrayList::new));

registerForRemoteNotificationTypes: is not supported in iOS 8.0 and later

iOS 8 has changed notification registration in a non-backwards compatible way. While you need to support iOS 7 and 8 (and while apps built with the 8 SDK aren't accepted), you can check for the selectors you need and conditionally call them correctly for the running version.

Here's a category on UIApplication that will hide this logic behind a clean interface for you that will work in both Xcode 5 and Xcode 6.

Header:

//Call these from your application code for both iOS 7 and 8
//put this in the public header
@interface UIApplication (RemoteNotifications)

- (BOOL)pushNotificationsEnabled;
- (void)registerForPushNotifications;

@end

Implementation:

//these declarations are to quiet the compiler when using 7.x SDK
//put this interface in the implementation file of this category, so they are
//not visible to any other code.
@interface NSObject (IOS8)

- (BOOL)isRegisteredForRemoteNotifications;
- (void)registerForRemoteNotifications;

+ (id)settingsForTypes:(NSUInteger)types categories:(NSSet*)categories;
- (void)registerUserNotificationSettings:(id)settings;

@end

@implementation UIApplication (RemoteNotifications)

- (BOOL)pushNotificationsEnabled
{
    if ([self respondsToSelector:@selector(isRegisteredForRemoteNotifications)])
    {
        return [self isRegisteredForRemoteNotifications];
    }
    else
    {
        return ([self enabledRemoteNotificationTypes] & UIRemoteNotificationTypeAlert);
    }
}

- (void)registerForPushNotifications
{
    if ([self respondsToSelector:@selector(registerForRemoteNotifications)])
    {
        [self registerForRemoteNotifications];

        Class uiUserNotificationSettings = NSClassFromString(@"UIUserNotificationSettings");

        //If you want to add other capabilities than just banner alerts, you'll need to grab their declarations from the iOS 8 SDK and define them in the same way.
        NSUInteger UIUserNotificationTypeAlert   = 1 << 2;

        id settings = [uiUserNotificationSettings settingsForTypes:UIUserNotificationTypeAlert categories:[NSSet set]];            
        [self registerUserNotificationSettings:settings];

    }
    else
    {
        [self registerForRemoteNotificationTypes:UIRemoteNotificationTypeAlert];
    }
}

@end

T-SQL: Opposite to string concatenation - how to split string into multiple records

I wrote this awhile back. It assumes the delimiter is a comma and that the individual values aren't bigger than 127 characters. It could be modified pretty easily.

It has the benefit of not being limited to 4,000 characters.

Good luck!

ALTER Function [dbo].[SplitStr] ( 
        @txt text 
) 
Returns @tmp Table 
        ( 
                value varchar(127)
        ) 
as 
BEGIN 
        declare @str varchar(8000) 
                , @Beg int 
                , @last int 
                , @size int 

        set @size=datalength(@txt) 
        set @Beg=1 


        set @str=substring(@txt,@Beg,8000) 
        IF len(@str)<8000 set @Beg=@size 
        ELSE BEGIN 
                set @last=charindex(',', reverse(@str)) 
                set @str=substring(@txt,@Beg,8000-@last) 
                set @Beg=@Beg+8000-@last+1 
        END 

        declare @workingString varchar(25) 
                , @stringindex int 



        while @Beg<=@size Begin 
                WHILE LEN(@str) > 0 BEGIN 
                        SELECT @StringIndex = CHARINDEX(',', @str) 

                        SELECT 
                                @workingString = CASE 
                                        WHEN @StringIndex > 0 THEN SUBSTRING(@str, 1, @StringIndex-1) 
                                        ELSE @str 
                                END 

                        INSERT INTO 
                                @tmp(value)
                        VALUES 
                                (cast(rtrim(ltrim(@workingString)) as varchar(127)))
                        SELECT @str = CASE 
                                WHEN CHARINDEX(',', @str) > 0 THEN SUBSTRING(@str, @StringIndex+1, LEN(@str)) 
                                ELSE '' 
                        END 
                END 
                set @str=substring(@txt,@Beg,8000) 

                if @Beg=@size set @Beg=@Beg+1 
                else IF len(@str)<8000 set @Beg=@size 
                ELSE BEGIN 
                        set @last=charindex(',', reverse(@str)) 
                        set @str=substring(@txt,@Beg,8000-@last) 
                        set @Beg=@Beg+8000-@last+1 

                END 
        END     

        return
END 

Cannot get to $rootScope

I've found the following "pattern" to be very useful:

MainCtrl.$inject = ['$scope', '$rootScope', '$location', 'socket', ...];
function MainCtrl (scope, rootscope, location, thesocket, ...) {

where, MainCtrl is a controller. I am uncomfortable relying on the parameter names of the Controller function doing a one-for-one mimic of the instances for fear that I might change names and muck things up. I much prefer explicitly using $inject for this purpose.

How to return JSON with ASP.NET & jQuery

Just return object: it will be parser to JSON.

public Object Get(string id)
{
    return new { id = 1234 };
}

How to store directory files listing into an array?

Try with:

#! /bin/bash

i=0
while read line
do
    array[ $i ]="$line"        
    (( i++ ))
done < <(ls -ls)

echo ${array[1]}

In your version, the while runs in a subshell, the environment variables you modify in the loop are not visible outside it.

(Do keep in mind that parsing the output of ls is generally not a good idea at all.)

How do I switch between command and insert mode in Vim?

This has been mentioned in other questions, but ctrl + [ is an equivalent to ESC on all keyboards.

Angular2 Routing with Hashtag to page anchor

Sorry for answering it bit late; There is a pre-defined function in the Angular Routing Documentation which helps us in routing with a hashtag to page anchor i.e, anchorScrolling: 'enabled'

Step-1:- First Import the RouterModule in the app.module.ts file:-

imports:[ 
    BrowserModule, 
    FormsModule,
    RouterModule.forRoot(routes,{
      anchorScrolling: 'enabled'
    })
  ],

Step-2:- Go to the HTML Page, Create the navigation and add two important attributes like [routerLink] and fragment for matching the respective Div ID's:-

<ul>
    <li> <a [routerLink] = "['/']"  fragment="home"> Home </a></li>
    <li> <a [routerLink] = "['/']"  fragment="about"> About Us </a></li>
  <li> <a [routerLink] = "['/']"  fragment="contact"> Contact Us </a></li>
</ul>

Step-3:- Create a section/div by matching the ID name with the fragment:-

<section id="home" class="home-section">
      <h2>  HOME SECTION </h2>
</section>

<section id="about" class="about-section">
        <h2>  ABOUT US SECTION </h2>
</section>

<section id="contact" class="contact-section">
        <h2>  CONTACT US SECTION </h2>
</section>

For your reference, I have added the example below by creating a small demo which helps to solve your problem.

Demo : https://routing-hashtag-page-anchors.stackblitz.io/

Is there a performance difference between i++ and ++i in C?

A better answer is that ++i will sometimes be faster but never slower.

Everyone seems to be assuming that i is a regular built-in type such as int. In this case there will be no measurable difference.

However if i is complex type then you may well find a measurable difference. For i++ you must make a copy of your class before incrementing it. Depending on what's involved in a copy it could indeed be slower since with ++it you can just return the final value.

Foo Foo::operator++()
{
  Foo oldFoo = *this; // copy existing value - could be slow
  // yadda yadda, do increment
  return oldFoo;
}

Another difference is that with ++i you have the option of returning a reference instead of a value. Again, depending on what's involved in making a copy of your object this could be slower.

A real-world example of where this can occur would be the use of iterators. Copying an iterator is unlikely to be a bottle-neck in your application, but it's still good practice to get into the habit of using ++i instead of i++ where the outcome is not affected.

How to change Toolbar home icon color

This code works for me:

public static Drawable changeBackArrowColor(Context context, int color) {
    String resName;
    int res;

    resName = Build.VERSION.SDK_INT >= 23 ? "abc_ic_ab_back_material" : "abc_ic_ab_back_mtrl_am_alpha";
    res = context.getResources().getIdentifier(resName, "drawable", context.getPackageName());

    final Drawable upArrow = context.getResources().getDrawable(res);
    upArrow.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);

    return upArrow;
}

...

getSupportActionBar().setHomeAsUpIndicator(changeBackArrowColor(this, Color.rgb(50, 50, 50)));               
supportInvalidateOptionsMenu();

Also, if you want to change the toolbar text color:

Spannable spannableString = new SpannableString(t);
spannableString.setSpan(new ForegroundColorSpan(Color.rgb(50, 50, 50)), 0, t.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
toolbar.setText(spannableString);

Working from API 19 through 25.

Get all validation errors from Angular 2 FormGroup

This is another variant that collects the errors recursively and does not depend on any external library like lodash (ES6 only):

function isFormGroup(control: AbstractControl): control is FormGroup {
  return !!(<FormGroup>control).controls;
}

function collectErrors(control: AbstractControl): any | null {
  if (isFormGroup(control)) {
    return Object.entries(control.controls)
      .reduce(
        (acc, [key, childControl]) => {
          const childErrors = collectErrors(childControl);
          if (childErrors) {
            acc = {...acc, [key]: childErrors};
          }
          return acc;
        },
        null
      );
  } else {
    return control.errors;
  }
}

How to show a confirm message before delete?

var txt;
var r = confirm("Press a button!");
if (r == true) {
   txt = "You pressed OK!";
} else {
   txt = "You pressed Cancel!";
}

_x000D_
_x000D_
var txt;_x000D_
var r = confirm("Press a button!");_x000D_
if (r == true) {_x000D_
    txt = "You pressed OK!";_x000D_
} else {_x000D_
    txt = "You pressed Cancel!";_x000D_
}
_x000D_
_x000D_
_x000D_

How to list all functions in a Python module?

Use the inspect module:

from inspect import getmembers, isfunction

from somemodule import foo
print(getmembers(foo, isfunction))

Also see the pydoc module, the help() function in the interactive interpreter and the pydoc command-line tool which generates the documentation you are after. You can just give them the class you wish to see the documentation of. They can also generate, for instance, HTML output and write it to disk.

What is MVC and what are the advantages of it?

Jeff has a post about it, otherwise I found some useful documents on Apple's website, in Cocoa tutorials (this one for example).

Laravel - check if Ajax request

after writing the jquery code perform this validation in your route or in controller.

$.ajax({
url: "/id/edit",
data:
name:name,
method:'get',
success:function(data){
  console.log(data);}
});

Route::get('/', function(){
if(Request::ajax()){
  return 'it's ajax request';}
});

Thin Black Border for a Table

Style the td and th instead

td, th {
    border: 1px solid black;
}

And also to make it so there is no spacing between cells use:

table {
    border-collapse: collapse;
}

(also note, you have border-style: none; which should be border-style: solid;)

See an example here: http://jsfiddle.net/KbjNr/

HAX kernel module is not installed

After reading many questions on stackoverflow I found out that my CPU does not support Virtualization. I have to upgrade to the cpu which supports Virtualization in order to install Intel X 86 Emulator accelerator(Haxm Installer)

add to array if it isn't there already

With array_flip() it could look like this:

$flipped = array_flip($opts);
$flipped[$newValue] = 1;
$opts = array_keys($flipped);

With array_unique() - like this:

$opts[] = $newValue;
$opts = array_values(array_unique($opts));

Notice that array_values(...) — you need it if you're exporting array to JavaScript in JSON form. array_unique() alone would simply unset duplicate keys, without rebuilding the remaining elements'. So, after converting to JSON this would produce object, instead of array.

>>> json_encode(array_unique(['a','b','b','c']))
=> "{"0":"a","1":"b","3":"c"}"

>>> json_encode(array_values(array_unique(['a','b','b','c'])))
=> "["a","b","c"]"

How to post JSON to a server using C#?

WARNING! I have a very strong view on this subject.

.NET’s existing web clients are not developer friendly! WebRequest & WebClient are prime examples of "how to frustrate a developer". They are verbose & complicated to work with; when all you want to do is a simple Post request in C#. HttpClient goes some way in addressing these issues, but it still falls short. On top of that Microsoft’s documentation is bad … really bad; unless you want to sift through pages and pages of technical blurb.

Open-source to the rescue. There are three excellent open-source, free NuGet libraries as alternatives. Thank goodness! These are all well supported, documented and yes, easy - correction…super easy - to work with.

There is not much between them, but I would give ServiceStack.Text the slight edge …

  • Github stars are roughly the same.
  • Open Issues & importantly how quickly any issues closed down? ServiceStack takes the award here for the fastest issue resolution & no open issues.
  • Documentation? All have great documentation; however, ServiceStack takes it to the next level & is known for its ‘Golden standard’ for documentation.

Ok - so what does a Post Request in JSON look like within ServiceStack.Text?

var response = "http://example.org/login"
    .PostJsonToUrl(new Login { Username="admin", Password="mypassword" });

That is one line of code. Concise & easy! Compare the above to .NET’s Http libraries.

How do I insert a JPEG image into a python Tkinter window?

import tkinter as tk
from tkinter import ttk
from PIL import Image,  ImageTk
win = tk. Tk()
image1 = Image. open("Aoran. jpg")
image2 =  ImageTk. PhotoImage(image1)
image_label = ttk. Label(win , image =.image2)
image_label.place(x = 0 , y = 0)
win.mainloop()

com.apple.WebKit.WebContent drops 113 error: Could not find specified service

I had this problem I iOS 12.4 when calling evaluateJavascript. I solved it by wrapping the call in DispatchQueue.main.async { }

How to call a PHP file from HTML or Javascript

I just want to have a button on my website make a PHP file run

<form action="my.php" method="post">
    <input type="submit">
</form>

Generally speaking, however, unless you are sending new data to the server to be stored, you would just use a link.

<a href="my.php">run php</a>

(Although you should use link text that describes what happens from the user's point of view, not the servers)


I'm making a simple blog site for myself and I've got the code for the site and the javascript that can take the post I write in a textarea and display it immediately. I just want to link it to a PHP file that will create the permanent blog post on the server so that when I reload the page, the post is still there.

This is tricker.

First, you do need to use a form and POST (since you are sending data to be stored).

Then you need to store the data somewhere. This is normally done using a database. Read up on the PDO library for PHP. It is the standard way to interact with databases.

Then you need to pull the data back out again. The simplest approach here is to use the query string to pass the primary key for the database row with the entry you wish to display.

<a href="showBlogEntry.php?entry_id=123">...</a>

Make sure you also read up on SQL injection and XSS.

How to access form methods and controls from a class in C#?

Another solution would be to pass the textbox (or control you want to modify) into the method that will manipulate it as a parameter.

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        TestClass test = new TestClass();
        test.ModifyText(textBox1);
    }
}

public class TestClass
{
    public void ModifyText(TextBox textBox)
    {
        textBox.Text = "New text";
    }
}

SSIS Convert Between Unicode and Non-Unicode Error

On the above example I kept losing the values, I think that delaying the Validation will allow the new data types to be saved as part of the meta data.

On the connection Manager for 'Excel Connection Manager' set the Delay Validation to False from the Properties.

Then on the data flow Destination task for Excel set the ValidationExternalMetaData to False, again from the properties.

This will now allow you to right click on the Excel Destination Task and go to Advanced Editor for Excel Destination --> far right tab - Input and Output Properties. In the External Columns folder section you will be able to now change the Data Types and Length values of the problematic columns and this can now be saved.

Good Luck!

Add event handler for body.onload by javascript within <body> part

Simply wrap the code you want to execute into the onload event of the window object:

window.onload = function(){ 
   // your code here
}

How to modify existing XML file with XmlDocument and XmlNode in C#

You need to do something like this:

// instantiate XmlDocument and load XML from file
XmlDocument doc = new XmlDocument();
doc.Load(@"D:\test.xml");

// get a list of nodes - in this case, I'm selecting all <AID> nodes under
// the <GroupAIDs> node - change to suit your needs
XmlNodeList aNodes = doc.SelectNodes("/Equipment/DataCollections/GroupAIDs/AID");

// loop through all AID nodes
foreach (XmlNode aNode in aNodes)
{
   // grab the "id" attribute
   XmlAttribute idAttribute = aNode.Attributes["id"];

   // check if that attribute even exists...
   if (idAttribute != null)
   {
      // if yes - read its current value
      string currentValue = idAttribute.Value;

      // here, you can now decide what to do - for demo purposes,
      // I just set the ID value to a fixed value if it was empty before
      if (string.IsNullOrEmpty(currentValue))
      {
         idAttribute.Value = "515";
      }
   }
}

// save the XmlDocument back to disk
doc.Save(@"D:\test2.xml");

Angular ForEach in Angular4/Typescript?

in angular4 foreach like that. try this.

 selectChildren(data, $event) {
      let parentChecked = data.checked;
       this.hierarchicalData.forEach(obj => {
          obj.forEach(childObj=> {
            value.checked = parentChecked;
         });
      });
    }

Select and trigger click event of a radio button in jquery

You are triggering the event before the event is even bound.

Just move the triggering of the event to after attaching the event.

$(document).ready(function() {
  $("#checkbox_div input:radio").click(function() {

    alert("clicked");

   });

  $("input:radio:first").prop("checked", true).trigger("click");

});

Check Fiddle

Can I do a max(count(*)) in SQL?

This question is old, but was referenced in a new question on dba.SE. I feel the best solutions haven't been provided, yet, so I am adding another one.

First off, assuming referential integrity (typically enforced with foreign key constraints) you do not need to join to the table movie at all. That's dead freight in your query. All answers so far fail to point that out.


Can I do a max(count(*)) in SQL?

To answer the question in the title: Yes, in Postgres 8.4 (released 2009-07-01, before this question was asked) or later you can achieve that by nesting an aggregate function in a window function:

SELECT c.yr, count(*) AS ct, max(count(*)) OVER () AS max_ct
FROM   actor   a
JOIN   casting c ON c.actorid = a.id
WHERE  a.name = 'John Travolta'
GROUP  BY c.yr;

Consider the sequence of events in a SELECT query:

The (possible) downside: window functions do not aggregate rows. You get all rows left after the aggregate step. Useful in some queries, but not ideal for this one.


To get one row with the highest count, you can use ORDER BY ct LIMIT 1 like @wolph hinted:

SELECT c.yr, count(*) AS ct
FROM   actor   a
JOIN   casting c ON c.actorid = a.id
WHERE  a.name = 'John Travolta'
GROUP  BY c.yr
ORDER  BY ct DESC
LIMIT  1;

Using only basic SQL features available in any halfway decent RDBMS - the LIMIT implementation varies:

Or you can get one row per group with the highest count with DISTINCT ON (only Postgres):


Answer

But you asked for:

... rows for which count(*) is max.

Possibly more than one. The most elegant solution is with the window function rank() in a subquery. Ryan provided a query but it can be simpler (details in my answer above):

SELECT yr, ct
FROM  (
   SELECT c.yr, count(*) AS ct, rank() OVER (ORDER BY count(*) DESC) AS rnk
   FROM   actor   a
   JOIN   casting c ON c.actorid = a.id
   WHERE  a.name = 'John Travolta'
   GROUP  BY c.yr
   ) sub
WHERE  rnk = 1;

All major RDBMS support window functions nowadays. Except MySQL and forks (MariaDB seems to have implemented them at last in version 10.2).

Selecting non-blank cells in Excel with VBA

If you are looking for the last row of a column, use:

Sub SelectFirstColumn()
   SelectEntireColumn (1)
End Sub

Sub SelectSecondColumn()
    SelectEntireColumn (2)
End Sub

Sub SelectEntireColumn(columnNumber)
    Dim LastRow
    Sheets("sheet1").Select
    LastRow = ActiveSheet.Columns(columnNumber).SpecialCells(xlLastCell).Row

    ActiveSheet.Range(Cells(1, columnNumber), Cells(LastRow, columnNumber)).Select
End Sub

Other commands you will need to get familiar with are copy and paste commands:

Sub CopyOneToTwo()
    SelectEntireColumn (1)
    Selection.Copy

    Sheets("sheet1").Select
    ActiveSheet.Range("B1").PasteSpecial Paste:=xlPasteValues
End Sub

Finally, you can reference worksheets in other workbooks by using the following syntax:

Dim book2
Set book2 = Workbooks.Open("C:\book2.xls")
book2.Worksheets("sheet1")

"Error 404 Not Found" in Magento Admin Login Page

Finally, I found the solution to my problem.

I looked into the Magento system log file (var/log/system.log). There I saw the exact error.

The error is as below:-

Recoverable Error: Argument 1 passed to Mage_Core_Model_Store::setWebsite() must be an instance of Mage_Core_Model_Website, null given, called in YOUR_PATH\app\code\core\Mage\Core\Model\App.php on line 555 and defined in YOUR_PATH\app\code\core\Mage\Core\Model\Store.php on line 285

Recoverable Error: Argument 1 passed to Mage_Core_Model_Store_Group::setWebsite() must be an instance of Mage_Core_Model_Website, null given, called in YOUR_PATH\app\code\core\Mage\Core\Model\App.php on line 575 and defined in YOUR_PATH\app\code\core\Mage\Core\Model\Store\Group.php on line 227

Actually, I had this error before. But, error display message like Error: 404 Not Found was new to me.

The reason for this error is that store_id and website_id for admin should be set to 0 (zero). But, when you import database to new server, somehow these values are not set to 0.

Open PhpMyAdmin and run the following query in your database:-

SET FOREIGN_KEY_CHECKS=0;
UPDATE `core_store` SET store_id = 0 WHERE code='admin';
UPDATE `core_store_group` SET group_id = 0 WHERE name='Default';
UPDATE `core_website` SET website_id = 0 WHERE code='admin';
UPDATE `customer_group` SET customer_group_id = 0 WHERE customer_group_code='NOT LOGGED IN';
SET FOREIGN_KEY_CHECKS=1;

I have written about this problem and solution over here:-

Magento: Solution to "Error: 404 Not Found" in Admin Login Page

Why am I getting InputMismatchException?

Here you can see the nature of Scanner:

double nextDouble()

Returns the next token as a double. If the next token is not a float or is out of range, InputMismatchException is thrown.

Try to catch the exception

try {
    // ...
} catch (InputMismatchException e) {
    System.out.print(e.getMessage()); //try to find out specific reason.
}

UPDATE

CASE 1

I tried your code and there is nothing wrong with it. Your are getting that error because you must have entered String value. When I entered a numeric value, it runs without any errors. But once I entered String it throw the same Exception which you have mentioned in your question.

CASE 2

You have entered something, which is out of range as I have mentioned above.

I'm really wondering what you could have tried to enter. In my system, it is running perfectly without changing a single line of code. Just copy as it is and try to compile and run it.

import java.util.*;

public class Test {
    public static void main(String... args) {
        new Test().askForMarks(5);
    }

    public void askForMarks(int student) {
        double marks[] = new double[student];
        int index = 0;
        Scanner reader = new Scanner(System.in);
        while (index < student) {
            System.out.print("Please enter a mark (0..30): ");
            marks[index] = (double) checkValueWithin(0, 30); 
            index++;
        }
    }

    public double checkValueWithin(int min, int max) {
        double num;
        Scanner reader = new Scanner(System.in);
        num = reader.nextDouble();                         
        while (num < min || num > max) {                 
            System.out.print("Invalid. Re-enter number: "); 
            num = reader.nextDouble();                         
        } 

        return num;
    }
}

As you said, you have tried to enter 1.0, 2.8 and etc. Please try with this code.

Note : Please enter number one by one, on separate lines. I mean, enter 2.7, press enter and then enter second number (e.g. 6.7).

EXCEL VBA, inserting blank row and shifting cells

If you want to just shift everything down you can use:

Rows(1).Insert shift:=xlShiftDown

Similarly to shift everything over:

Columns(1).Insert shift:=xlShiftRight

How can I open a website in my web browser using Python?

I think it should be

import webbrowser

webbrowser.open('http://gatedin.com')

NOTE: make sure that you give http or https

if you give "www." instead of "http:" instead of opening a broser the interprete displays boolean OutPut TRUE. here you are importing webbrowser library

How do I mock a class without an interface?

The standard mocking frameworks are creating proxy classes. This is the reason why they are technically limited to interfaces and virtual methods.

If you want to mock 'normal' methods as well, you need a tool that works with instrumentation instead of proxy generation. E.g. MS Moles and Typemock can do that. But the former has a horrible 'API', and the latter is commercial.

Creating a JSON dynamically with each input value using jquery

Like this:

function createJSON() {
    jsonObj = [];
    $("input[class=email]").each(function() {

        var id = $(this).attr("title");
        var email = $(this).val();

        item = {}
        item ["title"] = id;
        item ["email"] = email;

        jsonObj.push(item);
    });

    console.log(jsonObj);
}

Explanation

You are looking for an array of objects. So, you create a blank array. Create an object for each input by using 'title' and 'email' as keys. Then you add each of the objects to the array.

If you need a string, then do

jsonString = JSON.stringify(jsonObj);

Sample Output

[{"title":"QA","email":"a@b"},{"title":"PROD","email":"b@c"},{"title":"DEV","email":"c@d"}] 

How to disable Hyper-V in command line?

You can have a Windows 10 configuration with and without Hyper-V as follows in an Admin prompt:

bcdedit /copy {current} /d "Windows 10 no Hyper-V"

find the new id of the just created "Windows 10 no Hyper-V" bootentry, eg. {094a0b01-3350-11e7-99e1-bc5ec82bc470}

bcdedit /set {094a0b01-3350-11e7-99e1-bc5ec82bc470} hypervisorlaunchtype Off

After rebooting you can choose between Windows 10 with and without Hyper-V at startup

Encrypt and decrypt a String in java

    public String encrypt(String str) {
        try {
            // Encode the string into bytes using utf-8
            byte[] utf8 = str.getBytes("UTF8");

            // Encrypt
            byte[] enc = ecipher.doFinal(utf8);

            // Encode bytes to base64 to get a string
            return new sun.misc.BASE64Encoder().encode(enc);
        } catch (javax.crypto.BadPaddingException e) {
        } catch (IllegalBlockSizeException e) {
        } catch (UnsupportedEncodingException e) {
        } catch (java.io.IOException e) {
        }
        return null;
    }

    public String decrypt(String str) {
        try {
            // Decode base64 to get bytes
            byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);

            // Decrypt
            byte[] utf8 = dcipher.doFinal(dec);

            // Decode using utf-8
            return new String(utf8, "UTF8");
        } catch (javax.crypto.BadPaddingException e) {
        } catch (IllegalBlockSizeException e) {
        } catch (UnsupportedEncodingException e) {
        } catch (java.io.IOException e) {
        }
        return null;
    }
}

Here's an example that uses the class:

try {
    // Generate a temporary key. In practice, you would save this key.
    // See also Encrypting with DES Using a Pass Phrase.
    SecretKey key = KeyGenerator.getInstance("DES").generateKey();

    // Create encrypter/decrypter class
    DesEncrypter encrypter = new DesEncrypter(key);

    // Encrypt
    String encrypted = encrypter.encrypt("Don't tell anybody!");

    // Decrypt
    String decrypted = encrypter.decrypt(encrypted);
} catch (Exception e) {
}

Setting public class variables

Inside class Testclass:

public function __construct($new_value)
{
    $this->testvar = $new_value;
}

Finding what branch a Git commit came from

As an experiment, I made a post-commit hook that stores information about the currently checked out branch in the commit metadata. I also slightly modified gitk to show that information.

You can check it out here: https://github.com/pajp/branch-info-commits

Using Server.MapPath in external C# Classes in ASP.NET

Whether you're running within the context of ASP.NET or not, you should be able to use HostingEnvironment.ApplicationPhysicalPath

Display SQL query results in php

You need to fetch the data from each row of the resultset obtained from the query. You can use mysql_fetch_array() for this.

// Process all rows
while($row = mysql_fetch_array($result)) {
    echo $row['column_name']; // Print a single column data
    echo print_r($row);       // Print the entire row data
}

Change your code to this :

require_once('db.php');  
$sql="SELECT * FROM  modul1open WHERE idM1O>=(SELECT FLOOR( MAX( idM1O ) * RAND( ) )  FROM  modul1open) 
ORDER BY idM1O LIMIT 1"

$result = mysql_query($sql);
while($row = mysql_fetch_array($result)) {
    echo $row['fieldname']; 
}

display:inline vs display:block

Block Elements: Elements liked div, p, headings are block level. They start from new line and occupy full width of parent element. Inline Elements: Elements liked b, i, span, img are inline level. They never start from new line and occupy width of content.

Explanation of "ClassCastException" in Java

You can better understand ClassCastException and casting once you realize that the JVM cannot guess the unknown. If B is an instance of A it has more class members and methods on the heap than A. The JVM cannot guess how to cast A to B since the mapping target is larger, and the JVM will not know how to fill the additional members.

But if A was an instance of B, it would be possible, because A is a reference to a complete instance of B, so the mapping will be one-to-one.

Using TortoiseSVN how do I merge changes from the trunk to a branch and vice versa?

Take a look at svnmerge.py. It's command-line, can't be invoked by TortoiseSVN, but it's more powerful. From the FAQ:

Traditional subversion will let you merge changes, but it doesn't "remember" what you've already merged. It also doesn't provide a convenient way to exclude a change set from being merged. svnmerge.py automates some of the work, and simplifies it. Svnmerge also creates a commit message with the log messages from all of the things it merged.

What are sessions? How do they work?

Think of HTTP as a person(A) who has SHORT TERM MEMORY LOSS and forgets every person as soon as that person goes out of sight.

Now, to remember different persons, A takes a photo of that person and keeps it. Each Person's pic has an ID number. When that person comes again in sight, that person tells it's ID number to A and A finds their picture by ID number. And voila !!, A knows who is that person.

Same is with HTTP. It is suffering from SHORT TERM MEMORY LOSS. It uses Sessions to record everything you did while using a website, and then, when you come again, it identifies you with the help of Cookies(Cookie is like a token). Picture is the Session here, and ID is the Cookie here.

What is the purpose of global.asax in asp.net

The root directory of a web application has a special significance and certain content can be present on in that folder. It can have a special file called as “Global.asax”. ASP.Net framework uses the content in the global.asax and creates a class at runtime which is inherited from HttpApplication. During the lifetime of an application, ASP.NET maintains a pool of Global.asax derived HttpApplication instances. When an application receives an http request, the ASP.Net page framework assigns one of these instances to process that request. That instance is responsible for managing the entire lifetime of the request it is assigned to and the instance can only be reused after the request has been completed when it is returned to the pool. The instance members in Global.asax cannot be used for sharing data across requests but static member can be. Global.asax can contain the event handlers of HttpApplication object and some other important methods which would execute at various points in a web application

Should I use the datetime or timestamp data type in MySQL?

I would always use a Unix timestamp when working with MySQL and PHP. The main reason for this being the default date method in PHP uses a timestamp as the parameter, so there would be no parsing needed.

To get the current Unix timestamp in PHP, just do time();
and in MySQL do SELECT UNIX_TIMESTAMP();.

MySQL connection not working: 2002 No such file or directory

The error 2002 means that MySQL can't connect to local database server through the socket file (e.g. /tmp/mysql.sock).

To find out where is your socket file, run:

mysql_config --socket

then double check that your application uses the right Unix socket file or connect through the TCP/IP port instead.

Then double check if your PHP has the right MySQL socket set-up:

php -i | grep mysql.default_socket

and make sure that file exists.

Test the socket:

mysql --socket=/var/mysql/mysql.sock

If the Unix socket is wrong or does not exist, you may symlink it, for example:

ln -vs /Applications/MAMP/tmp/mysql/mysql.sock /var/mysql/mysql.sock

or correct your configuration file (e.g. php.ini).

To test the PDO connection directly from PHP, you may run:

php -r "new PDO('mysql:host=localhost;port=3306;charset=utf8;dbname=dbname', 'root', 'root');"

Check also the configuration between Apache and CLI (command-line interface), as the configuration can be differ.

It might be that the server is running, but you are trying to connect using a TCP/IP port, named pipe, or Unix socket file different from the one on which the server is listening. To correct that you need to invoke a client program (e.g. specifying --port option) to indicate the proper port number, or the proper named pipe or Unix socket file (e.g. --socket option).

See: Troubleshooting Problems Connecting to MySQL


Other utils/commands which can help to track the problem:

  • mysql --socket=$(php -r 'echo ini_get("mysql.default_socket");')
  • netstat -ln | grep mysql
  • php -r "phpinfo();" | grep mysql
  • php -i | grep mysql
  • Use XDebug with xdebug.show_exception_trace=1 in your xdebug.ini
  • On OS X try sudo dtruss -fn mysqld, on Linux debug with strace
  • Check permissions on Unix socket: stat $(mysql_config --socket) and if you've enough free space (df -h).
  • Restart your MySQL.
  • Check net.core.somaxconn.

MS SQL compare dates?

SELECT CASE WHEN CAST(date1 AS DATE) <= CAST(date2 AS DATE) ...

Should do what you need.

Test Case

WITH dates(date1, date2, date3, date4)
     AS (SELECT CAST('20101231 15:13:48.593' AS DATETIME),
                CAST('20101231 00:00:00.000' AS DATETIME),
                CAST('20101231 15:13:48.593' AS DATETIME),
                CAST('20101231 00:00:00.000' AS DATETIME))
SELECT CASE
         WHEN CAST(date1 AS DATE) <= CAST(date2 AS DATE) THEN 'Y'
         ELSE 'N'
       END AS COMPARISON_WITH_CAST,
       CASE
         WHEN date3 <= date4 THEN 'Y'
         ELSE 'N'
       END AS COMPARISON_WITHOUT_CAST
FROM   dates 

Returns

COMPARISON_WITH_CAST   |  COMPARISON_WITHOUT_CAST
Y                         N

Programmatically open new pages on Tabs

This works 100%

window.open('http://www.google.com/','_newtab' + Date.now());

Handling optional parameters in javascript

I know this is a pretty old question, but I dealt with this recently. Let me know what you think of this solution.

I created a utility that lets me strongly type arguments and let them be optional. You basically wrap your function in a proxy. If you skip an argument, it's undefined. It may get quirky if you have multiple optional arguments with the same type right next to each other. (There are options to pass functions instead of types to do custom argument checks, as well as specifying default values for each parameter.)

This is what the implementation looks like:

function displayOverlay(/*message, timeout, callback*/) {
  return arrangeArgs(arguments, String, Number, Function, 
    function(message, timeout, callback) {
      /* ... your code ... */
    });
};

For clarity, here is what is going on:

function displayOverlay(/*message, timeout, callback*/) {
  //arrangeArgs is the proxy
  return arrangeArgs(
           //first pass in the original arguments
           arguments, 
           //then pass in the type for each argument
           String,  Number,  Function, 
           //lastly, pass in your function and the proxy will do the rest!
           function(message, timeout, callback) {

             //debug output of each argument to verify it's working
             console.log("message", message, "timeout", timeout, "callback", callback);

             /* ... your code ... */

           }
         );
};

You can view the arrangeArgs proxy code in my GitHub repository here:

https://github.com/joelvh/Sysmo.js/blob/master/sysmo.js

Here is the utility function with some comments copied from the repository:

/*
 ****** Overview ******
 * 
 * Strongly type a function's arguments to allow for any arguments to be optional.
 * 
 * Other resources:
 * http://ejohn.org/blog/javascript-method-overloading/
 * 
 ****** Example implementation ******
 * 
 * //all args are optional... will display overlay with default settings
 * var displayOverlay = function() {
 *   return Sysmo.optionalArgs(arguments, 
 *            String, [Number, false, 0], Function, 
 *            function(message, timeout, callback) {
 *              var overlay = new Overlay(message);
 *              overlay.timeout = timeout;
 *              overlay.display({onDisplayed: callback});
 *            });
 * }
 * 
 ****** Example function call ******
 * 
 * //the window.alert() function is the callback, message and timeout are not defined.
 * displayOverlay(alert);
 * 
 * //displays the overlay after 500 miliseconds, then alerts... message is not defined.
 * displayOverlay(500, alert);
 * 
 ****** Setup ******
 * 
 * arguments = the original arguments to the function defined in your javascript API.
 * config = describe the argument type
 *  - Class - specify the type (e.g. String, Number, Function, Array) 
 *  - [Class/function, boolean, default] - pass an array where the first value is a class or a function...
 *                                         The "boolean" indicates if the first value should be treated as a function.
 *                                         The "default" is an optional default value to use instead of undefined.
 * 
 */
arrangeArgs: function (/* arguments, config1 [, config2] , callback */) {
  //config format: [String, false, ''], [Number, false, 0], [Function, false, function(){}]
  //config doesn't need a default value.
  //config can also be classes instead of an array if not required and no default value.

  var configs = Sysmo.makeArray(arguments),
      values = Sysmo.makeArray(configs.shift()),
      callback = configs.pop(),
      args = [],
      done = function() {
        //add the proper number of arguments before adding remaining values
        if (!args.length) {
          args = Array(configs.length);
        }
        //fire callback with args and remaining values concatenated
        return callback.apply(null, args.concat(values));
      };

  //if there are not values to process, just fire callback
  if (!values.length) {
    return done();
  }

  //loop through configs to create more easily readable objects
  for (var i = 0; i < configs.length; i++) {

    var config = configs[i];

    //make sure there's a value
    if (values.length) {

      //type or validator function
      var fn = config[0] || config,
          //if config[1] is true, use fn as validator, 
          //otherwise create a validator from a closure to preserve fn for later use
          validate = (config[1]) ? fn : function(value) {
            return value.constructor === fn;
          };

      //see if arg value matches config
      if (validate(values[0])) {
        args.push(values.shift());
        continue;
      }
    }

    //add a default value if there is no value in the original args
    //or if the type didn't match
    args.push(config[2]);
  }

  return done();
}

Using awk to print all columns from the nth to the last

Perl solution:

perl -lane 'splice @F,0,1; print join " ",@F' file

These command-line options are used:

  • -n loop around every line of the input file, do not automatically print every line

  • -l removes newlines before processing, and adds them back in afterwards

  • -a autosplit mode – split input lines into the @F array. Defaults to splitting on whitespace

  • -e execute the perl code

splice @F,0,1 cleanly removes column 0 from the @F array

join " ",@F joins the elements of the @F array, using a space in-between each element


Python solution:

python -c "import sys;[sys.stdout.write(' '.join(line.split()[1:]) + '\n') for line in sys.stdin]" < file

How do I apply CSS3 transition to all properties except background-position?

You can try using the standard W3C way:

.transition { transition: all 0.2s, top 0s, left 0s, width 0s, height 0s; }

http://jsfiddle.net/H2jet/60/

Oracle: how to set user password unexpire?

The following statement causes a user's password to expire:

ALTER USER user PASSWORD EXPIRE;

If you cause a database user's password to expire with PASSWORD EXPIRE, then the user (or the DBA) must change the password before attempting to log in to the database following the expiration. Tools such as SQL*Plus allow the user to change the password on the first attempted login following the expiration.

ALTER USER scott IDENTIFIED BY password;

Will set/reset the users password.

See the alter user doc for more info

How to highlight text using javascript

I was wondering that too, you could try what I learned on this post.

I used:

_x000D_
_x000D_
function highlightSelection() {_x000D_
   var userSelection = window.getSelection();_x000D_
   for(var i = 0; i < userSelection.rangeCount; i++) {_x000D_
    highlightRange(userSelection.getRangeAt(i));_x000D_
   }_x000D_
   _x000D_
  }_x000D_
   _x000D_
   function highlightRange(range) {_x000D_
       var newNode = document.createElement("span");_x000D_
       newNode.setAttribute(_x000D_
          "style",_x000D_
          "background-color: yellow; display: inline;"_x000D_
       );_x000D_
       range.surroundContents(newNode);_x000D_
   }
_x000D_
<html>_x000D_
 <body contextmenu="mymenu">_x000D_
_x000D_
  <menu type="context" id="mymenu">_x000D_
   <menuitem label="Highlight Yellow" onclick="highlightSelection()" icon="/images/comment_icon.gif"></menuitem>_x000D_
  </menu>_x000D_
  <p>this is text, select and right click to high light me! if you can`t see the option, please use this<button onclick="highlightSelection()">button </button><p>
_x000D_
_x000D_
_x000D_

you could also try it here: http://henriquedonati.com/projects/Extension/extension.html

xc

How to add title to subplots in Matplotlib?

ax.set_title() should set the titles for separate subplots:

import matplotlib.pyplot as plt

if __name__ == "__main__":
    data = [1, 2, 3, 4, 5]

    fig = plt.figure()
    fig.suptitle("Title for whole figure", fontsize=16)
    ax = plt.subplot("211")
    ax.set_title("Title for first plot")
    ax.plot(data)

    ax = plt.subplot("212")
    ax.set_title("Title for second plot")
    ax.plot(data)

    plt.show()

Can you check if this code works for you? Maybe something overwrites them later?

How to get the fragment instance from the FragmentActivity?

You can use use findFragmentById in FragmentManager.

Since you are using the Support library (you are extending FragmentActivity) you can use:

getSupportFragmentManager().findFragmentById(R.id.pageview)

If you are not using the support library (so you are on Honeycomb+ and you don't want to use the support library):

getFragmentManager().findFragmentById(R.id.pageview)

Please consider that using the support library is recommended even on Honeycomb+.

WPF: Setting the Width (and Height) as a Percentage Value

You can put the textboxes inside a grid to do percentage values on the rows or columns of the grid and let the textboxes auto-fill to their parent cells (as they will by default). Example:

<Grid>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="2*" />
        <ColumnDefinition Width="3*" />
    </Grid.ColumnDefinitions>

    <TextBox Grid.Column="0" />
    <TextBox Grid.Column="1" />
</Grid>

This will make #1 2/5 of the width, and #2 3/5.

Save bitmap to location

// |==| Create a PNG File from Bitmap :

void devImjFylFnc(String pthAndFylTtlVar, Bitmap iptBmjVar)
{
    try
    {
        FileOutputStream fylBytWrtrVar = new FileOutputStream(pthAndFylTtlVar);
        iptBmjVar.compress(Bitmap.CompressFormat.PNG, 100, fylBytWrtrVar);
        fylBytWrtrVar.close();
    }
    catch (Exception errVar) { errVar.printStackTrace(); }
}

// |==| Get Bimap from File :

Bitmap getBmjFrmFylFnc(String pthAndFylTtlVar)
{
    return BitmapFactory.decodeFile(pthAndFylTtlVar);
}

passing form data to another HTML page

Using pure JavaScript.It's very easy using local storage.
The first page form:

_x000D_
_x000D_
function getData()
{
    //gettting the values
    var email = document.getElementById("email").value;
    var password= document.getElementById("password").value; 
    var telephone= document.getElementById("telephone").value; 
    var mobile= document.getElementById("mobile").value; 
    //saving the values in local storage
    localStorage.setItem("txtValue", email);
    localStorage.setItem("txtValue1", password);
    localStorage.setItem("txtValue2", mobile);
    localStorage.setItem("txtValue3", telephone);   
}
_x000D_
  input{
    font-size: 25px;
  }
  label{
    color: rgb(16, 8, 46);
    font-weight: bolder;
  }
  #data{

  }
_x000D_
   <fieldset style="width: fit-content; margin: 0 auto; font-size: 30px;">
        <form action="action.html">
        <legend>Sign Up Form</legend>
        <label>Email:<br />
        <input type="text" name="email" id="email"/></label><br />
        <label>Password<br />
        <input type="text" name="password" id="password"/></label><br>
        <label>Mobile:<br />
        <input type="text" name="mobile" id="mobile"/></label><br />
        <label>Telephone:<br />
        <input type="text" name="telephone" id="telephone"/></label><br> 
        <input type="submit" value="Submit" onclick="getData()">
    </form>
    </fieldset>
_x000D_
_x000D_
_x000D_

This is the second page:

_x000D_
_x000D_
//displaying the value from local storage to another page by their respective Ids
document.getElementById("data").innerHTML=localStorage.getItem("txtValue");
document.getElementById("data1").innerHTML=localStorage.getItem("txtValue1");
document.getElementById("data2").innerHTML=localStorage.getItem("txtValue2");
document.getElementById("data3").innerHTML=localStorage.getItem("txtValue3");
_x000D_
 <div style=" font-size: 30px;  color: rgb(32, 7, 63); text-align: center;">
    <div style="font-size: 40px; color: red; margin: 0 auto;">
        Here's Your data
    </div>
    The Email is equal to: <span id="data"> Email</span><br> 
    The Password is equal to <span id="data1"> Password</span><br>
    The Mobile is equal to <span id="data2"> Mobile</span><br>
    The Telephone is equal to <span id="data3"> Telephone</span><br>
    </div>
_x000D_
_x000D_
_x000D_

Important Note:

Please don't forget to give name "action.html" to the second html file to work the code properly. I can't use multiple pages in a snippet, that's why its not working here try in the browser in your editor where it will surely work.

How to select option in drop down using Capybara

If you take a look at the source of the select method, you can see that what it does when you pass a from key is essentially:

find(:select, from, options).find(:option, value, options).select_option

In other words, it finds the <select> you're interested in, then finds the <option> within that, then calls select_option on the <option> node.

You've already pretty much done the first two things, I'd just rearrange them. Then you can tack the select_option method on the end:

find('#organizationSelect').find(:xpath, 'option[2]').select_option

When using Spring Security, what is the proper way to obtain current username (i.e. SecurityContext) information in a bean?

A lot has changed in the Spring world since this question was answered. Spring has simplified getting the current user in a controller. For other beans, Spring has adopted the suggestions of the author and simplified the injection of 'SecurityContextHolder'. More details are in the comments.


This is the solution I've ended up going with. Instead of using SecurityContextHolder in my controller, I want to inject something which uses SecurityContextHolder under the hood but abstracts away that singleton-like class from my code. I've found no way to do this other than rolling my own interface, like so:

public interface SecurityContextFacade {

  SecurityContext getContext();

  void setContext(SecurityContext securityContext);

}

Now, my controller (or whatever POJO) would look like this:

public class FooController {

  private final SecurityContextFacade securityContextFacade;

  public FooController(SecurityContextFacade securityContextFacade) {
    this.securityContextFacade = securityContextFacade;
  }

  public void doSomething(){
    SecurityContext context = securityContextFacade.getContext();
    // do something w/ context
  }

}

And, because of the interface being a point of decoupling, unit testing is straightforward. In this example I use Mockito:

public class FooControllerTest {

  private FooController controller;
  private SecurityContextFacade mockSecurityContextFacade;
  private SecurityContext mockSecurityContext;

  @Before
  public void setUp() throws Exception {
    mockSecurityContextFacade = mock(SecurityContextFacade.class);
    mockSecurityContext = mock(SecurityContext.class);
    stub(mockSecurityContextFacade.getContext()).toReturn(mockSecurityContext);
    controller = new FooController(mockSecurityContextFacade);
  }

  @Test
  public void testDoSomething() {
    controller.doSomething();
    verify(mockSecurityContextFacade).getContext();
  }

}

The default implementation of the interface looks like this:

public class SecurityContextHolderFacade implements SecurityContextFacade {

  public SecurityContext getContext() {
    return SecurityContextHolder.getContext();
  }

  public void setContext(SecurityContext securityContext) {
    SecurityContextHolder.setContext(securityContext);
  }

}

And, finally, the production Spring config looks like this:

<bean id="myController" class="com.foo.FooController">
     ...
  <constructor-arg index="1">
    <bean class="com.foo.SecurityContextHolderFacade">
  </constructor-arg>
</bean>

It seems more than a little silly that Spring, a dependency injection container of all things, has not supplied a way to inject something similar. I understand SecurityContextHolder was inherited from acegi, but still. The thing is, they're so close - if only SecurityContextHolder had a getter to get the underlying SecurityContextHolderStrategy instance (which is an interface), you could inject that. In fact, I even opened a Jira issue to that effect.

One last thing - I've just substantially changed the answer I had here before. Check the history if you're curious but, as a coworker pointed out to me, my previous answer would not work in a multi-threaded environment. The underlying SecurityContextHolderStrategy used by SecurityContextHolder is, by default, an instance of ThreadLocalSecurityContextHolderStrategy, which stores SecurityContexts in a ThreadLocal. Therefore, it is not necessarily a good idea to inject the SecurityContext directly into a bean at initialization time - it may need to be retrieved from the ThreadLocal each time, in a multi-threaded environment, so the correct one is retrieved.

Ignore fields from Java object dynamically while sending as JSON from Spring MVC

In your entity class add @JsonInclude(JsonInclude.Include.NON_NULL) annotation to resolve the problem

it will look like

@Entity
@JsonInclude(JsonInclude.Include.NON_NULL)

Copying Code from Inspect Element in Google Chrome

Click on the line or element you want to copy. Copy to clipboard. Paste.

The only tricky thing is if you click on a line, you get everything that line includes if it was folded. For example if you click on a div, and copy, you get everything that the div includes.

You can also get only what you want by Right Clicking, and select 'Edit as HTML'. This will make that section essentially text, with none of the folding activated. You can then select, copy and paste the relevant bits.

Android "Only the original thread that created a view hierarchy can touch its views."

I was working with a class that did not contain a reference to the context. So it was not possible for me to use runOnUIThread(); I used view.post(); and it was solved.

timer.scheduleAtFixedRate(new TimerTask() {

    @Override
    public void run() {
        final int currentPosition = mediaPlayer.getCurrentPosition();
        audioMessage.seekBar.setProgress(currentPosition / 1000);
        audioMessage.tvPlayDuration.post(new Runnable() {
            @Override
            public void run() {
                audioMessage.tvPlayDuration.setText(ChatDateTimeFormatter.getDuration(currentPosition));
            }
        });
    }
}, 0, 1000);

What represents a double in sql server?

You should map it to FLOAT(53)- that's what LINQ to SQL does.

Getting values from JSON using Python

If you want to iterate over both keys and values of the dictionary, do this:

for key, value in data.items():
    print key, value

How to add color to Github's README.md file

<span color="red">red</span>

#!/bin/bash

# convert ansi-colored terminal output to github markdown

# to colorize text on github, we use <span color="red">red</span> etc
# depends on: aha, xclip
# license: CC0-1.0
# note: some tools may need other arguments than `--color=always`
# sample use: colors-to-github.sh diff a.txt b.txt

cmd="$1"
shift
(
    echo '<pre>'
    $cmd --color=always "$@" 2>&1 | aha --no-header
    echo '</pre>'
) \
| sed -E 's/<span style="[^"]*color:([^;"]+);"/<span color="\1"/g' \
| sed -E 's/ style="[^"]*"//g' \
| xclip -i -sel clipboard

trivial :)

How to find EOF through fscanf?

while (fscanf(input,"%s",arr) != EOF && count!=7) {
  len=strlen(arr); 
  count++; 
}

Converting Secret Key into a String and Vice Versa

Actually what Luis proposed did not work for me. I had to figure out another way. This is what helped me. Might help you too. Links:

  1. *.getEncoded(): https://docs.oracle.com/javase/7/docs/api/java/security/Key.html

  2. Encoder information: https://docs.oracle.com/javase/8/docs/api/java/util/Base64.Encoder.html

  3. Decoder information: https://docs.oracle.com/javase/8/docs/api/java/util/Base64.Decoder.html

Code snippets: For encoding:

String temp = new String(Base64.getEncoder().encode(key.getEncoded()));

For decoding:

byte[] encodedKey = Base64.getDecoder().decode(temp);
SecretKey originalKey = new SecretKeySpec(encodedKey, 0, encodedKey.length, "DES");

Write a file on iOS

Try making

NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"MyFile"];

as

NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"MyFile.txt"];

open read and close a file in 1 line of code

I frequently do something like this when I need to get a few lines surrounding something I've grepped in a log file:

$ grep -n "xlrd" requirements.txt | awk -F ":" '{print $1}'
54

$ python -c "with open('requirements.txt') as file: print ''.join(file.readlines()[52:55])"
wsgiref==0.1.2
xlrd==0.9.2
xlwt==0.7.5

How to find index of list item in Swift?

You can also use the functional library Dollar to do an indexOf on an array as such http://www.dollarswift.org/#indexof-indexof

$.indexOf([1, 2, 3, 1, 2, 3], value: 2) 
=> 1

How to discard local commits in Git?

I had to do a :

git checkout -b master

as git said that it doesn't exists, because it's been wipe with the

git -D master

Move a view up only when the keyboard covers an input field

Why not implement this in a UITableViewController instead? The keyboard won't hide any text fields when its shown.

JavaScript ES6 promise for loop

As you already hinted in your question, your code creates all promises synchronously. Instead they should only be created at the time the preceding one resolves.

Secondly, each promise that is created with new Promise needs to be resolved with a call to resolve (or reject). This should be done when the timer expires. That will trigger any then callback you would have on that promise. And such a then callback (or await) is a necessity in order to implement the chain.

With those ingredients, there are several ways to perform this asynchronous chaining:

  1. With a for loop that starts with an immediately resolving promise

  2. With Array#reduce that starts with an immediately resolving promise

  3. With a function that passes itself as resolution callback

  4. With ECMAScript2017's async / await syntax

  5. With ECMAScript2020's for await...of syntax

See a snippet and comments for each of these options below.

1. With for

You can use a for loop, but you must make sure it doesn't execute new Promise synchronously. Instead you create an initial immediately resolving promise, and then chain new promises as the previous ones resolve:

_x000D_
_x000D_
for (let i = 0, p = Promise.resolve(); i < 10; i++) {
    p = p.then(_ => new Promise(resolve =>
        setTimeout(function () {
            console.log(i);
            resolve();
        }, Math.random() * 1000)
    ));
}
_x000D_
_x000D_
_x000D_

2. With reduce

This is just a more functional approach to the previous strategy. You create an array with the same length as the chain you want to execute, and start out with an immediately resolving promise:

_x000D_
_x000D_
[...Array(10)].reduce( (p, _, i) => 
    p.then(_ => new Promise(resolve =>
        setTimeout(function () {
            console.log(i);
            resolve();
        }, Math.random() * 1000)
    ))
, Promise.resolve() );
_x000D_
_x000D_
_x000D_

This is probably more useful when you actually have an array with data to be used in the promises.

3. With a function passing itself as resolution-callback

Here we create a function and call it immediately. It creates the first promise synchronously. When it resolves, the function is called again:

_x000D_
_x000D_
(function loop(i) {
    if (i < 10) new Promise((resolve, reject) => {
        setTimeout( () => {
            console.log(i);
            resolve();
        }, Math.random() * 1000);
    }).then(loop.bind(null, i+1));
})(0);
_x000D_
_x000D_
_x000D_

This creates a function named loop, and at the very end of the code you can see it gets called immediately with argument 0. This is the counter, and the i argument. The function will create a new promise if that counter is still below 10, otherwise the chaining stops.

The call to resolve() will trigger the then callback which will call the function again. loop.bind(null, i+1) is just a different way of saying _ => loop(i+1).

4. With async/await

Modern JS engines support this syntax:

_x000D_
_x000D_
(async function loop() {
    for (let i = 0; i < 10; i++) {
        await new Promise(resolve => setTimeout(resolve, Math.random() * 1000));
        console.log(i);
    }
})();
_x000D_
_x000D_
_x000D_

It may look strange, as it seems like the new Promise() calls are executed synchronously, but in reality the async function returns when it executes the first await. Every time an awaited promise resolves, the function's running context is restored, and proceeds after the await, until it encounters the next one, and so it continues until the loop finishes.

As it may be a common thing to return a promise based on a timeout, you could create a separate function for generating such a promise. This is called promisifying a function, in this case setTimeout. It may improve the readability of the code:

_x000D_
_x000D_
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));

(async function loop() {
    for (let i = 0; i < 10; i++) {
        await delay(Math.random() * 1000);
        console.log(i);
    }
})();
_x000D_
_x000D_
_x000D_

5. With for await...of

With EcmaScript 2020, the for await...of found its way to modern JavaScript engines. Although it does not really reduce code in this case, it allows to isolate the definition of the random interval chain from the actual iteration of it:

_x000D_
_x000D_
const delay = ms => new Promise(resolve => setTimeout(resolve, ms));
async function * randomDelays(count ,max) {
    for (let i = 0; i < count; i++) yield delay(Math.random() * max).then(() => i);
}

(async function loop() {
    for await (let i of randomDelays(10, 1000)) console.log(i);
})();
_x000D_
_x000D_
_x000D_