Programs & Examples On #Cross product

Fit Image into PictureBox

The PictureBox.SizeMode options are missing a "fill" or "cover" mode which would be like zoom except with cropping to ensure you're filling the picture box. In CSS it's the "cover" option.

This code should enable that:

static public void fillPictureBox(PictureBox pbox, Bitmap bmp)
{
    pbox.SizeMode = PictureBoxSizeMode.Normal;
    bool source_is_wider = (float)bmp.Width / bmp.Height > (float)pbox.Width / pbox.Height;

    var resized = new Bitmap(pbox.Width, pbox.Height);
    var g = Graphics.FromImage(resized);        
    var dest_rect = new Rectangle(0, 0, pbox.Width, pbox.Height);
    Rectangle src_rect;

    if (source_is_wider)
    {
        float size_ratio = (float)pbox.Height / bmp.Height;
        int sample_width = (int)(pbox.Width / size_ratio);
        src_rect = new Rectangle((bmp.Width - sample_width) / 2, 0, sample_width, bmp.Height);
    }
    else
    {
        float size_ratio = (float)pbox.Width / bmp.Width;
        int sample_height = (int)(pbox.Height / size_ratio);
        src_rect = new Rectangle(0, (bmp.Height - sample_height) / 2, bmp.Width, sample_height);
    }

    g.DrawImage(bmp, dest_rect, src_rect, GraphicsUnit.Pixel);
    g.Dispose();

    pbox.Image = resized;
}

How do I parse a URL into hostname and path in javascript?

Stop reinventing the wheel. Use https://github.com/medialize/URI.js/

var uri = new URI("http://example.org:80/foo/hello.html");
// get host
uri.host(); // returns string "example.org:80"
// set host
uri.host("example.org:80");

What is the difference between ng-if and ng-show/ng-hide

One interesting difference in ng-if and ng-show is:

SECURITY

DOM elements present in ng-if block will not be rendered in case of its value as false

where as in case of ng-show, the user can open your Inspect Element Window and set its value to TRUE.

And with a whoop, whole contents that was meant to be hidden gets displayed, which is a security breach. :)

What is the format for the PostgreSQL connection string / URL?

Here is the documentation for JDBC, the general URL is "jdbc:postgresql://host:port/database"

Chapter 3 here documents the ADO.NET connection string, the general connection string is Server=host;Port=5432;User Id=username;Password=secret;Database=databasename;

PHP documentation us here, the general connection string is host=hostname port=5432 dbname=databasename user=username password=secret

If you're using something else, you'll have to tell us.

JAVA_HOME does not point to the JDK

I had a similar problem and it turned out the issue was having both versions 6 & 7 of OpenJDK. The answer comes from r-senior on ubuntu forums (http://ubuntuforums.org/showthread.php?t=1977619) --- just uninstall version 6:

sudo apt-get remove openjdk-6-*

make sure that JAVA_HOME and CLASSPATH aren't set to anything since that isn't actually the problem.

What causes the Broken Pipe Error?

Maybe the 40 bytes fits into the pipe buffer, and the 40000 bytes doesn't?

Edit:

The sending process is sent a SIGPIPE signal when you try to write to a closed pipe. I don't know exactly when the signal is sent, or what effect the pipe buffer has on this. You may be able to recover by trapping the signal with the sigaction call.

Java: get greatest common divisor

For int and long, as primitives, not really. For Integer, it is possible someone wrote one.

Given that BigInteger is a (mathematical/functional) superset of int, Integer, long, and Long, if you need to use these types, convert them to a BigInteger, do the GCD, and convert the result back.

private static int gcdThing(int a, int b) {
    BigInteger b1 = BigInteger.valueOf(a);
    BigInteger b2 = BigInteger.valueOf(b);
    BigInteger gcd = b1.gcd(b2);
    return gcd.intValue();
}

Execute jQuery function after another function completes

You should use a callback parameter:

function Typer(callback)
{
    var srcText = 'EXAMPLE ';
    var i = 0;
    var result = srcText[i];
    var interval = setInterval(function() {
        if(i == srcText.length - 1) {
            clearInterval(interval);
            callback();
            return;
        }
        i++;
        result += srcText[i].replace("\n", "<br />");
        $("#message").html(result);
    },
    100);
    return true;


}

function playBGM () {
    alert("Play BGM function");
    $('#bgm').get(0).play();
}

Typer(function () {
    playBGM();
});

// or one-liner: Typer(playBGM);

So, you pass a function as parameter (callback) that will be called in that if before return.

Also, this is a good article about callbacks.

_x000D_
_x000D_
function Typer(callback)_x000D_
{_x000D_
    var srcText = 'EXAMPLE ';_x000D_
    var i = 0;_x000D_
    var result = srcText[i];_x000D_
    var interval = setInterval(function() {_x000D_
        if(i == srcText.length - 1) {_x000D_
            clearInterval(interval);_x000D_
            callback();_x000D_
            return;_x000D_
        }_x000D_
        i++;_x000D_
        result += srcText[i].replace("\n", "<br />");_x000D_
        $("#message").html(result);_x000D_
    },_x000D_
    100);_x000D_
    return true;_x000D_
        _x000D_
    _x000D_
}_x000D_
_x000D_
function playBGM () {_x000D_
    alert("Play BGM function");_x000D_
    $('#bgm').get(0).play();_x000D_
}_x000D_
_x000D_
Typer(function () {_x000D_
    playBGM();_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>_x000D_
<div id="message">_x000D_
</div>_x000D_
<audio id="bgm" src="http://www.freesfx.co.uk/rx2/mp3s/9/10780_1381246351.mp3">_x000D_
</audio>
_x000D_
_x000D_
_x000D_

JSFIDDLE

Datatables on-the-fly resizing

Have you tried capturing the div resize event and doing .fnDraw() on the datatable? fnDraw should resize the table for you

C# code to validate email address

The most elegant way is to use .Net's built in methods.

These methods:

  • Are tried and tested. These methods are used in my own professional projects.

  • Use regular expressions internally, which are reliable and fast.

  • Made by Microsoft for C#. There's no need to reinvent the wheel.

  • Return a bool result. True means the email is valid.

For users of .Net 4.5 and greater

Add this Reference to your project:

System.ComponentModel.DataAnnotations

Now you can use the following code:

(new EmailAddressAttribute().IsValid("[email protected]"));

Example of use

Here are some methods to declare:

protected List<string> GetRecipients() // Gets recipients from TextBox named `TxtRecipients`
{
    List<string> MethodResult = null;

    try
    {
        List<string> Recipients = TxtRecipients.Text.Replace(",",";").Replace(" ", "").Split(';').ToList();

        List<string> RecipientsCleaned = new List<string>();

        foreach (string Recipient in RecipientsCleaned)
        {
            if (!String.IsNullOrWhiteSpace(Recipient))
            {
                RecipientsNoBlanks.Add(Recipient);

            }

        }

        MethodResult = RecipientsNoBlanks;

    }
    catch//(Exception ex)
    {
        //ex.HandleException();
    }

    return MethodResult;

}


public static bool IsValidEmailAddresses(List<string> recipients)
{
    List<string> InvalidAddresses = GetInvalidEmailAddresses(recipients);

    return InvalidAddresses != null && InvalidAddresses.Count == 0;

}

public static List<string> GetInvalidEmailAddresses(List<string> recipients)
{
    List<string> MethodResult = null;

    try
    {
        List<string> InvalidEmailAddresses = new List<string>();

        foreach (string Recipient in recipients)
        {
            if (!(new EmailAddressAttribute().IsValid(Recipient)) && !InvalidEmailAddresses.Contains(Recipient))
            {
                InvalidEmailAddresses.Add(Recipient);

            }

        }

        MethodResult = InvalidEmailAddresses;

    }
    catch//(Exception ex)
    {
        //ex.HandleException();

    }

    return MethodResult;

}

...and code demonstrating them in action:

List<string> Recipients = GetRecipients();

bool IsValidEmailAddresses = IsValidEmailAddresses(Recipients);

if (IsValidEmailAddresses)
{
    //Emails are valid. Your code here

}
else
{
    StringBuilder sb = new StringBuilder();

    sb.Append("The following addresses are invalid:");

    List<string> InvalidEmails = GetInvalidEmailAddresses(Recipients);

    foreach (string InvalidEmail in InvalidEmails)
    {
        sb.Append("\n" + InvalidEmail);

    }

    MessageBox.Show(sb.ToString());

}

In addition, this example:

  • Extends beyond the spec since a single string is used to contain 0, one or many email addresses sperated by a semi-colon ;.
  • Clearly demonstrates how to use the IsValid method of the EmailAddressAttribute object.

Alternative, for users of a version of .Net less than 4.5

For situations where .Net 4.5 is not available, I use the following solution:

Specifically, I use:

public static bool IsValidEmailAddress(string emailAddress)
{
    bool MethodResult = false;

    try
    {
        MailAddress m = new MailAddress(emailAddress);

        MethodResult = m.Address == emailAddress;

    }
    catch //(Exception ex)
    {
        //ex.HandleException();

    }

    return MethodResult;

}

public static List<string> GetInvalidEmailAddresses(List<string> recipients)
{
    List<string> MethodResult = null;

    try
    {
        List<string> InvalidEmailAddresses = new List<string>();

        foreach (string Recipient in recipients)
        {
            if (!IsValidEmail(Recipient) && !InvalidEmailAddresses.Contains(Recipient))
            {
                InvalidEmailAddresses.Add(Recipient);

            }

        }

        MethodResult = InvalidEmailAddresses;

    }
    catch //(Exception ex)
    {
        //ex.HandleException();

    }

    return MethodResult;

}

How to use npm with node.exe?

I just installed latest version of node (0.6.12) in Windows 7 using msi (node-v0.6.12.msi).

npm is already shipped with it, no need to include it separately.

I was facing permission issue while running npm (npm install mysql), from the path where my nodejs resided, i.e. C:\Program Files (x86)\nodejs

Then I followed below steps:

1) Added C:\Program Files (x86)\nodejs\npm in environment variables - Path system variable.

2) went back to only C:\ in command prompt and gave the command - npm install mysql - and voila! it worked..

Hope this helps.

How to check if a process is in hang state (Linux)

Is there any command in Linux through which i can know if the process is in hang state.

There is no command, but once I had to do a very dumb hack to accomplish something similar. I wrote a Perl script which periodically (every 30 seconds in my case):

  • run ps to find list of PIDs of the watched processes (along with exec time, etc)
  • loop over the PIDs
  • start gdb attaching to the process using its PID, dumping stack trace from it using thread apply all where, detaching from the process
  • a process was declared hung if:
    • its stack trace didn't change and time didn't change after 3 checks
    • its stack trace didn't change and time was indicating 100% CPU load after 3 checks
  • hung process was killed to give a chance for a monitoring application to restart the hung instance.

But that was very very very very crude hack, done to reach an about-to-be-missed deadline and it was removed a few days later, after a fix for the buggy application was finally installed.

Otherwise, as all other responders absolutely correctly commented, there is no way to find whether the process hung or not: simply because the hang might occur for way to many reasons, often bound to the application logic.

The only way is for application itself being capable of indicating whether it is alive or not. Simplest way might be for example a periodic log message "I'm alive".

jQuery - Trigger event when an element is removed from the DOM

an extension to Adam's answer incase you need to prevend default, here is a work around:

$(document).on('DOMNodeRemoved', function(e){
        if($(e.target).hasClass('my-elm') && !e.target.hasAttribute('is-clone')){
            let clone = $(e.target).clone();
            $(clone).attr('is-clone', ''); //allows the clone to be removed without triggering the function again

            //you can do stuff to clone here (ex: add a fade animation)

            $(clone).insertAfter(e.target);
            setTimeout(() => {
                //optional remove clone after 1 second
                $(clone).remove();
            }, 1000);
        }
    });

How to convert password into md5 in jquery?

Download and include this plugin

<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/3.1.2/rollups/md5.js"></script>

and use like

if(CryptoJS.MD5($("#txtOldPassword").val())) != oldPassword) {

}

//Following lines shows md5 value
//var hash = CryptoJS.MD5("Message");
//alert(hash);

Live Video Streaming with PHP

PHP will let you build the pages of your site that make up your video conferencing and chat applications, but it won't deliver or stream video for you - PHP runs on the server only and renders out HTML to a client browser.

For the video, the first thing you'll need is a live streaming account with someone like akamai or the numerous others in the field. Using this account gives you an ingress point for your video - ie: the server that you will stream your live video up to.

Next, you want to get your video out to the browsers - windows media player, flash or silverlight will let you achieve this - embedding the appropriate control for your chosen technology into your page (using PHP or whatever) and given the address of your live video feed.

PHP (or other scripting language) would be used to build the chat part of the application and bring the whole thing together (the chat and the embedded video player).

Hope this helps.

What are the differences between LDAP and Active Directory?

https://jumpcloud.com/blog/difference-between-ldap-and-active-directory/

Realistically, there are probably more differences than similarities between the two directory solutions. Microsoft’s AD is largely a directory for Windows users, devices, and applications. AD requires a Microsoft Domain Controller to be present and when it is, users are able to single sign-on to Windows resources that live within the domain structure.

LDAP, on the other hand, has largely worked outside of the Windows structure focusing on the Linux / Unix environment and with more technical applications. LDAP doesn’t have the same concepts of domains or single sign-on. LDAP is largely implemented with open source solutions and as a result has more flexibility than AD.

Another critical difference between LDAP and Active Directory is how AD and LDAP each approach device management. AD manages Windows devices through and Group Policy Objects (GPOs). A similar concept doesn’t exist within LDAP. Both LDAP and AD are highly different solutions and as a result many organization must leverage both to serve different purposes.

This is why there’s an obvious opportunity for innovation. Why leverage and manage two complete systems, when one system can effectively merge the two?

How to append strings using sprintf?

What about:

char s[100] = "";

sprintf(s, "%s%s", s, "s1");

sprintf(s, "%s%s", s, "s2");

sprintf(s, "%s%s", s, "s3");

printf("%s", s);

But take into account possible buffer ovewflows!

How do I get the calling method name and type using reflection?

You can use it by using the StackTrace and then you can get reflective types from that.

StackTrace stackTrace = new StackTrace();           // get call stack
StackFrame[] stackFrames = stackTrace.GetFrames();  // get method calls (frames)

StackFrame callingFrame = stackFrames[1];
MethodInfo method = callingFrame.GetMethod();
Console.Write(method.Name);
Console.Write(method.DeclaringType.Name);

What's faster, SELECT DISTINCT or GROUP BY in MySQL?

Go for the simplest and shortest if you can -- DISTINCT seems to be more what you are looking for only because it will give you EXACTLY the answer you need and only that!

An exception of type 'System.NullReferenceException' occurred in myproject.DLL but was not handled in user code

It means somewhere in your chain of calls, you tried to access a Property or call a method on an object that was null.

Given your statement:

img1.ImageUrl = ConfigurationManager
                    .AppSettings
                    .Get("Url")
                    .Replace("###", randomString) 
                + Server.UrlEncode(
                      ((System.Web.UI.MobileControls.Form)Page
                      .FindControl("mobileForm"))
                      .Title);

I'm guessing either the call to AppSettings.Get("Url") is returning null because the value isn't found or the call to Page.FindControl("mobileForm") is returning null because the control isn't found.

You could easily break this out into multiple statements to solve the problem:

var configUrl = ConfigurationManager.AppSettings.Get("Url");
var mobileFormControl = Page.FindControl("mobileForm")
                            as System.Web.UI.MobileControls.Form;

if(configUrl != null && mobileFormControl != null)
{
    img1.ImageUrl = configUrl.Replace("###", randomString) + mobileControl.Title;
}

Upload Progress Bar in PHP

HTML5 introduced a file upload api that allows you to monitor the progress of file uploads but for older browsers there's plupload a framework that specifically made to monitor file uploads and give information about them. plus it has plenty of callbacks so it can work across all browsers

Get the value of checked checkbox?

If you want to get the values of all checkboxes using jQuery, this might help you. This will parse the list and depending on the desired result, you can execute other code. BTW, for this purpose, one does not need to name the input with brackets []. I left them off.

  $(document).on("change", ".messageCheckbox", function(evnt){
    var data = $(".messageCheckbox");
    data.each(function(){
      console.log(this.defaultValue, this.checked);
      // Do something... 
    });
  }); /* END LISTENER messageCheckbox */

Android Firebase, simply get one child object's data

Firebase listeners fire for both the initial data and any changes.

If you're looking to synchronize the data in a collection, use ChildEventListener. If you're looking to synchronize a single object, use ValueEventListener. Note that in both cases you're not "getting" the data. You're synchronizing it, which means that the callback may be invoked multiple times: for the initial data and whenever the data gets updated.

