Programs & Examples On #Django nonrel

Django-nonrel is an independent branch of Django that adds NoSQL database support to the ORM. The long-term goal is to add NoSQL support to the official Django release.

How to upload files in asp.net core?

you can try below code

1- model or view model

public class UploadImage 
{
  public string ImageFile { get; set; }
  public string ImageName { get; set; }
  public string ImageDescription { get; set; }
}

2- View page

<form class="form-horizontal" asp-controller="Image" asp-action="UploadImage" method="POST" enctype="multipart/form-data">

<input type="file" asp-for="ImageFile">
<input type="text" asp-for="ImageName">
<input type="text" asp-for="ImageDescription">
</form>

3- Controller

 public class Image
    {

      private IHostingEnvironment _hostingEnv;
      public Image(IHostingEnvironment hostingEnv)
      {
         _hostingEnv = hostingEnv;
      }

      [HttpPost]
      public async Task<IActionResult> UploadImage(UploadImage model, IFormFile ImageFile)
      {
        if (ModelState.IsValid)
         {
        var filename = ContentDispositionHeaderValue.Parse(ImageFile.ContentDisposition).FileName.Trim('"');
        var path = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "images", ImageFile.FileName);
        using (System.IO.Stream stream = new FileStream(path, FileMode.Create))
         {
            await ImageFile.CopyToAsync(stream);
         }
          model.ImageFile = filename;
         _context.Add(model);
         _context.SaveChanges();
         }        

      return RedirectToAction("Index","Home");   
    }

In Mongoose, how do I sort by date? (node.js)

The correct answer is:

Blah.find({}).sort({date: -1}).execFind(function(err,docs){

});

Joda DateTime to Timestamp conversion

It is a common misconception that time (a measurable 4th dimension) is different over the world. Timestamp as a moment in time is unique. Date however is influenced how we "see" time but actually it is "time of day".

An example: two people look at the clock at the same moment. The timestamp is the same, right? But one of them is in London and sees 12:00 noon (GMT, timezone offset is 0), and the other is in Belgrade and sees 14:00 (CET, Central Europe, daylight saving now, offset is +2).

Their perception is different but the moment is the same.

You can find more details in this answer.

UPDATE

OK, it's not a duplicate of this question but it is pointless since you are confusing the terms "Timestamp = moment in time (objective)" and "Date[Time] = time of day (subjective)".

Let's look at your original question code broken down like this:

// Get the "original" value from database.
Timestamp momentFromDB = rs.getTimestamp("anytimestampcolumn");

// Turn it into a Joda DateTime with time zone.
DateTime dt = new DateTime(momentFromDB, DateTimeZone.forID("anytimezone"));

// And then turn it back into a timestamp but "with time zone".
Timestamp ts = new Timestamp(dt.getMillis());

I haven't run this code but I am certain it will print true and the same number of milliseconds each time:

System.out.println("momentFromDB == dt : " + (momentFromDB.getTime() == dt.getTimeInMillis());
System.out.println("momentFromDB == ts : " + (momentFromDB.getTime() == ts.getTime()));
System.out.println("dt == ts : " + (dt.getTimeInMillis() == ts.getTime()));

System.out.println("momentFromDB [ms] : " + momentFromDB.getTime());
System.out.println("ts [ms] : " + ts.getTime());
System.out.println("dt [ms] : " + dt.getTimeInMillis());

But as you said yourself printing them out as strings will result in "different" time because DateTime applies the time zone. That's why "time" is stored and transferred as Timestamp objects (which basically wraps a long) and displayed or entered as Date[Time].

In your own answer you are artificially adding an offset and creating a "wrong" time. If you use that timestamp to create another DateTime and print it out it will be offset twice.

// Turn it back into a Joda DateTime with time zone.
DateTime dt = new DateTime(ts, DateTimeZone.forID("anytimezone"));

P.S. If you have the time go through the very complex Joda Time source code to see how it holds the time (millis) and how it prints it.

JUnit Test as proof

import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

import org.junit.Before;
import org.junit.Test;


public class WorldTimeTest {
    private static final int MILLIS_IN_HOUR = 1000 * 60 * 60;
    private static final String ISO_FORMAT_NO_TZ = "yyyy-MM-dd'T'HH:mm:ss.SSS";
    private static final String ISO_FORMAT_WITH_TZ = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";

    private TimeZone londonTimeZone;
    private TimeZone newYorkTimeZone;
    private TimeZone sydneyTimeZone;
    private long nowInMillis;
    private Date now;

    public static SimpleDateFormat createDateFormat(String pattern, TimeZone timeZone) throws Exception {
        SimpleDateFormat result = new SimpleDateFormat(pattern);
        // Must explicitly set the time zone with "setCalendar()".
        result.setCalendar(Calendar.getInstance(timeZone));
        return result;
    }

    public static SimpleDateFormat createDateFormat(String pattern) throws Exception {
        return createDateFormat(pattern, TimeZone.getDefault());
    }

    public static SimpleDateFormat createDateFormat() throws Exception {
        return createDateFormat(ISO_FORMAT_WITH_TZ, TimeZone.getDefault());
    }

    public void printSystemInfo() throws Exception {
        final String[] propertyNames = {
                "java.runtime.name", "java.runtime.version", "java.vm.name", "java.vm.version",
                "os.name", "os.version", "os.arch",
                "user.language", "user.country", "user.script", "user.variant",
                "user.language.format", "user.country.format", "user.script.format",
                "user.timezone" };

        System.out.println();
        System.out.println("System Information:");
        for (String name : propertyNames) {
            if (name == null || name.length() == 0) {
                continue;
            }
            String value = System.getProperty(name);
            if (value != null && value.length() > 0) {
                System.out.println("  " + name + " = " + value);
            }
        }

        final TimeZone defaultTZ = TimeZone.getDefault();
        final int defaultOffset = defaultTZ.getOffset(nowInMillis) / MILLIS_IN_HOUR;
        final int userOffset = TimeZone.getTimeZone(System
                .getProperty("user.timezone")).getOffset(nowInMillis) / MILLIS_IN_HOUR;
        final Locale defaultLocale = Locale.getDefault();

        System.out.println("  default.timezone-offset (hours) = " + userOffset);
        System.out.println("  default.timezone = " + defaultTZ.getDisplayName());
        System.out.println("  default.timezone.id = " + defaultTZ.getID());
        System.out.println("  default.timezone-offset (hours) = " + defaultOffset);
        System.out.println("  default.locale = "
                + defaultLocale.getLanguage() + "_" + defaultLocale.getCountry()
                + " (" + defaultLocale.getDisplayLanguage()
                + "," + defaultLocale.getDisplayCountry() + ")");
        System.out.println("  now = " + nowInMillis + " [ms] or "
                + createDateFormat().format(now));
        System.out.println();
    }

    @Before
    public void setUp() throws Exception {
        // Remember this moment.
        now = new Date();
        nowInMillis = now.getTime(); // == System.currentTimeMillis();

        // Print out some system information.
        printSystemInfo();

        // "Europe/London" time zone is DST aware, we'll use fixed offset.
        londonTimeZone = TimeZone.getTimeZone("GMT");
        // The same applies to "America/New York" time zone ...
        newYorkTimeZone = TimeZone.getTimeZone("GMT-5");
        // ... and for the "Australia/Sydney" time zone.
        sydneyTimeZone = TimeZone.getTimeZone("GMT+10");
    }

    @Test
    public void testDateFormatting() throws Exception {
        int londonOffset = londonTimeZone.getOffset(nowInMillis) / MILLIS_IN_HOUR; // in hours
        Calendar londonCalendar = Calendar.getInstance(londonTimeZone);
        londonCalendar.setTime(now);

        int newYorkOffset = newYorkTimeZone.getOffset(nowInMillis) / MILLIS_IN_HOUR;
        Calendar newYorkCalendar = Calendar.getInstance(newYorkTimeZone);
        newYorkCalendar.setTime(now);

        int sydneyOffset = sydneyTimeZone.getOffset(nowInMillis) / MILLIS_IN_HOUR;
        Calendar sydneyCalendar = Calendar.getInstance(sydneyTimeZone);
        sydneyCalendar.setTime(now);

        // Check each time zone offset.
        assertThat(londonOffset, equalTo(0));
        assertThat(newYorkOffset, equalTo(-5));
        assertThat(sydneyOffset, equalTo(10));

        // Check that calendars are not equals (due to time zone difference).
        assertThat(londonCalendar, not(equalTo(newYorkCalendar)));
        assertThat(londonCalendar, not(equalTo(sydneyCalendar)));

        // Check if they all point to the same moment in time, in milliseconds.
        assertThat(londonCalendar.getTimeInMillis(), equalTo(nowInMillis));
        assertThat(newYorkCalendar.getTimeInMillis(), equalTo(nowInMillis));
        assertThat(sydneyCalendar.getTimeInMillis(), equalTo(nowInMillis));

        // Check if they all point to the same moment in time, as Date.
        assertThat(londonCalendar.getTime(), equalTo(now));
        assertThat(newYorkCalendar.getTime(), equalTo(now));
        assertThat(sydneyCalendar.getTime(), equalTo(now));

        // Check if hours are all different (skip local time because
        // this test could be executed in those exact time zones).
        assertThat(newYorkCalendar.get(Calendar.HOUR_OF_DAY),
                not(equalTo(londonCalendar.get(Calendar.HOUR_OF_DAY))));
        assertThat(sydneyCalendar.get(Calendar.HOUR_OF_DAY),
                not(equalTo(londonCalendar.get(Calendar.HOUR_OF_DAY))));


        // Display London time in multiple forms.
        SimpleDateFormat dfLondonNoTZ = createDateFormat(ISO_FORMAT_NO_TZ, londonTimeZone);
        SimpleDateFormat dfLondonWithTZ = createDateFormat(ISO_FORMAT_WITH_TZ, londonTimeZone);
        System.out.println("London (" + londonTimeZone.getDisplayName(false, TimeZone.SHORT)
                + ", " + londonOffset + "):");
        System.out.println("  time (ISO format w/o TZ) = "
                + dfLondonNoTZ.format(londonCalendar.getTime()));
        System.out.println("  time (ISO format w/ TZ)  = "
                + dfLondonWithTZ.format(londonCalendar.getTime()));
        System.out.println("  time (default format)    = "
                + londonCalendar.getTime() + " / " + londonCalendar.toString());
        // Using system default time zone.
        System.out.println("  time (default TZ)        = "
                + createDateFormat(ISO_FORMAT_NO_TZ).format(londonCalendar.getTime())
                + " / " + createDateFormat().format(londonCalendar.getTime()));


        // Display New York time in multiple forms.
        SimpleDateFormat dfNewYorkNoTZ = createDateFormat(ISO_FORMAT_NO_TZ, newYorkTimeZone);
        SimpleDateFormat dfNewYorkWithTZ = createDateFormat(ISO_FORMAT_WITH_TZ, newYorkTimeZone);
        System.out.println("New York (" + newYorkTimeZone.getDisplayName(false, TimeZone.SHORT)
                + ", " + newYorkOffset + "):");
        System.out.println("  time (ISO format w/o TZ) = "
                + dfNewYorkNoTZ.format(newYorkCalendar.getTime()));
        System.out.println("  time (ISO format w/ TZ)  = "
                + dfNewYorkWithTZ.format(newYorkCalendar.getTime()));
        System.out.println("  time (default format)    = "
                + newYorkCalendar.getTime() + " / " + newYorkCalendar.toString());
        // Using system default time zone.
        System.out.println("  time (default TZ)        = "
                + createDateFormat(ISO_FORMAT_NO_TZ).format(newYorkCalendar.getTime())
                + " / " + createDateFormat().format(newYorkCalendar.getTime()));


        // Display Sydney time in multiple forms.
        SimpleDateFormat dfSydneyNoTZ = createDateFormat(ISO_FORMAT_NO_TZ, sydneyTimeZone);
        SimpleDateFormat dfSydneyWithTZ = createDateFormat(ISO_FORMAT_WITH_TZ, sydneyTimeZone);
        System.out.println("Sydney (" + sydneyTimeZone.getDisplayName(false, TimeZone.SHORT)
                + ", " + sydneyOffset + "):");
        System.out.println("  time (ISO format w/o TZ) = "
                + dfSydneyNoTZ.format(sydneyCalendar.getTime()));
        System.out.println("  time (ISO format w/ TZ)  = "
                + dfSydneyWithTZ.format(sydneyCalendar.getTime()));
        System.out.println("  time (default format)    = "
                + sydneyCalendar.getTime() + " / " + sydneyCalendar.toString());
        // Using system default time zone.
        System.out.println("  time (default TZ)        = "
                + createDateFormat(ISO_FORMAT_NO_TZ).format(sydneyCalendar.getTime())
                + " / " + createDateFormat().format(sydneyCalendar.getTime()));
    }

    @Test
    public void testDateParsing() throws Exception {
        // Create date parsers that look for time zone information in a date-time string.
        final SimpleDateFormat londonFormatTZ = createDateFormat(ISO_FORMAT_WITH_TZ, londonTimeZone);
        final SimpleDateFormat newYorkFormatTZ = createDateFormat(ISO_FORMAT_WITH_TZ, newYorkTimeZone);
        final SimpleDateFormat sydneyFormatTZ = createDateFormat(ISO_FORMAT_WITH_TZ, sydneyTimeZone);

        // Create date parsers that ignore time zone information in a date-time string.
        final SimpleDateFormat londonFormatLocal = createDateFormat(ISO_FORMAT_NO_TZ, londonTimeZone);
        final SimpleDateFormat newYorkFormatLocal = createDateFormat(ISO_FORMAT_NO_TZ, newYorkTimeZone);
        final SimpleDateFormat sydneyFormatLocal = createDateFormat(ISO_FORMAT_NO_TZ, sydneyTimeZone);

        // We are looking for the moment this millenium started, the famous Y2K,
        // when at midnight everyone welcomed the New Year 2000, i.e. 2000-01-01 00:00:00.
        // Which of these is the right one?
        // a) "2000-01-01T00:00:00.000-00:00"
        // b) "2000-01-01T00:00:00.000-05:00"
        // c) "2000-01-01T00:00:00.000+10:00"
        // None of them? All of them?
        // For those who guessed it - yes, it is a trick question because we didn't specify
        // the "where" part, or what kind of time (local/global) we are looking for.
        // The first (a) is the local Y2K moment in London, which is at the same time global.
        // The second (b) is the local Y2K moment in New York, but London is already celebrating for 5 hours.
        // The third (c) is the local Y2K moment in Sydney, and they started celebrating 15 hours before New York did.
        // The point here is that each answer is correct because everyone thinks of that moment in terms of "celebration at midnight".
        // The key word here is "midnight"! That moment is actually a "time of day" moment illustrating our perception of time based on the movement of our Sun.

        // These are global Y2K moments, i.e. the same moment all over the world, UTC/GMT midnight.
        final String MIDNIGHT_GLOBAL = "2000-01-01T00:00:00.000-00:00";
        final Date milleniumInLondon = londonFormatTZ.parse(MIDNIGHT_GLOBAL);
        final Date milleniumInNewYork = newYorkFormatTZ.parse(MIDNIGHT_GLOBAL);
        final Date milleniumInSydney = sydneyFormatTZ.parse(MIDNIGHT_GLOBAL);

        // Check if they all point to the same moment in time.
        // And that parser ignores its own configured time zone and uses the information from the date-time string.
        assertThat(milleniumInNewYork, equalTo(milleniumInLondon));
        assertThat(milleniumInSydney, equalTo(milleniumInLondon));


        // These are all local Y2K moments, a.k.a. midnight at each location on Earth, with time zone information.
        final String MIDNIGHT_LONDON = "2000-01-01T00:00:00.000-00:00";
        final String MIDNIGHT_NEW_YORK = "2000-01-01T00:00:00.000-05:00";
        final String MIDNIGHT_SYDNEY = "2000-01-01T00:00:00.000+10:00";
        final Date midnightInLondonTZ = londonFormatLocal.parse(MIDNIGHT_LONDON);
        final Date midnightInNewYorkTZ = newYorkFormatLocal.parse(MIDNIGHT_NEW_YORK);
        final Date midnightInSydneyTZ = sydneyFormatLocal.parse(MIDNIGHT_SYDNEY);

        // Check if they all point to the same moment in time.
        assertThat(midnightInNewYorkTZ, not(equalTo(midnightInLondonTZ)));
        assertThat(midnightInSydneyTZ, not(equalTo(midnightInLondonTZ)));

        // Check if the time zone offset is correct.
        assertThat(midnightInLondonTZ.getTime() - midnightInNewYorkTZ.getTime(),
                equalTo((long) newYorkTimeZone.getOffset(milleniumInLondon.getTime())));
        assertThat(midnightInLondonTZ.getTime() - midnightInSydneyTZ.getTime(),
                equalTo((long) sydneyTimeZone.getOffset(milleniumInLondon.getTime())));


        // These are also local Y2K moments, just withouth the time zone information.
        final String MIDNIGHT_ANYWHERE = "2000-01-01T00:00:00.000";
        final Date midnightInLondon = londonFormatLocal.parse(MIDNIGHT_ANYWHERE);
        final Date midnightInNewYork = newYorkFormatLocal.parse(MIDNIGHT_ANYWHERE);
        final Date midnightInSydney = sydneyFormatLocal.parse(MIDNIGHT_ANYWHERE);

        // Check if these are the same as the local moments with time zone information.
        assertThat(midnightInLondon, equalTo(midnightInLondonTZ));
        assertThat(midnightInNewYork, equalTo(midnightInNewYorkTZ));
        assertThat(midnightInSydney, equalTo(midnightInSydneyTZ));

        // Check if they all point to the same moment in time.
        assertThat(midnightInNewYork, not(equalTo(midnightInLondon)));
        assertThat(midnightInSydney, not(equalTo(midnightInLondon)));

        // Check if the time zone offset is correct.
        assertThat(midnightInLondon.getTime() - midnightInNewYork.getTime(),
                equalTo((long) newYorkTimeZone.getOffset(milleniumInLondon.getTime())));
        assertThat(midnightInLondon.getTime() - midnightInSydney.getTime(),
                equalTo((long) sydneyTimeZone.getOffset(milleniumInLondon.getTime())));


        // Final check - if Y2K moment is in London ..
        final String Y2K_LONDON = "2000-01-01T00:00:00.000Z";
        // .. New York local time would be still 5 hours in 1999 ..
        final String Y2K_NEW_YORK = "1999-12-31T19:00:00.000-05:00";
        // .. and Sydney local time would be 10 hours in 2000.
        final String Y2K_SYDNEY = "2000-01-01T10:00:00.000+10:00";

        final String londonTime = londonFormatTZ.format(milleniumInLondon);
        final String newYorkTime = newYorkFormatTZ.format(milleniumInLondon);
        final String sydneyTime = sydneyFormatTZ.format(milleniumInLondon);

        // WHat do you think, will the test pass?
        assertThat(londonTime, equalTo(Y2K_LONDON));
        assertThat(newYorkTime, equalTo(Y2K_NEW_YORK));
        assertThat(sydneyTime, equalTo(Y2K_SYDNEY));
    }
}

org.hibernate.TransientObjectException: object references an unsaved transient instance - save the transient instance before flushing

your issue will be resolved by properly defining cascading depedencies or by saving the referenced entities before saving the entity that references. Defining cascading is really tricky to get right because of all the subtle variations in how they are used.

Here is how you can define cascades:

@Entity
public class Userrole implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    private long userroleid;

    private Timestamp createddate;

    private Timestamp deleteddate;

    private String isactive;

    //bi-directional many-to-one association to Role
    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name="ROLEID")
    private Role role;

    //bi-directional many-to-one association to User
    @ManyToOne(cascade = CascadeType.ALL)
    @JoinColumn(name="USERID")
    private User user;

}