This is covered in Firebase's quickstart guide for Android. The relevant code and quote:

FirebaseRef.child("message").addValueEventListener(new ValueEventListener() {
  @Override
  public void onDataChange(DataSnapshot snapshot) {
    System.out.println(snapshot.getValue());  //prints "Do you have data? You'll love Firebase."
  }
  @Override
  public void onCancelled(DatabaseError databaseError) {        
  }
});

In the example above, the value event will fire once for the initial state of the data, and then again every time the value of that data changes.

Please spend a few moments to go through that quick start. It shouldn't take more than 15 minutes and it will save you from a lot of head scratching and questions. The Firebase Android Guide is probably a good next destination, for this question specifically: https://firebase.google.com/docs/database/android/read-and-write

Test if string is a number in Ruby on Rails

this is how i do it, but i think too there must be a better way

object.to_i.to_s == object || object.to_f.to_s == object

How do I initialize a byte array in Java?

You can use the Java UUID class to store these values, instead of byte arrays:

UUID

public UUID(long mostSigBits,
            long leastSigBits)

Constructs a new UUID using the specified data. mostSigBits is used for the most significant 64 bits of the UUID and leastSigBits becomes the least significant 64 bits of the UUID.

How to send an HTTP request using Telnet

You could do

telnet stackoverflow.com 80

And then paste

GET /questions HTTP/1.0
Host: stackoverflow.com


# add the 2 empty lines above but not this one

Here is a transcript

$ telnet stackoverflow.com 80
Trying 151.101.65.69...
Connected to stackoverflow.com.
Escape character is '^]'.
GET /questions HTTP/1.0
Host: stackoverflow.com

HTTP/1.1 200 OK
Content-Type: text/html; charset=utf-8
...

The client and server cannot communicate, because they do not possess a common algorithm - ASP.NET C# IIS TLS 1.0 / 1.1 / 1.2 - Win32Exception

Enabling TLS 1.0 solved our issues as well (after disabling SSL v3). (Server 2012 R2 with ASP.net 4.0 website processing against PPI pay services). This is the RegEdit script I used to set everything the way I wanted. We only disabled SSL v3 for the Client and not the server as doing that broke other things that we were not ready to deal with yet. After we upgrade the site to .Net 4.5.2 then we will disable TLS 1.0 again.

This script enables all protocols, Server and Client except for SSL v3 for the Client.

Be sure to backup your registry!

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 3.0\Client]
"Enabled"=dword:00000000

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 3.0\Server]
"Enabled"=dword:00000001

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.0\Client]
"Enabled"=dword:00000001

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.0\Client]
"DisabledByDefault"=dword:00000000

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.0\Server]
"Enabled"=dword:00000001

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.0\Server]
"DisabledByDefault"=dword:00000000

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Client]
"Enabled"=dword:00000001

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Client]
"DisabledByDefault"=dword:00000000

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Server]
"Enabled"=dword:00000001

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Server]
"DisabledByDefault"=dword:00000000

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client]
"Enabled"=dword:00000001

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client]
"DisabledByDefault"=dword:00000000

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server]
"Enabled"=dword:00000001

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server]
"DisabledByDefault"=dword:00000000

How to make a transparent HTML button?

**add the icon top button like this **

_x000D_
_x000D_
#copy_btn{_x000D_
 align-items: center;_x000D_
 position: absolute;_x000D_
 width: 30px;_x000D_
  height: 30px;_x000D_
     background-color: Transparent;_x000D_
    background-repeat:no-repeat;_x000D_
    border: none;_x000D_
    cursor:pointer;_x000D_
    overflow: hidden;_x000D_
    outline:none;_x000D_
}_x000D_
.icon_copy{_x000D_
 position: absolute;_x000D_
 padding: 0px;_x000D_
 top:0;_x000D_
 left: 0;_x000D_
width: 25px;_x000D_
  height: 35px;_x000D_
  _x000D_
}
_x000D_
<button id="copy_btn">_x000D_
_x000D_
                        <img class="icon_copy" src="./assest/copy.svg" alt="Copy Text">_x000D_
</button>
_x000D_
_x000D_
_x000D_

imagecreatefromjpeg and similar functions are not working in PHP

You must enable the library GD2.

Find your (proper) php.ini file

Find the line: ;extension=php_gd2.dll and remove the semicolon in the front.

The line should look like this:

extension=php_gd2.dll

Then restart apache and you should be good to go.

Remove object from a list of objects in python

In python there are no arrays, lists are used instead. There are various ways to delete an object from a list:

my_list = [1,2,4,6,7]

del my_list[1] # Removes index 1 from the list
print my_list # [1,4,6,7]
my_list.remove(4) # Removes the integer 4 from the list, not the index 4
print my_list # [1,6,7]
my_list.pop(2) # Removes index 2 from the list

In your case the appropriate method to use is pop, because it takes the index to be removed:

x = object()
y = object()
array = [x, y]
array.pop(0)
# Using the del statement
del array[0]

Regex match everything after question mark?

\?(.*)$

If you want to match all chars after "?" you can use a group to match any char, and you'd better use the "$" sign to indicate the end of line.

How to create and add users to a group in Jenkins for authentication?

I installed the Role plugin under Jenkins-3.5, but it does not show the "Manage Roles" option under "Manage Jenkins", and when one follows the security install page from the wiki, all users are locked out instantly. I had to manually shutdown Jenkins on the server, restore the correct configuration settings (/me is happy to do proper backups) and restart Jenkins.

I didn't have high hopes, as that plugin was last updated in 2011

Sort collection by multiple fields in Kotlin

sortedWith + compareBy (taking a vararg of lambdas) do the trick:

val sortedList = list.sortedWith(compareBy({ it.age }, { it.name }))

You can also use the somewhat more succinct callable reference syntax:

val sortedList = list.sortedWith(compareBy(Person::age, Person::name))

Adding dictionaries together, Python

dic0.update(dic1)

Note this doesn't actually return the combined dictionary, it just mutates dic0.

UnsatisfiedDependencyException: Error creating bean with name

Add @Repository annotation to the Spring Data JPA repo

onActivityResult is not being called in Fragment

Simply use the below code for the fragment.

@Override
public void onOtherButtonClick(ActionSheet actionSheet, int index) {

    if (index == 1)
    {
        Intent intent = new Intent(Intent.ACTION_PICK,
                                   android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        intent.setType("image/*");
        startActivityForResult(Intent.createChooser(intent,
                                                    "Select Picture"), 1);
     }
}

public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if (resultCode == 1) {
        if (requestCode == 1) {
            Uri selectedImageUri = data.getData();
            //selectedImagePath = getPath(selectedImageUri);
        }
    }
}

onActivityResult will call without calling its parent.

How to elegantly check if a number is within a range?

If it's to validate method parameters, none of the solutions throw ArgumentOutOfRangeException and allow easy/proper configuration of inclusive/exclusive min/max values.

Use like this

public void Start(int pos)
{
    pos.CheckRange(nameof(pos), min: 0);

    if (pos.IsInRange(max: 100, maxInclusive: false))
    {
        // ...
    }
}

I just wrote these beautiful functions. It also has the advantage of having no branching (a single if) for valid values. The hardest part is to craft the proper exception messages.

/// <summary>
/// Returns whether specified value is in valid range.
/// </summary>
/// <typeparam name="T">The type of data to validate.</typeparam>
/// <param name="value">The value to validate.</param>
/// <param name="min">The minimum valid value.</param>
/// <param name="minInclusive">Whether the minimum value is valid.</param>
/// <param name="max">The maximum valid value.</param>
/// <param name="maxInclusive">Whether the maximum value is valid.</param>
/// <returns>Whether the value is within range.</returns>
public static bool IsInRange<T>(this T value, T? min = null, bool minInclusive = true, T? max = null, bool maxInclusive = true)
    where T : struct, IComparable<T>
{
    var minValid = min == null || (minInclusive && value.CompareTo(min.Value) >= 0) || (!minInclusive && value.CompareTo(min.Value) > 0);
    var maxValid = max == null || (maxInclusive && value.CompareTo(max.Value) <= 0) || (!maxInclusive && value.CompareTo(max.Value) < 0);
    return minValid && maxValid;
}

/// <summary>
/// Validates whether specified value is in valid range, and throws an exception if out of range.
/// </summary>
/// <typeparam name="T">The type of data to validate.</typeparam>
/// <param name="value">The value to validate.</param>
/// <param name="name">The name of the parameter.</param>
/// <param name="min">The minimum valid value.</param>
/// <param name="minInclusive">Whether the minimum value is valid.</param>
/// <param name="max">The maximum valid value.</param>
/// <param name="maxInclusive">Whether the maximum value is valid.</param>
/// <returns>The value if valid.</returns>
public static T CheckRange<T>(this T value, string name, T? min = null, bool minInclusive = true, T? max = null, bool maxInclusive = true)
where T : struct, IComparable<T>
{
    if (!value.IsInRange(min, minInclusive, max, maxInclusive))
    {
        if (min.HasValue && minInclusive && max.HasValue && maxInclusive)
        {
            var message = "{0} must be between {1} and {2}.";
            throw new ArgumentOutOfRangeException(name, value, message.FormatInvariant(name, min, max));
        }
        else
        {
            var messageMin = min.HasValue ? GetOpText(true, minInclusive).FormatInvariant(min) : null;
            var messageMax = max.HasValue ? GetOpText(false, maxInclusive).FormatInvariant(max) : null;
            var message = (messageMin != null && messageMax != null) ?
                "{0} must be {1} and {2}." :
                "{0} must be {1}.";
            throw new ArgumentOutOfRangeException(name, value, message.FormatInvariant(name, messageMin ?? messageMax, messageMax));
        }
    }
    return value;
}

private static string GetOpText(bool greaterThan, bool inclusive)
{
    return (greaterThan && inclusive) ? "greater than or equal to {0}" :
        greaterThan ? "greater than {0}" :
        inclusive ? "less than or equal to {0}" :
        "less than {0}";
}

public static string FormatInvariant(this string format, params object?[] args) => string.Format(CultureInfo.InvariantCulture, format, args);

How to convert an Stream into a byte[] in C#?

if you post a file from mobile device or other

    byte[] fileData = null;
    using (var binaryReader = new BinaryReader(Request.Files[0].InputStream))
    {
        fileData = binaryReader.ReadBytes(Request.Files[0].ContentLength);
    }

Apache Tomcat Not Showing in Eclipse Server Runtime Environments

You may get more success if you do a "search" for the runtime env from the preferences screen instead of hitting "add" - see this demo on youtube. http://www.youtube.com/watch?v=EOkN5IPoJVs&playnext_from=TL&videos=rVnITzSU2Z8 - When you hit search, you are prompted to point to the tomcat directory and then it SHOULD add it as a server runtime environment. Unfortunately for me, that is not the case (I get "no new server runtime environments were found") But you might have more success.

How to put text over images in html?

You can try this...

<div class="image">

      <img src="" alt="" />

      <h2>Text you want to display over the image</h2>

</div>

CSS

.image { 
   position: relative; 
   width: 100%; /* for IE 6 */
}

h2 { 
   position: absolute; 
   top: 200px; 
   left: 0; 
   width: 100%; 
}

Build unsigned APK file with Android Studio

AndroidStudio 3.4


After Grade Build Running complete, you will see the notification at bottom-right corner like.

Click on locate and you will see your debuggable APK

Illegal Escape Character "\"

You can use:

\\

That's ok, for example:

if (invName.substring(j,k).equals("\\")) {
    copyf=invName.substring(0,j);
}

How to set a variable to be "Today's" date in Python/Pandas

Using pandas: pd.Timestamp("today").strftime("%m/%d/%Y")

PHP How to find the time elapsed since a date time?

I liked Mithun's code, but I tweaked it a bit to make it give more reasonable answers.

function getTimeSince($eventTime)
{
    $totaldelay = time() - strtotime($eventTime);
    if($totaldelay <= 0)
    {
        return '';
    }
    else
    {
        $first = '';
        $marker = 0;
        if($years=floor($totaldelay/31536000))
        {
            $totaldelay = $totaldelay % 31536000;
            $plural = '';
            if ($years > 1) $plural='s';
            $interval = $years." year".$plural;
            $timesince = $timesince.$first.$interval;
            if ($marker) return $timesince;
            $marker = 1;
            $first = ", ";
        }
        if($months=floor($totaldelay/2628000))
        {
            $totaldelay = $totaldelay % 2628000;
            $plural = '';
            if ($months > 1) $plural='s';
            $interval = $months." month".$plural;
            $timesince = $timesince.$first.$interval;
            if ($marker) return $timesince;
            $marker = 1;
            $first = ", ";
        }
        if($days=floor($totaldelay/86400))
        {
            $totaldelay = $totaldelay % 86400;
            $plural = '';
            if ($days > 1) $plural='s';
            $interval = $days." day".$plural;
            $timesince = $timesince.$first.$interval;
            if ($marker) return $timesince;
            $marker = 1;
            $first = ", ";
        }
        if ($marker) return $timesince;
        if($hours=floor($totaldelay/3600))
        {
            $totaldelay = $totaldelay % 3600;
            $plural = '';
            if ($hours > 1) $plural='s';
            $interval = $hours." hour".$plural;
            $timesince = $timesince.$first.$interval;
            if ($marker) return $timesince;
            $marker = 1;
            $first = ", ";

        }
        if($minutes=floor($totaldelay/60))
        {
            $totaldelay = $totaldelay % 60;
            $plural = '';
            if ($minutes > 1) $plural='s';
            $interval = $minutes." minute".$plural;
            $timesince = $timesince.$first.$interval;
            if ($marker) return $timesince;
            $first = ", ";
        }
        if($seconds=floor($totaldelay/1))
        {
            $totaldelay = $totaldelay % 1;
            $plural = '';
            if ($seconds > 1) $plural='s';
            $interval = $seconds." second".$plural;
            $timesince = $timesince.$first.$interval;
        }        
        return $timesince;

    }
}

ORA-12170: TNS:Connect timeout occurred

TROUBLESHOOTING STEPS (Doc ID 730066.1)

Connection Timeout errors ORA-3135 and ORA-3136 A connection timeout error can be issued when an attempt to connect to the database does not complete its connection and authentication phases within the time period allowed by the following: SQLNET.INBOUND_CONNECT_TIMEOUT and/or INBOUND_CONNECT_TIMEOUT_ server-side parameters.

Starting with Oracle 10.2, the default for these parameters is 60 seconds where in previous releases it was 0, meaning no timeout.

On a timeout, the client program will receive the ORA-3135 (or possibly TNS-3135) error:

ORA-3135 connection lost contact

and the database will log the ORA-3136 error in its alert.log:

... Sat May 10 02:21:38 2008 WARNING: inbound connection timed out (ORA-3136) ...

  • Authentication SQL

When a database session is in the authentication phase, it will issue a sequence of SQL statements. The authentication is not complete until all these are parsed, executed, fetched completely. Some of the SQL statements in this list e.g. on 10.2 are:

select value$ from props$ where name = 'GLOBAL_DB_NAME'

select privilege#,level from sysauth$ connect by grantee#=prior privilege# 
and privilege#>0 start with grantee#=:1 and privilege#>0

select SYS_CONTEXT('USERENV', 'SERVER_HOST'), SYS_CONTEXT('USERENV', 'DB_UNIQUE_NAME'),
SYS_CONTEXT('USERENV', 'INSTANCE_NAME'), SYS_CONTEXT('USERENV', 'SERVICE_NAME'), 
INSTANCE_NUMBER, STARTUP_TIME, SYS_CONTEXT('USERENV', 'DB_DOMAIN') 
from v$instance where INSTANCE_NAME=SYS_CONTEXT('USERENV', 'INSTANCE_NAME')

select privilege# from sysauth$ where (grantee#=:1 or grantee#=1) and privilege#>0

ALTER SESSION SET NLS_LANGUAGE= 'AMERICAN' NLS_TERRITORY= 'AMERICA' NLS_CURRENCY= '$'
NLS_ISO_CURRENCY= 'AMERICA' NLS_NUMERIC_CHARACTERS= '.,' NLS_CALENDAR= 'GREGORIAN'
NLS_DATE_FORMAT= 'DD-MON-RR' NLS_DATE_LANGUAGE= 'AMERICAN' NLS_SORT= 'BINARY' TIME_ZONE= '+02:00'
NLS_COMP= 'BINARY' NLS_DUAL_CURRENCY= '$' NLS_TIME_FORMAT= 'HH.MI.SSXFF AM' NLS_TIMESTAMP_FORMAT=
'DD-MON-RR HH.MI.SSXFF AM' NLS_TIME_TZ_FORMAT= 'HH.MI.SSXFF AM TZR' NLS_TIMESTAMP_TZ_FORMAT=
'DD-MON-RR HH.MI.SSXFF AM TZR'

NOTE: The list of SQL above is not complete and does not represent the ordering of the authentication SQL . Differences may also exist from release to release.

  • Hangs during Authentication

The above SQL statements need to be Parsed, Executed and Fetched as happens for all SQL inside an Oracle Database. It follows that any problem encountered during these phases which appears as a hang or severe slow performance may result in a timeout.

Symptoms of such hangs will be seen by the authenticating session as waits for: • cursor: pin S wait on X • latch: row cache objects • row cache lock Other types of wait events are possible; this list may not be complete.

The issue here is that the authenticating session is blocked waiting to get a shared resource which is held by another session inside the database. That blocker session is itself occupied in a long-running activity (or its own hang) which prevents it from releasing the shared resource needed by the authenticating session in a timely fashion. This results in the timeout being eventually reported to the authenticating session.

  • Troubleshooting of Authentication hangs

In such situations, we need to find out the blocker process holding the shared resource needed by the authenticating session in order to see what is happening to it.

Typical diagnostics used in such cases are the following:

  1. Three consecutive systemstate dumps at level 266 during the time that one or more authenticating sessions are blocked. It is likely that the blocking session will have caused timeouts to more than one connection attempt. Hence, systemstate dumps can be useful even when the time needed to generate them exceeds the period of a single timeout e.g. 60 sec:
      $ sqlplus -prelim '/ as sysdba' 

       oradebug setmypid 
       oradebug unlimit 
       oradebug dump systemstate 266 
       ...wait 90 seconds 
       oradebug dump systemstate 266 
       ...wait 90 seconds 
       oradebug dump systemstate 266 
       quit
  • ASH reports covering e.g. 10-15 minutes of a time period during which several timeout errors were seen.
  • If possible, Two consecutive queries on V$LATCHHOLDER view for the case where the shared resource being waited for is a latch. select * from v$latchholder; The systemstate dumps should help in identifying the blocker session. Level 266 will show us in what code it is executing which may help in locating any existing bug as the root cause.

Examples of issues which can result in Authentication hangs

  • Unpublished Bug 6879763 shared pool simulator bug fixed by patch for unpublished Bug 6966286 see Note 563149.1
  • Unpublished Bug 7039896 workaround parameter _enable_shared_pool_durations=false see Note 7039896.8

  • Other approaches to avoid the problem

In some cases, it may be possible to avoid problems with Authentication SQL by pinning such statements in the Shared Pool soon after the instance is started and they are freshly loaded. You can use the following artcile to advise on this: Document 726780.1 How to Pin a Cursor in the Shared Pool using DBMS_SHARED_POOL.KEEP

Pinning will prevent them from being flushed out due to inactivity and aging and will therefore prevent them for needing to be reloaded in the future i.e. needing to be reparsed and becoming susceptible to Authentication hang issues.

SQL Server using wildcard within IN

How about something like this?

declare @search table
(
    searchString varchar(10)
)

-- add whatever criteria you want...
insert into @search select '0711%' union select '0712%'

select j.*
from jobdetails j
    join @search s on j.job_no like s.searchString

Use Async/Await with Axios in React.js

In my experience over the past few months, I've realized that the best way to achieve this is:

class App extends React.Component{
  constructor(){
   super();
   this.state = {
    serverResponse: ''
   }
  }
  componentDidMount(){
     this.getData();
  }
  async getData(){
   const res = await axios.get('url-to-get-the-data');
   const { data } = await res;
   this.setState({serverResponse: data})
 }
 render(){
  return(
     <div>
       {this.state.serverResponse}
     </div>
  );
 }
}

If you are trying to make post request on events such as click, then call getData() function on the event and replace the content of it like so:

async getData(username, password){
 const res = await axios.post('url-to-post-the-data', {
   username,
   password
 });
 ...
}

Furthermore, if you are making any request when the component is about to load then simply replace async getData() with async componentDidMount() and change the render function like so:

render(){
 return (
  <div>{this.state.serverResponse}</div>
 )
}

Specify path to node_modules in package.json

Yarn supports this feature:

# .yarnrc file in project root
--modules-folder /node_modules

But your experience can vary depending on which packages you use. I'm not sure you'd want to go into that rabbit hole.

How to increase an array's length

First things first:

  • In Java, once an array is created, it's length is fixed. Arrays cannot be resized.
  • You can copy the elements of an array to a new array with a different size. The easiest way to do this, is to use one of the Arrays.copyOf() methods.
  • If you need a collection of variable size, you're probably better off using an ArrayList instead of an array.

That being said, there might be situations where you have no other choice than to change the size of an array that is created somewhere outside of your code.1 The only way to do that is to manipulate the generated bytecode of the code that creates the array.

Proof-of-concept

Below is a small proof-of-concept project that uses Java instrumentation to dynamically change the size of an array2. The sample project is a maven project with the following structure:

.
+- pom.xml
+- src
   +- main
      +- java
         +- com
            +- stackoverflow
               +- agent
                  +- Agent.java
                  +- test
                     +- Main.java

Main.java

This file contains the target class of which we're going to manipulate the bytecode:

package com.stackoverflow.agent.test;

import java.util.Arrays;

public class Main {
    public static void main(String[] args) {
        String[] array = {"Zero"};

        fun(array);

        System.out.println(Arrays.toString(array));
    }

    public static void fun(String[] array) {
        array[1] = "One";
        array[2] = "Two";
        array[3] = "Three";
        array[4] = "Four";
    }
}

In the main method, we create a String array of size 1. In the fun method, 4 additional values are assigned outside of the array's bounds. Running this code as-is will obviously result in an error.

Agent.java

This file contains the class that will perform the bytecode manipulation:

package com.stackoverflow.agent;

import java.lang.instrument.ClassFileTransformer;
import java.lang.instrument.Instrumentation;
import java.security.ProtectionDomain;

public class Agent {
    public static void premain(String args, Instrumentation instrumentation) {
        instrumentation.addTransformer(new ClassFileTransformer() {
            public byte[] transform(ClassLoader l, String name, Class<?> c,
                    ProtectionDomain d, byte[] b) {

                if (name.equals("com/stackoverflow/agent/test/Main")) {
                    byte iconst1 = (byte) 0x04;
                    byte iconst5 = (byte) 0x08;
                    byte anewarray = (byte) 0xbd;

                    for (int i = 0; i <= b.length - 1; i++) {
                        if (b[i] == iconst1 && b[i + 1] == anewarray) {
                            b[i] = iconst5;
                        }
                    }

                    return b;
                }

                return null;
            }
        });
    }
}

On the bytecode level, the creation of the String array in the Main class consists of two commands:

  • iconst_1, which pushes an int constant with value 1 onto the stack (0x04).
  • anewarray, which pops the value of the stack and creates a reference array3 of the same size (0xbd). The above code looks for that combination of commands in the Main class, and if found, replaces the const_1 command with a const_5 command (0x08), effectively changing the dimensions of the array to 5.4

pom.xml

The maven POM file is used to build the application JAR and configure the main class and the Java agent class.5

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
                             http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.stackoverflow</groupId>
  <artifactId>agent</artifactId>
  <version>1.0-SNAPSHOT</version>

  <build>
    <finalName>${project.artifactId}</finalName>
    <plugins>
      <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-jar-plugin</artifactId>
        <version>3.1.1</version>
        <configuration>
          <archive>
            <manifestEntries>
              <Main-Class>com.stackoverflow.agent.test.Main</Main-Class>
              <Premain-Class>com.stackoverflow.agent.Agent</Premain-Class>
              <Agent-Class>com.stackoverflow.agent.Agent</Agent-Class>
              <Can-Retransform-Classes>true</Can-Retransform-Classes>
            </manifestEntries>
          </archive>
        </configuration>
      </plugin>
    </plugins>
  </build>
</project>

Build and execute

The sample project can be built using the standard mvn clean package command.

Executing without referencing the agent code will yield the expected error:

$> java -jar target/agent.jar 
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1
        at com.stackoverflow.agent.test.Main.fun(Main.java:15)
        at com.stackoverflow.agent.test.Main.main(Main.java:9)

While executing with the agent code will yield:

$> java -javaagent:target/agent.jar -jar target/agent.jar
[Zero, One, Two, Three, Four]

This demonstrates that the size of the array was successfully changed using bytecode manipulation.


1 Such situations came up in questions here and here, the latter of which prompted me to write this answer.
2 Technically, the sample project doesn't resize the array. It just creates it with a different size than the size specified in code. Actually resizing an existing array while maintaining its reference and copying its elements would be a fair bit more complicated.
3 For a primitive array, the corresponding bytecode operation would be newarray (0xbc) instead.
4 As noted, this is just a proof of concept (and a very hacky one at that). Instead of randomly replacing bytes, a more robust implementation could use a bytecode manipulation library like ASM to insert a pop command followed by an sipush command before any newarray or anewarray command. Some more hints towards that solution can be found in the comments to this answer.
5 In a real-world scenario, the agent code would obviously be in a separate project.

XPath: select text node

your xpath should work . i have tested your xpath and mine in both MarkLogic and Zorba Xquery/ Xpath implementation.

Both should work.

/node/child::text()[1] - should return Text1
/node/child::text()[2] - should return text2


/node/text()[1] - should return Text1
/node/text()[2] - should return text2

Add a thousands separator to a total with Javascript or jQuery?

Use toLocaleString()
In your case do:

return "Total Pounds Entered : " + tot.toLocaleString(); 

Passing string parameter in JavaScript function

Change your code to

document.write("<td width='74'><button id='button' type='button' onclick='myfunction(\""+ name + "\")'>click</button></td>")

What causes a SIGSEGV

Here is an example of SIGSEGV.

root@pierr-desktop:/opt/playGround# cat test.c
int main()
{
     int * p ;
     * p = 0x1234;
     return 0 ;
}
root@pierr-desktop:/opt/playGround# g++ -o test test.c  
root@pierr-desktop:/opt/playGround# ./test 
Segmentation fault

And here is the detail.

How to handle it?

  1. Avoid it as much as possible in the first place.

    Program defensively: use assert(), check for NULL pointer , check for buffer overflow.

    Use static analysis tools to examine your code.

    compile your code with -Werror -Wall.

    Has somebody review your code.

  2. When that actually happened.

    Examine you code carefully.

    Check what you have changed since the last time you code run successfully without crash.

    Hopefully, gdb will give you a call stack so that you know where the crash happened.


EDIT : sorry for a rush. It should be *p = 0x1234; instead of p = 0x1234;

req.body empty on posts

You have to check whether the body-parser middleware is set properly to the type of request(json, urlencoded).

If you have set,

app.use(bodyParser.json());

then in postman you have to send the data as raw.

https://i.stack.imgur.com/k9IdQ.png postman screenshot

If you have set,

app.use(bodyParser.urlencoded({
    extended: true
}));

then 'x-www-form-urlencoded' option should be selected.

How to get a file directory path from file path?

dirname and basename are the tools you're looking for for extracting path components:

$ export VAR='/home/pax/file.c'
$ echo "$(dirname "${VAR}")" ; echo "$(basename "${VAR}")"
/home/pax
file.c

They're not internal Bash commands but they're part of the POSIX standard - see dirname and basename. Hence, they're probably available on, or can be obtained for, most platforms that are capable of running bash.

Binding a generic list to a repeater - ASP.NET

Code Behind:

public class Friends
{
    public string   ID      { get; set; }
    public string   Name    { get; set; }
    public string   Image   { get; set; }
}

protected void Page_Load(object sender, EventArgs e)
{
        List <Friends> friendsList = new List<Friends>();

        foreach (var friend  in friendz)
        {
            friendsList.Add(
                new Friends { ID = friend.id, Name = friend.name }    
            );

        }

        this.rptFriends.DataSource = friendsList;
        this.rptFriends.DataBind();
}

.aspx Page

<asp:Repeater ID="rptFriends" runat="server">
            <HeaderTemplate>
                <table border="0" cellpadding="0" cellspacing="0">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>Name</th>
                        </tr>
                    </thead>
                    <tbody>
            </HeaderTemplate>
            <ItemTemplate>
                    <tr>
                        <td><%# Eval("ID") %></td>
                        <td><%# Eval("Name") %></td>
                    </tr>
            </ItemTemplate>
            <FooterTemplate>
                    </tbody>
                </table>
            </FooterTemplate>
        </asp:Repeater>

Visual Studio Code Automatic Imports

I got this working by installing the various plugins below.

Most of the time things just import by themselves as soon as I type the class name. Alternatively, a lightbulb appears that you can click on. Or you can push F1, and type "import..." and there are various options there too. I kinda use all of them. Also F1 Implement for implementing an interface is helpful, but doesn't always work.

List of Plugins

Screenshot of Extensions

screenshot of extensions
*click for full resolution

how to change onclick event with jquery?

You can easily change the onclick event of an element with jQuery without running the new function with:

$("#id").attr("onclick","new_function_name()");

By writing this line you actually change the onclick attribute of #id.

You can also use:

document.getElementById("id").attribute("onclick","new_function_name()");

select from one table, insert into another table oracle sql query

You can use

insert into <table_name> select <fieldlist> from <tables>

Git refusing to merge unrelated histories on rebase

I am using the rebase for years and I had never encountered such a problem. However, your first problem is, that you try to do it directly on the remote branch development from the remote repository, called origin. That is literally wrong because rebase is a dangerous command, that restructures the git history. Having said that, you should first try on your local repository and pushing it only, if it works for you as expected.

So, my usual rebase workflow looks like following (but please keep in mind, that you should not use rebase on branches, which you are not the only one committee. For such branches, use simply merge and resolve conflicts, if applicable):

  1. make sure you have a clean working tree (no uncommit changes)
  2. checkout to the branch you want to rebase onto (for instance, let's say it's master; as a one-line command): git checkout master && git pull origin master && git checkout development
  3. Do the actual rebase: git rebase master
  4. If it's done and everything works as expected, push it to your remote. For doing so, you need to force it, because the remote host already has the history in another order, the remote would answer with nothing to push. So, we need to say "my local version of the history is correct, overwrite everything on that remote branch using my local version of the history": git push -f origin development

As I already mentioned, keep in mind, that rebase manipulates the git history, that is usually a bad thing. However, it's possible to do that on branches, where no one else commits to. In order to keep the branch pull-able for the other developers, use another merge strategy like merge itself, squash or cherrypick. So, in other words: Rebase shouldn't be your tool on distributed development. It works fine for you if you are the only one who works on this repository.

We use the feature branch strategy. In this, I usually use rebase in order to get the "updates" from the other developers, that happened in the meantime on the master branch. Doing so, it reduces the size of commits that are visible in a pull request. Therefore, it makes it easier for the code reviewer to see my changes made in this feature branch.

How to get a path to a resource in a Java JAR file

In my case, I have used a URL object instead Path.

File

File file = new File("my_path");
URL url = file.toURI().toURL();

Resource in classpath using classloader

URL url = MyClass.class.getClassLoader().getResource("resource_name")

When I need to read the content, I can use the following code:

InputStream stream = url.openStream();

And you can access the content using an InputStream.

How to count no of lines in text file and store the value into a variable using batch script?

Try this:

@Echo off
Set _File=file.txt
Set /a _Lines=0
For /f %%j in ('Find "" /v /c ^< %_File%') Do Set /a _Lines=%%j
Echo %_File% has %_Lines% lines.

It eliminates the extra FindStr and doesn't need expansion.


- edited to use ChrisJJ's redirect suggestion. Removal of the TYPE command makes it three times faster.

PHP Echo text Color

How about writing out some escape sequences?

echo "\033[01;31m Request has been sent. Please wait for my reply! \033[0m";

Won't work through browser though, only from console ;))

How to pass a value from one jsp to another jsp page?

Use below code for passing string from one jsp to another jsp

A.jsp

   <% String userid="Banda";%>
    <form action="B.jsp" method="post">
    <%
    session.setAttribute("userId", userid);
        %>
        <input type="submit"
                            value="Login">
    </form>

B.jsp

    <%String userid = session.getAttribute("userId").toString(); %>
    Hello<%=userid%>

Is Constructor Overriding Possible?

You can have many constructors as long as they take in different parameters. But the compiler putting a default constructor in is not called "constructor overriding".

Viewing contents of a .jar file

Eclipse 3.4 JDT

It is not the quickest way because you have to drag it into your eclipse first. But you will have full java class browsing, even with decompile enabled.