In this scenario, every time you save, update, delete, etc Userrole, the assocaited Role and User will also be saved, updated...

Again, if your use case demands that you do not modify User or Role when updating Userrole, then simply save User or Role before modifying Userrole

Additionally, bidirectional relationships have a one-way ownership. In this case, User owns Bloodgroup. Therefore, cascades will only proceed from User -> Bloodgroup. Again, you need to save User into the database (attach it or make it non-transient) in order to associate it with Bloodgroup.

Get parent of current directory from Python script

import os
current_file = os.path.abspath(os.path.dirname(__file__))
parent_of_parent_dir = os.path.join(current_file, '../../')

Open youtube video in Fancybox jquery

Thanx, Alexander!

And to set the fancy-close button above the youtube's flash-content add 'wmode' to 'swf' parameters:

'swf': {'allowfullscreen':'true', 'wmode':'transparent'}

Count distinct value pairs in multiple columns in SQL

Having to return the count of a unique Bill of Materials (BOM) where each BOM have multiple positions, I dd something like this:

select t_item, t_pono, count(distinct ltrim(rtrim(t_item)) + cast(t_pono as varchar(3))) as [BOM Pono Count]
from BOMMaster
where t_pono = 1
group by t_item, t_pono

Given t_pono is a smallint datatype and t_item is a varchar(16) datatype

Scp command syntax for copying a folder from local machine to a remote server

In stall PuTTY in our system and set the environment variable PATH Pointing to putty path. open the command prompt and move to putty folder. Using PSCP command

Please check this

How do I horizontally center a span element inside a div

only css div you can center content

div{
       display:table;
       margin:0 auto;
    }

http://jsfiddle.net/4q2r69te/1/

Excel VBA Open a Folder

If you want to open a windows file explorer, you should call explorer.exe

Call Shell("explorer.exe" & " " & "P:\Engineering", vbNormalFocus)

Equivalent syxntax

Shell "explorer.exe" & " " & "P:\Engineering", vbNormalFocus

insert/delete/update trigger in SQL server

Not possible, per MSDN:

You can have the same code execute for multiple trigger types, but the syntax does not allow for multiple code blocks in one trigger:

Trigger on an INSERT, UPDATE, or DELETE statement to a table or view (DML Trigger)

CREATE TRIGGER [ schema_name . ]trigger_name 
ON { table | view } 
[ WITH <dml_trigger_option> [ ,...n ] ]
{ FOR | AFTER | INSTEAD OF } 
{ [ INSERT ] [ , ] [ UPDATE ] [ , ] [ DELETE ] } 
[ NOT FOR REPLICATION ] 
AS { sql_statement  [ ; ] [ ,...n ] | EXTERNAL NAME <method specifier [ ; ] > }

val() doesn't trigger change() in jQuery

You need to chain the method like this:

$('#input').val('test').change();

How to export a Vagrant virtual machine to transfer it

None of the above answers worked for me. I have been 2 days working out the way to migrate a Vagrant + VirtualBox Machine from a computer to another... It's possible!

First, you need to understand that the virtual machine is separated from your sync / shared folder. So when you pack your machine you're packing it without your files, but with the databases.

What you need to do:

1- Open the CMD of your computer 1 host machine (Command line. Open it as Adminitrator with the right button -> "Run as administrator") and go to your vagrant installed files. On my case: C:/VVV You will see your Vagrantfile an also these folders:

/config/
/database/
/log/
/provision/
/www/
Vagrantfile
...

The /www/ folder is where I have my Sync Folder with my development domains. You may have your sync folder in other place, just be sure to understand what you are doing. Also /config and /database are sync folders.

2- run this command: vagrant package --vagrantfile Vagrantfile

(This command does a package of your virtual machine using you Vagrantfile configuration.)

Here's what you can read on the Vagrant documentation about the command:

A common misconception is that the --vagrantfile option will package a Vagrantfile that is used when vagrant init is used with this box. This is not the case. Instead, a Vagrantfile is loaded and read as part of the Vagrant load process when the box is used. For more information, read about the Vagrantfile load order.

https://www.vagrantup.com/docs/cli/package.html

When finnished, you will have a package.box file.

3- Copy all these files (/config, /database, Vagrantfile, package.box, etc.) and paste them on your Computer 2 just where you want to install your virtual machine (on my case D:/VVV).

Now you have a copy of everything you need on your computer 2 host.

4- run this: vagrant box add package.box --name VVV

(The --name is used to name your virtual machine. On my case it's named VVV) (You can use --force if you already have a virtual machine with this name and want to overwrite it. (Use carefully !))

This will unpack your new vagrant Virtual machine.

5- When finnished, run: vagrant up

The machine will install and you should see it on the "Oracle virtual machine box manager". If you cannot see the virtual machine, try running the Oracle VM box as administrator (right click -> Run as administrator)

You now may have everything ok but remember to see if your hosts are as you expected:

c:/windows/system32/hosts

6- Maybe it's a good idea to copy your host file from your Computer 1 to your Computer 2. Or copy the lines you need. In my case these are the hosts I need:

192.168.50.4 test.dev
192.168.50.4 vvv.dev
...

Where the 192.168.50.4 is the IP of my Virtual machine and test.dev and vvv.dev are developing hosts.

I hope this can help you :) I'll be happy if you feedback your go.

Some particularities of my case that you may find:

When I ran vagrant up, there was a problem with mysql, it wasn't working. I had to run on the Virtual server (right click on the oracle virtual machine -> Show console): apt-get install mysql-server

After this, I ran again vagrant up and everything was working but without data on the databases. So I did a mysqldump all-tables from the Computer 1 and upload them to Computer 2.

OTHER NOTES: My virtual machine is not exactly on Computer 1 and Computer 2. For example, I made some time ago internal configuration to use NFS (to speed up the server sync folders) and I needed to run again this command on the Computer 2 host: vagrant plugin install vagrant-winnfsd

LINQ Aggregate algorithm explained

In addition to all the great answers here already, I've also used it to walk an item through a series of transformation steps.

If a transformation is implemented as a Func<T,T>, you can add several transformations to a List<Func<T,T>> and use Aggregate to walk an instance of T through each step.

A more concrete example

You want to take a string value, and walk it through a series of text transformations that could be built programatically.

var transformationPipeLine = new List<Func<string, string>>();
transformationPipeLine.Add((input) => input.Trim());
transformationPipeLine.Add((input) => input.Substring(1));
transformationPipeLine.Add((input) => input.Substring(0, input.Length - 1));
transformationPipeLine.Add((input) => input.ToUpper());

var text = "    cat   ";
var output = transformationPipeLine.Aggregate(text, (input, transform)=> transform(input));
Console.WriteLine(output);

This will create a chain of transformations: Remove leading and trailing spaces -> remove first character -> remove last character -> convert to upper-case. Steps in this chain can be added, removed, or reordered as needed, to create whatever kind of transformation pipeline is required.

The end result of this specific pipeline, is that " cat " becomes "A".


This can become very powerful once you realize that T can be anything. This could be used for image transformations, like filters, using BitMap as an example;

Is there a Google Sheets formula to put the name of the sheet into a cell?

Not using script:

I think I've found a stupid workaround using =cell() and a helper sheet. Thus avoiding custom functions and apps script.

=cell("address",[reference]) will provide you with a string reference (i.e. "$A$1") to the address of the cell referred to. Problem is it will not provide the sheet reference unless the cell is in a different sheet!

So:

Solution

where

Helper column in helper sheet

This also works for named sheets. Then by all means adjust to work for your use case.

Source: https://docs.google.com/spreadsheets/d/1_iTD6if3Br6nV5Bn5vd0E0xRCKcXhJLZOQqkuSWvDtE/edit#gid=1898848593

SQL Server equivalent to MySQL enum data type?

IMHO Lookup tables is the way to go, with referential integrity. But only if you avoid "Evil Magic Numbers" by following an example such as this one: Generate enum from a database lookup table using T4

Have Fun!

What special characters must be escaped in regular expressions?

Which characters you must and which you mustn't escape indeed depends on the regex flavor you're working with.

For PCRE, and most other so-called Perl-compatible flavors, escape these outside character classes:

.^$*+?()[{\|

and these inside character classes:

^-]\

For POSIX extended regexes (ERE), escape these outside character classes (same as PCRE):

.^$*+?()[{\|

Escaping any other characters is an error with POSIX ERE.

Inside character classes, the backslash is a literal character in POSIX regular expressions. You cannot use it to escape anything. You have to use "clever placement" if you want to include character class metacharacters as literals. Put the ^ anywhere except at the start, the ] at the start, and the - at the start or the end of the character class to match these literally, e.g.:

[]^-]

In POSIX basic regular expressions (BRE), these are metacharacters that you need to escape to suppress their meaning:

.^$*[\

Escaping parentheses and curly brackets in BREs gives them the special meaning their unescaped versions have in EREs. Some implementations (e.g. GNU) also give special meaning to other characters when escaped, such as \? and +. Escaping a character other than .^$*(){} is normally an error with BREs.

Inside character classes, BREs follow the same rule as EREs.

If all this makes your head spin, grab a copy of RegexBuddy. On the Create tab, click Insert Token, and then Literal. RegexBuddy will add escapes as needed.

How to scale an Image in ImageView to keep the aspect ratio

I have an algorithm to scale a bitmap to bestFit the container dimensions, maintaining its aspect ratio. Please find my solution here

Hope this helps someone down the lane!

WAMP Server ERROR "Forbidden You don't have permission to access /phpmyadmin/ on this server."

I faced this problem

Forbidden You don't have permission to access /phpmyadmin/ on this server

Some help about this:

First check you installed a fresh wamp or replace the existing one. If it's fresh there is no problem, For done existing installation.

Follow these steps.

  1. Open your wamp\bin\mysql directory
  2. Check if in this folder there is another folder of mysql with different name, if exists delete it.
  3. enter to remain mysql folder and delete files with duplication.
  4. start your wamp server again. Wamp will be working.

Convert date to another timezone in JavaScript

there is server issue pick gmt+0000 standard time zone you can change it by using library moment-timezone in javascript

const moment = require("moment-timezone")
const dateNew = new Date()
const changeZone = moment(dateNew);
changeZone.tz("Asia/Karachi").format("ha z");
// here you can paste "your time zone string"

Convert integer to hex and hex to integer

SQL Server equivalents to Excel's string-based DEC2HEX, HEX2DEC functions:

--Convert INT to hex string:
PRINT CONVERT(VARCHAR(8),CONVERT(VARBINARY(4), 16777215),2) --DEC2HEX

--Convert hex string to INT:
PRINT CONVERT(INT,CONVERT(VARBINARY(4),'00FFFFFF',2)) --HEX2DEC

Multiline strings in VB.NET

You could (should?) put the string in a resource-file (e.g. "My Project"/Resources) and then get it with

 Dim a = My.Resources.Whatever_you_chose

Passing HTML to template using Flask/Jinja2

You can also declare it HTML safe from the code:

from flask import Markup
value = Markup('<strong>The HTML String</strong>')

Then pass that value to the templates and they don't have to |safe it.

Rounding float in Ruby

you can use this for rounding to a precison..

//to_f is for float

salary= 2921.9121
puts salary.to_f.round(2) // to 2 decimal place                   

puts salary.to_f.round() // to 3 decimal place          

Convert char array to string use C

Assuming array is a character array that does not end in \0, you will want to use strncpy:

char * strncpy(char * destination, const char * source, size_t num);

like so:

strncpy(string, array, 20);
string[20] = '\0'

Then string will be a null terminated C string, as desired.

Does functional programming replace GoF design patterns?

Brian's comments on the tight linkage between language and pattern is to the point,

The missing part of this discussion is the concept of idiom. James O. Coplien's book, "Advanced C++" was a huge influence here. Long before he discovered Christopher Alexander and the Column Without a Name (and you can't talk sensibly about patterns without reading Alexander either), he talked about the importance of mastering idioms in truly learning a language. He used string copy in C as an example, while(*from++ = *to++); You can see this as a bandaid for a missing language feature (or library feature), but what really matters about it is that it's a larger unit of thought, or of expression, than any of its parts.

That is what patterns, and languages, are trying to do, to allow us to express our intentions more succinctly. The richer the units of thought the more complex the thoughts you can express. Having a rich, shared vocabulary at a range of scales - from system architecture down to bit twiddling - allows us to have more intelligent conversations, and thoughts about what we should be doing.

We can also, as individuals, learn. Which is the entire point of the exercise. We each can understand and use things we would never be able to think of ourselves. Languages, frameworks, libraries, patterns, idioms and so on all have their place in sharing the intellectual wealth.

"Cannot send session cache limiter - headers already sent"

"Headers already sent" means that your PHP script already sent the HTTP headers, and as such it can't make modifications to them now.

Check that you don't send ANY content before calling session_start. Better yet, just make session_start the first thing you do in your PHP file (so put it at the absolute beginning, before all HTML etc).

Install a Nuget package in Visual Studio Code

Example for .csproj file

  <ItemGroup>
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="1.1.2" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="1.1.2" />
    <PackageReference Include="MySql.Data.EntityFrameworkCore" Version="7.0.7-m61" />
  </ItemGroup>

Just get package name and version number from NuGet and add to .csproj then save. You will be prompted to run restore that will import new packages.

Getting "method not valid without suitable object" error when trying to make a HTTP request in VBA?

You probably haven't added a reference to Microsoft XML (any version) for Dim objHTTP As New MSXML2.XMLHTTP in the VBA window's Tools/References... dialog.

Also, it's a good idea to avoid using late binding (CreateObject...); better to use early binding (Dim objHTTP As New MSXML2.XMLHTTP), as early binding allows you to use Intellisense to list the members and do all sorts of design-time validation.

How to clear gradle cache?

Take care with gradle daemon, you have to stop it before clear and re-run gradle.

Stop first daemon:

./gradlew --stop

Clean cache using:

rm -rf ~/.gradle/caches/

Run again you compilation

How to get am pm from the date time string using moment js

You are using the wrong format tokens when parsing your input. You should use ddd for an abbreviation of the name of day of the week, DD for day of the month, MMM for an abbreviation of the month's name, YYYY for the year, hh for the 1-12 hour, mm for minutes and A for AM/PM. See moment(String, String) docs.

Here is a working live sample:

_x000D_
_x000D_
console.log( moment('Mon 03-Jul-2017, 11:00 AM', 'ddd DD-MMM-YYYY, hh:mm A').format('hh:mm A') );_x000D_
console.log( moment('Mon 03-Jul-2017, 11:00 PM', 'ddd DD-MMM-YYYY, hh:mm A').format('hh:mm A') );
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.18.1/moment.min.js"></script>
_x000D_
_x000D_
_x000D_

Changing navigation bar color in Swift

First set the isTranslucent property of navigationBar to false to get the desired colour. Then change the navigationBar colour like this:

@IBOutlet var NavigationBar: UINavigationBar!

NavigationBar.isTranslucent = false
NavigationBar.barTintColor = UIColor (red: 117/255, green: 23/255, blue: 49/255, alpha: 1.0)

What use is find_package() if you need to specify CMAKE_MODULE_PATH anyway?

You don't need to specify the module path per se. CMake ships with its own set of built-in find_package scripts, and their location is in the default CMAKE_MODULE_PATH.

The more normal use case for dependent projects that have been CMakeified would be to use CMake's external_project command and then include the Use[Project].cmake file from the subproject. If you just need the Find[Project].cmake script, copy it out of the subproject and into your own project's source code, and then you won't need to augment the CMAKE_MODULE_PATH in order to find the subproject at the system level.

Python script to convert from UTF-8 to ASCII

data="UTF-8 DATA"
udata=data.decode("utf-8")
asciidata=udata.encode("ascii","ignore")

Auto highlight text in a textbox control

In ASP.NET:

textbox.Attributes.Add("onfocus","this.select();");

Python Request Post with param data

params is for GET-style URL parameters, data is for POST-style body information. It is perfectly legal to provide both types of information in a request, and your request does so too, but you encoded the URL parameters into the URL already.

Your raw post contains JSON data though. requests can handle JSON encoding for you, and it'll set the correct Content-Type header too; all you need to do is pass in the Python object to be encoded as JSON into the json keyword argument.

You could split out the URL parameters as well:

params = {'sessionKey': '9ebbd0b25760557393a43064a92bae539d962103', 'format': 'xml', 'platformId': 1}

then post your data with:

import requests

url = 'http://192.168.3.45:8080/api/v2/event/log'

data = {"eventType": "AAS_PORTAL_START", "data": {"uid": "hfe3hf45huf33545", "aid": "1", "vid": "1"}}
params = {'sessionKey': '9ebbd0b25760557393a43064a92bae539d962103', 'format': 'xml', 'platformId': 1}

requests.post(url, params=params, json=data)

The json keyword is new in requests version 2.4.2; if you still have to use an older version, encode the JSON manually using the json module and post the encoded result as the data key; you will have to explicitly set the Content-Type header in that case:

import requests
import json

headers = {'content-type': 'application/json'}
url = 'http://192.168.3.45:8080/api/v2/event/log'

data = {"eventType": "AAS_PORTAL_START", "data": {"uid": "hfe3hf45huf33545", "aid": "1", "vid": "1"}}
params = {'sessionKey': '9ebbd0b25760557393a43064a92bae539d962103', 'format': 'xml', 'platformId': 1}

requests.post(url, params=params, data=json.dumps(data), headers=headers)

How to change the color of the axis, ticks and labels for a plot in matplotlib

motivated by previous contributors, this is an example of three axes.

import matplotlib.pyplot as plt

x_values1=[1,2,3,4,5]
y_values1=[1,2,2,4,1]

x_values2=[-1000,-800,-600,-400,-200]
y_values2=[10,20,39,40,50]

x_values3=[150,200,250,300,350]
y_values3=[-10,-20,-30,-40,-50]


fig=plt.figure()
ax=fig.add_subplot(111, label="1")
ax2=fig.add_subplot(111, label="2", frame_on=False)
ax3=fig.add_subplot(111, label="3", frame_on=False)

ax.plot(x_values1, y_values1, color="C0")
ax.set_xlabel("x label 1", color="C0")
ax.set_ylabel("y label 1", color="C0")
ax.tick_params(axis='x', colors="C0")
ax.tick_params(axis='y', colors="C0")

ax2.scatter(x_values2, y_values2, color="C1")
ax2.set_xlabel('x label 2', color="C1") 
ax2.xaxis.set_label_position('bottom') # set the position of the second x-axis to bottom
ax2.spines['bottom'].set_position(('outward', 36))
ax2.tick_params(axis='x', colors="C1")
ax2.set_ylabel('y label 2', color="C1")       
ax2.yaxis.tick_right()
ax2.yaxis.set_label_position('right') 
ax2.tick_params(axis='y', colors="C1")

ax3.plot(x_values3, y_values3, color="C2")
ax3.set_xlabel('x label 3', color='C2')
ax3.xaxis.set_label_position('bottom')
ax3.spines['bottom'].set_position(('outward', 72))
ax3.tick_params(axis='x', colors='C2')
ax3.set_ylabel('y label 3', color='C2')
ax3.yaxis.tick_right()
ax3.yaxis.set_label_position('right') 
ax3.spines['right'].set_position(('outward', 36))
ax3.tick_params(axis='y', colors='C2')


plt.show()

How to convert String to DOM Document object in java?

you can try

DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader("<root><node1></node1></root>"));