How to have Java method return generic list of any type?

private Object actuallyT;

public <T> List<T> magicalListGetter(Class<T> klazz) {
    List<T> list = new ArrayList<>();
    list.add(klazz.cast(actuallyT));
    try {
        list.add(klazz.getConstructor().newInstance()); // If default constructor
    } ...
    return list;
}

One can give a generic type parameter to a method too. You have correctly deduced that one needs the correct class instance, to create things (klazz.getConstructor().newInstance()).

Encrypt and Decrypt text with RSA in PHP

Security warning: This code snippet is vulnerable to Bleichenbacher's 1998 padding oracle attack. See this answer for better security.

class MyEncryption
{

    public $pubkey = '...public key here...';
    public $privkey = '...private key here...';

    public function encrypt($data)
    {
        if (openssl_public_encrypt($data, $encrypted, $this->pubkey))
            $data = base64_encode($encrypted);
        else
            throw new Exception('Unable to encrypt data. Perhaps it is bigger than the key size?');

        return $data;
    }

    public function decrypt($data)
    {
        if (openssl_private_decrypt(base64_decode($data), $decrypted, $this->privkey))
            $data = $decrypted;
        else
            $data = '';

        return $data;
    }
}

Getting "Lock wait timeout exceeded; try restarting transaction" even though I'm not using a transaction

Can you update any other record within this table, or is this table heavily used? What I am thinking is that while it is attempting to acquire a lock that it needs to update this record the timeout that was set has timed out. You may be able to increase the time which may help.

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.

PHP: Limit foreach() statement?

you should use the break statement

usually it's use this way

$i = 0;
foreach($data as $key => $row){
    if(++$i > 2) break;
}

on the same fashion the continue statement exists if you need to skip some items.

Refresh an asp.net page on button click

Page reload can be done using javascript code. Use either a HTML button and implement it like...

<input type="button" value="Reload Page" onClick="document.location.reload(true)">

RegEx to make sure that the string contains at least one lower case char, upper case char, digit and symbol

Bart Kiers, your regex has a couple issues. The best way to do that is this:

(.*[a-z].*)       // For lower cases
(.*[A-Z].*)       // For upper cases
(.*\d.*)          // For digits

In this way you are searching no matter if at the beginning, at the end or at the middle. In your have I have a lot of troubles with complex passwords.

getString Outside of a Context or Activity

It's better to use something like this without context and activity:

Resources.getSystem().getString(R.string.my_text)

What is &#39; and why does Google search replace it with apostrophe?

It's HTML character references for encoding a character by its decimal code point

Look at the ASCII table here and you'll see that 39 (hex 0x27, octal 47) is the code for apostrophe

ASCII table

Jquery $(this) Child Selector

In the click event "this" is the a tag that was clicked

jQuery('.class1 a').click( function() {
   var divToSlide = $(this).parent().find(".class2");
   if (divToSlide.is(":hidden")) {
      divToSlide.slideDown("slow");
   } else {
      divToSlide.slideUp();
   }
});

There's multiple ways to get to the div though you could also use .siblings, .next etc

Extract part of a regex match

Note that starting Python 3.8, and the introduction of assignment expressions (PEP 572) (:= operator), it's possible to improve a bit on Krzysztof Krason's solution by capturing the match result directly within the if condition as a variable and re-use it in the condition's body:

# pattern = '<title>(.*)</title>'
# text = '<title>hello</title>'
if match := re.search(pattern, text, re.IGNORECASE):
  title = match.group(1)
# hello

pandas how to check dtype for all columns in a dataframe?

The singular form dtype is used to check the data type for a single column. And the plural form dtypes is for data frame which returns data types for all columns. Essentially:

For a single column:

dataframe.column.dtype

For all columns:

dataframe.dtypes

Example:

import pandas as pd
df = pd.DataFrame({'A': [1,2,3], 'B': [True, False, False], 'C': ['a', 'b', 'c']})

df.A.dtype
# dtype('int64')
df.B.dtype
# dtype('bool')
df.C.dtype
# dtype('O')

df.dtypes
#A     int64
#B      bool
#C    object
#dtype: object

Adding new column to existing DataFrame in Python pandas

Foolproof:

df.loc[:, 'NewCol'] = 'New_Val'

Example:

df = pd.DataFrame(data=np.random.randn(20, 4), columns=['A', 'B', 'C', 'D'])

df

           A         B         C         D
0  -0.761269  0.477348  1.170614  0.752714
1   1.217250 -0.930860 -0.769324 -0.408642
2  -0.619679 -1.227659 -0.259135  1.700294
3  -0.147354  0.778707  0.479145  2.284143
4  -0.529529  0.000571  0.913779  1.395894
5   2.592400  0.637253  1.441096 -0.631468
6   0.757178  0.240012 -0.553820  1.177202
7  -0.986128 -1.313843  0.788589 -0.707836
8   0.606985 -2.232903 -1.358107 -2.855494
9  -0.692013  0.671866  1.179466 -1.180351
10 -1.093707 -0.530600  0.182926 -1.296494
11 -0.143273 -0.503199 -1.328728  0.610552
12 -0.923110 -1.365890 -1.366202 -1.185999
13 -2.026832  0.273593 -0.440426 -0.627423
14 -0.054503 -0.788866 -0.228088 -0.404783
15  0.955298 -1.430019  1.434071 -0.088215
16 -0.227946  0.047462  0.373573 -0.111675
17  1.627912  0.043611  1.743403 -0.012714
18  0.693458  0.144327  0.329500 -0.655045
19  0.104425  0.037412  0.450598 -0.923387


df.drop([3, 5, 8, 10, 18], inplace=True)

df

           A         B         C         D
0  -0.761269  0.477348  1.170614  0.752714
1   1.217250 -0.930860 -0.769324 -0.408642
2  -0.619679 -1.227659 -0.259135  1.700294
4  -0.529529  0.000571  0.913779  1.395894
6   0.757178  0.240012 -0.553820  1.177202
7  -0.986128 -1.313843  0.788589 -0.707836
9  -0.692013  0.671866  1.179466 -1.180351
11 -0.143273 -0.503199 -1.328728  0.610552
12 -0.923110 -1.365890 -1.366202 -1.185999
13 -2.026832  0.273593 -0.440426 -0.627423
14 -0.054503 -0.788866 -0.228088 -0.404783
15  0.955298 -1.430019  1.434071 -0.088215
16 -0.227946  0.047462  0.373573 -0.111675
17  1.627912  0.043611  1.743403 -0.012714
19  0.104425  0.037412  0.450598 -0.923387

df.loc[:, 'NewCol'] = 0

df
           A         B         C         D  NewCol
0  -0.761269  0.477348  1.170614  0.752714       0
1   1.217250 -0.930860 -0.769324 -0.408642       0
2  -0.619679 -1.227659 -0.259135  1.700294       0
4  -0.529529  0.000571  0.913779  1.395894       0
6   0.757178  0.240012 -0.553820  1.177202       0
7  -0.986128 -1.313843  0.788589 -0.707836       0
9  -0.692013  0.671866  1.179466 -1.180351       0
11 -0.143273 -0.503199 -1.328728  0.610552       0
12 -0.923110 -1.365890 -1.366202 -1.185999       0
13 -2.026832  0.273593 -0.440426 -0.627423       0
14 -0.054503 -0.788866 -0.228088 -0.404783       0
15  0.955298 -1.430019  1.434071 -0.088215       0
16 -0.227946  0.047462  0.373573 -0.111675       0
17  1.627912  0.043611  1.743403 -0.012714       0
19  0.104425  0.037412  0.450598 -0.923387       0

How can you have SharePoint Link Lists default to opening in a new window?

You can edit the page in SharePoint designer, convert the List View web part to an XSLT Data View. (by right click + "Convert to XSLT Data View").
Then you can edit the XSLT - find the A tag and add an attribute target="_blank"

How to catch segmentation fault in Linux?

C++ solution found here (http://www.cplusplus.com/forum/unices/16430/)

#include <signal.h>
#include <stdio.h>
#include <unistd.h>
void ouch(int sig)
{
    printf("OUCH! - I got signal %d\n", sig);
}
int main()
{
    struct sigaction act;
    act.sa_handler = ouch;
    sigemptyset(&act.sa_mask);
    act.sa_flags = 0;
    sigaction(SIGINT, &act, 0);
    while(1) {
        printf("Hello World!\n");
        sleep(1);
    }
}

Log4j2 configuration - No log4j2 configuration file found

You need to choose one of the following solutions:

  1. Put the log4j2.xml file in resource directory in your project so the log4j will locate files under class path.
  2. Use system property -Dlog4j.configurationFile=file:/path/to/file/log4j2.xml

Call Class Method From Another Class

class CurrentValue:

    def __init__(self, value):
        self.value = value

    def set_val(self, k):
        self.value = k

    def get_val(self):
        return self.value


class AddValue:

    def av(self, ocv):
        print('Before:', ocv.get_val())
        num = int(input('Enter number to add : '))
        nnum = num + ocv.get_val()
        ocv.set_val(nnum)
        print('After add :', ocv.get_val())


cvo = CurrentValue(5)

avo = AddValue()

avo.av(cvo)

We define 2 classes, CurrentValue and AddValue We define 3 methods in the first class One init in order to give to the instance variable self.value an initial value A set_val method where we set the self.value to a k A get_val method where we get the valuue of self.value We define one method in the second class A av method where we pass as parameter(ovc) an object of the first class We create an instance (cvo) of the first class We create an instance (avo) of the second class We call the method avo.av(cvo) of the second class and pass as an argument the object we have already created from the first class. So by this way I would like to show how it is possible to call a method of a class from another class.

I am sorry for any inconvenience. This will not happen again.

Before: 5

Enter number to add : 14

After add : 19

Detect viewport orientation, if orientation is Portrait display alert message advising user of instructions

If you have the latest browsers window.orientation might not work. In that case use following code for getting angle -

var orientation = window.screen.orientation.angle;

This is still an experimental technology, you can check the browser compatibility here

Using "&times" word in html changes to ×

Use the &#215 code instead of &times Because JSF don't understand the &times; code.

Use: &#215 with ;

This link provides some additional information about the topic.

Static class initializer in PHP

If you don't like public static initializer, reflection can be a workaround.

<?php

class LanguageUtility
{
    public static function initializeClass($class)
    {
        try
        {
            // Get a static method named 'initialize'. If not found,
            // ReflectionMethod() will throw a ReflectionException.
            $ref = new \ReflectionMethod($class, 'initialize');

            // The 'initialize' method is probably 'private'.
            // Make it accessible before calling 'invoke'.
            // Note that 'setAccessible' is not available
            // before PHP version 5.3.2.
            $ref->setAccessible(true);

            // Execute the 'initialize' method.
            $ref->invoke(null);
        }   
        catch (Exception $e)
        {
        }
    }
}

class MyClass
{
    private static function initialize()
    {
    }
}

LanguageUtility::initializeClass('MyClass');

?>

How to center a WPF app on screen?

Put this in your window constructor

WindowStartupLocation = System.Windows.WindowStartupLocation.CenterScreen;

.NET FrameworkSupported in: 4, 3.5, 3.0

.NET Framework Client ProfileSupported in: 4, 3.5 SP1

Check if enum exists in Java

Since Java 8, we could use streams instead of for loops. Also, it might be apropriate to return an Optional if the enum does not have an instance with such a name.

I have come up with the following three alternatives on how to look up an enum:

private enum Test {
    TEST1, TEST2;

    public Test fromNameOrThrowException(String name) {
        return Arrays.stream(values())
                .filter(e -> e.name().equals(name))
                .findFirst()
                .orElseThrow(() -> new IllegalArgumentException("No enum with name " + name));
    }

    public Test fromNameOrNull(String name) {
        return Arrays.stream(values()).filter(e -> e.name().equals(name)).findFirst().orElse(null);
    }

    public Optional<Test> fromName(String name) {
        return Arrays.stream(values()).filter(e -> e.name().equals(name)).findFirst();
    }
}

Java Constructor Inheritance

Because a (super)class must have complete control over how it is constructed. If the programmer decides that it doesn't make sense to provide a default (no args) constructor as part of the class's contract, then the compiler should not provide one.

Python Requests - No connection adapters

One more reason, maybe your url include some hiden characters, such as '\n'.

If you define your url like below, this exception will raise:

url = '''
http://google.com
'''

because there are '\n' hide in the string. The url in fact become:

\nhttp://google.com\n

How to set a fixed width column with CSS flexbox

You should use the flex or flex-basis property rather than width. Read more on MDN.

.flexbox .red {
  flex: 0 0 25em;
}

The flex CSS property is a shorthand property specifying the ability of a flex item to alter its dimensions to fill available space. It contains:

flex-grow: 0;     /* do not grow   - initial value: 0 */
flex-shrink: 0;   /* do not shrink - initial value: 1 */
flex-basis: 25em; /* width/height  - initial value: auto */

A simple demo shows how to set the first column to 50px fixed width.

_x000D_
_x000D_
.flexbox {_x000D_
  display: flex;_x000D_
}_x000D_
.red {_x000D_
  background: red;_x000D_
  flex: 0 0 50px;_x000D_
}_x000D_
.green {_x000D_
  background: green;_x000D_
  flex: 1;_x000D_
}_x000D_
.blue {_x000D_
  background: blue;_x000D_
  flex: 1;_x000D_
}
_x000D_
<div class="flexbox">_x000D_
  <div class="red">1</div>_x000D_
  <div class="green">2</div>_x000D_
  <div class="blue">3</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_


See the updated codepen based on your code.

How do you change video src using jQuery?

     $(document).ready(function () {     
    setTimeout(function () {
                    $(".imgthumbnew").click(function () {
                        $("#divVideo video").attr({
                            "src": $(this).data("item"),
                            "autoplay": "autoplay",        
                        })
                    })
                }, 2000); 
            }
        });

here ".imgthumbnew" is the class of images which are thumbs of videos, an extra attribute is given to them which have video url. u can change according to your convenient.
i would suggest you to give an ID to ur Video tag it would be easy to handle.

An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll

I think your EmpID column is string and you forget to use ' ' in your value.

Because when you write EmpID=" + id.Text, your command looks like EmpID = 12345 instead of EmpID = '12345'

Change your SqlCommand to

SqlCommand cmd = new SqlCommand("SELECT EmpName FROM Employee WHERE EmpID='" + id.Text +"'", con);

Or as a better way you can (and should) always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.

SqlCommand cmd = new SqlCommand("SELECT EmpName FROM Employee WHERE EmpID = @id", con);
cmd.Parameters.AddWithValue("@id", id.Text);

I think your EmpID column keeps your employee id's, so it's type should some numerical type instead of character.

Shell script to delete directories older than n days

find supports -delete operation, so:

find /base/dir/* -ctime +10 -delete;

I think there's a catch that the files need to be 10+ days older too. Haven't tried, someone may confirm in comments.

The most voted solution here is missing -maxdepth 0 so it will call rm -rf for every subdirectory, after deleting it. That doesn't make sense, so I suggest:

find /base/dir/* -maxdepth 0  -type d -ctime +10 -exec rm -rf {} \;

The -delete solution above doesn't use -maxdepth 0 because find would complain the dir is not empty. Instead, it implies -depth and deletes from the bottom up.

Get the first N elements of an array?

Use array_slice()

This is an example from the PHP manual: array_slice

$input = array("a", "b", "c", "d", "e");
$output = array_slice($input, 0, 3);   // returns "a", "b", and "c"

There is only a small issue

If the array indices are meaningful to you, remember that array_slice will reset and reorder the numeric array indices. You need the preserve_keys flag set to trueto avoid this. (4th parameter, available since 5.0.2).

Example:

$output = array_slice($input, 2, 3, true);

Output:

array([3]=>'c', [4]=>'d', [5]=>'e');

Java Set retain order?

There are 2 different things.

  1. Sort the elements in a set. For which we have SortedSet and similar implementations.
  2. Maintain insertion order in a set. For which LinkedHashSet and CopyOnWriteArraySet (thread-safe) can be used.

Cannot read property 'getContext' of null, using canvas

This might seem like overkill, but if in another case you were trying to load a canvas from js (like I am doing), you could use a setInterval function and an if statement to constantly check if the canvas has loaded.

//set up the interval
var thisInterval = setInterval(function{
  //this if statment checks if the id "thisCanvas" is linked to something
  if(document.getElementById("thisCanvas") != null){
    //do what you want


    //clearInterval() will remove the interval if you have given your interval a name.
    clearInterval(thisInterval)
  }
//the 500 means that you will loop through this every 500 milliseconds (1/2 a second)
},500)

(In this example the canvas I am trying to load has an id of "thisCanvas")

ORA-29283: invalid file operation ORA-06512: at "SYS.UTL_FILE", line 536

On Windows also check whether the file is not encrypted using EFS. I had the same problem untill I decrypted the file manualy.

int *array = new int[n]; what is this function actually doing?

int *array = new int[n];

It declares a pointer to a dynamic array of type int and size n.

A little more detailed answer: new allocates memory of size equal to sizeof(int) * n bytes and return the memory which is stored by the variable array. Also, since the memory is dynamically allocated using new, you've to deallocate it manually by writing (when you don't need anymore, of course):

delete []array;

Otherwise, your program will leak memory of at least sizeof(int) * n bytes (possibly more, depending on the allocation strategy used by the implementation).

Swift apply .uppercaseString to only the first letter of a string

Including mutating and non mutating versions that are consistent with API guidelines.

Swift 3:

extension String {
    func capitalizingFirstLetter() -> String {
        let first = String(characters.prefix(1)).capitalized
        let other = String(characters.dropFirst())
        return first + other
    }

    mutating func capitalizeFirstLetter() {
        self = self.capitalizingFirstLetter()
    }
}

Swift 4:

extension String {
    func capitalizingFirstLetter() -> String {
      return prefix(1).uppercased() + self.lowercased().dropFirst()
    }

    mutating func capitalizeFirstLetter() {
      self = self.capitalizingFirstLetter()
    }
}

Is it good practice to use the xor operator for boolean checks?

I personally prefer the "boolean1 ^ boolean2" expression due to its succinctness.

If I was in your situation (working in a team), I would strike a compromise by encapsulating the "boolean1 ^ boolean2" logic in a function with a descriptive name such as "isDifferent(boolean1, boolean2)".

For example, instead of using "boolean1 ^ boolean2", you would call "isDifferent(boolean1, boolean2)" like so:

if (isDifferent(boolean1, boolean2))
{
  //do it
}

Your "isDifferent(boolean1, boolean2)" function would look like:

private boolean isDifferent(boolean1, boolean2)
{
    return boolean1 ^ boolean2;
}

Of course, this solution entails the use of an ostensibly extraneous function call, which in itself is subject to Best Practices scrutiny, but it avoids the verbose (and ugly) expression "(boolean1 && !boolean2) || (boolean2 && !boolean1)"!

How do I concatenate text in a query in sql server?

You have to explicitly cast the string types to the same in order to concatenate them, In your case you may solve the issue by simply addig an 'N' in front of 'SomeText' (N'SomeText'). If that doesn't work, try Cast('SomeText' as nvarchar(8)).

Where do I put image files, css, js, etc. in Codeigniter?

The link_tag() helper is clearly the way to do this. Put your css where it usually belongs, in site_root/css/ and then use the helper:

From The CodeIgniter docs...

echo link_tag('css/mystyles.css');

Output

<link href="http://example.com/css/mystyles.css" rel="stylesheet" type="text/css" />

How to find and turn on USB debugging mode on Nexus 4

Looking for About Phone in Settings. And scroll down till you see Build number. Tap here till you see Toast message tell you have just enable developer mode.

Back to settings, you can see options: "Developer options"

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

The System.Linq.Enumerable.Count extension method on IEnumerable<T> has the following implementation:

ICollection<T> c = source as ICollection<TSource>;
if (c != null)
    return c.Count;

int result = 0;
using (IEnumerator<T> enumerator = source.GetEnumerator())
{
    while (enumerator.MoveNext())
        result++;
}
return result;

So it tries to cast to ICollection<T>, which has a Count property, and uses that if possible. Otherwise it iterates.

So your best bet is to use the Count() extension method on your IEnumerable<T> object, as you will get the best performance possible that way.

How to remove Firefox's dotted outline on BUTTONS as well as links?

This will get the range control:

:focus {
    outline:none;
}
::-moz-focus-inner {
    border:0;
}
input[type=range]::-moz-focus-outer {
    border: 0;
}

From: Remove dotted outline from range input element in Firefox

Getting and removing the first character of a string

There is also str_sub from the stringr package

x <- 'hello stackoverflow'
str_sub(x, 2) # or
str_sub(x, 2, str_length(x))
[1] "ello stackoverflow"

Vue component event after render

updated might be what you're looking for. https://vuejs.org/v2/api/#updated

Bash script prints "Command Not Found" on empty lines

Problems with running scripts may also be connected to bad formatting of multi-line commands, for example if you have a whitespace character after line-breaking "\". E.g. this:

./run_me.sh \ 
--with-some parameter

(please note the extra space after "\") will cause problems, but when you remove that space, it will run perfectly fine.

Python MySQLdb TypeError: not all arguments converted during string formatting

'%' keyword is so dangerous because it major cause of 'SQL INJECTION ATTACK'.
So you just using this code.

cursor.execute("select * from table where example=%s", (example,))

or

t = (example,)
cursor.execute("select * from table where example=%s", t)

if you want to try insert into table, try this.

name = 'ksg'
age = 19
sex = 'male'
t  = (name, age, sex)
cursor.execute("insert into table values(%s,%d,%s)", t)

What is the default root pasword for MySQL 5.7

MySQL server 5.7 was already installed by default on my new Linux Mint 19.

But, what's the MySQL root password? It turns out that:

The default installation uses auth_socket for authentication, in lieu of passwords!

It allows a password-free login, provided that one is logged into the Linux system with the same user name. To login as the MySQL root user, one can use sudo:

sudo mysql --user=root

But how to then change the root password? To illustrate what's going on, I created a new user "me", with full privileges, with:

mysql> CREATE USER 'me'@'localhost' IDENTIFIED BY 'my_new_password';
mysql> GRANT ALL PRIVILEGES ON *.* TO 'me'@'localhost' WITH GRANT OPTION;
mysql> FLUSH PRIVILEGES;

Comparing "me" with "root":

mysql> SELECT user, plugin, HEX(authentication_string)  FROM mysql.user WHERE user = 'me' or user = 'root';
+------+-----------------------+----------------------------------------------------------------------------+
| user | plugin                | HEX(authentication_string)                                                 |
+------+-----------------------+----------------------------------------------------------------------------+
| root | auth_socket           |                                                                            |
| me   | mysql_native_password | 2A393846353030304545453239394634323734333139354241344642413245373537313... |
+------+-----------------------+----------------------------------------------------------------------------+

Because it's using auth_socket, the root password cannot be changed: the SET PASSWORD command fails, and mysql_secure_installation desn't attain anything...

==> To zap this alternate authentication mode and return the MySQL root user to using passwords:

ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'SOME_NEW_ROOT_PASSWORD';

A good explanation.

More details from the MySQL manual.

Go test string contains substring

To compare, there are more options:

import (
    "fmt"
    "regexp"
    "strings"
)

const (
    str    = "something"
    substr = "some"
)

// 1. Contains
res := strings.Contains(str, substr)
fmt.Println(res) // true

// 2. Index: check the index of the first instance of substr in str, or -1 if substr is not present
i := strings.Index(str, substr)
fmt.Println(i) // 0

// 3. Split by substr and check len of the slice, or length is 1 if substr is not present
ss := strings.Split(str, substr)
fmt.Println(len(ss)) // 2

// 4. Check number of non-overlapping instances of substr in str
c := strings.Count(str, substr)
fmt.Println(c) // 1

// 5. RegExp
matched, _ := regexp.MatchString(substr, str)
fmt.Println(matched) // true

// 6. Compiled RegExp
re = regexp.MustCompile(substr)
res = re.MatchString(str)
fmt.Println(res) // true

Benchmarks: Contains internally calls Index, so the speed is almost the same (btw Go 1.11.5 showed a bit bigger difference than on Go 1.14.3).

BenchmarkStringsContains-4              100000000               10.5 ns/op             0 B/op          0 allocs/op
BenchmarkStringsIndex-4                 117090943               10.1 ns/op             0 B/op          0 allocs/op
BenchmarkStringsSplit-4                  6958126               152 ns/op              32 B/op          1 allocs/op
BenchmarkStringsCount-4                 42397729                29.1 ns/op             0 B/op          0 allocs/op
BenchmarkStringsRegExp-4                  461696              2467 ns/op            1326 B/op         16 allocs/op
BenchmarkStringsRegExpCompiled-4         7109509               168 ns/op               0 B/op          0 allocs/op

How do I convert a String to a BigInteger?

Using the constructor

BigInteger(String val)

Translates the decimal String representation of a BigInteger into a BigInteger.

Javadoc

Xcode: failed to get the task for process

Change the profile for code signing. Select your project, go to Build Settings > Code Signing Identity. Switch to other developer profile.

Static variables in C++

A static variable declared in a header file outside of the class would be file-scoped in every .c file which includes the header. That means separate copy of a variable with same name is accessible in each of the .c files where you include the header file.

A static class variable on the other hand is class-scoped and the same static variable is available to every compilation unit that includes the header containing the class with static variable.

How to set portrait and landscape media queries in css?

iPad Media Queries (All generations - including iPad mini)

Thanks to Apple's work in creating a consistent experience for users, and easy time for developers, all 5 different iPads (iPads 1-5 and iPad mini) can be targeted with just one CSS media query. The next few lines of code should work perfect for a responsive design.

iPad in portrait & landscape

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px)  { /* STYLES GO HERE */}

iPad in landscape

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : landscape) { /* STYLES GO HERE */}

iPad in portrait

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : portrait) { /* STYLES GO HERE */ }

iPad 3 & 4 Media Queries

If you're looking to target only 3rd and 4th generation Retina iPads (or tablets with similar resolution) to add @2x graphics, or other features for the tablet's Retina display, use the following media queries.

Retina iPad in portrait & landscape

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px)
and (-webkit-min-device-pixel-ratio: 2) { /* STYLES GO HERE */}

Retina iPad in landscape

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : landscape)
and (-webkit-min-device-pixel-ratio: 2) { /* STYLES GO HERE */}

Retina iPad in portrait

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : portrait)
and (-webkit-min-device-pixel-ratio: 2) { /* STYLES GO HERE */ }

iPad 1 & 2 Media Queries

If you're looking to supply different graphics or choose different typography for the lower resolution iPad display, the media queries below will work like a charm in your responsive design!

iPad 1 & 2 in portrait & landscape

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (-webkit-min-device-pixel-ratio: 1){ /* STYLES GO HERE */}

iPad 1 & 2 in landscape

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : landscape)
and (-webkit-min-device-pixel-ratio: 1)  { /* STYLES GO HERE */}

iPad 1 & 2 in portrait

@media only screen 
and (min-device-width : 768px) 
and (max-device-width : 1024px) 
and (orientation : portrait) 
and (-webkit-min-device-pixel-ratio: 1) { /* STYLES GO HERE */ }

Source: http://stephen.io/mediaqueries/

How does one convert a HashMap to a List in Java?

If you only want it to iterate over your HashMap, no need for a list:

HashMap<Integer, String> map = new HashMap<Integer, String>();
map.put (1, "Mark");
map.put (2, "Tarryn");
for (String s : map.values()) {
    System.out.println(s);
}

Of course, if you want to modify your map structurally (i.e. more than only changing the value for an existing key) while iterating, then you better use the "copy to ArrayList" method, since otherwise you'll get a ConcurrentModificationException. Or export as an array:

HashMap<Integer, String> map = new HashMap<Integer, String>();
map.put (1, "Mark");
map.put (2, "Tarryn");
for (String s : map.values().toArray(new String[]{})) {
    System.out.println(s);
}

How can I get the ID of an element using jQuery?

id is a property of an html Element. However, when you write $("#something"), it returns a jQuery object that wraps the matching DOM element(s). To get the first matching DOM element back, call get(0)

$("#test").get(0)

On this native element, you can call id, or any other native DOM property or function.

$("#test").get(0).id

That's the reason why id isn't working in your code.

Alternatively, use jQuery's attr method as other answers suggest to get the id attribute of the first matching element.

$("#test").attr("id")

How to show a running progress bar while page is loading

I have copied the relevant code below from This page. Hope this might help you.

$.ajax({
  xhr: function() {
    var xhr = new window.XMLHttpRequest();
    //Upload progress
    xhr.upload.addEventListener("progress", function(evt) {
      if (evt.lengthComputable) {
        var percentComplete = evt.loaded / evt.total;
        //Do something with upload progress
        console.log(percentComplete);
      }
    }, false);
    //Download progress
    xhr.addEventListener("progress", function(evt) {
      if (evt.lengthComputable) {
        var percentComplete = evt.loaded / evt.total;
        //Do something with download progress
        console.log(percentComplete);
      }
    }, false);
    return xhr;
  },
  type: 'POST',
  url: "/",
  data: {},
  success: function(data) {
    //Do something success-ish
  }
});

DevTools failed to load SourceMap: Could not load content for chrome-extension

Right: it has nothing to do with your code. I've found two valid solutions to this warning (not just disabling it). To better understand what a SourceMap is, I suggest you check out this answer, where it explains how it's something that helps you debug:

The .map files are for js and css (and now ts too) files that have been minified. They are called SourceMaps. When you minify a file, like the angular.js file, it takes thousands of lines of pretty code and turns it into only a few lines of ugly code. Hopefully, when you are shipping your code to production, you are using the minified code instead of the full, unminified version. When your app is in production, and has an error, the sourcemap will help take your ugly file, and will allow you to see the original version of the code. If you didn't have the sourcemap, then any error would seem cryptic at best.

  1. First solution: apparently, Mr Heelis was the closest one: you should add the .map file and there are some tools that help you with this problem (Grunt, Gulp and Google closure for example, quoting the answer). Otherwise you can download the .map file from official sites like Bootstrap, jquery, font-awesome, preload and so on.. (maybe installing things like popper or swiper by the npm command in a random folder and copying just the .map file in your js/css destination folder)

  2. Second solution (the one I used): add the source files using a CDN (here all the advantages of using a CDN). Using the Content delivery network (CDN) you can simply add the cdn link, instead of the path to your folder. You can find cdn on official websites (Bootstrap, jquery, popper, etc..) or you can easily search on some websites like cloudflare, cdnjs, etc..

PHP write file from input to txt

use fwrite() instead of file_put_contents()

Find elements inside forms and iframe using Java and Selenium WebDriver

When using an iframe, you will first have to switch to the iframe, before selecting the elements of that iframe

You can do it using:

driver.switchTo().frame(driver.findElement(By.id("frameId")));
//do your stuff
driver.switchTo().defaultContent();

In case if your frameId is dynamic, and you only have one iframe, you can use something like:

driver.switchTo().frame(driver.findElement(By.tagName("iframe")));

How do you enable mod_rewrite on any OS?

network solutions offers the advice to put a php.ini in the cgi-bin to enable mod_rewrite

What's the bad magic number error?

I just faced the same issue with Fedora26 where many tools such as dnf were broken due to bad magic number for six. For an unknown reason i've got a file /usr/bin/six.pyc, with the unexpected magic number. Deleting this file fix the problem

How can you tell when a layout has been drawn?

An alternative to the usual methods is to hook into the drawing of the view.

OnPreDrawListener is called many times when displaying a view, so there is no specific iteration where your view has valid measured width or height. This requires that you continually verify (view.getMeasuredWidth() <= 0) or set a limit to the number of times you check for a measuredWidth greater than zero.

There is also a chance that the view will never be drawn, which may indicate other problems with your code.

final View view = [ACQUIRE REFERENCE]; // Must be declared final for inner class
ViewTreeObserver viewTreeObserver = view.getViewTreeObserver();
viewTreeObserver.addOnPreDrawListener(new ViewTreeObserver.OnPreDrawListener() {
    @Override
    public boolean onPreDraw() {
        if (view.getMeasuredWidth() > 0) {     
            view.getViewTreeObserver().removeOnPreDrawListener(this);
            int width = view.getMeasuredWidth();
            int height = view.getMeasuredHeight();
            //Do something with width and height here!
        }
        return true; // Continue with the draw pass, as not to stop it
    }
});

CSS background-image - What is the correct usage?

just check the directory structure where exactly image is suppose you have a css folder and images folder outside css folder then you will have to use"../images/image.jpg" and it will work as it did for me just make sure the directory stucture.

Cannot implicitly convert type 'System.DateTime?' to 'System.DateTime'. An explicit conversion exists

dt is nullable you need to access its Value

if (datetime.HasValue)
    dt = datetime.Value;

It is important to remember that it can be NULL. That is why the nullablestruct has the HasValue property that tells you if it is NULL or not.

You can also use the null-coalescing operator ?? to assign a default value

dt = datetime ?? DateTime.Now;

This will assign the value on the right if the value on the left is NULL