Document doc = db.parse(is);

refer this http://www.java2s.com/Code/Java/XML/ParseanXMLstringUsingDOMandaStringReader.htm

Add placeholder text inside UITextView in Swift?

Another solution could be to use keyboardWillHide and keyboardWillShow notifications, as I did.

First you need to handle listening, and unlistening to the notifications in the viewWillAppear and viewWillAppear methods respectively (to handle memory leaks).

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    setupKeyboardNotificationListeners(enable: true)
}

override func viewWillDisappear(_ animated: Bool) {
    super.viewWillDisappear(animated)
    setupKeyboardNotificationListeners(enable: false)
}

Then the method to handle listening/unlistening to the notifications:

private func setupKeyboardNotificationListeners(enable: Bool) {
        if enable {
            NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillShow), name: NSNotification.Name.UIKeyboardWillShow, object: nil)
            NotificationCenter.default.addObserver(self, selector: #selector(self.keyboardWillHide), name: NSNotification.Name.UIKeyboardWillHide, object: nil)
        } else {
            NotificationCenter.default.removeObserver(self)
        }
    }

Then in the both methods for keyboardWillHide and keyboardWillShow you handle the placeholder and color changes of the text.

@objc func keyboardWillShow(notification: NSNotification) {
    if self.textView.text == self.placeholder {
        self.textView.text = ""
        self.textView.textColor = .black
    }
}

@objc func keyboardWillHide(notification: NSNotification) {
    if self.textView.text.isEmpty {
        self.textView.text = self.placeholder
        self.textView.textColor = .lightGrey
    }
}

I found this solution to be the best one so far since the text will be removed as soon as the keyboard appears instead of when the user starts typing, which can cause confusion.

What's the difference between next() and nextLine() methods from Scanner class?

I also got a problem concerning a delimiter. the question was all about inputs of

  1. enter your name.
  2. enter your age.
  3. enter your email.
  4. enter your address.

The problem

  1. I finished successfully with name, age, and email.
  2. When I came up with the address of two words having a whitespace (Harnet street) I just got the first one "harnet".

The solution

I used the delimiter for my scanner and went out successful.

Example

 public static void main (String args[]){
     //Initialize the Scanner this way so that it delimits input using a new line character.
    Scanner s = new Scanner(System.in).useDelimiter("\n");
    System.out.println("Enter Your Name: ");
    String name = s.next();
    System.out.println("Enter Your Age: ");
    int age = s.nextInt();
    System.out.println("Enter Your E-mail: ");
    String email = s.next();
    System.out.println("Enter Your Address: ");
    String address = s.next();

    System.out.println("Name: "+name);
    System.out.println("Age: "+age);
    System.out.println("E-mail: "+email);
    System.out.println("Address: "+address);
}

Java String split removed empty values

From String.split() API Doc:

Splits this string around matches of the given regular expression. This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.

Overloaded String.split(regex, int) is more appropriate for your case.

How can I hide an HTML table row <tr> so that it takes up no space?

You need to put the change the input type to hidden, all the functions of it work but it is not visible on the page

<input type="hidden" name="" id="" value="">

as long as the input type is set to that you can change the rest. Good Luck!!

curl: (35) error:1408F10B:SSL routines:ssl3_get_record:wrong version number

* Uses proxy env variable http_proxy == 'https://proxy.in.tum.de:8080'   
                                         ^^^^^

The https:// is wrong, it should be http://. The proxy itself should be accessed by HTTP and not HTTPS even though the target URL is HTTPS. The proxy will nevertheless properly handle HTTPS connection and keep the end-to-end encryption. See HTTP CONNECT method for details how this is done.

Is it possible to indent JavaScript code in Notepad++?

Could you use online services like this ?

Update: (as per request)

Google chrome will do this also http://cristian-radulescu.ro/article/pretty-print-javascript-with-google-chrome.html

Sleep/Wait command in Batch

Ok, yup you use the timeout command to sleep. But to do the whole process silently, it's not possible with cmd/batch. One of the ways is to create a VBScript that will run the Batch File without opening/showing any window. And here is the script:

Set WshShell = CreateObject("WScript.Shell")
WshShell.Run chr(34) & "PATH OF BATCH FILE WITH QUOTATION MARKS" & Chr(34), 0
Set WshShell = Nothing

Copy and paste the above code on notepad and save it as Anyname.**vbs ** An example of the *"PATH OF BATCH FILE WITH QUOTATION MARKS" * might be: "C:\ExampleFolder\MyBatchFile.bat"

ORA-00904: invalid identifier

I was passing the values without the quotes. Once I passed the conditions inside the single quotes worked like a charm.

Select * from emp_table where emp_id=123;

instead of the above use this:

Select * from emp_table where emp_id='123';

Stop jQuery .load response from being cached

Another approach to put the below line only when require to get data from server,Append the below line along with your ajax url.

'?_='+Math.round(Math.random()*10000)

jQuery click / toggle between two functions

DEMO

.one() documentation.

I am very late to answer but i think it's shortest code and might help.

function handler1() {
    alert('First handler: ' + $(this).text());
    $(this).one("click", handler2);
}
function handler2() {
    alert('Second handler: ' + $(this).text());
    $(this).one("click", handler1);
}
$("div").one("click", handler1);

DEMO With Op's Code

function handler1() {
    $(this).animate({
        width: "260px"
    }, 1500);
    $(this).one("click", handler2);
}

function handler2() {
    $(this).animate({
        width: "30px"
    }, 1500);
    $(this).one("click", handler1);
}
$("#time").one("click", handler1);

Can you blur the content beneath/behind a div?

you can do this with css3, this blurs the whole element

div (or whatever element) {
  -webkit-filter: blur(5px);
  -moz-filter: blur(5px);
  -o-filter: blur(5px);
  -ms-filter: blur(5px);
  filter: blur(5px);
}

Fiddle: http://jsfiddle.net/H4DU4/

Jquery, set value of td in a table?

You can try below code:

$("Your button id or class").live("click", function(){

    $('#detailInfo').html('set your value as you want');

});

Good Luck...

How to make my font bold using css?

You can use the CSS declaration font-weight: bold;.

I would advise you to read the CSS beginner guide at http://htmldog.com/guides/cssbeginner/ .

XML shape drawable not rendering desired color

I had a similar problem and found that if you remove the size definition, it works for some reason.

Remove:

<size
    android:width="60dp"
    android:height="40dp" />

from the shape.

Let me know if this works!

How do I add 1 day to an NSDate?

Use following code:

NSDate *now = [NSDate date];
int daysToAdd = 1;
NSDate *newDate1 = [now dateByAddingTimeInterval:60*60*24*daysToAdd];

As

addTimeInterval

is now deprecated.

jQuery Scroll to Div

You can also use 'name' instead of 'href' for a cleaner url:

    $('a[name^=#]').click(function(){
    var target = $(this).attr('name');
    if (target == '#')
      $('html, body').animate({scrollTop : 0}, 600);
    else
      $('html, body').animate({
        scrollTop: $(target).offset().top - 100
    }, 600);
});

How do I access my SSH public key?

In UBUNTU +18.04

         ssh-keygen -o -t rsa -b 4096 -C "[email protected]" 

And After that Just Copy And Paste

         cat ~/.ssh/id_rsa.pub 

or

         cat ~/.ssh/id_dsa.pub

100% height minus header?

If your browser supports CSS3, try using the CSS element Calc()

height: calc(100% - 65px);

you might also want to adding browser compatibility options:

height: -o-calc(100% - 65px); /* opera */
height: -webkit-calc(100% - 65px); /* google, safari */
height: -moz-calc(100% - 65px); /* firefox */

also make sure you have spaces between values, see: https://stackoverflow.com/a/16291105/427622

How can I get client information such as OS and browser

The browser sends this information in the HTTP header. See the snoop example of Tomcat for some code (source, online demo).

Note that this information is not reliable. Browser can and do lie about who they are and what OS they run on.

overlay a smaller image on a larger image python OpenCv

When attempting to write to the destination image using any of these answers above and you get the following error:

ValueError: assignment destination is read-only

A quick potential fix is to set the WRITEABLE flag to true.

img.setflags(write=1)

How can I add shadow to the widget in flutter?

Maybe it is sufficient if you wrap a Card around the Widget and play a bit with the elevation prop.

I use this trick to make my ListTile look nicer in Lists.

For your code it could look like this:

return Card(
   elevation: 3, // PLAY WITH THIS VALUE 
   child: Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      children: <Widget>[
         // ... MORE OF YOUR CODE 
      ],
   ),
);

Safely remove migration In Laravel

I accidentally created two times create_users_table. It overrided some classes and turned rollback into ErrorException.

What you need to do is find autoload_classmap.php in vendor/composer folder and look for the specific line of code such as

'CreateUsersTable' => $baseDir . '/app/database/migrations/2013_07_04_014051_create_users_table.php',

and edit path. Then your rollback should be fine.

Python sum() function with list parameter

numbers = [1, 2, 3]
numsum = sum(list(numbers))
print(numsum)

This would work, if your are trying to Sum up a list.

Add Bean Programmatically to Spring Web App Context

First initialize Property values

MutablePropertyValues mutablePropertyValues = new MutablePropertyValues();
mutablePropertyValues.add("hostName", details.getHostName());
mutablePropertyValues.add("port", details.getPort());

DefaultListableBeanFactory context = new DefaultListableBeanFactory();
GenericBeanDefinition connectionFactory = new GenericBeanDefinition();
connectionFactory.setBeanClass(Class);
connectionFactory.setPropertyValues(mutablePropertyValues);

context.registerBeanDefinition("beanName", connectionFactory);

Add to the list of beans

ConfigurableListableBeanFactory beanFactory = ((ConfigurableApplicationContext) applicationContext).getBeanFactory();
beanFactory.registerSingleton("beanName", context.getBean("beanName"));

How to remove focus from input field in jQuery?

If you have readonly attribute, blur by itself would not work. Contraption below should do the job.

$('#myInputID').removeAttr('readonly').trigger('blur').attr('readonly','readonly');

PDO's query vs execute

Gilean's answer is great, but I just wanted to add that sometimes there are rare exceptions to best practices, and you might want to test your environment both ways to see what will work best.

In one case, I found that query worked faster for my purposes because I was bulk transferring trusted data from an Ubuntu Linux box running PHP7 with the poorly supported Microsoft ODBC driver for MS SQL Server.

I arrived at this question because I had a long running script for an ETL that I was trying to squeeze for speed. It seemed intuitive to me that query could be faster than prepare & execute because it was calling only one function instead of two. The parameter binding operation provides excellent protection, but it might be expensive and possibly avoided if unnecessary.

Given a couple rare conditions:

  1. If you can't reuse a prepared statement because it's not supported by the Microsoft ODBC driver.

  2. If you're not worried about sanitizing input and simple escaping is acceptable. This may be the case because binding certain datatypes isn't supported by the Microsoft ODBC driver.

  3. PDO::lastInsertId is not supported by the Microsoft ODBC driver.

Here's a method I used to test my environment, and hopefully you can replicate it or something better in yours:

To start, I've created a basic table in Microsoft SQL Server

CREATE TABLE performancetest (
    sid INT IDENTITY PRIMARY KEY,
    id INT,
    val VARCHAR(100)
);

And now a basic timed test for performance metrics.

$logs = [];

$test = function (String $type, Int $count = 3000) use ($pdo, &$logs) {
    $start = microtime(true);
    $i = 0;
    while ($i < $count) {
        $sql = "INSERT INTO performancetest (id, val) OUTPUT INSERTED.sid VALUES ($i,'value $i')";
        if ($type === 'query') {
            $smt = $pdo->query($sql);
        } else {
            $smt = $pdo->prepare($sql);
            $smt ->execute();
        }
        $sid = $smt->fetch(PDO::FETCH_ASSOC)['sid'];
        $i++;
    }
    $total = (microtime(true) - $start);
    $logs[$type] []= $total;
    echo "$total $type\n";
};

$trials = 15;
$i = 0;
while ($i < $trials) {
    if (random_int(0,1) === 0) {
        $test('query');
    } else {
        $test('prepare');
    }
    $i++;
}

foreach ($logs as $type => $log) {
    $total = 0;
    foreach ($log as $record) {
        $total += $record;
    }
    $count = count($log);
    echo "($count) $type Average: ".$total/$count.PHP_EOL;
}

I've played with multiple different trial and counts in my specific environment, and consistently get between 20-30% faster results with query than prepare/execute

5.8128969669342 prepare
5.8688418865204 prepare
4.2948560714722 query
4.9533629417419 query
5.9051351547241 prepare
4.332102060318 query
5.9672858715057 prepare
5.0667371749878 query
3.8260300159454 query
4.0791549682617 query
4.3775160312653 query
3.6910600662231 query
5.2708210945129 prepare
6.2671611309052 prepare
7.3791449069977 prepare
(7) prepare Average: 6.0673267160143
(8) query Average: 4.3276024162769

I'm curious to see how this test compares in other environments, like MySQL.

Embed youtube videos that play in fullscreen automatically

This was pretty well answered over here: How to make a YouTube embedded video a full page width one?

If you add '?rel=0&autoplay=1' to the end of the url in the embed code (like this)

<iframe id="video" src="//www.youtube.com/embed/5iiPC-VGFLU?rel=0&autoplay=1" frameborder="0" allowfullscreen></iframe>

of the video it should play on load. Here's a demo over at jsfiddle.

Is PowerShell ready to replace my Cygwin shell on Windows?

I am not a very experienced PowerShell user by any means, but the little bit of it that I was exposed to impressed me a great deal. You can chain the built-in cmdlets together to do just about anything that you could do at a Unix prompt, and there's some additional goodness for doing things like exporting to CSV, HTML tables, and for more in-depth system administration types of jobs.

And if you really needed something like sed, there's always UnixUtils or GnuWin32, which you could integrate with PowerShell fairly easily.

As a longtime Unix user, I did however have a bit of trouble getting used to the command naming scheme, and I certainly would have benefitted more from it if I knew more .NET.

So essentially, I say it's well worth learning it if the Windows-only-ness of it doesn't pose a problem.

Troubleshooting "Warning: session_start(): Cannot send session cache limiter - headers already sent"

For others who may run across this - it can also occur if someone carelessly leaves trailing spaces from a php include file. Example:

 <?php 
    require_once('mylib.php');
    session_start();
 ?>

In the case above, if the mylib.php has blank spaces after its closing ?> tag, this will cause an error. This obviously can get annoying if you've included/required many files. Luckily the error tells you which file is offending.

HTH

CSS values using HTML5 data attribute

There is, indeed, prevision for such feature, look http://www.w3.org/TR/css3-values/#attr-notation

This fiddle should work like what you need, but will not for now.

Unfortunately, it's still a draft, and isn't fully implemented on major browsers.

It does work for content on pseudo-elements, though.

Python - OpenCV - imread - Displaying Image

Looks like the image is too big and the window simply doesn't fit the screen. Create window with the cv2.WINDOW_NORMAL flag, it will make it scalable. Then you can resize it to fit your screen like this:

from __future__ import division
import cv2


img = cv2.imread('1.jpg')

screen_res = 1280, 720
scale_width = screen_res[0] / img.shape[1]
scale_height = screen_res[1] / img.shape[0]
scale = min(scale_width, scale_height)
window_width = int(img.shape[1] * scale)
window_height = int(img.shape[0] * scale)

cv2.namedWindow('dst_rt', cv2.WINDOW_NORMAL)
cv2.resizeWindow('dst_rt', window_width, window_height)

cv2.imshow('dst_rt', img)
cv2.waitKey(0)
cv2.destroyAllWindows()

According to the OpenCV documentation CV_WINDOW_KEEPRATIO flag should do the same, yet it doesn't and it's value not even presented in the python module.

How to redirect both stdout and stderr to a file

The simplest syntax to redirect both is:

command &> logfile

If you want to append to the file instead of overwrite:

command &>> logfile

Object of class stdClass could not be converted to string - laravel

You might need to change your object to an array first. I dont know what export does, but I assume its expecting an array.

You can either use

get_object_vars()

Or if its a simple object, you can just typecast it.

$arr = (array) $Object;

What is the syntax to insert one list into another list in python?

If you want to add the elements in a list (list2) to the end of other list (list), then you can use the list extend method

list = [1, 2, 3]
list2 = [4, 5, 6]
list.extend(list2)
print list
[1, 2, 3, 4, 5, 6]

Or if you want to concatenate two list then you can use + sign

list3 = list + list2
print list3
[1, 2, 3, 4, 5, 6]

HTML5 File API read as text and binary

Note in 2018: readAsBinaryString is outdated. For use cases where previously you'd have used it, these days you'd use readAsArrayBuffer (or in some cases, readAsDataURL) instead.


readAsBinaryString says that the data must be represented as a binary string, where:

...every byte is represented by an integer in the range [0..255].

JavaScript originally didn't have a "binary" type (until ECMAScript 5's WebGL support of Typed Array* (details below) -- it has been superseded by ECMAScript 2015's ArrayBuffer) and so they went with a String with the guarantee that no character stored in the String would be outside the range 0..255. (They could have gone with an array of Numbers instead, but they didn't; perhaps large Strings are more memory-efficient than large arrays of Numbers, since Numbers are floating-point.)

If you're reading a file that's mostly text in a western script (mostly English, for instance), then that string is going to look a lot like text. If you read a file with Unicode characters in it, you should notice a difference, since JavaScript strings are UTF-16** (details below) and so some characters will have values above 255, whereas a "binary string" according to the File API spec wouldn't have any values above 255 (you'd have two individual "characters" for the two bytes of the Unicode code point).

If you're reading a file that's not text at all (an image, perhaps), you'll probably still get a very similar result between readAsText and readAsBinaryString, but with readAsBinaryString you know that there won't be any attempt to interpret multi-byte sequences as characters. You don't know that if you use readAsText, because readAsText will use an encoding determination to try to figure out what the file's encoding is and then map it to JavaScript's UTF-16 strings.

You can see the effect if you create a file and store it in something other than ASCII or UTF-8. (In Windows you can do this via Notepad; the "Save As" as an encoding drop-down with "Unicode" on it, by which looking at the data they seem to mean UTF-16; I'm sure Mac OS and *nix editors have a similar feature.) Here's a page that dumps the result of reading a file both ways:

<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-type" content="text/html;charset=UTF-8">
<title>Show File Data</title>
<style type='text/css'>
body {
    font-family: sans-serif;
}
</style>
<script type='text/javascript'>

    function loadFile() {
        var input, file, fr;

        if (typeof window.FileReader !== 'function') {
            bodyAppend("p", "The file API isn't supported on this browser yet.");
            return;
        }

        input = document.getElementById('fileinput');
        if (!input) {
            bodyAppend("p", "Um, couldn't find the fileinput element.");
        }
        else if (!input.files) {
            bodyAppend("p", "This browser doesn't seem to support the `files` property of file inputs.");
        }
        else if (!input.files[0]) {
            bodyAppend("p", "Please select a file before clicking 'Load'");
        }
        else {
            file = input.files[0];
            fr = new FileReader();
            fr.onload = receivedText;
            fr.readAsText(file);
        }

        function receivedText() {
            showResult(fr, "Text");

            fr = new FileReader();
            fr.onload = receivedBinary;
            fr.readAsBinaryString(file);
        }

        function receivedBinary() {
            showResult(fr, "Binary");
        }
    }

    function showResult(fr, label) {
        var markup, result, n, aByte, byteStr;

        markup = [];
        result = fr.result;
        for (n = 0; n < result.length; ++n) {
            aByte = result.charCodeAt(n);
            byteStr = aByte.toString(16);
            if (byteStr.length < 2) {
                byteStr = "0" + byteStr;
            }
            markup.push(byteStr);
        }
        bodyAppend("p", label + " (" + result.length + "):");
        bodyAppend("pre", markup.join(" "));
    }

    function bodyAppend(tagName, innerHTML) {
        var elm;

        elm = document.createElement(tagName);
        elm.innerHTML = innerHTML;
        document.body.appendChild(elm);
    }

</script>
</head>
<body>
<form action='#' onsubmit="return false;">
<input type='file' id='fileinput'>
<input type='button' id='btnLoad' value='Load' onclick='loadFile();'>
</form>
</body>
</html>

If I use that with a "Testing 1 2 3" file stored in UTF-16, here are the results I get:

Text (13):

54 65 73 74 69 6e 67 20 31 20 32 20 33

Binary (28):

ff fe 54 00 65 00 73 00 74 00 69 00 6e 00 67 00 20 00 31 00 20 00 32 00 20 00 33 00

As you can see, readAsText interpreted the characters and so I got 13 (the length of "Testing 1 2 3"), and readAsBinaryString didn't, and so I got 28 (the two-byte BOM plus two bytes for each character).


* XMLHttpRequest.response with responseType = "arraybuffer" is supported in HTML 5.

** "JavaScript strings are UTF-16" may seem like an odd statement; aren't they just Unicode? No, a JavaScript string is a series of UTF-16 code units; you see surrogate pairs as two individual JavaScript "characters" even though, in fact, the surrogate pair as a whole is just one character. See the link for details.

How Should I Set Default Python Version In Windows?

The Python installer installs Python Launcher for Windows. This program (py.exe) is associated with the Python file extensions and looks for a "shebang" comment to specify the python version to run. This allows many versions of Python to co-exist and allows Python scripts to explicitly specify which version to use, if desired. If it is not specified, the default is to use the latest Python version for the current architecture (x86 or x64). This default can be customized through a py.ini file or PY_PYTHON environment variable. See the docs for more details.

Newer versions of Python update the launcher. The latest version has a py -0 option to list the installed Pythons and indicate the current default.

Here's how to check if the launcher is registered correctly from the console:

C:\>assoc .py
.py=Python.File

C:\>ftype Python.File
Python.File="C:\Windows\py.exe" "%1" %*

Above, .py files are associated with the Python.File type. The command line for Python.File is the Python Launcher, which is installed in the Windows directory since it is always in the PATH.

For the association to work, run scripts from the command line with script.py, not "python script.py", otherwise python will be run instead of py. If fact it's best to remove Python directories from the PATH, so "python" won't run anything and enforce using py.

py.exe can also be run with switches to force a Python version:

py -3 script.py       # select latest Python 3.X version to be used.
py -3.6 script.py     # select version 3.6 specifically.
py -3.9-32 script.py  # select version 3.9 32-bit specifically.
py -0                 # list installed Python versions (latest PyLauncher).

Additionally, add .py;.pyw;.pyc;.pyo to the PATHEXT environment variable and then the command line can just be script with no extension.

$(window).width() not the same as media query

What i do ;

<body>
<script>
function getWidth(){
return Math.max(document.body.scrollWidth,
document.documentElement.scrollWidth,
document.body.offsetWidth,
document.documentElement.offsetWidth,
document.documentElement.clientWidth);
}
var aWidth=getWidth();
</script>
...

and call aWidth variable anywhere afterwards.

You need to put the getWidth() up in your document body to make sure that the scrollbar width is counted, else scrollbar width of the browser subtracted from getWidth().

Error in launching AVD with AMD processor

While creating a Virtual Device select the ARM system Image. Others have suggested to install HAXM, but the truth is haxm wont work on amd platform or even if it does as android studio does not supports amd-vt on windows the end result will still be a very very slow emulator to run and operate. My recommendation would be to either use alternative emulator like Genymotion (works like a charm with Gapps installed) or switch to linux as then you will get the benefit of amd-vt and emulator will run a lot faster.

How do I properly set the permgen size?

Don't put the environment configuration in catalina.bat/catalina.sh. Instead you should create a new file in CATALINA_BASE\bin\setenv.bat to keep your customizations separate of tomcat installation.

jQuery check if an input is type checkbox?

>>> a=$("#communitymode")[0]
<input id="communitymode" type="checkbox" name="communitymode">
>>> a.type
"checkbox"

Or, more of the style of jQuery:

$("#myinput").attr('type') == 'checkbox'

Contain an image within a div?

  <div id ="container">
    <img src = "http://animalia-life.com/data_images/duck/duck9.jpg"/>
#container img {
        max-width:250px;
        max-height:250px;
        width: 250px;
        height: 250px;
        border:1px solid #000;
    }

The img will lose aspect ratio

What are rvalues, lvalues, xvalues, glvalues, and prvalues?

One addendum to the excellent answers above, on a point that confused me even after I had read Stroustrup and thought I understood the rvalue/lvalue distinction. When you see

int&& a = 3,

it's very tempting to read the int&& as a type and conclude that a is an rvalue. It's not:

int&& a = 3;
int&& c = a; //error: cannot bind 'int' lvalue to 'int&&'
int& b = a; //compiles

a has a name and is ipso facto an lvalue. Don't think of the && as part of the type of a; it's just something telling you what a is allowed to bind to.

This matters particularly for T&& type arguments in constructors. If you write

Foo::Foo(T&& _t) : t{_t} {}

you will copy _t into t. You need

Foo::Foo(T&& _t) : t{std::move(_t)} {} if you want to move. Would that my compiler warned me when I left out the move!

How to set transparent background for Image Button in code?

Try like this

ImageButton imagetrans=(ImageButton)findViewById(R.id.ImagevieID);

imagetrans.setBackgroundColor(Color.TRANSPARENT);

OR

include this in your .xml file in res/layout

android:background="@android:color/transparent 

JQuery confirm dialog

You can use jQuery UI and do something like this

Html:

<button id="callConfirm">Confirm!</button>

<div id="dialog" title="Confirmation Required">
  Are you sure about this?
</div>?

Javascript:

$("#dialog").dialog({
   autoOpen: false,
   modal: true,
   buttons : {
        "Confirm" : function() {
            alert("You have confirmed!");            
        },
        "Cancel" : function() {
          $(this).dialog("close");
        }
      }
    });

$("#callConfirm").on("click", function(e) {
    e.preventDefault();
    $("#dialog").dialog("open");
});

?

Width of input type=text element

I think you are forgetting about the border. Having a one-pixel-wide border on the Div will take away two pixels of total length. Therefore it will appear as though the div is two pixels shorter than it actually is.

Angular 2: 404 error occur when I refresh through the browser

For people reading this that use Angular 2 rc4 or later, it appears LocationStrategy has been moved from router to common. You'll have to import it from there.

Also note the curly brackets around the 'provide' line.

main.ts

// Imports for loading & configuring the in-memory web api
import { XHRBackend } from '@angular/http';

// The usual bootstrapping imports
import { bootstrap }      from '@angular/platform-browser-dynamic';
import { HTTP_PROVIDERS } from '@angular/http';

import { AppComponent }         from './app.component';
import { APP_ROUTER_PROVIDERS } from './app.routes';
import { Location, LocationStrategy, HashLocationStrategy} from '@angular/common';

bootstrap(AppComponent, [
    APP_ROUTER_PROVIDERS,
    HTTP_PROVIDERS,
    {provide: LocationStrategy, useClass: HashLocationStrategy}
]);

global variable for all controller and views

At first, a config file is appropriate for this kind of things but you may also use another approach, which is as given below (Laravel - 4):

// You can keep this in your filters.php file
App::before(function($request) {
    App::singleton('site_settings', function(){
        return Setting::all();
    });

    // If you use this line of code then it'll be available in any view
    // as $site_settings but you may also use app('site_settings') as well
    View::share('site_settings', app('site_settings'));
});

To get the same data in any controller you may use:

$site_settings = app('site_settings');

There are many ways, just use one or another, which one you prefer but I'm using the Container.

How to change permissions for a folder and its subfolders/files in one step?

You want to make sure that appropriate files and directories are chmod-ed/permissions for those are appropriate. For all directories you want

find /opt/lampp/htdocs -type d -exec chmod 711 {} \;

And for all the images, JavaScript, CSS, HTML...well, you shouldn't execute them. So use