How to remove unused imports from Eclipse

Use ALT + CTRL + O. It will organize all the imports. You can find various other options in the "Code" Menu.

EDIT: Sorry it is CTRL + SHIFT + O

Get all object attributes in Python?

What you probably want is dir().

The catch is that classes are able to override the special __dir__ method, which causes dir() to return whatever the class wants (though they are encouraged to return an accurate list, this is not enforced). Furthermore, some objects may implement dynamic attributes by overriding __getattr__, may be RPC proxy objects, or may be instances of C-extension classes. If your object is one these examples, they may not have a __dict__ or be able to provide a comprehensive list of attributes via __dir__: many of these objects may have so many dynamic attrs it doesn't won't actually know what it has until you try to access it.

In the short run, if dir() isn't sufficient, you could write a function which traverses __dict__ for an object, then __dict__ for all the classes in obj.__class__.__mro__; though this will only work for normal python objects. In the long run, you may have to use duck typing + assumptions - if it looks like a duck, cross your fingers, and hope it has .feathers.

ClassNotFoundException: org.slf4j.LoggerFactory

I had the same on Android. This is how i fixed it:

including ONLY the file:

slf4j-api-1.7.6.jar

in my libs/ folder

Having any additional slf4j* file, caused the NoClassDefFoundError.

Obviously, the rest of the libs can be there (android-support-v4, etc)

Versions: Eclipse Kepler 2013 06 14 - 02 29 ADT 22.3 Android SDK: 4.4.2

Hope someone saves the time i wasted thanks to this!

LINQ: Select an object and change some properties without creating a new object

There shouldn't be any LINQ magic keeping you from doing this. Don't use projection though that'll return an anonymous type.

User u = UserCollection.FirstOrDefault(u => u.Id == 1);
u.FirstName = "Bob"

That will modify the real object, as well as:

foreach (User u in UserCollection.Where(u => u.Id > 10)
{
    u.Property = SomeValue;
}

Can't pickle <type 'instancemethod'> when using multiprocessing Pool.map()

There's another short-cut you can use, although it can be inefficient depending on what's in your class instances.

As everyone has said the problem is that the multiprocessing code has to pickle the things that it sends to the sub-processes it has started, and the pickler doesn't do instance-methods.

However, instead of sending the instance-method, you can send the actual class instance, plus the name of the function to call, to an ordinary function that then uses getattr to call the instance-method, thus creating the bound method in the Pool subprocess. This is similar to defining a __call__ method except that you can call more than one member function.

Stealing @EricH.'s code from his answer and annotating it a bit (I retyped it hence all the name changes and such, for some reason this seemed easier than cut-and-paste :-) ) for illustration of all the magic:

import multiprocessing
import os

def call_it(instance, name, args=(), kwargs=None):
    "indirect caller for instance methods and multiprocessing"
    if kwargs is None:
        kwargs = {}
    return getattr(instance, name)(*args, **kwargs)

class Klass(object):
    def __init__(self, nobj, workers=multiprocessing.cpu_count()):
        print "Constructor (in pid=%d)..." % os.getpid()
        self.count = 1
        pool = multiprocessing.Pool(processes = workers)
        async_results = [pool.apply_async(call_it,
            args = (self, 'process_obj', (i,))) for i in range(nobj)]
        pool.close()
        map(multiprocessing.pool.ApplyResult.wait, async_results)
        lst_results = [r.get() for r in async_results]
        print lst_results

    def __del__(self):
        self.count -= 1
        print "... Destructor (in pid=%d) count=%d" % (os.getpid(), self.count)

    def process_obj(self, index):
        print "object %d" % index
        return "results"

Klass(nobj=8, workers=3)

The output shows that, indeed, the constructor is called once (in the original pid) and the destructor is called 9 times (once for each copy made = 2 or 3 times per pool-worker-process as needed, plus once in the original process). This is often OK, as in this case, since the default pickler makes a copy of the entire instance and (semi-) secretly re-populates it—in this case, doing:

obj = object.__new__(Klass)
obj.__dict__.update({'count':1})

—that's why even though the destructor is called eight times in the three worker processes, it counts down from 1 to 0 each time—but of course you can still get into trouble this way. If necessary, you can provide your own __setstate__:

    def __setstate__(self, adict):
        self.count = adict['count']

in this case for instance.

Syntax error due to using a reserved word as a table or column name in MySQL

The Problem

In MySQL, certain words like SELECT, INSERT, DELETE etc. are reserved words. Since they have a special meaning, MySQL treats it as a syntax error whenever you use them as a table name, column name, or other kind of identifier - unless you surround the identifier with backticks.

As noted in the official docs, in section 10.2 Schema Object Names (emphasis added):

Certain objects within MySQL, including database, table, index, column, alias, view, stored procedure, partition, tablespace, and other object names are known as identifiers.

...

If an identifier contains special characters or is a reserved word, you must quote it whenever you refer to it.

...

The identifier quote character is the backtick ("`"):

A complete list of keywords and reserved words can be found in section 10.3 Keywords and Reserved Words. In that page, words followed by "(R)" are reserved words. Some reserved words are listed below, including many that tend to cause this issue.

  • ADD
  • AND
  • BEFORE
  • BY
  • CALL
  • CASE
  • CONDITION
  • DELETE
  • DESC
  • DESCRIBE
  • FROM
  • GROUP
  • IN
  • INDEX
  • INSERT
  • INTERVAL
  • IS
  • KEY
  • LIKE
  • LIMIT
  • LONG
  • MATCH
  • NOT
  • OPTION
  • OR
  • ORDER
  • PARTITION
  • RANK
  • REFERENCES
  • SELECT
  • TABLE
  • TO
  • UPDATE
  • WHERE

The Solution

You have two options.

1. Don't use reserved words as identifiers

The simplest solution is simply to avoid using reserved words as identifiers. You can probably find another reasonable name for your column that is not a reserved word.

Doing this has a couple of advantages:

  • It eliminates the possibility that you or another developer using your database will accidentally write a syntax error due to forgetting - or not knowing - that a particular identifier is a reserved word. There are many reserved words in MySQL and most developers are unlikely to know all of them. By not using these words in the first place, you avoid leaving traps for yourself or future developers.

  • The means of quoting identifiers differs between SQL dialects. While MySQL uses backticks for quoting identifiers by default, ANSI-compliant SQL (and indeed MySQL in ANSI SQL mode, as noted here) uses double quotes for quoting identifiers. As such, queries that quote identifiers with backticks are less easily portable to other SQL dialects.

Purely for the sake of reducing the risk of future mistakes, this is usually a wiser course of action than backtick-quoting the identifier.

2. Use backticks

If renaming the table or column isn't possible, wrap the offending identifier in backticks (`) as described in the earlier quote from 10.2 Schema Object Names.

An example to demonstrate the usage (taken from 10.3 Keywords and Reserved Words):

mysql> CREATE TABLE interval (begin INT, end INT);
ERROR 1064 (42000): You have an error in your SQL syntax.
near 'interval (begin INT, end INT)'

mysql> CREATE TABLE `interval` (begin INT, end INT); Query OK, 0 rows affected (0.01 sec)

Similarly, the query from the question can be fixed by wrapping the keyword key in backticks, as shown below:

INSERT INTO user_details (username, location, `key`)
VALUES ('Tim', 'Florida', 42)";               ^   ^

How do I show my global Git configuration?

You can also call git config -e to open the configuration file in your editor directly. The Git configuration file is much more readable that the -l output, so I always tend to use the -e flag.

So to summarise:

git config -l  # List Git configuration settings (same as --list)
git config -e  # Opens Git configuration in the default editor (same as --edit)
  • Without parameters it interacts with the local .git/config.
  • With --global it interacts with ~/.gitconfig.
  • And with --system it interacts with $(prefix)/etc/gitconfig.

(I couldn't really find what $(prefix) means, but it seems to default to $HOME.)

How to delete from a table where ID is in a list of IDs?

delete from t
where id in (1, 4, 6, 7)

Converting Swagger specification JSON to HTML documentation

Try to use redoc-cli.

I was using bootprint-openapi by which I was generating a bunch of files (bundle.js, bundle.js.map, index.html, main.css and main.css.map) and then you can convert it into a single .html file using html-inline to generate a simple index.html file.

Then I found redoc-cli very easy to to use and output is really-2 awesome, a single and beautiful index.html file.

Installation:

npm install -g redoc-cli

Usage:

redoc-cli bundle -o index.html swagger.json

find all the name using mysql query which start with the letter 'a'

Try this simple select:

select * 
from artists 
where name like "a%"

Date format Mapping to JSON Jackson

Working for me. SpringBoot.

 import com.alibaba.fastjson.annotation.JSONField;

 @JSONField(format = "yyyy-MM-dd HH:mm:ss")  
 private Date createTime;

output:

{ 
   "createTime": "2019-06-14 13:07:21"
}

PHP removing a character in a string

$splitPos = strpos($url, "?/");
if ($splitPos !== false) {
    $url = substr($url, 0, $splitPos) . "?" . substr($url, $splitPos + 2);
}

Iterating over ResultSet and adding its value in an ArrayList

Just for the fun, I'm offering an alternative solution using jOOQ and Java 8. Instead of using jOOQ, you could be using any other API that maps JDBC ResultSet to List, such as Spring JDBC or Apache DbUtils, or write your own ResultSetIterator:

jOOQ 3.8 or less

List<Object> list =
DSL.using(connection)
   .fetch("SELECT col1, col2, col3, ...")
   .stream()
   .flatMap(r -> Arrays.stream(r.intoArray()))
   .collect(Collectors.toList());

jOOQ 3.9

List<Object> list =
DSL.using(connection)
   .fetch("SELECT col1, col2, col3, ...")
   .stream()
   .flatMap(Record::intoStream)
   .collect(Collectors.toList());

(Disclaimer, I work for the company behind jOOQ)

How to make a Bootstrap accordion collapse when clicking the header div?

Here's a solution for Bootstrap4. You just need to put the card-header class in the a tag. This is a modified from an example in W3Schools.

_x000D_
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script>_x000D_
_x000D_
<div class="container">_x000D_
  <div id="accordion">_x000D_
    <div class="card">_x000D_
      <a class="card-link card-header" data-toggle="collapse" href="#collapseOne" >_x000D_
        Collapsible Group Item #1_x000D_
      </a>_x000D_
      <div id="collapseOne" class="collapse" data-parent="#accordion">_x000D_
        <div class="card-body">_x000D_
          Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat._x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
    <div class="card">_x000D_
      <a class="collapsed card-link card-header" data-toggle="collapse" href="#collapseTwo">_x000D_
        Collapsible Group Item #2_x000D_
      </a>_x000D_
      <div id="collapseTwo" class="collapse" data-parent="#accordion">_x000D_
        <div class="card-body">_x000D_
          Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat._x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
    <div class="card">_x000D_
      <a class="card-link card-header" data-toggle="collapse" href="#collapseThree">_x000D_
        Collapsible Group Item #3_x000D_
      </a>_x000D_
      <div id="collapseThree" class="collapse" data-parent="#accordion">_x000D_
        <div class="card-body">_x000D_
          Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat._x000D_
        </div>_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

String vs. StringBuilder

The performance of a concatenation operation for a String or StringBuilder object depends on how often a memory allocation occurs. A String concatenation operation always allocates memory, whereas a StringBuilder concatenation operation only allocates memory if the StringBuilder object buffer is too small to accommodate the new data. Consequently, the String class is preferable for a concatenation operation if a fixed number of String objects are concatenated. In that case, the individual concatenation operations might even be combined into a single operation by the compiler. A StringBuilder object is preferable for a concatenation operation if an arbitrary number of strings are concatenated; for example, if a loop concatenates a random number of strings of user input.

Source: MSDN

Looping over elements in jQuery

don't think you need quotations on this:

var child = $("this");

try:

var child = $(this);

Executing a shell script from a PHP script

It's a simple problem. When you are running from terminal, you are running the php file from terminal as a privileged user. When you go to the php from your web browser, the php script is being run as the web server user which does not have permissions to execute files in your home directory. In Ubuntu, the www-data user is the apache web server user. If you're on ubuntu you would have to do the following: chown yourusername:www-data /home/testuser/testscript chmod g+x /home/testuser/testscript

what the above does is transfers user ownership of the file to you, and gives the webserver group ownership of it. the next command gives the group executable permission to the file. Now the next time you go ahead and do it from the browser, it should work.

python save image from url

A sample code that works for me on Windows:

import requests

with open('pic1.jpg', 'wb') as handle:
        response = requests.get(pic_url, stream=True)

        if not response.ok:
            print response

        for block in response.iter_content(1024):
            if not block:
                break

            handle.write(block)

Xcode swift am/pm time to 24 hour format

Swift 3 *

Code to convert 12 hours (i.e. AM and PM) to 24 hours format which includes-

Hours:Minutes:Seconds:AM/PM to Hours:Minutes:Seconds

func timeConversion24(time12: String) -> String {
    let dateAsString = time12
    let df = DateFormatter()
    df.dateFormat = "hh:mm:ssa"

    let date = df.date(from: dateAsString)
    df.dateFormat = "HH:mm:ss"

    let time24 = df.string(from: date!)
    print(time24)
    return time24
}

Input

07:05:45PM

Output

19:05:45

Similarly

Code to convert 24 hours to 12 hours (i.e. AM and PM) format which includes-

Hours:Minutes:Seconds to Hours:Minutes:Seconds:AM/PM

func timeConversion12(time24: String) -> String {
    let dateAsString = time24
    let df = DateFormatter()
    df.dateFormat = "HH:mm:ss"

    let date = df.date(from: dateAsString)
    df.dateFormat = "hh:mm:ssa"

    let time12 = df.string(from: date!)
    print(time12)
    return time12
}

Input

19:05:45

Output

07:05:45PM

Best way to get hostname with php

What about gethostname()?

Edit: This might not be an option I suppose, depending on your environment. It's new in PHP 5.3. php_uname('n') might work as an alternative.

How to execute an SSIS package from .NET?

To add to @Craig Schwarze answer,

Here are some related MSDN links:

Loading and Running a Local Package Programmatically:

Loading and Running a Remote Package Programmatically

Capturing Events from a Running Package:

using System;
using Microsoft.SqlServer.Dts.Runtime;

namespace RunFromClientAppWithEventsCS
{
  class MyEventListener : DefaultEvents
  {
    public override bool OnError(DtsObject source, int errorCode, string subComponent, 
      string description, string helpFile, int helpContext, string idofInterfaceWithError)
    {
      // Add application-specific diagnostics here.
      Console.WriteLine("Error in {0}/{1} : {2}", source, subComponent, description);
      return false;
    }
  }
  class Program
  {
    static void Main(string[] args)
    {
      string pkgLocation;
      Package pkg;
      Application app;
      DTSExecResult pkgResults;

      MyEventListener eventListener = new MyEventListener();

      pkgLocation =
        @"C:\Program Files\Microsoft SQL Server\100\Samples\Integration Services" +
        @"\Package Samples\CalculatedColumns Sample\CalculatedColumns\CalculatedColumns.dtsx";
      app = new Application();
      pkg = app.LoadPackage(pkgLocation, eventListener);
      pkgResults = pkg.Execute(null, null, eventListener, null, null);

      Console.WriteLine(pkgResults.ToString());
      Console.ReadKey();
    }
  }
}

mysqli::query(): Couldn't fetch mysqli

Check if db name do not have "_" or "-" that helps in my case

Converting string from snake_case to CamelCase in Ruby

Source: http://rubydoc.info/gems/extlib/0.9.15/String#camel_case-instance_method

For learning purpose:

class String
  def camel_case
    return self if self !~ /_/ && self =~ /[A-Z]+.*/
    split('_').map{|e| e.capitalize}.join
  end
end

"foo_bar".camel_case          #=> "FooBar"

And for the lowerCase variant:

class String
  def camel_case_lower
    self.split('_').inject([]){ |buffer,e| buffer.push(buffer.empty? ? e : e.capitalize) }.join
  end
end

"foo_bar".camel_case_lower          #=> "fooBar"

jQuery position DIV fixed at top on scroll

instead of doing it like that, why not just make the flyout position:fixed, top:0; left:0; once your window has scrolled pass a certain height:

jQuery

  $(window).scroll(function(){
      if ($(this).scrollTop() > 135) {
          $('#task_flyout').addClass('fixed');
      } else {
          $('#task_flyout').removeClass('fixed');
      }
  });

css

.fixed {position:fixed; top:0; left:0;}

Example

What is difference between png8 and png24

From the Web Designer’s Guide to PNG Image Format

PNG-8 and PNG-24

There are two PNG formats: PNG-8 and PNG-24. The numbers are shorthand for saying "8-bit PNG" or "24-bit PNG." Not to get too much into technicalities — because as a web designer, you probably don’t care — 8-bit PNGs mean that the image is 8 bits per pixel, while 24-bit PNGs mean 24 bits per pixel.

To sum up the difference in plain English: Let’s just say PNG-24 can handle a lot more color and is good for complex images with lots of color such as photographs (just like JPEG), while PNG-8 is more optimized for things with simple colors, such as logos and user interface elements like icons and buttons.

Another difference is that PNG-24 natively supports alpha transparency, which is good for transparent backgrounds. This difference is not 100% true because Adobe products’ Save for Web command allows PNG-8 with alpha transparency.

C split a char array into different variables

One option is strtok

example:

char name[20];
//pretend name is set to the value "My name"

You want to split it at the space between the two words

split=strtok(name," ");

while(split != NULL)
{
    word=split;
    split=strtok(NULL," ");
}

Android SQLite: Update Statement

The SQLiteDatabase object depends on the type of operation on the database.

More information, visit the official website:

https://developer.android.com/training/basics/data-storage/databases.html#UpdateDbRow

It explains how to manipulate consultations on the SQLite database.

INSERT ROW

Gets the data repository in write mode

SQLiteDatabase db = mDbHelper.getWritableDatabase();

Create a new map of values, where column names are the keys

ContentValues values = new ContentValues();
values.put(FeedEntry.COLUMN_NAME_ENTRY_ID, id);
values.put(FeedEntry.COLUMN_NAME_TITLE, title);
values.put(FeedEntry.COLUMN_NAME_CONTENT, content);

Insert the new row, returning the primary key value of the new row

long newRowId;
newRowId = db.insert(
     FeedEntry.TABLE_NAME,
     FeedEntry.COLUMN_NAME_NULLABLE,
     values);

UPDATE ROW

Define 'where' part of query.

String selection = FeedEntry.COLUMN_NAME_ENTRY_ID + " LIKE ?";

Specify arguments in placeholder order.

String[] selectionArgs = { String.valueOf(rowId) };


SQLiteDatabase db = mDbHelper.getReadableDatabase();

New value for one column

ContentValues values = new ContentValues();
values.put(FeedEntry.COLUMN_NAME_TITLE, title);

Which row to update, based on the ID

String selection = FeedEntry.COLUMN_NAME_ENTRY_ID + " LIKE ?";
String[] selectionArgs = { String.valueOf(rowId) };
    int count = db.update(
    FeedReaderDbHelper.FeedEntry.TABLE_NAME,
    values,
    selection,
    selectionArgs);

Array slices in C#

static byte[] SliceMe(byte[] source, int length)
{
    byte[] destfoo = new byte[length];
    Array.Copy(source, 0, destfoo, 0, length);
    return destfoo;
}

//

var myslice = SliceMe(sourcearray,41);

Validating input using java.util.Scanner

For checking Strings for letters you can use regular expressions for example:

someString.matches("[A-F]");

For checking numbers and stopping the program crashing, I have a quite simple class you can find below where you can define the range of values you want. Here

    public int readInt(String prompt, int min, int max)
    {
    Scanner scan = new Scanner(System.in);

    int number = 0;

    //Run once and loop until the input is within the specified range.
    do 
    {
        //Print users message.
        System.out.printf("\n%s > ", prompt);

        //Prevent string input crashing the program.
        while (!scan.hasNextInt()) 
        {
            System.out.printf("Input doesn't match specifications. Try again.");
            System.out.printf("\n%s > ", prompt);
            scan.next(); 
        }

        //Set the number.
        number = scan.nextInt();

        //If the number is outside range print an error message.
        if (number < min || number > max)
            System.out.printf("Input doesn't match specifications. Try again.");

    } while (number < min || number > max);

    return number;
}

Android Closing Activity Programmatically

You Can use just finish(); everywhere after Activity Start for clear that Activity from Stack.

How to call a stored procedure (with parameters) from another stored procedure without temp table

You can just call the Execute command.

EXEC spDoSomthing @myDate

Edit:

Since you want to return data..that's a little harder. You can use user defined functions instead that return data.

Is it valid to replace http:// with // in a <script src="http://...">?

It is indeed correct, as other answers have stated. You should note though, that some web crawlers will set off 404s for these by requesting them on your server as if a local URL. (They disregard the double slash and treat it as a single slash).

You may want to set up a rule on your webserver to catch these and redirect them.

For example, with Nginx, you'd add something like:

location ~* /(?<redirect_domain>((([a-z]|[0-9]|\-)+)\.)+([a-z])+)/(?<redirect_path>.*) {
  return 301 $scheme:/$redirect_domain/$redirect_path;
}

Do note though, that if you use periods in your URIs, you'll need to increase the specificity or it will end up redirecting those pages to nonexistent domains.

Also, this is a rather massive regex to be running for each query -- in my opinion, it's worth punishing non-compliant browsers with 404s over a (slight) performance hit on the majority of compliant browsers.

Excel Formula to SUMIF date falls in particular month

=SUMPRODUCT( (MONTH($A$2:$A$6)=1) * ($B$2:$B$6) )

Explanation:

  • (MONTH($A$2:$A$6)=1) creates an array of 1 and 0, it's 1 when the month is january, thus in your example the returned array would be [1, 1, 1, 0, 0]

  • SUMPRODUCT first multiplies each value of the array created in the above step with values of the array ($B$2:$B$6), then it sums them. Hence in your example it does this: (1 * 430) + (1 * 96) + (1 * 440) + (0 * 72.10) + (0 * 72.30)

This works also in OpenOffice and Google Spreadsheets

How to change the plot line color from blue to black?

The usual way to set the line color in matplotlib is to specify it in the plot command. This can either be done by a string after the data, e.g. "r-" for a red line, or by explicitely stating the color argument.

import matplotlib.pyplot as plt

plt.plot([1,2,3], [2,3,1], "r-") # red line
plt.plot([1,2,3], [5,5,3], color="blue") # blue line

plt.show()

See also the plot command's documentation.

In case you already have a line with a certain color, you can change that with the lines2D.set_color() method.

line, = plt.plot([1,2,3], [4,5,3], color="blue")
line.set_color("black")


Setting the color of a line in a pandas plot is also best done at the point of creating the plot:

import matplotlib.pyplot as plt
import pandas as pd

df = pd.DataFrame({ "x" : [1,2,3,5], "y" : [3,5,2,6]})
df.plot("x", "y", color="r") #plot red line

plt.show()

If you want to change this color later on, you can do so by

plt.gca().get_lines()[0].set_color("black")

This will get you the first (possibly the only) line of the current active axes.
In case you have more axes in the plot, you could loop through them

for ax in plt.gcf().axes:
    ax.get_lines()[0].set_color("black")

and if you have more lines you can loop over them as well.

Mongoose limit/offset and count query

Instead of using 2 separate queries, you can use aggregate() in a single query:

Aggregate "$facet" can be fetch more quickly, the Total Count and the Data with skip & limit

    db.collection.aggregate([

      //{$sort: {...}}

      //{$match:{...}}

      {$facet:{

        "stage1" : [ {"$group": {_id:null, count:{$sum:1}}} ],

        "stage2" : [ { "$skip": 0}, {"$limit": 2} ]
  
      }},
     
     {$unwind: "$stage1"},
  
      //output projection
     {$project:{
        count: "$stage1.count",
        data: "$stage2"
     }}

 ]);

output as follows:-

[{
     count: 50,
     data: [
        {...},
        {...}
      ]
 }]

Also, have a look at https://docs.mongodb.com/manual/reference/operator/aggregation/facet/

How to resolve /var/www copy/write permission denied?

are you in a develpment enviroment? why just not do

chown -R user.group /var/www

so you will be able to write with your user.

Subset of rows containing NA (missing) values in a chosen column of a data frame

Try changing this:

new_DF<-dplyr::filter(DF,is.na(Var2)) 

Remove unused imports in Android Studio

you can use Alt + Enter in Android Studio as Shortcut Key

Triggering a checkbox value changed event in DataGridView

Working with an unbound control (ie I manage the content programmatically), without the EndEdit() it only called the CurrentCellDirtyStateChanged once and then never again; but I found that with the EndEdit() CurrentCellDirtyStateChanged was called twice (the second probably caused by the EndEdit() but I didn't check), so I did the following, which worked best for me:

    bool myGridView_DoCheck = false;
    private void myGridView_CurrentCellDirtyStateChanged(object sender, EventArgs e)
    {
        if (!myGridView_DoCheck)
        {
            myGridView_DoCheck = true;
            myGridView.EndEdit();
            // do something here
        }
        else
            myGridView_DoCheck = false;
    }

How to list all properties of a PowerShell object

Try this:

Get-WmiObject -Class "Win32_computersystem" | Format-List *
Get-WmiObject -Class "Win32_computersystem" | Format-List -Property *

For certain objects, PowerShell provides a set of formatting instructions that can affect either the table or list formats. These are usually meant to limit the display of reams of properties down to just the essential properties. However there are times when you really want to see everything. In those cases Format-List * will show all the properties. Note that in the case where you're trying to view a PowerShell error record, you need to use "Format-List * -Force" to truly see all the error information, for example,

$error[0] | Format-List * -force

Note that the wildcard can be used like a traditional wilcard this:

Get-WmiObject -Class "Win32_computersystem" | Format-List M*

How to create Python egg file

I think you should use python wheels for distribution instead of egg now.

Wheels are the new standard of python distribution and are intended to replace eggs. Support is offered in pip >= 1.4 and setuptools >= 0.8.

How do I draw a circle in iOS Swift?

Here is my version using Swift 5 and Core Graphics.

I have created a class to draw two circles. The first circle is created using addEllipse(). It puts the ellipse into a square, thus creating a circle. I find it surprising that there is no function addCircle(). The second circle is created using addArc() of 2pi radians

import UIKit

@IBDesignable
class DrawCircles: UIView {

    override init(frame: CGRect) {
        super.init(frame: frame)
    }

    required public init?(coder aDecoder: NSCoder) {
        super.init(coder: aDecoder)
    }

    override func draw(_ rect: CGRect) {

        guard let context = UIGraphicsGetCurrentContext() else {
            print("could not get graphics context")
            return
        }

        context.setLineWidth(2)

        context.setStrokeColor(UIColor.blue.cgColor)

        context.addEllipse(in: CGRect(x: 30, y: 30, width: 50.0, height: 50.0))

        context.strokePath()

        context.setStrokeColor(UIColor.red.cgColor)

        context.beginPath() // this prevents a straight line being drawn from the current point to the arc

        context.addArc(center: CGPoint(x:100, y: 100), radius: 20, startAngle: 0, endAngle: 2.0*CGFloat.pi, clockwise: false)

        context.strokePath()
    }
}

in your ViewController's didViewLoad() add the following:

let myView = DrawCircles(frame: CGRect(x: 50, y: 50, width: 300, height: 300))

self.view.addSubview(myView)

When it runs it should look like this. I hope you like my solution!

enter image description here

Decimal separator comma (',') with numberDecimal inputType in EditText

My solution is:

  • In main activity:

    char separator =DecimalFormatSymbols.getInstance().getDecimalSeparator(); textViewPitchDeadZone.setKeyListener(DigitsKeyListener.getInstance("0123456789" + separator));

  • In xml file: android:imeOptions="flagNoFullscreen" android:inputType="numberDecimal"

and I took the double in the editText as a String.

MVC pattern on Android

There is no universally unique MVC pattern. MVC is a concept rather than a solid programming framework. You can implement your own MVC on any platform. As long as you stick to the following basic idea, you are implementing MVC:

  • Model: What to render
  • View: How to render
  • Controller: Events, user input

Also think about it this way: When you program your model, the model should not need to worry about the rendering (or platform specific code). The model would say to the view, I don't care if your rendering is Android or iOS or Windows Phone, this is what I need you to render. The view would only handle the platform-specific rendering code.

This is particularly useful when you use Mono to share the model in order to develop cross-platform applications.

How do I access nested HashMaps in Java?

You can get the nested value by repeating .get(), but with deeply nested maps you have to do a lot of casting into Map. An easier way is to use a generic method for getting a nested value.

Implementation

public static <T> T getNestedValue(Map map, String... keys) {
    Object value = map;

    for (String key : keys) {
        value = ((Map) value).get(key);
    }

    return (T) value;
}

Usage

// Map contents with string and even a list:
{
  "data": {
    "vehicles": {
      "list": [
        {
          "registration": {
            "owner": {
              "id": "3643619"
            }
          }
        }
      ]
    }
  }
}
List<Map> list = getNestedValue(mapContents, "data", "vehicles", "list");
Map first = list.get(0);
String id = getNestedValue(first, "registration", "owner", "id");

How to clear a data grid view

YourGrid.Items.Clear();
YourGrid.Items.Refresh();

selecting from multi-index pandas

One way is to use the get_level_values Index method:

In [11]: df
Out[11]:
     0
A B
1 4  1
2 5  2
3 6  3

In [12]: df.iloc[df.index.get_level_values('A') == 1]
Out[12]:
     0
A B
1 4  1

In 0.13 you'll be able to use xs with drop_level argument:

df.xs(1, level='A', drop_level=False) # axis=1 if columns

Note: if this were column MultiIndex rather than index, you could use the same technique:

In [21]: df1 = df.T

In [22]: df1.iloc[:, df1.columns.get_level_values('A') == 1]
Out[22]:
A  1
B  4
0  1

Use PPK file in Mac Terminal to connect to remote connection over SSH

There is a way to do this without installing putty on your Mac. You can easily convert your existing PPK file to a PEM file using PuTTYgen on Windows.

Launch PuTTYgen and then load the existing private key file using the Load button. From the "Conversions" menu select "Export OpenSSH key" and save the private key file with the .pem file extension.

Copy the PEM file to your Mac and set it to be read-only by your user:

chmod 400 <private-key-filename>.pem

Then you should be able to use ssh to connect to your remote server

ssh -i <private-key-filename>.pem username@hostname

What is the use of BindingResult interface in spring MVC?

Basically BindingResult is an interface which dictates how the object that stores the result of validation should store and retrieve the result of the validation(errors, attempt to bind to disallowed fields etc)

From Spring MVC Form Validation with Annotations Tutorial:

[BindingResult] is Spring’s object that holds the result of the validation and binding and contains errors that may have occurred. The BindingResult must come right after the model object that is validated or else Spring will fail to validate the object and throw an exception.

When Spring sees @Valid, it tries to find the validator for the object being validated. Spring automatically picks up validation annotations if you have “annotation-driven” enabled. Spring then invokes the validator and puts any errors in the BindingResult and adds the BindingResult to the view model.

How to encrypt String in Java

This is the first page that shows up via Google and the security vulnerabilities in all the implementations make me cringe so I'm posting this to add information regarding encryption for others as it has been 7 Years from the original post. I hold a Masters Degree in Computer Engineering and spent a lot of time studying and learning Cryptography so I'm throwing my two cents to make the internet a safer place.

Also, do note that a lot of implementation might be secure for a given situation, but why use those and potentially accidentally make a mistake? Use the strongest tools you have available unless you have a specific reason not to. Overall I highly advise using a library and staying away from the nitty gritty details if you can.

UPDATE 4/5/18: I rewrote some parts to make them simpler to understand and changed the recommended library from Jasypt to Google's new library Tink, I would recommend completely removing Jasypt from an existing setup.

Foreword

I will outline the basics of secure symmetric cryptography below and point out common mistakes I see online when people implement crypto on their own with the standard Java library. If you want to just skip all the details run over to Google's new library Tink import that into your project and use AES-GCM mode for all your encryptions and you shall be secure.

Now if you want to learn the nitty gritty details on how to encrypt in java read on :)

Block Ciphers

First thing first you need to pick a symmetric key Block Cipher. A Block Cipher is a computer function/program used to create Pseudo-Randomness. Pseudo-Randomness is fake randomness that no computer other than a Quantum Computer would be able to tell the difference between it and real randomness. The Block Cipher is like the building block to cryptography, and when used with different modes or schemes we can create encryptions.

Now regarding Block Cipher Algorithms available today, Make sure to NEVER, I repeat NEVER use DES, I would even say NEVER use 3DES. The only Block Cipher that even Snowden's NSA release was able to verify being truly as close to Pseudo-Random as possible is AES 256. There also exists AES 128; the difference is AES 256 works in 256-bit blocks, while AES 128 works in 128 blocks. All in all, AES 128 is considered secure although some weaknesses have been discovered, but 256 is as solid as it gets.

Fun fact DES was broken by the NSA back when it was initially founded and actually kept a secret for a few years. Although some people still claim 3DES is secure, there are quite a few research papers that have found and analyzed weaknesses in 3DES.

Encryption Modes

Encryption is created when you take a block cipher and use a specific scheme so that the randomness is combined with a key to creating something that is reversible as long as you know the key. This is referred to as an Encryption Mode.

Here is an example of an encryption mode and the simplest mode known as ECB just so you can visually understand what is happening:

ECB Mode

The encryption modes you will see most commonly online are the following:

ECB CTR, CBC, GCM

There exist other modes outside of the ones listed and researchers are always working toward new modes to improve existing problems.

Now let's move on to implementations and what is secure. NEVER use ECB this is bad at hiding repeating data as shown by the famous Linux penguin.Linux Penguin Example

When implementing in Java, note that if you use the following code, ECB mode is set by default:

Cipher cipher = Cipher.getInstance("AES");

... DANGER THIS IS A VULNERABILITY! and unfortunately, this is seen all over StackOverflow and online in tutorials and examples.

Nonces and IVs

In response to the issue found with ECB mode nounces also known as IVs were created. The idea is that we generate a new random variable and attach it to every encryption so that when you encrypt two messages that are the same they come out different. The beauty behind this is that an IV or nonce is public knowledge. That means an attacker can have access to this but as long as they don't have your key, they cant do anything with that knowledge.

Common issues I will see is that people will set the IV as a static value as in the same fixed value in their code. and here is the pitfall to IVs the moment you repeat one you actually compromise the entire security of your encryption.

Generating A Random IV

SecureRandom randomSecureRandom = SecureRandom.getInstance("SHA1PRNG");
byte[] iv = new byte[cipher.getBlockSize()];
randomSecureRandom.nextBytes(iv);
IvParameterSpec ivParams = new IvParameterSpec(iv);

Note: SHA1 is broken but I couldn't find how to implement SHA256 into this use case properly, so if anyone wants to take a crack at this and update it would be awesome! Also SHA1 attacks still are unconventional as it can take a few years on a huge cluster to crack. Check out details here.

CTR Implementation

No padding is required for CTR mode.

 Cipher cipher = Cipher.getInstance("AES/CTR/NoPadding");

CBC Implementation

If you choose to implement CBC Mode do so with PKCS7Padding as follows:

 Cipher cipher = Cipher.getInstance("AES/CBC/PKCS7Padding");

CBC and CTR Vulnerability and Why You Should Use GCM

Although some other modes such as CBC and CTR are secure they run into the issue where an attacker can flip the encrypted data, changing its value when decrypted. So let's say you encrypt an imaginary bank message "Sell 100", your encrypted message looks like this "eu23ng" the attacker changes one bit to "eu53ng" and all of a sudden when decrypted your message, it reads as "Sell 900".

To avoid this the majority of the internet uses GCM, and every time you see HTTPS they are probably using GCM. GCM signs the encrypted message with a hash and checks to verify that the message has not been changed using this signature.

I would avoid implementing GCM because of its complexity. You are better off using Googles new library Tink because here again if you accidentally repeat an IV you are compromising the key in the case with GCM, which is the ultimate security flaw. New researchers are working towards IV repeat resistant encryption modes where even if you repeat the IV the key is not in danger but this has yet to come mainstream.

Now if you do want to implement GCM, here is a link to a nice GCM implementation. However, I can not ensure the security or if its properly implemented but it gets the basis down. Also note with GCM there is no padding.

Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");

Keys vs Passwords

Another very important note, is that when it comes to cryptography a Key and a Password are not the same things. A Key in cryptography needs to have a certain amount of entropy and randomness to be considered secure. This is why you need to make sure to use the proper cryptographic libraries to generate the key for you.

So you really have two implementations you can do here, the first is to use the code found on this StackOverflow thread for Random Key Generation. This solution uses a secure random number generator to create a key from scratch that you can the use.

The other less secure option is to use, user input such as a password. The issue as we discussed is that the password doesn't have enough entropy, so we would have to use PBKDF2, an algorithm that takes the password and strengthens it. Here is a StackOverflow implementation I liked. However Google Tink library has all this built in and you should take advantage of it.

Android Developers

One important point to point out here is know that your android code is reverse engineerable and most cases most java code is too. That means if you store the password in plain text in your code. A hacker can easily retrieve it. Usually, for these type of encryption, you want to use Asymmetric Cryptography and so on. This is outside the scope of this post so I will avoid diving into it.

An interesting reading from 2013: Points out that 88% of Crypto implementations in Android were done improperly.

Final Thoughts

Once again I would suggest avoid implementing the java library for crypto directly and use Google Tink, it will save you the headache as they have really done a good job of implementing all the algorithms properly. And even then make sure you check up on issues brought up on the Tink github, vulnerabilities popup here and there.

If you have any questions or feedback feel free to comment! Security is always changing and you need to do your best to keep up with it :)

Add an object to a python list

If i am correct in believing that you are adding a variable to the array but when you change that variable outside of the array, it also changes inside the array but you don't want it to then it is a really simple solution.

When you are saving the variable to the array you should turn it into a string by simply putting str(variablename). For example:

array.append(str(variablename))

Using this method your code should look like this:

arrayList = []
for x in allValues:
    result = model(x)
    arrayList.append(str(wM))        #this is the only line that is changed.
    wM.reset()

Property [title] does not exist on this collection instance

$about->first()->id or $stm->first()->title and your problem is sorted out.

How to recursively find the latest modified file in a directory?

This gives a sorted list:

find . -type f -ls 2>/dev/null | sort -M -k8,10 | head -n5

Reverse the order by placing a '-r' in the sort command. If you only want filenames, insert "awk '{print $11}' |" before '| head'

Re-assign host access permission to MySQL user

Similar issue where I was getting permissions failed. On my setup, I SSH in only. So What I did to correct the issue was

sudo MySQL
SELECT User, Host FROM mysql.user WHERE Host <> '%';
MariaDB [(none)]> SELECT User, Host FROM mysql.user WHERE Host <> '%';
+-------+-------------+
| User  | Host        |
+-------+-------------+
| root  | 169.254.0.% |
| foo   | 192.168.0.% |
| bar   | 192.168.0.% |
+-------+-------------+
4 rows in set (0.00 sec)

I need these users moved to 'localhost'. So I issued the following:

UPDATE mysql.user SET host = 'localhost' WHERE user = 'foo';
UPDATE mysql.user SET host = 'localhost' WHERE user = 'bar';

Run SELECT User, Host FROM mysql.user WHERE Host <> '%'; again and we see:

MariaDB [(none)]> SELECT User, Host FROM mysql.user WHERE Host <> '%';
+-------+-------------+
| User  | Host        |
+-------+-------------+
| root  | 169.254.0.% |
| foo   | localhost   |
| bar   | localhost   |
+-------+-------------+
4 rows in set (0.00 sec)

And then I was able to work normally again. Hope that helps someone.

$ mysql -u foo -p
Enter password:
Welcome to the MariaDB monitor.  Commands end with ; or \g.
Your MariaDB connection id is 74
Server version: 10.1.23-MariaDB-9+deb9u1 Raspbian 9.0

Copyright (c) 2000, 2017, Oracle, MariaDB Corporation Ab and others.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

MariaDB [(none)]>

How do I add an integer value with javascript (jquery) to a value that's returning a string?

Parse int is the tool you should use here, but like any tool it should be used correctly. When using parseInt you should always use the radix parameter to ensure the correct base is used

var currentValue = parseInt($("#replies").text(),10);

In Java how does one turn a String into a char or a char into a String?

In order to convert string to char

 String str = "abcd";
char arr [] = new char[len]; // len is the length of the array
arr = str.toCharArray();

How to adjust gutter in Bootstrap 3 grid system?

You could create a CSS class for this and apply it to your columns. Since the gutter (spacing between columns) is controlled by padding in Bootstrap 3, adjust the padding accordingly:

.col {
  padding-right:7px;
  padding-left:7px;
}

Demo: http://bootply.com/93473

EDIT If you only want the spacing between columns you can select all cols except first and last like this..

.col:not(:first-child,:last-child) {
  padding-right:7px;
  padding-left:7px;
}

Updated Bootply

For Bootstrap 4 see: Remove gutter space for a specific div only

Best place to insert the Google Analytics code

If you want your scripts to load after page has been rendered, you can use:

function getScript(a, b) {
    var c = document.createElement("script");
    c.src = a;
    var d = document.getElementsByTagName("head")[0],
        done = false;
    c.onload = c.onreadystatechange = function() {
        if (!done && (!this.readyState || this.readyState == "loaded" || this.readyState == "complete")) {
            done = true;
            b();
            c.onload = c.onreadystatechange = null;
            d.removeChild(c)
        }
    };
    d.appendChild(c)
}

//call the function
getScript("http://www.google-analytics.com/ga.js", function() {
    // do stuff after the script has loaded
});

Class file for com.google.android.gms.internal.zzaja not found

I solved the problem in june of 2017 changing the play-services versions for the latest firebase versions (9.6.1). When I used the latest play-services version (10.2.4) I got that error. The code in the gradle looks like this:

Before

compile 'com.google.android.gms:play-services-maps:10.2.4'
compile 'com.google.android.gms:play-services-places:10.2.4'
compile 'com.google.firebase:firebase-core:9.6.1'
compile 'com.google.firebase:firebase-auth:9.6.1'

After

compile 'com.google.android.gms:play-services-maps:9.6.1'
compile 'com.google.android.gms:play-services-places:9.6.1'
compile 'com.google.firebase:firebase-core:9.6.1'
compile 'com.google.firebase:firebase-auth:9.6.1'

PowerShell equivalent to grep -f

but select-String doesn't seem to have this option.

Correct. PowerShell is not a clone of *nix shells' toolset.

However it is not hard to build something like it yourself:

$regexes = Get-Content RegexFile.txt | 
           Foreach-Object { new-object System.Text.RegularExpressions.Regex $_ }

$fileList | Get-Content | Where-Object {
  foreach ($r in $regexes) {
    if ($r.IsMatch($_)) {
      $true
      break
    }
  }
  $false
}

Return background color of selected cell

If you are looking at a Table, a Pivot Table, or something with conditional formatting, you can try:

ActiveCell.DisplayFormat.Interior.Color

This also seems to work just fine on regular cells.

Declare variable in table valued function

There are two flavors of table valued functions. One that is just a select statement and one that can have more rows than just a select statement.

This can not have a variable:

create function Func() returns table
as
return
select 10 as ColName

You have to do like this instead:

create function Func()
returns @T table(ColName int)
as
begin
  declare @Var int
  set @Var = 10
  insert into @T(ColName) values (@Var)
  return
end

MySQL GROUP BY two columns

First, let's make some test data:

create table client (client_id integer not null primary key auto_increment,
                     name varchar(64));
create table portfolio (portfolio_id integer not null primary key auto_increment,
                        client_id integer references client.id,
                        cash decimal(10,2),
                        stocks decimal(10,2));
insert into client (name) values ('John Doe'), ('Jane Doe');
insert into portfolio (client_id, cash, stocks) values (1, 11.11, 22.22),
                                                       (1, 10.11, 23.22),
                                                       (2, 30.30, 40.40),
                                                       (2, 40.40, 50.50);

If you didn't need the portfolio ID, it would be easy:

select client_id, name, max(cash + stocks)
from client join portfolio using (client_id)
group by client_id

+-----------+----------+--------------------+
| client_id | name     | max(cash + stocks) |
+-----------+----------+--------------------+
|         1 | John Doe |              33.33 | 
|         2 | Jane Doe |              90.90 | 
+-----------+----------+--------------------+

Since you need the portfolio ID, things get more complicated. Let's do it in steps. First, we'll write a subquery that returns the maximal portfolio value for each client:

select client_id, max(cash + stocks) as maxtotal
from portfolio
group by client_id

+-----------+----------+
| client_id | maxtotal |
+-----------+----------+
|         1 |    33.33 | 
|         2 |    90.90 | 
+-----------+----------+

Then we'll query the portfolio table, but use a join to the previous subquery in order to keep only those portfolios the total value of which is the maximal for the client:

 select portfolio_id, cash + stocks from portfolio 
 join (select client_id, max(cash + stocks) as maxtotal 
       from portfolio
       group by client_id) as maxima
 using (client_id)
 where cash + stocks = maxtotal

+--------------+---------------+
| portfolio_id | cash + stocks |
+--------------+---------------+
|            5 |         33.33 | 
|            6 |         33.33 | 
|            8 |         90.90 | 
+--------------+---------------+

Finally, we can join to the client table (as you did) in order to include the name of each client:

select client_id, name, portfolio_id, cash + stocks
from client
join portfolio using (client_id)
join (select client_id, max(cash + stocks) as maxtotal
      from portfolio 
      group by client_id) as maxima
using (client_id)
where cash + stocks = maxtotal

+-----------+----------+--------------+---------------+
| client_id | name     | portfolio_id | cash + stocks |
+-----------+----------+--------------+---------------+
|         1 | John Doe |            5 |         33.33 | 
|         1 | John Doe |            6 |         33.33 | 
|         2 | Jane Doe |            8 |         90.90 | 
+-----------+----------+--------------+---------------+

Note that this returns two rows for John Doe because he has two portfolios with the exact same total value. To avoid this and pick an arbitrary top portfolio, tag on a GROUP BY clause:

select client_id, name, portfolio_id, cash + stocks
from client
join portfolio using (client_id)
join (select client_id, max(cash + stocks) as maxtotal
      from portfolio 
      group by client_id) as maxima
using (client_id)
where cash + stocks = maxtotal
group by client_id, cash + stocks

+-----------+----------+--------------+---------------+
| client_id | name     | portfolio_id | cash + stocks |
+-----------+----------+--------------+---------------+
|         1 | John Doe |            5 |         33.33 | 
|         2 | Jane Doe |            8 |         90.90 | 
+-----------+----------+--------------+---------------+

MySQL: Can't create table (errno: 150)

If the PK table is created in one CHARSET and then you create FK table in another CHARSET..then also you might get this error...I too got this error but after changing the charset to PK charset then it got executed without errors

create table users
(
------------
-------------
)DEFAULT CHARSET=latin1;


create table Emp
(
---------
---------
---------
FOREIGN KEY (userid) REFERENCES users(id) on update cascade on delete cascade)ENGINE=InnoDB, DEFAULT CHARSET=latin1;

Is it not possible to stringify an Error using JSON.stringify?

None of the answers above seemed to properly serialize properties which are on the prototype of Error (because getOwnPropertyNames() does not include inherited properties). I was also not able to redefine the properties like one of the answers suggested.

This is the solution I came up with - it uses lodash but you could replace lodash with generic versions of those functions.

 function recursivePropertyFinder(obj){
    if( obj === Object.prototype){
        return {};
    }else{
        return _.reduce(Object.getOwnPropertyNames(obj), 
            function copy(result, value, key) {
                if( !_.isFunction(obj[value])){
                    if( _.isObject(obj[value])){
                        result[value] = recursivePropertyFinder(obj[value]);
                    }else{
                        result[value] = obj[value];
                    }
                }
                return result;
            }, recursivePropertyFinder(Object.getPrototypeOf(obj)));
    }
}


Error.prototype.toJSON = function(){
    return recursivePropertyFinder(this);
}

Here's the test I did in Chrome:

var myError = Error('hello');
myError.causedBy = Error('error2');
myError.causedBy.causedBy = Error('error3');
myError.causedBy.causedBy.displayed = true;
JSON.stringify(myError);

{"name":"Error","message":"hello","stack":"Error: hello\n    at <anonymous>:66:15","causedBy":{"name":"Error","message":"error2","stack":"Error: error2\n    at <anonymous>:67:20","causedBy":{"name":"Error","message":"error3","stack":"Error: error3\n    at <anonymous>:68:29","displayed":true}}}  

Error: package or namespace load failed for ggplot2 and for data.table

Faced same issue and solved by :

remove.packages("ggplot2")
install.packages('ggplot2', dependencies = TRUE)

How to convert a String to a Date using SimpleDateFormat?

You have used some type errors. If you want to set 08/16/2011 to following pattern. It is wrong because,

mm stands for minutes, use MM as it is for Months

DD is wrong, it should be dd which represents Days

Try this to achieve the output you want to get ( Tue Aug 16 "Whatever Time" IST 2011 ),

    String date = "08/16/2011"; //input date as String

    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MM/dd/yyyy"); // date pattern

    Date myDate = simpleDateFormat.parse(date); // returns date object 

    System.out.println(myDate); //outputs: Tue Aug 16 00:00:00 IST 2011