chmod 644 img/* js/* html/*

But for all the logic code (for instance PHP code), you should set permissions such that the user can't see that code:

chmod 600 file

Update ViewPager dynamically?

I know am late for the Party. I've fixed the problem by calling TabLayout#setupWithViewPager(myViewPager); just after FragmentPagerAdapter#notifyDataSetChanged();

How to check for empty array in vba macro

Public Function IsEmptyArray(InputArray As Variant) As Boolean

   On Error GoTo ErrHandler:
   IsEmptyArray = Not (UBound(InputArray) >= 0)
   Exit Function

   ErrHandler:
   IsEmptyArray = True

End Function

Does C++ support 'finally' blocks? (And what's this 'RAII' I keep hearing about?)

I also think that RIIA is not a fully useful replacement for exception handling and having a finally. BTW, I also think RIIA is a bad name all around. I call these types of classes 'janitors' and use them a LOT. 95% of the time they are neither initializing nor acquiring resources, they are applying some change on a scoped basis, or taking something already set up and making sure it's destroyed. This being the official pattern name obsessed internet I get abused for even suggesting my name might be better.

I just don't think it's reasonable to require that that every complicated setup of some ad hoc list of things has to have a class written to contain it in order to avoid complications when cleaning it all back up in the face of needing to catch multiple exception types if something goes wrong in the process. This would lead to lots of ad hoc classes that just wouldn't be necessary otherwise.

Yes it's fine for classes that are designed to manage a particular resource, or generic ones that are designed to handle a set of similar resources. But, even if all of the things involved have such wrappers, the coordination of cleanup may not just be a simple in reverse order invocation of destructors.

I think it makes perfect sense for C++ to have a finally. I mean, jeez, so many bits and bobs have been glued onto it over the last decades that it seems odd folks would suddenly become conservative over something like finally which could be quite useful and probably nothing near as complicated as some other things that have been added (though that's just a guess on my part.)

Dialogs / AlertDialogs: How to "block execution" while dialog is up (.NET-style)

UserSelect =null

AlertDialog.Builder builder = new Builder(ImonaAndroidApp.LoginScreen);
            builder.setMessage("you message");
            builder.setPositiveButton("OK", new OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    UserSelect = true ;

                }
            });

            builder.setNegativeButton("Cancel", new OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    UserSelect = false ;

                }
            });
           // in UI thread
        builder.show();             
        // wait until the user select
            while(UserSelect ==null);

Update rows in one table with data from another table based on one column in each being equal

update 
  table1 t1
set
  (
    t1.column1, 
    t1.column2
      ) = (
    select
      t2.column1, 
      t2.column2
    from
      table2  t2
    where
      t2.column1 = t1.column1
     )
    where exists (
      select 
        null
      from 
        table2 t2
      where 
        t2.column1 = t1.column1
      );

Or this (if t2.column1 <=> t1.column1 are many to one and anyone of them is good):

update 
  table1 t1
set
  (
    t1.column1, 
    t1.column2
      ) = (
    select
      t2.column1, 
      t2.column2
    from
      table2  t2
    where
      t2.column1 = t1.column1
    and
      rownum = 1    
     )
    where exists (
      select 
        null
      from 
        table2 t2
      where 
        t2.column1 = t1.column1
      ); 

How to call a asp:Button OnClick event using JavaScript?

Set style= "display:none;". By setting visible=false, it will not render button in the browser. Thus,client side script wont execute.

<asp:Button ID="savebtn" runat="server" OnClick="savebtn_Click" style="display:none" />

html markup should be

<button id="btnsave" onclick="fncsave()">Save</button>

Change javascript to

<script type="text/javascript">
     function fncsave()
     {
        document.getElementById('<%= savebtn.ClientID %>').click();
     }
</script>

How would you make two <div>s overlap?

I might approach it like so (CSS and HTML):

_x000D_
_x000D_
html,_x000D_
body {_x000D_
  margin: 0px;_x000D_
}_x000D_
#logo {_x000D_
  position: absolute; /* Reposition logo from the natural layout */_x000D_
  left: 75px;_x000D_
  top: 0px;_x000D_
  width: 300px;_x000D_
  height: 200px;_x000D_
  z-index: 2;_x000D_
}_x000D_
#content {_x000D_
  margin-top: 100px; /* Provide buffer for logo */_x000D_
}_x000D_
#links {_x000D_
  height: 75px;_x000D_
  margin-left: 400px; /* Flush links (with a 25px "padding") right of logo */_x000D_
}
_x000D_
<div id="logo">_x000D_
  <img src="https://via.placeholder.com/200x100" />_x000D_
</div>_x000D_
<div id="content">_x000D_
  _x000D_
  <div id="links">dssdfsdfsdfsdf</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How can I add a key/value pair to a JavaScript object?

In order to prepend a key-value pair to an object so the for in works with that element first do this:

    var nwrow = {'newkey': 'value' };
    for(var column in row){
        nwrow[column] = row[column];
    }
    row = nwrow;

How to write log to file

I usually print the logs on screen and write into a file as well. Hope this helps someone.

f, err := os.OpenFile("/tmp/orders.log", os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
if err != nil {
    log.Fatalf("error opening file: %v", err)
}
defer f.Close()
wrt := io.MultiWriter(os.Stdout, f)
log.SetOutput(wrt)
log.Println(" Orders API Called")

NoSuchMethodError in javax.persistence.Table.indexes()[Ljavax/persistence/Index

There are multiple JPA providers in your classpath. Or atleast in your Application server lib folder.

If you are using Maven Check for dependencies using command mentioned here https://stackoverflow.com/a/47474708/3333878

Then fix by removing/excluding unwanted dependency.

If you just have one dependecy in your classpath, then the application server's class loader might be the issue.

As JavaEE application servers like Websphere, Wildfly, Tomee etc., have their own implementations of JPA and other EE Standards, The Class loader might load it's own implementation instead of picking from your classpath in WAR/EAR file.

To avoid this, you can try below steps.

  1. Removing the offending jar in Application Servers library path. Proceed with Caution, as it might break other hosted applications.

In Tomee 1.7.5 Plume/ Web it will have bundled eclipselink-2.4.2 in the lib folder using JPA 2.0, but I had to use JPA 2.1 from org.hibernate:hibernate-core:5.1.17, so removed the eclipselink jar and added all related/ transitive dependencies from hibernate core.

  1. Add a shared library. and manually add jars to the app server's path. Websphere has this option.

  2. In Websphere, execution of class loader can be changed. so making it the application server's classpath to load last i.e, parent last and having your path load first. Can solve this.

Check if your appserver has above features, before proceeding with first point.

Ibm websphere References :

https://www.ibm.com/support/knowledgecenter/SSEQTP_9.0.5/com.ibm.websphere.base.doc/ae/trun_classload_server.html

https://www.ibm.com/support/pages/how-create-shared-library-and-associate-it-application-server-or-enterprise-application-websphere-application-server

Android: Expand/collapse animation

Here are two simple kotlin extension functions over view.

fun View.expand() {
    visibility = View.VISIBLE
    val animate = TranslateAnimation(0f, 0f, -height.toFloat(), 0f)
    animate.duration = 200
    animate.fillAfter = true
    startAnimation(animate)
}

fun View.collapse() {
    val animate = TranslateAnimation(0f, 0f, 0f, -height.toFloat() )
    animate.duration = 200
    animate.fillAfter = true
    startAnimation(animate)
}

Left align and right align within div in Bootstrap

We can achieve by Bootstrap 4 Flexbox:

<div class="d-flex justify-content-between w-100">
<p>TotalCost</p> <p>$42</p>
</div>

d-flex // Display Flex
justify-content-between // justify-content:space-between
w-100 // width:100%

Example: JSFiddle

Ruby: character to ascii from a string

The c variable already contains the char code!

"string".each_byte do |c|
    puts c
end

yields

115
116
114
105
110
103

In SQL Server, how do I generate a CREATE TABLE statement for a given table?

A query based on Hubbitus answer.

  • includes schema names
  • fixes foreign keys with more than one field
  • includes CASCADE UPDATE & DELETE
  • includes a conditioned DROP TABLE
SELECT 
  Schema_Name = SCHEMA_NAME(obj.uid)
, Table_Name = name
, Drop_Table = 'IF (EXISTS (SELECT * FROM INFORMATION_SCHEMA.TABLES  WHERE TABLE_SCHEMA = ''' + SCHEMA_NAME(obj.uid) + '''  AND  TABLE_NAME = ''' + obj.name + '''))
DROP TABLE [' + SCHEMA_NAME(obj.uid) + '].[' + obj.name + '] '
, Create_Table ='
CREATE TABLE [' + SCHEMA_NAME(obj.uid) + '].[' + obj.name + '] (' + LEFT(cols.list, LEN(cols.list) - 1 ) + ')' + ISNULL(' ' + refs.list, '')
    FROM sysobjects obj
    CROSS APPLY (
        SELECT 
            CHAR(10)
            + ' [' + column_name + '] '
            + data_type
            + CASE data_type
                WHEN 'sql_variant' THEN ''
                WHEN 'text' THEN ''
                WHEN 'ntext' THEN ''
                WHEN 'xml' THEN ''
                WHEN 'decimal' THEN '(' + CAST(numeric_precision as VARCHAR) + ', ' + CAST(numeric_scale as VARCHAR) + ')'
                ELSE COALESCE('(' + CASE WHEN character_maximum_length = -1 THEN 'MAX' ELSE CAST(character_maximum_length as VARCHAR) END + ')', '')
            END
            + ' '
            + case when exists ( -- Identity skip
                                select id from syscolumns
                                where id = obj.id
                                and name = column_name
                                and columnproperty(id, name, 'IsIdentity') = 1 
                                ) then
                        'IDENTITY(' + 
                            cast(ident_seed(obj.name) as varchar) + ',' + 
                            cast(ident_incr(obj.name) as varchar) + ')'
            else ''
            end + ' '
            + CASE WHEN IS_NULLABLE = 'No' THEN 'NOT ' ELSE '' END
            + 'NULL'
            + CASE WHEN IC.column_default IS NOT NULL THEN ' DEFAULT ' + IC.column_default ELSE '' END
            + ','
        FROM INFORMATION_SCHEMA.COLUMNS IC
        WHERE IC.table_name   = obj.name
          AND IC.TABLE_SCHEMA = SCHEMA_NAME(obj.uid)
        ORDER BY ordinal_position
        FOR XML PATH('')
    ) cols (list)
    CROSS APPLY(
        SELECT
            CHAR(10) + 'ALTER TABLE [' + SCHEMA_NAME(obj.uid) + '].[' + obj.name + '] ADD ' + LEFT(alt, LEN(alt)-1)
        FROM(
            SELECT
                CHAR(10)
                + ' CONSTRAINT ' + tc.constraint_name
                + ' ' + tc.constraint_type + ' (' + LEFT(c.list, LEN(c.list)-1) + ')'
                + COALESCE(CHAR(10) + r.list, ', ')
            FROM information_schema.table_constraints tc
                CROSS APPLY(
                    SELECT   '[' + kcu.column_name + '], '
                    FROM     information_schema.key_column_usage kcu
                    WHERE    kcu.constraint_name = tc.constraint_name
                    ORDER BY kcu.ordinal_position
                    FOR XML PATH('')
                ) c (list)
                OUTER APPLY(
                    -- // http://stackoverflow.com/questions/3907879/sql-server-howto-get-foreign-key-reference-from-information-schema
                    SELECT LEFT(f.list, LEN(f.list)-1) + ')' + IIF(rc.DELETE_RULE = 'NO ACTION', '', ' ON DELETE ' + rc.DELETE_RULE) + IIF(rc.UPDATE_RULE = 'NO ACTION', '', ' ON UPDATE ' + rc.UPDATE_RULE) + ', '
                    FROM information_schema.referential_constraints rc
                    CROSS APPLY(
                        SELECT IIF(kcu.ordinal_position = 1, ' REFERENCES [' + kcu.table_schema + '].[' + kcu.table_name + '] (', '') 
                                + '[' + kcu.column_name + '], '
                        FROM information_schema.key_column_usage kcu 
                        WHERE kcu.constraint_catalog = rc.unique_constraint_catalog AND kcu.constraint_schema = rc.unique_constraint_schema AND kcu.constraint_name = rc.unique_constraint_name
                        ORDER BY kcu.ordinal_position
                        FOR XML PATH('')
                    ) f (list)
                    WHERE rc.constraint_catalog = tc.constraint_catalog 
                      AND rc.constraint_schema  = tc.constraint_schema 
                      AND rc.constraint_name    = tc.constraint_name
                ) r (list)
            WHERE tc.table_name = obj.name
            FOR XML PATH('')
        ) a (alt)
    ) refs (list)
    WHERE xtype = 'U'

To combine drop table (if exists) with create use like this:

SELECT Drop_Table + CHAR(10) + Create_Table FROM SysCreateTables

Which characters make a URL invalid?

In your supplementary question you asked if www.example.com/file[/].html is a valid URL.

That URL isn't valid because a URL is a type of URI and a valid URI must have a scheme like http: (see RFC 3986).

If you meant to ask if http://www.example.com/file[/].html is a valid URL then the answer is still no because the square bracket characters aren't valid there.

The square bracket characters are reserved for URLs in this format: http://[2001:db8:85a3::8a2e:370:7334]/foo/bar (i.e. an IPv6 literal instead of a host name)

It's worth reading RFC 3986 carefully if you want to understand the issue fully.

Correct way to add external jars (lib/*.jar) to an IntelliJ IDEA project

If you are building your project with gradle, you just need to add one line to the dependencies in the build.gradle:

buildscript {
    ...
}
...

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
}

and then add the folder to your root project or module:

enter image description here

Then you drop your jars in there and you are good to go :-)

How to get client IP address in Laravel 5+

When we want the user's ip_address:

$_SERVER['REMOTE_ADDR']

and want to server address:

$_SERVER['SERVER_ADDR']

Detecting superfluous #includes in C/C++?

CLion, the C/C++ IDE from JetBrains, detects redundant includes out-of-the-box. These are grayed-out in the editor, but there are also functions to optimise includes in the current file or whole project.

I've found that you pay for this functionality though; CLion takes a while to scan and analyse your project when first loaded.

How to paste text to end of every line? Sublime 2

Here's the workflow I use all the time, using the keyboard only

  1. Ctrl/Cmd + A Select All
  2. Ctrl/Cmd + Shift + L Split into Lines
  3. ' Surround every line with quotes

Note that this doesn't work if there are blank lines in the selection.

Root password inside a Docker container

try the following command to get the root access

$ sudo -i 

Get IFrame's document, from JavaScript in main document

In case you get a cross-domain error:

If you have control over the content of the iframe - that is, if it is merely loaded in a cross-origin setup such as on Amazon Mechanical Turk - you can circumvent this problem with the <body onload='my_func(my_arg)'> attribute for the inner html.

For example, for the inner html, use the this html parameter (yes - this is defined and it refers to the parent window of the inner body element):

<body onload='changeForm(this)'>

In the inner html :

    function changeForm(window) {
        console.log('inner window loaded: do whatever you want with the inner html');
        window.document.getElementById('mturk_form').style.display = 'none';
    </script>

Disabling Chrome Autofill

Jan 20 chrome update

None of the solutions above, including adding fake fields or setting autocomplete=new-password works. Yes with these chrome will not autocomplete but when you enter the password field it will suggest the password again.

I found that if you remove the password field and then add it again without an id then chrome does not autofill it and does not suggest the password on entry.

Use a class to get get the password value instead of an id.

For firefox there is still a need to add a dummy element.

This solution also allows allowing/forbidding autocomplete based on a flag:

html:

<!-- form is initially hidden, password field has a dummy id and a class 'id' -->
<form id="loginForm" style="display:none;">
   <span>email:</span><input type="text" placeholder="Email" id="loginEmailInputID"/>
   <span>Password:</span><input class="loginPasswordInput" type="password" placeholder="Password" id="justForAutocomplete"/>
</form>

page load:

function hideAutoComplete(formId) {
    let passwordElem=$('#'+formId+' input:password'), prev=passwordElem.prev();
    passwordElem.remove();
    prev.after($('<input type="password" style="display:none">'), passwordElem.clone().val('').removeAttr('id'));
}

if (!allowAutoComplete) hideAutoComplete('loginForm');
$('#loginForm').show();

when you need the password:

$('.loginPasswordInput').val();

Converting dd/mm/yyyy formatted string to Datetime

You need to use DateTime.ParseExact with format "dd/MM/yyyy"

DateTime dt=DateTime.ParseExact("24/01/2013", "dd/MM/yyyy", CultureInfo.InvariantCulture);

Its safer if you use d/M/yyyy for the format, since that will handle both single digit and double digits day/month. But that really depends if you are expecting single/double digit values.


Your date format day/Month/Year might be an acceptable date format for some cultures. For example for Canadian Culture en-CA DateTime.Parse would work like:

DateTime dt = DateTime.Parse("24/01/2013", new CultureInfo("en-CA"));

Or

System.Threading.Thread.CurrentThread.CurrentCulture = new CultureInfo("en-CA");
DateTime dt = DateTime.Parse("24/01/2013"); //uses the current Thread's culture

Both the above lines would work because the the string's format is acceptable for en-CA culture. Since you are not supplying any culture to your DateTime.Parse call, your current culture is used for parsing which doesn't support the date format. Read more about it at DateTime.Parse.


Another method for parsing is using DateTime.TryParseExact

DateTime dt;
if (DateTime.TryParseExact("24/01/2013", 
                            "d/M/yyyy", 
                            CultureInfo.InvariantCulture, 
                            DateTimeStyles.None,
    out dt))
{
    //valid date
}
else
{
    //invalid date
}

The TryParse group of methods in .Net framework doesn't throw exception on invalid values, instead they return a bool value indicating success or failure in parsing.

Notice that I have used single d and M for day and month respectively. Single d and M works for both single/double digits day and month. So for the format d/M/yyyy valid values could be:

  • "24/01/2013"
  • "24/1/2013"
  • "4/12/2013" //4 December 2013
  • "04/12/2013"

For further reading you should see: Custom Date and Time Format Strings

"make clean" results in "No rule to make target `clean'"

You have fallen victim to the most common of errors in Makefiles. You always need to put a Tab at the beginning of each command. You've put spaces before the $(CC) $(CFLAGS) -o $@ $^ $(LDFLAGS) and @rm -f $(PROGRAMS) *.o core lines. If you replace them with a Tab, you'll be fine.

However, this error doesn't lead to a "No rule to make target ..." error. That probably means your issue lies beyond your Makefile. Have you checked this is the correct Makefile, as in the one you want to be specifying your commands? Try explicitly passing it as a parameter to make, make -f Makefile and let us know what happens.

Java Loop every minute

If you are using a SpringBoot application it's as simple as

ScheduledProcess

@Log
@Component
public class ScheduledProcess {

    @Scheduled(fixedRate = 5000)
    public void run() {
        log.info("this runs every 5 seconds..");
    }

}

Application.class

@SpringBootApplication
// ADD THIS ANNOTATION TO YOUR APPLICATION CLASS
@EnableScheduling
public class SchedulingTasksApplication {

    public static void main(String[] args) {
        SpringApplication.run(SchedulingTasksApplication.class);
    }
}

How can I use console logging in Internet Explorer?

For IE8 or console support limited to console.log (no debug, trace, ...) you can do the following:

  • If console OR console.log undefined: Create dummy functions for console functions (trace, debug, log, ...)

    window.console = { debug : function() {}, ...};

  • Else if console.log is defined (IE8) AND console.debug (any other) is not defined: redirect all logging functions to console.log, this allows to keep those logs !

    window.console = { debug : window.console.log, ...};

Not sure about the assert support in various IE versions, but any suggestions are welcome.

How do I create a MongoDB dump of my database?

use "path" for windows else it gives the error as: positional arguments not allowed

os.walk without digging into directories below

Use the walklevel function.

import os

def walklevel(some_dir, level=1):
    some_dir = some_dir.rstrip(os.path.sep)
    assert os.path.isdir(some_dir)
    num_sep = some_dir.count(os.path.sep)
    for root, dirs, files in os.walk(some_dir):
        yield root, dirs, files
        num_sep_this = root.count(os.path.sep)
        if num_sep + level <= num_sep_this:
            del dirs[:]

It works just like os.walk, but you can pass it a level parameter that indicates how deep the recursion will go.

Numpy - add row to array

You can use numpy.append() to append a row to numpty array and reshape to a matrix later on.

import numpy as np
a = np.array([1,2])
a = np.append(a, [3,4])
print a
# [1,2,3,4]
# in your example
A = [1,2]
for row in X:
    A = np.append(A, row)

How do you get the length of a string?

You don't need jquery, just use yourstring.length. See reference here and also here.

Update:

To support unicode strings, length need to be computed as following:

[...""].length

or create an auxiliary function

function uniLen(s) {
    return [...s].length
}

Remove #N/A in vlookup result

To avoid errors in any excel function, use the Error Handling functions that start with IS* in Excel. Embed your function with these error handing functions and avoid the undesirable text in your results. More info in OfficeTricks Page

The target principal name is incorrect. Cannot generate SSPI context

Just to add another potential solution to this most ambiguous of errors The target principal name is incorrect. Cannot generate SSPI context. (.Net SqlClient Data Provider) :

Verify that the IP that is resolved when pinging the SQL Server is the same as the one in the Configuration Manager. To check, open SQL Server Configuration Manager and then go to SQL Server Network Configuration > Protocols for MSSQLServer > TCP/IP.

Make sure TCP/IP is enabled and in the IP Addresses tab, make sure that the IP that the server resolves to when pinging is the same one here. That fixed this error for me.

Get folder name from full file path

You could use this:

string path = @"c:\projects\roott\wsdlproj\devlop\beta2\text";
string lastDirectory = path.Split(new char[] { System.IO.Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries).Last();

Using HttpClient and HttpPost in Android with post parameters

I've just checked and i have the same code as you and it works perferctly. The only difference is how i fill my List for the params :

I use a : ArrayList<BasicNameValuePair> params

and fill it this way :

 params.add(new BasicNameValuePair("apikey", apikey);

I do not use any JSONObject to send params to the webservices.

Are you obliged to use the JSONObject ?

Align contents inside a div

text-align aligns text and other inline content. It doesn't align block element children.

To do that, you want to give the element you want aligned a width, with ‘auto’ left and right margins. This is the standards-compliant way that works everywhere except IE5.x.

<div style="width: 50%; margin: 0 auto;">Hello</div>

For this to work in IE6, you need to make sure Standards Mode is on by using a suitable DOCTYPE.

If you really need to support IE5/Quirks Mode, which these days you shouldn't really, it is possible to combine the two different approaches to centering:

<div style="text-align: center">
    <div style="width: 50%; margin: 0 auto; text-align: left">Hello</div>
</div>

(Obviously, styles are best put inside a stylesheet, but the inline version is illustrative.)

apache and httpd running but I can't see my website

Did you restart the server after you changed the config file?

Can you telnet to the server from a different machine?

Can you telnet to the server from the server itself?

telnet <ip address> 80

telnet localhost 80

Jquery mouseenter() vs mouseover()

You see the behavior when your target element contains child elements:

http://jsfiddle.net/ZCWvJ/7/

Each time your mouse enters or leaves a child element, mouseover is triggered, but not mouseenter.

_x000D_
_x000D_
$('#my_div').bind("mouseover mouseenter", function(e) {_x000D_
  var el = $("#" + e.type);_x000D_
  var n = +el.text();_x000D_
  el.text(++n);_x000D_
});
_x000D_
#my_div {_x000D_
  padding: 0 20px 20px 0;_x000D_
  background-color: #eee;_x000D_
  margin-bottom: 10px;_x000D_
  width: 90px;_x000D_
  overflow: hidden;_x000D_
}_x000D_
_x000D_
#my_div>div {_x000D_
  float: left;_x000D_
  margin: 20px 0 0 20px;_x000D_
  height: 25px;_x000D_
  width: 25px;_x000D_
  background-color: #aaa;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"></script>_x000D_
_x000D_
<div>MouseEnter: <span id="mouseenter">0</span></div>_x000D_
<div>MouseOver: <span id="mouseover">0</span></div>_x000D_
_x000D_
<div id="my_div">_x000D_
  <div></div>_x000D_
  <div></div>_x000D_
  <div></div>_x000D_
  <div></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Fatal Error :1:1: Content is not allowed in prolog

It could be not supported file encoding. Change it to UTF-8 for example.

I've done this using Sublime

Ineligible Devices section appeared in Xcode 6.x.x

Upgrade XCode to ensure that it supports your current iOS version on device.

(In my case, my phone was on iOS 9.1.x) `but XCode version was 7, which supported iOS 9.0 devices)

HTML5 Video autoplay on iPhone

Here is the little hack to overcome all the struggles you have for video autoplay in a website:

  1. Check video is playing or not.
  2. Trigger video play on event like body click or touch.

Note: Some browsers don't let videos to autoplay unless the user interacts with the device.

So scripts to check whether video is playing is:

Object.defineProperty(HTMLMediaElement.prototype, 'playing', {
get: function () {
    return !!(this.currentTime > 0 && !this.paused && !this.ended && this.readyState > 2);
}});

And then you can simply autoplay the video by attaching event listeners to the body:

$('body').on('click touchstart', function () {
        const videoElement = document.getElementById('home_video');
        if (videoElement.playing) {
            // video is already playing so do nothing
        }
        else {
            // video is not playing
            // so play video now
            videoElement.play();
        }
});

Note: autoplay attribute is very basic which needs to be added to the video tag already other than these scripts.

You can see the working example with code here at this link:

How to autoplay video when the device is in low power mode / data saving mode / safari browser issue

How to find rows in one table that have no corresponding row in another table

select parentTable.id from parentTable
left outer join childTable on (parentTable.id = childTable.parentTableID) 
where childTable.id is null

Check if an element is present in an array

ECMAScript 2016 incorporates an includes() method for arrays that specifically solves the problem, and so is now the preferred method.

[1, 2, 3].includes(2);     // true
[1, 2, 3].includes(4);     // false
[1, 2, 3].includes(1, 2);  // false (second parameter is the index position in this array at which to begin searching)

As of JULY 2018, this has been implemented in almost all major browsers, if you need to support an older browser a polyfill is available.

Edit: Note that this returns false if the item in the array is an object. This is because similar objects are two different objects in JavaScript.

How to list physical disks?

If you want "physical" access, we're developing this API that will eventually allows you to communicate with storage devices. It's open source and you can see the current code for some information. Check back for more features: https://github.com/virtium/vtStor

String concatenation in Jinja

Just another hack can be like this.

I have Array of strings which I need to concatenate. So I added that array into dictionary and then used it inside for loop which worked.

{% set dict1 = {'e':''} %}
{% for i in list1 %}
{% if dict1.update({'e':dict1.e+":"+i+"/"+i}) %} {% endif %}
{% endfor %}
{% set layer_string = dict1['e'] %}

How do I get a button to open another activity?

Button T=(Button)findViewById(R.id.button_timer);
T.setOnClickListener(new View.OnClickListener() {

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        Intent i=new Intent(getApplicationContext(),YOURACTIVITY.class);
        startActivity(i);
    }
});

What does "control reaches end of non-void function" mean?

Make sure that your code is returning a value of given return-type irrespective of conditional statements

This code snippet was showing the same error

int search(char arr[], int start, int end, char value)
{
    int i;
    for(i=start; i<=end; i++)
    {
        if(arr[i] == value)
            return i;
    }
}

This is the working code after little changes

int search(char arr[], int start, int end, char value)
{
    int i;
    int index=-1;
    for(i=start; i<=end; i++)
    {
        if(arr[i] == value)
            index=i;
    }
    return index;
}

Accessing dict keys like an attribute?

What would be the caveats and pitfalls of accessing dict keys in this manner?

As @Henry suggests, one reason dotted-access may not be used in dicts is that it limits dict key names to python-valid variables, thereby restricting all possible names.

The following are examples on why dotted-access would not be helpful in general, given a dict, d:

Validity

The following attributes would be invalid in Python:

d.1_foo                           # enumerated names
d./bar                            # path names
d.21.7, d.12:30                   # decimals, time
d.""                              # empty strings
d.john doe, d.denny's             # spaces, misc punctuation 
d.3 * x                           # expressions  

Style

PEP8 conventions would impose a soft constraint on attribute naming:

A. Reserved keyword (or builtin function) names:

d.in
d.False, d.True
d.max, d.min
d.sum
d.id

If a function argument's name clashes with a reserved keyword, it is generally better to append a single trailing underscore ...

B. The case rule on methods and variable names:

Variable names follow the same convention as function names.

d.Firstname
d.Country

Use the function naming rules: lowercase with words separated by underscores as necessary to improve readability.


Sometimes these concerns are raised in libraries like pandas, which permits dotted-access of DataFrame columns by name. The default mechanism to resolve naming restrictions is also array-notation - a string within brackets.

If these constraints do not apply to your use case, there are several options on dotted-access data structures.

Make XmlHttpRequest POST using JSON

If you use JSON properly, you can have nested object without any issue :

var xmlhttp = new XMLHttpRequest();   // new HttpRequest instance 
var theUrl = "/json-handler";
xmlhttp.open("POST", theUrl);
xmlhttp.setRequestHeader("Content-Type", "application/json;charset=UTF-8");
xmlhttp.send(JSON.stringify({ "email": "[email protected]", "response": { "name": "Tester" } }));

AngularJS - Does $destroy remove event listeners?

Event listeners

First off it's important to understand that there are two kinds of "event listeners":

  1. Scope event listeners registered via $on:

    $scope.$on('anEvent', function (event, data) {
      ...
    });
    
  2. Event handlers attached to elements via for example on or bind:

    element.on('click', function (event) {
      ...
    });
    

$scope.$destroy()

When $scope.$destroy() is executed it will remove all listeners registered via $on on that $scope.

It will not remove DOM elements or any attached event handlers of the second kind.

This means that calling $scope.$destroy() manually from example within a directive's link function will not remove a handler attached via for example element.on, nor the DOM element itself.


element.remove()

Note that remove is a jqLite method (or a jQuery method if jQuery is loaded before AngularjS) and is not available on a standard DOM Element Object.

When element.remove() is executed that element and all of its children will be removed from the DOM together will all event handlers attached via for example element.on.

It will not destroy the $scope associated with the element.

To make it more confusing there is also a jQuery event called $destroy. Sometimes when working with third-party jQuery libraries that remove elements, or if you remove them manually, you might need to perform clean up when that happens:

element.on('$destroy', function () {
  scope.$destroy();
});

What to do when a directive is "destroyed"

This depends on how the directive is "destroyed".

A normal case is that a directive is destroyed because ng-view changes the current view. When this happens the ng-view directive will destroy the associated $scope, sever all the references to its parent scope and call remove() on the element.

This means that if that view contains a directive with this in its link function when it's destroyed by ng-view:

scope.$on('anEvent', function () {
 ...
});

element.on('click', function () {
 ...
});

Both event listeners will be removed automatically.

However, it's important to note that the code inside these listeners can still cause memory leaks, for example if you have achieved the common JS memory leak pattern circular references.

Even in this normal case of a directive getting destroyed due to a view changing there are things you might need to manually clean up.

For example if you have registered a listener on $rootScope:

var unregisterFn = $rootScope.$on('anEvent', function () {});

scope.$on('$destroy', unregisterFn);

This is needed since $rootScope is never destroyed during the lifetime of the application.

The same goes if you are using another pub/sub implementation that doesn't automatically perform the necessary cleanup when the $scope is destroyed, or if your directive passes callbacks to services.

Another situation would be to cancel $interval/$timeout:

var promise = $interval(function () {}, 1000);

scope.$on('$destroy', function () {
  $interval.cancel(promise);
});

If your directive attaches event handlers to elements for example outside the current view, you need to manually clean those up as well:

var windowClick = function () {
   ...
};

angular.element(window).on('click', windowClick);

scope.$on('$destroy', function () {
  angular.element(window).off('click', windowClick);
});

These were some examples of what to do when directives are "destroyed" by Angular, for example by ng-view or ng-if.

If you have custom directives that manage the lifecycle of DOM elements etc. it will of course get more complex.

Join String list elements with a delimiter in one step

If you just want to log the list of elements, you can use the list toString() method which already concatenates all the list elements.

Clear and refresh jQuery Chosen dropdown list

Using .trigger("chosen:updated"); you can update the options list after appending.

Updating Chosen Dynamically: If you need to update the options in your select field and want Chosen to pick up the changes, you'll need to trigger the "chosen:updated" event on the field. Chosen will re-build itself based on the updated content.

Your code:

$("#refreshgallery").click(function(){
        $('#picturegallery').empty(); //remove all child nodes
        var newOption = $('<option value="1">test</option>');
        $('#picturegallery').append(newOption);
        $('#picturegallery').trigger("chosen:updated");
    });

Select method in List<t> Collection

Generic List<T> have the Where<T>(Func<T, Boolean>) extension method that can be used to filter data.

In your case with a row array:

var rows = rowsArray.Where(row => row["LastName"].ToString().StartsWith("a"));

If you are using DataRowCollection, you need to cast it first.

var rows = dataTableRows.Cast<DataRow>().Where(row => row["LastName"].ToString().StartsWith("a"));

Compiler error "archive for required library could not be read" - Spring Tool Suite

Alternatively, below commands also worked for me:

mvn -s settings.xml eclipse:clean
mvn -s settings.xml eclipse:eclipse

Better way to generate array of all letters in the alphabet

with io.vavr

public static char[] alphanumericAlphabet() {
    return CharSeq
            .rangeClosed('0','9')
            .appendAll(CharSeq.rangeClosed('a','z'))
            .appendAll(CharSeq.rangeClosed('A','Z'))
            .toCharArray();
}

How to check visibility of software keyboard in Android?

The solution provided by Reuben Scratton and Kachi seems to rely on the pixel density of the devices, if you have a high density device the height difference can be bigger than 100 even with the keyboard down. A little work around that would be to see the initial height difference (with keyboard down) and then compare with the current difference.

boolean isOpened = false;
int firstHeightDiff = -1;

public void setListenerToRootView(){
    final View activityRootView = getActivity().getWindow().getDecorView().findViewById(android.R.id.content);
    Rect r = new Rect();
    activityRootView.getWindowVisibleDisplayFrame(r);
    firstHeightDiff = activityRootView.getRootView().getHeight() - (r.bottom - r.top);
    activityRootView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            if (isAdded()) {
                Rect r = new Rect();
                activityRootView.getWindowVisibleDisplayFrame(r);
                int heightDiff = activityRootView.getRootView().getHeight() - (r.bottom - r.top);
                isOpened = heightDiff>firstHeightDiff+100;
                if (isAdded())
                    if(isOpened) {
                        //TODO stuff for when it is up
                    } else {
                        //TODO stuf for when it is down
                    }
            }
        }
    });
}

How to remove button shadow (android)

Kotlin

stateListAnimator = null

Java

setStateListAnimator(null);

XML

android:stateListAnimator="@null"

How to cast Object to its actual type?

If multiple types are possible, the method itself does not know the type to cast, but the caller does, you might use something like this:

void TheObliviousHelperMethod<T>(object obj) {
    (T)obj.ThatClassMethodYouWantedToInvoke();
}

// Meanwhile, where the method is called:
TheObliviousHelperMethod<ActualType>(obj);

Restrictions on the type could be added using the where keyword after the parentheses.

Does this app use the Advertising Identifier (IDFA)? - AdMob 6.8.0

Yes, it does. From the AdMob page:

The Mobile Ads SDK for iOS utilizes Apple's advertising identifier (IDFA). The SDK uses IDFA under the guidelines laid out in the iOS developer program license agreement. You must ensure you are in compliance with the iOS developer program license agreement policies governing the use of this identifier.

remove duplicates from sql union

Union will remove duplicates. Union All does not.

Side-by-side list items as icons within a div (css)

I would recommend that you use display: inline;. float is screwed up in IE. Here is an example of how I would approach it:

<ul class="side-by-side">
  <li>item 1<li>
  <li>item 2<li>
  <li>item 3<li>
</ul>

and here's the css:

.side-by-side {
  width: 100%;
  border: 1px solid black;

}
.side-by-side li {
  display: inline;
}

Also, if you use floats the ul will not wrap around the li's and will instead have a hight of 0 in this example:

.side-by-side li {
  float: left;
}

How to find out if an installed Eclipse is 32 or 64 bit version?

In Linux, run file on the Eclipse executable, like this:

$ file /usr/bin/eclipse
eclipse: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), dynamically linked (uses shared libs), for GNU/Linux 2.4.0, not stripped

'Missing contentDescription attribute on image' in XML

Follow this link for solution: Android Lint contentDescription warning

Resolved this warning by setting attribute android:contentDescription for my ImageView

android:contentDescription="@string/desc"

Android Lint support in ADT 16 throws this warning to ensure that image widgets provide a contentDescription

This defines text that briefly describes the content of the view. This property is used primarily for accessibility. Since some views do not have textual representation this attribute can be used for providing such.

Non-textual widgets like ImageViews and ImageButtons should use the contentDescription attribute to specify a textual description of the widget such that screen readers and other accessibility tools can adequately describe the user interface.

This link for explanation: Accessibility, It's Impact and Development Resources

Many Android users have disabilities that require them to interact with their Android devices in different ways. These include users who have visual, physical or age-related disabilities that prevent them from fully seeing or using a touchscreen.

Android provides accessibility features and services for helping these users navigate their devices more easily, including text-to-speech, haptic feedback, trackball and D-pad navigation that augments their experience. Android application developers can take advantage of these services to make their applications more accessible and also build their own accessibility services.

This guide is for making your app accessible: Making Apps More Accessible

Making sure your application is accessible to all users is relatively easy, particularly when you use framework-provided user interface components. If you only use these standard components for your application, there are just a few steps required to ensure your application is accessible:

  1. Label your ImageButton, ImageView, EditText, CheckBox and other user interface controls using the android:contentDescription attribute.

  2. Make all of your user interface elements accessible with a directional controller, such as a trackball or D-pad.

  3. Test your application by turning on accessibility services like TalkBack and Explore by Touch, and try using your application using only directional controls.

How to use PHP to connect to sql server

MS SQL connect to php

  1. Install the drive from microsoft link https://www.microsoft.com/en-us/download/details.aspx?id=20098

  2. After install you will get some files. Store it in your system temp folder

  3. Check your php version , thread or non thread , and window bit - 32 or 64 (Thread or non thread , this is get you by phpinfo() )

  4. According to your system & xampp configration (php version and all ) copy 2 files (php_sqlsrv & php_pdo_sqlsrv) to xampp/php/ext folder .

  5. Add to php.ini file extension=php_sqlsrv_72_ts_x64 (php_sqlsrv_72_ts_x64.dll is your file which your copy in 4th step ) extension=php_pdo_sqlsrv_72_ts_x64 (php_pdo_sqlsrv_72_ts_x64.dll is your file which your copy in 4th step )

  6. Next Php Code

    $serverName ="DESKTOP-me\MSSQLSERVER01"; (servername\instanceName)

    // Since UID and PWD are not specified in the $connectionInfo array, // The connection will be attempted using Windows Authentication.

    $connectionInfo = array("Database"=>"testdb","CharacterSet"=>"UTF-8");

    $conn = sqlsrv_connect( $serverName, $connectionInfo);

    if( $conn ) { //echo "Connection established.
    "; }else{ echo "Connection could not be established.
    "; die( print_r( sqlsrv_errors(), true)); }

    //$sql = "INSERT INTO dbo.master ('name') VALUES ('test')"; $sql = "SELECT * FROM dbo.master"; $stmt = sqlsrv_query( $conn, $sql );

    while( $row = sqlsrv_fetch_array( $stmt, SQLSRV_FETCH_ASSOC) ) { echo $row['id'].", ".$row['name']."
    "; }

    sqlsrv_free_stmt( $stmt);

White space at top of page

Check for any webkit styles being applied to elements like ul, h4 etc. For me it was margin-before and after causing this.

-webkit-margin-before: 1.33em;
-webkit-margin-after: 1.33em;

How to write text on a image in windows using python opencv2

Here's the code with parameter labels

def draw_text(self, frame, text, x, y, color=BGR_COMMON['green'], thickness=1.3, size=0.3,):
    if x is not None and y is not None:
        cv2.putText(
            frame, text, (int(x), int(y)), cv2.FONT_HERSHEY_SIMPLEX, size, color, thickness)

For font name please see another answer in this thread.

Excerpt from answer by @Roeffus

This is indeed a bit of an annoying problem. For python 2.x.x you use:

cv2.CV_FONT_HERSHEY_SIMPLEX and for Python 3.x.x:

cv2.FONT_HERSHEY_SIMPLEX

For more see this http://www.programcreek.com/python/example/83399/cv2.putText

Best way to write to the console in PowerShell

The middle one writes to the pipeline. Write-Host and Out-Host writes to the console. 'echo' is an alias for Write-Output which writes to the pipeline as well. The best way to write to the console would be using the Write-Host cmdlet.

When an object is written to the pipeline it can be consumed by other commands in the chain. For example:

"hello world" | Do-Something

but this won't work since Write-Host writes to the console, not to the pipeline (Do-Something will not get the string):

Write-Host "hello world" | Do-Something

How do I use CMake?

CMake takes a CMakeList file, and outputs it to a platform-specific build format, e.g. a Makefile, Visual Studio, etc.

You run CMake on the CMakeList first. If you're on Visual Studio, you can then load the output project/solution.

Regex for parsing directory and filename

What language? and why use regex for this simple task?

If you must:

^(.*)/([^/]*)$

gives you the two parts you wanted. You might need to quote the parentheses:

^\(.*\)/\([^/]*\)$

depending on your preferred language syntax.

But I suggest you just use your language's string search function that finds the last "/" character, and split the string on that index.

Zoom in on a point (using scale and translate)

You need to get the point in world space (opposed to screen space) before and after zooming, and then translate by the delta.

mouse_world_position = to_world_position(mouse_screen_position);
zoom();
mouse_world_position_new = to_world_position(mouse_screen_position);
translation += mouse_world_position_new - mouse_world_position;

Mouse position is in screen space, so you have to transform it to world space. Simple transforming should be similar to this:

world_position = screen_position / scale - translation

Backup a single table with its data from a database in sql server 2008

You can create table script along with its data using following steps:

  1. Right click on the database.
  2. Select Tasks > Generate scripts ...
  3. Click next.
  4. Click next.
  5. In Table/View Options, set Script Data to True; then click next.
  6. Select the Tables checkbox and click next.
  7. Select your table name and click next.
  8. Click next until the wizard is done.

For more information, see Eric Johnson's blog.

How to change the name of a Django app?

If you use Pycharm, renaming an app is very easy with refactoring(Shift+F6 default) for all project files.
But make sure you delete the __pycache__ folders in the project directory & its sub-directories. Also be careful as it also renames comments too which you can exclude in the refactor preview window it will show you.
And you'll have to rename OldNameConfig(AppConfig): in apps.py of your renamed app in addition.

If you do not want to lose data of your database, you'll have to manually do it with query in database like the aforementioned answer.

T-SQL STOP or ABORT command in SQL Server

Why not simply add the following to the beginning of the script

PRINT 'INACTIVE SCRIPT'
RETURN

Type datetime for input parameter in procedure

In this part of your SP:

IF @DateFirst <> '' and @DateLast <> ''
   set @FinalSQL  = @FinalSQL
       + '  or convert (Date,DateLog) >=     ''' + @DateFirst
       + ' and convert (Date,DateLog) <=''' + @DateLast  

you are trying to concatenate strings and datetimes.

As the datetime type has higher priority than varchar/nvarchar, the + operator, when it happens between a string and a datetime, is interpreted as addition, not as concatenation, and the engine then tries to convert your string parts (' or convert (Date,DateLog) >= ''' and others) to datetime or numeric values. And fails.

That doesn't happen if you omit the last two parameters when invoking the procedure, because the condition evaluates to false and the offending statement isn't executed.

To amend the situation, you need to add explicit casting of your datetime variables to strings:

set @FinalSQL  = @FinalSQL
    + '  or convert (Date,DateLog) >=     ''' + convert(date, @DateFirst)
    + ' and convert (Date,DateLog) <=''' + convert(date, @DateLast)

You'll also need to add closing single quotes:

set @FinalSQL  = @FinalSQL
    + '  or convert (Date,DateLog) >=     ''' + convert(date, @DateFirst) + ''''
    + ' and convert (Date,DateLog) <=''' + convert(date, @DateLast) + ''''

Using FileSystemWatcher to monitor a directory

You did not supply the file handling code, but I assume you made the same mistake everyone does when first writing such a thing: the filewatcher event will be raised as soon as the file is created. However, it will take some time for the file to be finished. Take a file size of 1 GB for example. The file may be created by another program (Explorer.exe copying it from somewhere) but it will take minutes to finish that process. The event is raised at creation time and you need to wait for the file to be ready to be copied.

You can wait for a file to be ready by using this function in a loop.

Python argparse: default value or specified value

The difference between:

parser.add_argument("--debug", help="Debug", nargs='?', type=int, const=1, default=7)

and

parser.add_argument("--debug", help="Debug", nargs='?', type=int, const=1)

is thus:

myscript.py => debug is 7 (from default) in the first case and "None" in the second

myscript.py --debug => debug is 1 in each case

myscript.py --debug 2 => debug is 2 in each case

Request UAC elevation from within a Python script?

This is mostly an upgrade to Jorenko's answer, that allows to use parameters with spaces in Windows, but should also work fairly well on Linux :) Also, will work with cx_freeze or py2exe since we don't use __file__ but sys.argv[0] as executable

import sys,ctypes,platform

def is_admin():
    try:
        return ctypes.windll.shell32.IsUserAnAdmin()
    except:
        raise False

if __name__ == '__main__':

    if platform.system() == "Windows":
        if is_admin():
            main(sys.argv[1:])
        else:
            # Re-run the program with admin rights, don't use __file__ since py2exe won't know about it
            # Use sys.argv[0] as script path and sys.argv[1:] as arguments, join them as lpstr, quoting each parameter or spaces will divide parameters
            lpParameters = ""
            # Litteraly quote all parameters which get unquoted when passed to python
            for i, item in enumerate(sys.argv[0:]):
                lpParameters += '"' + item + '" '
            try:
                ctypes.windll.shell32.ShellExecuteW(None, "runas", sys.executable, lpParameters , None, 1)
            except:
                sys.exit(1)
    else:
        main(sys.argv[1:])

Passing ArrayList through Intent

//arraylist/Pojo you can Pass using bundle  like this 
Intent intent = new Intent(MainActivity.this, SecondActivity.class);
Bundle args = new Bundle();
                        args.putSerializable("imageSliders",(Serializable)allStoriesPojo.getImageSliderPojos());
                        intent.putExtra("BUNDLE",args);
 startActivity(intent); 


Get SecondActivity like this
  Intent intent = getIntent();
        Bundle args = intent.getBundleExtra("BUNDLE");
String filter = bundle.getString("imageSliders");

//Happy coding

Load image from url

The accepted answer above is great if you are loading the image based on a button click, however if you are doing it in a new activity it freezes up the UI for a second or two. Looking around I found that a simple asynctask eliminated this problem.

To use an asynctask to add this class at the end of your activity:

private class DownloadImageTask extends AsyncTask<String, Void, Bitmap> {
  ImageView bmImage;

  public DownloadImageTask(ImageView bmImage) {
      this.bmImage = bmImage;
  }

  protected Bitmap doInBackground(String... urls) {
      String urldisplay = urls[0];
      Bitmap mIcon11 = null;
      try {
        InputStream in = new java.net.URL(urldisplay).openStream();
        mIcon11 = BitmapFactory.decodeStream(in);
      } catch (Exception e) {
          Log.e("Error", e.getMessage());
          e.printStackTrace();
      }
      return mIcon11;
  }

  protected void onPostExecute(Bitmap result) {
      bmImage.setImageBitmap(result);
  }
}

And call from your onCreate() method using:

new DownloadImageTask((ImageView) findViewById(R.id.imageView1))
        .execute(MY_URL_STRING);

Dont forget to add below permission in your manifest file

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

Works great for me. :)

How to create a library project in Android Studio and an application project that uses the library project

As theczechsensation comment above I try to search about Gradle Build Varians and I found this link: http://code.tutsplus.com/tutorials/using-gradle-build-variants--cms-25005 This is a very simple solution. This is what I did: - In build.gradle:

flavorDimensions "version"

productFlavors {
    trial{
        applicationId "org.de_studio.recentappswitcher.trial"
        flavorDimension "version"
    }
    pro{
        applicationId "org.de_studio.recentappswitcher.pro"
        flavorDimension "version"
    }

}

Then I have 2 more version of my app: pro and trial with 2 diffrent packageName which is 2 applicationId in above code so I can upload both to Google Play. I still just code in the "main" section and use the getpackageName to switch between to version. Just go to the link I gave for detail.

Docker how to change repository name or rename image?

docker tag CURRENT_IMAGE_NAME DESIRED_IMAGE_NAME

oracle varchar to number

Since the column is of type VARCHAR, you should convert the input parameter to a string rather than converting the column value to a number:

select * from exception where exception_value = to_char(105);

Return single column from a multi-dimensional array

join(',', array_map(function (array $tag) { return $tag['tag_name']; }, $array))

Copy a table from one database to another in Postgres

Using dblink would be more convenient!

truncate table tableA;

insert into tableA
select *
from dblink('hostaddr=xxx.xxx.xxx.xxx dbname=mydb user=postgres',
            'select a,b from tableA')
       as t1(a text,b text);

Error:com.android.tools.aapt2.Aapt2Exception: AAPT2 error: check logs for details

If you've seen this error after trying to run individual Android implementation tests or test classes (by clicking on the run icon in the gutter) in a Kotlin project in Android Studio 3.0.1, you can get around the error by instead running the full test package (by right-clicking on the test package and choosing "Run tests in...").

There is a known bug in Android Studio 3.0.1 that causes the IDE to run Kotlin implementation tests as regular JUnit tests, which caused the OP's error message to get shown on my machine. The bug is tracked at https://issuetracker.google.com/issues/71056937. It appears to have been fixed in Android Studio 3.1 Canary 7.

VBA - Range.Row.Count

This works for me especially in pivots table filtering when I want the count of cells with data on a filtered column. Reduce k accordingly (k - 1) if you have a header row for filtering:

k = Sheets("Sheet1").Range("$A:$A").SpecialCells(xlCellTypeVisible).SpecialCells(xlCellTypeConstants).Count

Assign a login to a user created without login (SQL Server)

Create a login for the user

Drop and re-create the user, WITH the login you created.

There are other topics discussing how to replicate the permissions of your user. I recommend that you take the opportunity to define those permissions in a Role and call sp_addrolemember to add the user to the Role.

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

I came across this, tot it would be nice to share...

What do you guys think?

$(document).ready(function() {
  window.mousemove = function(e) {
    p = $(e).position();  //remember $(e) - could be any html tag also.. 
    left = e.left;        //retrieving the left position of the div... 
    top = e.top;          //get the top position of the div... 
  }
});

and boom, there we have it..

Using Python, how can I access a shared folder on windows network?

How did you try it? Maybe you are working with \ and omit proper escaping.

Instead of

open('\\HOST\share\path\to\file')

use either Johnsyweb's solution with the /s, or try one of

open(r'\\HOST\share\path\to\file')

or

open('\\\\HOST\\share\\path\\to\\file')

.

How to use a DataAdapter with stored procedure and parameter

public class SQLCon
{
  public static string cs = 
   ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
}
protected void Page_Load(object sender, EventArgs e)
{
    SqlDataAdapter MyDataAdapter;
    SQLCon cs = new SQLCon();
    DataSet RsUser = new DataSet();
    RsUser = new DataSet();
    using (SqlConnection MyConnection = new SqlConnection(SQLCon.cs))
       {
        MyConnection.Open();
        MyDataAdapter = new SqlDataAdapter("GetAPPID", MyConnection);
        //'Set the command type as StoredProcedure.
        MyDataAdapter.SelectCommand.CommandType = CommandType.StoredProcedure;
        RsUser = new DataSet();
        MyDataAdapter.SelectCommand.Parameters.Add(new SqlParameter("@organizationID", 
        SqlDbType.Int));
        MyDataAdapter.SelectCommand.Parameters["@organizationID"].Value = TxtID.Text;
        MyDataAdapter.Fill(RsUser, "GetAPPID");
       }

      if (RsUser.Tables[0].Rows.Count > 0) //data was found
      {
        Session["AppID"] = RsUser.Tables[0].Rows[0]["AppID"].ToString();
       }
     else
       {

       }    
}    

How do I change the JAVA_HOME for ant?

There are 2 ways of changing the compiler:

  • export JAVA_HOME=/path/to/jdk before you start Ant.
  • Set <javac exectuable="/path/to/javac">

Another option would be to add a respective tools.jar to the classpath, but this is usually used if Ant is started from another tools like Maven.

For more details on these (or other) options of changing Java Compiler in Ant, see this article for example.

How to position two divs horizontally within another div

I agree with Darko Z on applying "overflow: hidden" to #sub-title. However, it should be mentioned that the overflow:hidden method of clearing floats does not work with IE6 unless you have a specified width or height. Or, if you don't want to specify a width or height, you can use "zoom: 1":

#sub-title { overflow:hidden; zoom: 1; }

How to set a dropdownlist item as selected in ASP.NET?

This is a very nice and clean example:(check this great tutorial for a full explanation link)

public static IEnumerable<SelectListItem> ToSelectListItems(
              this IEnumerable<Album> albums, int selectedId)
{
    return 
        albums.OrderBy(album => album.Name)
              .Select(album => 
                  new SelectListItem
                  {
                    Selected = (album.ID == selectedId),
                    Text = album.Name,
                    Value = album.ID.ToString()
                   });
}

In this MSDN link you can read de DropDownList method documentation.

Hope it helps.

Custom CSS Scrollbar for Firefox

Firefox 64 adds support for the spec draft CSS Scrollbars Module Level 1, which adds two new properties of scrollbar-width and scrollbar-color which give some control over how scrollbars are displayed.

You can set scrollbar-color to one of the following values (descriptions from MDN):

  • auto Default platform rendering for the track portion of the scrollbar, in the absence of any other related scrollbar color properties.
  • dark Show a dark scrollbar, which can be either a dark variant of scrollbar provided by the platform, or a custom scrollbar with dark colors.
  • light Show a light scrollbar, which can be either a light variant of scrollbar provided by the platform, or a custom scrollbar with light colors.
  • <color> <color> Applies the first color to the scrollbar thumb, the second to the scrollbar track.

Note that dark and light values are not currently implemented in Firefox.

macOS notes:

The auto-hiding semi-transparent scrollbars that are the macOS default cannot be colored with this rule (they still choose their own contrasting color based on the background). Only the permanently showing scrollbars (System Preferences > Show Scroll Bars > Always) are colored.

Visual Demo:

_x000D_
_x000D_
.scroll {_x000D_
  width: 20%;_x000D_
  height: 100px;_x000D_
  border: 1px solid grey;_x000D_
  overflow: scroll;_x000D_
  display: inline-block;_x000D_
}_x000D_
.scroll-color-auto {_x000D_
  scrollbar-color: auto;_x000D_
}_x000D_
.scroll-color-dark {_x000D_
  scrollbar-color: dark;_x000D_
}_x000D_
.scroll-color-light {_x000D_
  scrollbar-color: light;_x000D_
}_x000D_
.scroll-color-colors {_x000D_
  scrollbar-color: orange lightyellow;_x000D_
}
_x000D_
<div class="scroll scroll-color-auto">_x000D_
<p>auto</p><p>auto</p><p>auto</p><p>auto</p><p>auto</p><p>auto</p>_x000D_
</div>_x000D_
_x000D_
<div class="scroll scroll-color-dark">_x000D_
<p>dark</p><p>dark</p><p>dark</p><p>dark</p><p>dark</p><p>dark</p>_x000D_
</div>_x000D_
_x000D_
<div class="scroll scroll-color-light">_x000D_
<p>light</p><p>light</p><p>light</p><p>light</p><p>light</p><p>light</p>_x000D_
</div>_x000D_
_x000D_
<div class="scroll scroll-color-colors">_x000D_
<p>colors</p><p>colors</p><p>colors</p><p>colors</p><p>colors</p><p>colors</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

You can set scrollbar-width to one of the following values (descriptions from MDN):

  • auto The default scrollbar width for the platform.
  • thin A thin scrollbar width variant on platforms that provide that option, or a thinner scrollbar than the default platform scrollbar width.
  • none No scrollbar shown, however the element will still be scrollable.

You can also set a specific length value, according to the spec. Both thin and a specific length may not do anything on all platforms, and what exactly it does is platform-specific. In particular, Firefox doesn't appear to be currently support a specific length value (this comment on their bug tracker seems to confirm this). The thin keywork does appear to be well-supported however, with macOS and Windows support at-least.

It's probably worth noting that the length value option and the entire scrollbar-width property are being considered for removal in a future draft, and if that happens this particular property may be removed from Firefox in a future version.

Visual Demo:

_x000D_
_x000D_
.scroll {_x000D_
  width: 30%;_x000D_
  height: 100px;_x000D_
  border: 1px solid grey;_x000D_
  overflow: scroll;_x000D_
  display: inline-block;_x000D_
}_x000D_
.scroll-width-auto {_x000D_
  scrollbar-width: auto;_x000D_
}_x000D_
.scroll-width-thin {_x000D_
  scrollbar-width: thin;_x000D_
}_x000D_
.scroll-width-none {_x000D_
  scrollbar-width: none;_x000D_
}
_x000D_
<div class="scroll scroll-width-auto">_x000D_
<p>auto</p><p>auto</p><p>auto</p><p>auto</p><p>auto</p><p>auto</p>_x000D_
</div>_x000D_
_x000D_
<div class="scroll scroll-width-thin">_x000D_
<p>thin</p><p>thin</p><p>thin</p><p>thin</p><p>thin</p><p>thin</p>_x000D_
</div>_x000D_
_x000D_
<div class="scroll scroll-width-none">_x000D_
<p>none</p><p>none</p><p>none</p><p>none</p><p>none</p><p>none</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

RecyclerView expand/collapse items

Please don't use any library for this effect instead use the recommended way of doing it according to Google I/O. In your recyclerView's onBindViewHolder method do this:

final boolean isExpanded = position==mExpandedPosition;
holder.details.setVisibility(isExpanded?View.VISIBLE:View.GONE);
holder.itemView.setActivated(isExpanded);
holder.itemView.setOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        mExpandedPosition = isExpanded ? -1:position;
        TransitionManager.beginDelayedTransition(recyclerView);
        notifyDataSetChanged();
    }
});
  • Where details is my view that will be displayed on touch (call details in your case. Default Visibility.GONE).
  • mExpandedPosition is an int variable initialized to -1

And for the cool effects that you wanted, use these as your list_item attributes:

android:background="@drawable/comment_background"
android:stateListAnimator="@animator/comment_selection"

where comment_background is:

<selector
xmlns:android="http://schemas.android.com/apk/res/android"
android:constantSize="true"
android:enterFadeDuration="@android:integer/config_shortAnimTime"
android:exitFadeDuration="@android:integer/config_shortAnimTime">

<item android:state_activated="true" android:drawable="@color/selected_comment_background" />
<item android:drawable="@color/comment_background" />
</selector>

and comment_selection is:

<selector xmlns:android="http://schemas.android.com/apk/res/android">

<item android:state_activated="true">
    <objectAnimator
        android:propertyName="translationZ"
        android:valueTo="@dimen/z_card"
        android:duration="2000"
        android:interpolator="@android:interpolator/fast_out_slow_in" />
</item>

<item>
    <objectAnimator
        android:propertyName="translationZ"
        android:valueTo="0dp"
        android:duration="2000"
        android:interpolator="@android:interpolator/fast_out_slow_in" />
</item>
</selector>

HTTPS and SSL3_GET_SERVER_CERTIFICATE:certificate verify failed, CA is OK

I ended up here when trying to get GuzzleHttp (php+apache on Mac) to get a page from www.googleapis.com.

Here was my final solution in case it helps anyone.

Look at the certificate chain for whatever domain is giving you this error. For me it was googleapis.com

openssl s_client -host www.googleapis.com -port 443

You'll get back something like this:

Certificate chain
 0 s:/C=US/ST=California/L=Mountain View/O=Google Inc/CN=*.googleapis.com
   i:/C=US/O=Google Inc/CN=Google Internet Authority G2
 1 s:/C=US/O=Google Inc/CN=Google Internet Authority G2
   i:/C=US/O=GeoTrust Inc./CN=GeoTrust Global CA
 2 s:/C=US/O=GeoTrust Inc./CN=GeoTrust Global CA
   i:/C=US/O=Equifax/OU=Equifax Secure Certificate Authority

Note: I captured this after I fixed the issue, to your chain output may look different.

Then you need to look at the certificates allowed in php. Run phpinfo() in a page.

<?php echo phpinfo();

Then look for the certificate file that's loaded from the page output:

openssl.cafile  /usr/local/php5/ssl/certs/cacert.pem

This is the file you'll need to fix by adding the correct certificate(s) to it.

sudo nano /usr/local/php5/ssl/certs/cacert.pem

You basically need to append the correct certificate "signatures" to the end of this file.

You can find some of them here: You may need to google/search for others in the chain if you need them.

They look like this:

example certificate image

(Note: This is an image so people will not simply copy/paste certificates from stackoverflow)

Once the right certificates are in this file, restart apache and test.

What LaTeX Editor do you suggest for Linux?

I normally use Emacs (it has everything you need included).

Of course, there are other options available:

  • Kile is KDE's LaTeX editor; it's excellent if you're just learning or if you prefer the integrated environment approach;
  • Lyx is a WYSIWYG editor that uses LaTeX as a backend; i.e. you tell it what the text should look like and it generates the corresponding LaTeX

Cheers.

How to change color of Toolbar back button in Android?

If you want white back button (?) and white toolbar title, follow this:

<android.support.design.widget.AppBarLayout
        android:id="@+id/app_bar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light" />
    </android.support.design.widget.AppBarLayout>

Change theme from Dark to Light if you want black back button (?) and black toolbar title.

MongoDB: How to query for records where field is null or not set?

db.employe.find({ $and:[ {"dept":{ $exists:false }, "empno": { $in:[101,102] } } ] }).count();

How to fix "Incorrect string value" errors?

Hi i also got this error when i use my online databases from godaddy server i think it has the mysql version of 5.1 or more. but when i do from my localhost server (version 5.7) it was fine after that i created the table from local server and copied to the online server using mysql yog i think the problem is with character set

Screenshot Here

Run a .bat file using python code

You are just missing to make it raw. The issue is with "\". Adding r before the path would do the work :)

import os
os.system(r"D:\xxx1\xxx2XMLnew\otr.bat")

Use of Finalize/Dispose method in C#

Pattern from msdn

public class BaseResource: IDisposable
{
   private IntPtr handle;
   private Component Components;
   private bool disposed = false;
   public BaseResource()
   {
   }
   public void Dispose()
   {
      Dispose(true);      
      GC.SuppressFinalize(this);
   }
   protected virtual void Dispose(bool disposing)
   {
      if(!this.disposed)
      {        
         if(disposing)
         {
            Components.Dispose();
         }         
         CloseHandle(handle);
         handle = IntPtr.Zero;
       }
      disposed = true;         
   }
   ~BaseResource()      
   {      Dispose(false);
   }
   public void DoSomething()
   {
      if(this.disposed)
      {
         throw new ObjectDisposedException();
      }
   }
}
public class MyResourceWrapper: BaseResource
{
   private ManagedResource addedManaged;
   private NativeResource addedNative;
   private bool disposed = false;
   public MyResourceWrapper()
   {
   }
   protected override void Dispose(bool disposing)
   {
      if(!this.disposed)
      {
         try
         {
            if(disposing)
            {             
               addedManaged.Dispose();         
            }
            CloseHandle(addedNative);
            this.disposed = true;
         }
         finally
         {
            base.Dispose(disposing);
         }
      }
   }
}

C# Example of AES256 encryption using System.Security.Cryptography.Aes

Once I'd discovered all the information of how my client was handling the encryption/decryption at their end it was straight forward using the AesManaged example suggested by dtb.

The finally implemented code started like this:

    try
    {
        // Create a new instance of the AesManaged class.  This generates a new key and initialization vector (IV).
        AesManaged myAes = new AesManaged();

        // Override the cipher mode, key and IV
        myAes.Mode = CipherMode.ECB;
        myAes.IV = new byte[16] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // CRB mode uses an empty IV
        myAes.Key = CipherKey;  // Byte array representing the key
        myAes.Padding = PaddingMode.None;

        // Create a encryption object to perform the stream transform.
        ICryptoTransform encryptor = myAes.CreateEncryptor();

        // TODO: perform the encryption / decryption as required...

    }
    catch (Exception ex)
    {
        // TODO: Log the error 
        throw ex;
    }

Multiple Errors Installing Visual Studio 2015 Community Edition

My problem did not go away with just reinstalling the 2015 vc redistributables. But I was able to find the error using the same process as in the excellent blog post by Ezh (and thanks to Google Translate for making me able to read it).

In my case it was msvcp140.dll that was installed as a 64bit version in the Windows/SysWOW64 folder. Just uninstalling the redistributables did not remove the file, so I had to delete it manually. Then I was able to install the x86 redistributables again, which installed a correct version of the dll file. And, voilà, the installation of VS2015 finished without errors.

How to enable php7 module in apache?

I found the solution on the following thread : https://askubuntu.com/questions/760907/upgrade-to-16-04-php7-not-working-in-browser

Im my case not only the php wasn't working but phpmyadmin aswell i did step by step like that

sudo apt install php libapache2-mod-php
sudo apt install php7.0-mbstring
sudo a2dismod mpm_event
sudo a2enmod mpm_prefork
service apache2 restart

And then to:

gksu gedit /etc/apache2/apache2.conf

In the last line I do add Include /etc/phpmyadmin/apache.conf

That make a deal with all problems

Maciej

If it solves your problem, up vote this solution in the original post.

How to insert image in mysql database(table)?

You should use LOAD_FILE like so:

LOAD_FILE('/some/path/image.png')

Strip / trim all strings of a dataframe

You can use DataFrame.select_dtypes to select string columns and then apply function str.strip.

Notice: Values cannot be types like dicts or lists, because their dtypes is object.

df_obj = df.select_dtypes(['object'])
print (df_obj)
0    a  
1    c  

df[df_obj.columns] = df_obj.apply(lambda x: x.str.strip())
print (df)

   0   1
0  a  10
1  c   5

But if there are only a few columns use str.strip:

df[0] = df[0].str.strip()

Laravel 5.2 - Use a String as a Custom Primary Key for Eloquent Table becomes 0

This was added to the upgrade documentation on Dec 29, 2015, so if you upgraded before then you probably missed it.

When fetching any attribute from the model it checks if that column should be cast as an integer, string, etc.

By default, for auto-incrementing tables, the ID is assumed to be an integer in this method:

https://github.com/laravel/framework/blob/5.2/src/Illuminate/Database/Eloquent/Model.php#L2790

So the solution is:

class UserVerification extends Model
{
    protected $primaryKey = 'your_key_name'; // or null

    public $incrementing = false;

    // In Laravel 6.0+ make sure to also set $keyType
    protected $keyType = 'string';
}

Jquery find nearest matching element

var otherInput = $(this).closest('.row').find('.inputQty');

That goes up to a row level, then back down to .inputQty.

multiple figure in latex with captions

Look at the Subfloats section of http://en.wikibooks.org/wiki/LaTeX/Floats,_Figures_and_Captions.

\begin{figure}[htp]
  \centering
  \label{figur}\caption{equation...}

  \subfloat[Subcaption 1]{\label{figur:1}\includegraphics[width=60mm]{explicit3185.eps}}
  \subfloat[Subcaption 2]{\label{figur:2}\includegraphics[width=60mm]{explicit3183.eps}}
  \\
  \subfloat[Subcaption 3]{\label{figur:3}\includegraphics[width=60mm]{explicit1501.eps}}
  \subfloat[Subcaption 4]{\label{figur:4}\includegraphics[width=60mm]{explicit23185.eps}}
  \\
  \subfloat[Subcaption 5]{\label{figur:5}\includegraphics[width=60mm]{explicit23183.eps}}
  \subfloat[Subcaption 6]{\label{figur:6}\includegraphics[width=60mm]{explicit21501.eps}}

\end{figure}

Loop through JSON object List

Here it is:

success: 
    function(data) {
        $.each(data, function(i, item){
            alert("Mine is " + i + "|" + item.title + "|" + item.key);
        });
    }

Sample JSON text:

{"title": "camp crowhouse", 
"key": "agtnZW90YWdkZXYyMXIKCxIEUG9zdBgUDA"}

SQL Server 2008 Connection Error "No process is on the other end of the pipe"

Forcing the TCP/IP connection (by providing 127.0.0.1 instead of localhost or .) can reveal the real reason for the error. In my case, the database name specified in connection string was incorrect.

So, here is the checklist so far:

  • Make sure Named Pipe is enabled in configuration manager (don't forget to restart the server).
  • Make sure SQL Server Authentication (or Mixed Mode) is enabled.
  • Make sure your user name and password are correct.
  • Make sure the database you are connecting to exists.