Programs & Examples On #Horizontalfieldmanager

List append() in for loop

You don't need the assignment, list.append(x) will always append x to a and therefore there's no need te redefine a.

a = []
for i in range(5):    
    a.append(i)
print(a)

is all you need. This works because lists are mutable.

Also see the docs on data structures.

Convert UTF-8 encoded NSData to NSString

Just to summarize, here's a complete answer, that worked for me.

My problem was that when I used

[NSString stringWithUTF8String:(char *)data.bytes];

The string I got was unpredictable: Around 70% it did contain the expected value, but too often it resulted with Null or even worse: garbaged at the end of the string.

After some digging I switched to

[[NSString alloc] initWithBytes:(char *)data.bytes length:data.length encoding:NSUTF8StringEncoding];

And got the expected result every time.

Android fastboot waiting for devices

To use the fastboot command you first need to put your device in fastboot mode:

$ adb reboot bootloader

Once the device is in fastboot mode, you can boot it with your own kernel, for example:

$ fastboot boot myboot.img

The above will only boot your kernel once and the old kernel will be used again when you reboot the device. To replace the kernel on the device, you will need to flash it to the device:

$ fastboot flash boot myboot.img

Hope that helps.

How to apply box-shadow on all four sides?

Use this css code for all four sides: box-shadow: 0px 1px 7px 0px rgb(106, 111, 109);

Eclipse - Failed to load class "org.slf4j.impl.StaticLoggerBinder"

After placing the jar file in desired location, you need to add the jar file by right click on

Project --> properties --> Java Build Path --> Libraries --> Add Jar.

GnuPG: "decryption failed: secret key not available" error from gpg on Windows

when reimporting your keys from the old keyring, you need to specify the command:

gpg --allow-secret-key-import --import <keyring>

otherwise it will only import the public keys, not the private keys.

How to customize the configuration file of the official PostgreSQL Docker image?

I was also using the official image (FROM postgres) and I was able to change the config by executing the following commands.

The first thing is to locate the PostgreSQL config file. This can be done by executing this command in your running database.

SHOW config_file;

I my case it returns /data/postgres/postgresql.conf.

The next step is to find out what is the hash of your running PostgreSQL docker container.

docker ps -a

This should return a list of all the running containers. In my case it looks like this.

...
0ba35e5427d9    postgres    "docker-entrypoint.s…" ....
...

Now you have to switch to the bash inside your container by executing:

docker exec -it 0ba35e5427d9 /bin/bash

Inside the container check if the config is at the correct path and display it.

cat /data/postgres/postgresql.conf

I wanted to change the max connections from 100 to 1000 and the shared buffer from 128MB to 3GB. With the sed command I can do a search and replace with the corresponding variables ins the config.

sed -i -e"s/^max_connections = 100.*$/max_connections = 1000/" /data/postgres/postgresql.conf
sed -i -e"s/^shared_buffers = 128MB.*$/shared_buffers = 3GB/" /data/postgres/postgresql.conf

The last thing we have to do is to restart the database within the container. Find out which version you of PostGres you are using.

cd /usr/lib/postgresql/
ls 

In my case its 12 So you can now restart the database by executing the following command with the correct version in place.

su - postgres -c "PGDATA=$PGDATA /usr/lib/postgresql/12/bin/pg_ctl -w restart"

Warning - Build path specifies execution environment J2SE-1.4

In eclipse preferences, go to Java->Installed JREs->Execution Environment and set up a JRE Execution Environment for J2SE-1.4

Command line to remove an environment variable from the OS level configuration

To remove the variable from the current environment (not permanently):

set FOOBAR=

To permanently remove the variable from the user environment (which is the default place setx puts it):

REG delete HKCU\Environment /F /V FOOBAR

If the variable is set in the system environment (e.g. if you originally set it with setx /M), as an administrator run:

REG delete "HKLM\SYSTEM\CurrentControlSet\Control\Session Manager\Environment" /F /V FOOBAR

Note: The REG commands above won't affect any existing processes (and some new processes that are forked from existing processes), so if it's important for the change to take effect immediately, the easiest and surest thing to do is log out and back in or reboot. If this isn't an option or you want to dig deeper, some of the other answers here have some great suggestions that may suit your use case.

iOS 7.0 No code signing identities found

For Certificate

  1. Revoke Previous Certificate.
  2. Generate New Development Certificate.
  3. Download Certificate.
  4. Double Click to put in KeyChain.

For Provisioning profile

  1. Create New or Edit existing Provisioning profile.
  2. Download and install.

For BundleIdentifier.

  1. com.yourcompanyName.Something (Put same as in AppId)

enter image description here

CodeSigningIdentity.

  1. Select The Provisioning profile which you created.

enter image description here

Calling @Html.Partial to display a partial view belonging to a different controller

That's no problem.

@Html.Partial("../Controller/View", model)

or

@Html.Partial("~/Views/Controller/View.cshtml", model)

Should do the trick.

If you want to pass through the (other) controller, you can use:

@Html.Action("action", "controller", parameters)

or any of the other overloads

Getting the ID of the element that fired an event

I'm working with

jQuery Autocomplete

I tried looking for an event as described above, but when the request function fires it doesn't seem to be available. I used this.element.attr("id") to get the element's ID instead, and it seems to work fine.

how to send multiple data with $.ajax() jquery

you can use FormData

take look at my snippet from MVC

var fd = new FormData();
fd.append("ProfilePicture", $("#mydropzone")[0].files[0]);// getting value from form feleds 
d.append("id", @(((User) Session["User"]).ID));// getting value from session

$.ajax({
    url: '@Url.Action("ChangeUserPicture", "User")',
    dataType: "json",
    data: fd,//here is your data
    processData: false,
    contentType: false,
    type: 'post',
    success: function(data) {},

Is there a macro to conditionally copy rows to another worksheet?

This is partially pseudocode, but you will want something like:

rows = ActiveSheet.UsedRange.Rows
n = 0

while n <= rows
  if ActiveSheet.Rows(n).Cells(DateColumnOrdinal).Value > '8/1/08' AND < '8/30/08' then
     ActiveSheet.Rows(n).CopyTo(DestinationSheet)
  endif
  n = n + 1
wend

Why can't I find SQL Server Management Studio after installation?

Generally if the installation went smoothly, it will create the desktop icons/folders. Maybe check the installation summary log to see if there's any underlying errors.

It should be located C:\Program Files\Microsoft SQL Server\100\Setup Bootstrap\Log(date stamp)\

What is the difference between signed and unsigned int

In laymen's terms an unsigned int is an integer that can not be negative and thus has a higher range of positive values that it can assume. A signed int is an integer that can be negative but has a lower positive range in exchange for more negative values it can assume.

Why use @Scripts.Render("~/bundles/jquery")

Bundling is all about compressing several JavaScript or stylesheets files without any formatting (also referred as minified) into a single file for saving bandwith and number of requests to load a page.

As example you could create your own bundle:

bundles.Add(New ScriptBundle("~/bundles/mybundle").Include(
            "~/Resources/Core/Javascripts/jquery-1.7.1.min.js",
            "~/Resources/Core/Javascripts/jquery-ui-1.8.16.min.js",
            "~/Resources/Core/Javascripts/jquery.validate.min.js",
            "~/Resources/Core/Javascripts/jquery.validate.unobtrusive.min.js",
            "~/Resources/Core/Javascripts/jquery.unobtrusive-ajax.min.js",
            "~/Resources/Core/Javascripts/jquery-ui-timepicker-addon.js"))

And render it like this:

@Scripts.Render("~/bundles/mybundle")

One more advantage of @Scripts.Render("~/bundles/mybundle") over the native <script src="~/bundles/mybundle" /> is that @Scripts.Render() will respect the web.config debug setting:

  <system.web>
    <compilation debug="true|false" />

If debug="true" then it will instead render individual script tags for each source script, without any minification.

For stylesheets you will have to use a StyleBundle and @Styles.Render().

Instead of loading each script or style with a single request (with script or link tags), all files are compressed into a single JavaScript or stylesheet file and loaded together.

In Python, how do I read the exif data for an image?

import sys
import PIL
import PIL.Image as PILimage
from PIL import ImageDraw, ImageFont, ImageEnhance
from PIL.ExifTags import TAGS, GPSTAGS



class Worker(object):
    def __init__(self, img):
        self.img = img
        self.exif_data = self.get_exif_data()
        self.lat = self.get_lat()
        self.lon = self.get_lon()
        self.date =self.get_date_time()
        super(Worker, self).__init__()

    @staticmethod
    def get_if_exist(data, key):
        if key in data:
            return data[key]
        return None

    @staticmethod
    def convert_to_degress(value):
        """Helper function to convert the GPS coordinates
        stored in the EXIF to degress in float format"""
        d0 = value[0][0]
        d1 = value[0][1]
        d = float(d0) / float(d1)
        m0 = value[1][0]
        m1 = value[1][1]
        m = float(m0) / float(m1)

        s0 = value[2][0]
        s1 = value[2][1]
        s = float(s0) / float(s1)

        return d + (m / 60.0) + (s / 3600.0)

    def get_exif_data(self):
        """Returns a dictionary from the exif data of an PIL Image item. Also
        converts the GPS Tags"""
        exif_data = {}
        info = self.img._getexif()
        if info:
            for tag, value in info.items():
                decoded = TAGS.get(tag, tag)
                if decoded == "GPSInfo":
                    gps_data = {}
                    for t in value:
                        sub_decoded = GPSTAGS.get(t, t)
                        gps_data[sub_decoded] = value[t]

                    exif_data[decoded] = gps_data
                else:
                    exif_data[decoded] = value
        return exif_data

    def get_lat(self):
        """Returns the latitude and longitude, if available, from the 
        provided exif_data (obtained through get_exif_data above)"""
        # print(exif_data)
        if 'GPSInfo' in self.exif_data:
            gps_info = self.exif_data["GPSInfo"]
            gps_latitude = self.get_if_exist(gps_info, "GPSLatitude")
            gps_latitude_ref = self.get_if_exist(gps_info, 'GPSLatitudeRef')
            if gps_latitude and gps_latitude_ref:
                lat = self.convert_to_degress(gps_latitude)
                if gps_latitude_ref != "N":
                    lat = 0 - lat
                lat = str(f"{lat:.{5}f}")
                return lat
        else:
            return None

    def get_lon(self):
        """Returns the latitude and longitude, if available, from the 
        provided exif_data (obtained through get_exif_data above)"""
        # print(exif_data)
        if 'GPSInfo' in self.exif_data:
            gps_info = self.exif_data["GPSInfo"]
            gps_longitude = self.get_if_exist(gps_info, 'GPSLongitude')
            gps_longitude_ref = self.get_if_exist(gps_info, 'GPSLongitudeRef')
            if gps_longitude and gps_longitude_ref:
                lon = self.convert_to_degress(gps_longitude)
                if gps_longitude_ref != "E":
                    lon = 0 - lon
                lon = str(f"{lon:.{5}f}")
                return lon
        else:
            return None

    def get_date_time(self):
        if 'DateTime' in self.exif_data:
            date_and_time = self.exif_data['DateTime']
            return date_and_time 

if __name__ == '__main__':
    try:
        img = PILimage.open(sys.argv[1])
        image = Worker(img)
        lat = image.lat
        lon = image.lon
        date = image.date
        print(date, lat, lon)

    except Exception as e:
        print(e)

How do I send an HTML Form in an Email .. not just MAILTO

I don't know that what you want to do is possible. From my understanding, sending an email from a web form requires a server side language to communicate with a mail server and send messages.

Are you running PHP or ASP.NET?

ASP.NET Example

PHP Example

How to use wget in php?

If using Curl in php...

function disguise_curl($url) 
{ 
  $curl = curl_init(); 

  // Setup headers - I used the same headers from Firefox version 2.0.0.6 
  // below was split up because php.net said the line was too long. :/ 
  $header[0] = "Accept: text/xml,application/xml,application/xhtml+xml,"; 
  $header[0] .= "text/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5"; 
  $header[] = "Cache-Control: max-age=0"; 
  $header[] = "Connection: keep-alive"; 
  $header[] = "Keep-Alive: 300"; 
  $header[] = "Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.7"; 
  $header[] = "Accept-Language: en-us,en;q=0.5"; 
  $header[] = "Pragma: "; // browsers keep this blank. 

  curl_setopt($curl, CURLOPT_URL, $url); 
  curl_setopt($curl, CURLOPT_USERAGENT, 'Googlebot/2.1 (+http://www.google.com/bot.html)'); 
  curl_setopt($curl, CURLOPT_HTTPHEADER, $header); 
  curl_setopt($curl, CURLOPT_REFERER, 'http://www.google.com'); 
  curl_setopt($curl, CURLOPT_ENCODING, 'gzip,deflate'); 
  curl_setopt($curl, CURLOPT_AUTOREFERER, true); 
  curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1); 
  curl_setopt($curl, CURLOPT_TIMEOUT, 10); 

  $html = curl_exec($curl); // execute the curl command 
  curl_close($curl); // close the connection 

  return $html; // and finally, return $html 
} 

// uses the function and displays the text off the website 
$text = disguise_curl($url); 
echo $text; 
?> 

Continuous Integration vs. Continuous Delivery vs. Continuous Deployment

Difference between Continuous Integration, Continuous delivery and continuous deployment

enter image description here

MySQL Server has gone away when importing large sql file

I got same issue with

$image_base64 = base64_encode(file_get_contents($_FILES['file']['tmp_name']) );
$image = 'data:image/jpeg;base64,'.$image_base64;
$query = "insert into images(image) values('".$image."')";
mysqli_query($con,$query);

In \xampp\mysql\bin\my.ini file of phpmyadmin we get only

[mysqldump]
max_allowed_packet=110M

which is just for mysqldump -u root -p dbname . I resolved my issue by replacing above code with

max_allowed_packet=110M
[mysqldump]
max_allowed_packet=110M

Example using Hyperlink in WPF

If you want your application to open the link in a web browser you need to add a HyperLink with the RequestNavigate event set to a function that programmatically opens a web-browser with the address as a parameter.

<TextBlock>           
    <Hyperlink NavigateUri="http://www.google.com" RequestNavigate="Hyperlink_RequestNavigate">
        Click here
    </Hyperlink>
</TextBlock>

In the code-behind you would need to add something similar to this to handle the RequestNavigate event:

private void Hyperlink_RequestNavigate(object sender, RequestNavigateEventArgs e)
{
    // for .NET Core you need to add UseShellExecute = true
    // see https://docs.microsoft.com/dotnet/api/system.diagnostics.processstartinfo.useshellexecute#property-value
    Process.Start(new ProcessStartInfo(e.Uri.AbsoluteUri));
    e.Handled = true;
}

In addition you will also need the following imports:

using System.Diagnostics;
using System.Windows.Navigation;

It will look like this in your application:

oO

Show Error on the tip of the Edit Text Android

I got the solution of my problem Hope this will help others also.I have used onTextChnaged it invokes When an object of a type is attached to an Editable, its methods will be called when the text is changed.

public class MainActivity extends Activity {
    TextView emailId;
    ImageView continuebooking;
    EditText firstName;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        emailId = (TextView)findViewById(R.id.emailid);
        continuebooking = (ImageView)findViewById(R.id.continuebooking);
        firstName= (EditText)findViewById(R.id.firstName);
        emailId.setText("[email protected]");
        setTittle();
        continuebooking.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View arg0) {

                if(firstName.getText().toString().trim().equalsIgnoreCase("")){
                    firstName.setError("Enter FirstName");
                }

            }
        });
        firstName.addTextChangedListener(new TextWatcher() {

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                firstName.setError(null);

            }

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count,
                    int after) {
                // TODO Auto-generated method stub

            }

            @Override
            public void afterTextChanged(Editable s) {
                firstName.setError(null);

            }
        });
    }

How do you concatenate Lists in C#?

Try this:

myList1 = myList1.Concat(myList2).ToList();

Concat returns an IEnumerable<T> that is the two lists put together, it doesn't modify either existing list. Also, since it returns an IEnumerable, if you want to assign it to a variable that is List<T>, you'll have to call ToList() on the IEnumerable<T> that is returned.

How can I add a vertical scrollbar to my div automatically?

You have to add max-height property.

_x000D_
_x000D_
.ScrollStyle_x000D_
{_x000D_
    max-height: 150px;_x000D_
    overflow-y: scroll;_x000D_
}
_x000D_
<div class="ScrollStyle">_x000D_
  Scrollbar Test!<br/>_x000D_
  Scrollbar Test!<br/>_x000D_
  Scrollbar Test!<br/>_x000D_
  Scrollbar Test!<br/>_x000D_
  Scrollbar Test!<br/>_x000D_
  Scrollbar Test!<br/>_x000D_
  Scrollbar Test!<br/>_x000D_
  Scrollbar Test!<br/>_x000D_
  Scrollbar Test!<br/>_x000D_
  Scrollbar Test!<br/>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to count the number of letters in a string without the spaces?

MattBryant's answer is a good one, but if you want to exclude more types of letters than just spaces, it will get clunky. Here's a variation on your current code using Counter that will work:

from collections import Counter
import string

def count_letters(word, valid_letters=string.ascii_letters):
    count = Counter(word) # this counts all the letters, including invalid ones
    return sum(count[letter] for letter in valid_letters) # add up valid letters

Example output:

>>> count_letters("The grey old fox is an idiot.") # the period will be ignored
22

Count length of array and return 1 if it only contains one element

declare you array as:

$car = array("bmw")

EDIT

now with powershell syntax:)

$car = [array]"bmw"

How to insert a line break <br> in markdown

I know this post is about adding a single line break but I thought I would mention that you can create multiple line breaks with the backslash (\) character:

Hello
\
\
\
World!

This would result in 3 new lines after "Hello". To clarify, that would mean 2 empty lines between "Hello" and "World!". It would display like this:


Hello



World!



Personally I find this cleaner for a large number of line breaks compared to using <br>.

Note that backslashes are not recommended for compatibility reasons. So this may not be supported by your Markdown parser but it's handy when it is.

*.h or *.hpp for your class definitions

I've recently started using *.hpp for c++ headers.

The reason is that I use emacs as my primary editor and it enters automatically into c-mode when you load a *.h file and into c++-mode when you load a *.hpp file.

Apart that fact I see no good reasons for choosing *.h over *.hpp or vice-versa.

TypeError: list indices must be integers or slices, not str

First, array_length should be an integer and not a string:

array_length = len(array_dates)

Second, your for loop should be constructed using range:

for i in range(array_length):  # Use `xrange` for python 2.

Third, i will increment automatically, so delete the following line:

i += 1

Note, one could also just zip the two lists given that they have the same length:

import csv

dates = ['2020-01-01', '2020-01-02', '2020-01-03']
urls = ['www.abc.com', 'www.cnn.com', 'www.nbc.com']

csv_file_patch = '/path/to/filename.csv'

with open(csv_file_patch, 'w') as fout:
    csv_file = csv.writer(fout, delimiter=';', lineterminator='\n')
    result_array = zip(dates, urls)
    csv_file.writerows(result_array)

Can't start Tomcat as Windows Service

  1. Check the apache tomcat catalina log: ../logs/catalina.log
  2. If in the log you find the "port was used" exception, then Check windows used ports and processes with following command: Run cmd netstat -ao it will list all listening ports and corresponding process Id, you can find the port which was used by Tomcat from the configuration file: ../conf/server.xml

    <Connector port="8080" protocol="HTTP/1.1"
           connectionTimeout="20000"
           redirectPort="8443" />
    

and kill the process which use the tomcat port

Difference between using Makefile and CMake to compile the code

Make (or rather a Makefile) is a buildsystem - it drives the compiler and other build tools to build your code.

CMake is a generator of buildsystems. It can produce Makefiles, it can produce Ninja build files, it can produce KDEvelop or Xcode projects, it can produce Visual Studio solutions. From the same starting point, the same CMakeLists.txt file. So if you have a platform-independent project, CMake is a way to make it buildsystem-independent as well.

If you have Windows developers used to Visual Studio and Unix developers who swear by GNU Make, CMake is (one of) the way(s) to go.

I would always recommend using CMake (or another buildsystem generator, but CMake is my personal preference) if you intend your project to be multi-platform or widely usable. CMake itself also provides some nice features like dependency detection, library interface management, or integration with CTest, CDash and CPack.

Using a buildsystem generator makes your project more future-proof. Even if you're GNU-Make-only now, what if you later decide to expand to other platforms (be it Windows or something embedded), or just want to use an IDE?

How do I convert a Python program to a runnable .exe Windows program?

For this you have two choices:

  • A downgrade to python 2.6. This is generally undesirable because it is backtracking and may nullify a small portion of your scripts
  • Your second option is to use some form of exe converter. I recommend pyinstaller as it seems to have the best results.

How to set image width to be 100% and height to be auto in react native?

"resizeMode" isn't style property. Should move to Image component's Props like below code.

const win = Dimensions.get('window');

const styles = StyleSheet.create({
    image: {
        flex: 1,
        alignSelf: 'stretch',
        width: win.width,
        height: win.height,
    }
});

...
    <Image 
       style={styles.image}
       resizeMode={'contain'}   /* <= changed  */
       source={require('../../../images/collection-imag2.png')} /> 
...

Image's height won't become automatically because Image component is required both width and height in style props. So you can calculate by using getSize() method for remote images like this answer and you can also calculate image ratio for static images like this answer.

There are a lot of useful open source libraries -

jQuery getJSON save result into variable

You can't get value when calling getJSON, only after response.

var myjson;
$.getJSON("http://127.0.0.1:8080/horizon-update", function(json){
    myjson = json;
});

How to remove gaps between subplots in matplotlib?

Have you tried plt.tight_layout()?

with plt.tight_layout() enter image description here without it: enter image description here

Or: something like this (use add_axes)

left=[0.1,0.3,0.5,0.7]
width=[0.2,0.2, 0.2, 0.2]
rectLS=[]
for x in left:
   for y in left:
       rectLS.append([x, y, 0.2, 0.2])
axLS=[]
fig=plt.figure()
axLS.append(fig.add_axes(rectLS[0]))
for i in [1,2,3]:
     axLS.append(fig.add_axes(rectLS[i],sharey=axLS[-1]))    
axLS.append(fig.add_axes(rectLS[4]))
for i in [1,2,3]:
     axLS.append(fig.add_axes(rectLS[i+4],sharex=axLS[i],sharey=axLS[-1]))
axLS.append(fig.add_axes(rectLS[8]))
for i in [5,6,7]:
     axLS.append(fig.add_axes(rectLS[i+4],sharex=axLS[i],sharey=axLS[-1]))     
axLS.append(fig.add_axes(rectLS[12]))
for i in [9,10,11]:
     axLS.append(fig.add_axes(rectLS[i+4],sharex=axLS[i],sharey=axLS[-1]))

If you don't need to share axes, then simply axLS=map(fig.add_axes, rectLS) enter image description here

Custom toast on Android: a simple example

You can download code here.

Step 1:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity">

    <Button
        android:id="@+id/btnCustomToast"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Show Custom Toast" />
  </RelativeLayout>

Step 2:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="horizontal"
    android:gravity="center"
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

        <ImageView
            android:id="@+id/custom_toast_image"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@mipmap/ic_launcher"/>

        <TextView
            android:id="@+id/custom_toast_message"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="My custom Toast Example Text" />

</LinearLayout>

Step 3:

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {


    private Button btnCustomToast;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        btnCustomToast= (Button) findViewById(R.id.btnCustomToast);
        btnCustomToast.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                // Find custom toast example layout file
                View layoutValue = LayoutInflater.from(MainActivity.this).inflate(R.layout.android_custom_toast_example, null);
                // Creating the Toast object
                Toast toast = new Toast(getApplicationContext());
                toast.setDuration(Toast.LENGTH_SHORT);

                // gravity, xOffset, yOffset
                toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
                toast.setView(layoutValue);//setting the view of custom toast layout
                toast.show();
            }
        });
    }
}

What's the difference between a POST and a PUT HTTP REQUEST?

Actually there's no difference other than their title. There's actually a basic difference between GET and the others. With a "GET"-Request method, you send the data in the url-address-line, which are separated first by a question-mark, and then with a & sign.

But with a "POST"-request method, you can't pass data through the url, but you have to pass the data as an object in the so called "body" of the request. On the server side, you have then to read out the body of the received content in order to get the sent data. But there's on the other side no possibility to send content in the body, when you send a "GET"-Request.

The claim, that "GET" is only for getting data and "POST" is for posting data, is absolutely wrong. Noone can prevent you from creating new content, deleting existing content, editing existing content or do whatever in the backend, based on the data, that is sent by the "GET" request or by the "POST" request. And nobody can prevent you to code the backend in a way, that with a "POST"-Request, the client asks for some data.

With a request, no matter which method you use, you call a URL and send or don't send some data to specify, which information you want to pass to the server to deal with your request, and then the client gets an answer from the server. The data can contain whatever you want to send, the backend is allowed to do whatever it wants with the data and the response can contain any information, that you want to put in there.

There are only these two BASIC METHODS. GET and POST. But it's their structure, which makes them different and not what you code in the backend. In the backend you can code whatever you want to, with the received data. But with the "POST"-request you have to send/retrieve the data in the body and not in the url-addressline, and with a "GET" request, you have to send/retrieve data in the url-addressline and not in the body. That's all.

All the other methods, like "PUT", "DELETE" and so on, they have the same structure as "POST".

The POST Method is mainly used, if you want to hide the content somewhat, because whatever you write in the url-addressline, this will be saved in the cache and a GET-Method is the same as writing a url-addressline with data. So if you want to send sensitive data, which is not always necessarily username and password, but for example some ids or hashes, which you don't want to be shown in the url-address-line, then you should use the POST method.

Also the URL-Addressline's length is limited to 1024 symbols, whereas the "POST"-Method is not restricted. So if you have a bigger amount of data, you might not be able to send it with a GET-Request, but you'll need to use the POST-Request. So this is also another plus point for the POST-request.

But dealing with the GET-request is way easier, when you don't have complicated text to send. Otherwise, and this is another plus point for the POST method, is, that with the GET-method you need to url-encode the text, in order to be able to send some symbols within the text or even spaces. But with a POST method you have no restrictions and your content doesn't need to be changed or manipulated in any way.

No Spring WebApplicationInitializer types detected on classpath

I spent hours on this, and the solution was:

  • Stop Tomcat
  • "Project" menu -> Clean -> Clean all projects
  • Servers tab -> Tomcat -> Right click -> Clean...
  • Right click on project -> Run as -> Run on server

How do emulators work and how are they written?

Also check out Darek Mihocka's Emulators.com for great advice on instruction-level optimization for JITs, and many other goodies on building efficient emulators.

Joining two lists together

One way, I haven't seen mentioned that can be a bit more robust, particularly if you wanted to alter each element in some way (e.g. you wanted to .Trim() all of the elements.

List<string> a = new List<string>();
List<string> b = new List<string>();
// ...
b.ForEach(x=>a.Add(x.Trim()));

How to combine two strings together in PHP?

I am not exactly clear with what your requirements are but basically you could seperately define the two variables and thereafter combine them together.

$data1="The colour is ";
$data2="red";

$result=$data1.$data2;

By doing so you can even declare $data2 as a global level so you could change its value during execution, for instance it could obtain the answer "red" from a checkbox.

Prevent wrapping of span or div

Looks like divs will not go outside of their body's width. Even within another div.

I threw this up to test (without a doctype though) and it does not work as thought.

_x000D_
_x000D_
.slideContainer {_x000D_
    overflow-x: scroll;_x000D_
}_x000D_
.slide {_x000D_
    float: left;_x000D_
}
_x000D_
<div class="slideContainer">_x000D_
    <div class="slide" style="background: #f00">Some content Some content Some content Some content Some content Some content</div>_x000D_
    <div class="slide" style="background: #ff0">More content More content More content More content More content More content</div>_x000D_
    <div class="slide" style="background: #f0f">Even More content! Even More content! Even More content!</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

What i am thinking is that the inner div's could be loaded through an iFrame, since that is another page and its content could be very wide.

Update with two tables?

I was scratching my head, not being able to get John Sansom's Join syntax work, at least in MySQL 5.5.30 InnoDB.

It turns out that this doesn't work.

UPDATE A 
    SET A.x = 1
FROM A INNER JOIN B 
        ON A.name = B.name
WHERE A.x <> B.x

But this works:

UPDATE A INNER JOIN B 
    ON A.name = B.name
SET A.x = 1
WHERE A.x <> B.x

Understanding Apache's access log

And what does "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/535.19 (KHTML, like Gecko) Chrome/18.0.1025.5 Safari/535.19" means ?

This is the value of User-Agent, the browser identification string.

For this reason, most Web browsers use a User-Agent string value as follows:

Mozilla/[version] ([system and browser information]) [platform] ([platform details]) [extensions]. For example, Safari on the iPad has used the following:

Mozilla/5.0 (iPad; U; CPU OS 3_2_1 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Mobile/7B405 The components of this string are as follows:

Mozilla/5.0: Previously used to indicate compatibility with the Mozilla rendering engine. (iPad; U; CPU OS 3_2_1 like Mac OS X; en-us): Details of the system in which the browser is running. AppleWebKit/531.21.10: The platform the browser uses. (KHTML, like Gecko): Browser platform details. Mobile/7B405: This is used by the browser to indicate specific enhancements that are available directly in the browser or through third parties. An example of this is Microsoft Live Meeting which registers an extension so that the Live Meeting service knows if the software is already installed, which means it can provide a streamlined experience to joining meetings.

This value will be used to identify what browser is being used by end user.

Refer

How to center a "position: absolute" element

Here is easy and best solution for center element with “position: absolute”

_x000D_
_x000D_
 body,html{_x000D_
  min-height:100%;_x000D_
 }_x000D_
 _x000D_
 div.center{_x000D_
 width:200px;_x000D_
 left:50%;_x000D_
 margin-left:-100px;/*this is 50% value for width of the element*/_x000D_
 position:absolute;_x000D_
 background:#ddd;_x000D_
 border:1px solid #999;_x000D_
 height:100px;_x000D_
 text-align:center_x000D_
 }_x000D_
 _x000D_
 
_x000D_
<style>_x000D_
_x000D_
</style>_x000D_
_x000D_
<body>_x000D_
 <div class='center'>_x000D_
  should be centered verticaly_x000D_
 </div>_x000D_
</body>
_x000D_
_x000D_
_x000D_

Why doesn't height: 100% work to expand divs to the screen height?

if you want, for example, a left column (height 100%) and the content (height auto) you can use absolute :

#left_column {
    float:left;
    position: absolute;
    max-height:100%;
    height:auto !important;
    height: 100%;
    overflow: hidden;

    width : 180px; /* for example */
}

#left_column div {
    height: 2000px;
}

#right_column {
    float:left;
    height:100%;
    margin-left : 180px; /* left column's width */
}

in html :

  <div id="content">
      <div id="left_column">
        my navigation content
        <div></div>
      </div>

      <div id="right_column">
        my content
      </div>
   </div>

How to add noise (Gaussian/salt and pepper etc) to image in Python with OpenCV

The Function adds gaussian , salt-pepper , poisson and speckle noise in an image

Parameters
----------
image : ndarray
    Input image data. Will be converted to float.
mode : str
    One of the following strings, selecting the type of noise to add:

    'gauss'     Gaussian-distributed additive noise.
    'poisson'   Poisson-distributed noise generated from the data.
    's&p'       Replaces random pixels with 0 or 1.
    'speckle'   Multiplicative noise using out = image + n*image,where
                n is uniform noise with specified mean & variance.


import numpy as np
import os
import cv2
def noisy(noise_typ,image):
   if noise_typ == "gauss":
      row,col,ch= image.shape
      mean = 0
      var = 0.1
      sigma = var**0.5
      gauss = np.random.normal(mean,sigma,(row,col,ch))
      gauss = gauss.reshape(row,col,ch)
      noisy = image + gauss
      return noisy
   elif noise_typ == "s&p":
      row,col,ch = image.shape
      s_vs_p = 0.5
      amount = 0.004
      out = np.copy(image)
      # Salt mode
      num_salt = np.ceil(amount * image.size * s_vs_p)
      coords = [np.random.randint(0, i - 1, int(num_salt))
              for i in image.shape]
      out[coords] = 1

      # Pepper mode
      num_pepper = np.ceil(amount* image.size * (1. - s_vs_p))
      coords = [np.random.randint(0, i - 1, int(num_pepper))
              for i in image.shape]
      out[coords] = 0
      return out
  elif noise_typ == "poisson":
      vals = len(np.unique(image))
      vals = 2 ** np.ceil(np.log2(vals))
      noisy = np.random.poisson(image * vals) / float(vals)
      return noisy
  elif noise_typ =="speckle":
      row,col,ch = image.shape
      gauss = np.random.randn(row,col,ch)
      gauss = gauss.reshape(row,col,ch)        
      noisy = image + image * gauss
      return noisy

Intent.putExtra List

 //To send from the activity that is calling another activity via myIntent

    myIntent.putExtra("id","10");
    startActivity(myIntent);

    //To receive from another Activity

            Bundle bundle = getIntent().getExtras();
            String id=bundle.getString("id");

Uncaught TypeError: data.push is not a function

To use the push function of an Array your var needs to be an Array.

Change data{"name":"ananta","age":"15"} to following:

var data = [
    { 
        "name": "ananta",
        "age": "15",
        "country": "Atlanta"
    }
];

data.push({"name": "Tony Montana", "age": "99"});

data.push({"country": "IN"});

..

The containing Array Items will be typeof Object and you can do following:

var text = "You are " + data[0]->age + " old and come from " + data[0]->country;

Notice: Try to be consistent. In my example, one array contained object properties name and age while the other only contains country. If I iterate this with for or forEach then I can't always check for one property, because my example contains Items that changing.

Perfect would be: data.push({ "name": "Max", "age": "5", "country": "Anywhere" } );

So you can iterate and always can get the properties, even if they are empty, null or undefined.

edit

Cool stuff to know:

var array = new Array();

is similar to:

var array = [];

Also:

var object = new Object();

is similar to:

var object = {};

You also can combine them:

var objectArray = [{}, {}, {}];

Chrome Dev Tools - Modify javascript and reload

Great news, the fix is coming in March 2018, see this link: https://developers.google.com/web/updates/2018/01/devtools

"Local Overrides let you make changes in DevTools, and keep those changes across page loads. Previously, any changes that you made in DevTools would be lost when you reloaded the page. Local Overrides work for most file types

How it works:

  • You specify a directory where DevTools should save changes. When you make changes in DevTools, DevTools saves a copy of the modified file to your directory.
  • When you reload the page, DevTools serves the local, modified file, rather than the network resource.

To set up Local Overrides:

  1. Open the Sources panel.
  2. Open the Overrides tab.
  3. Click Setup Overrides.
  4. Select which directory you want to save your changes to.
  5. At the top of your viewport, click Allow to give DevTools read and write access to the directory.
  6. Make your changes."

UPDATE (March 19, 2018): It's live, detailed explanations here: https://developers.google.com/web/updates/2018/01/devtools#overrides

How to find out what group a given user has?

This one shows the user's uid as well as all the groups (with their gids) they belong to

id userid

Catching exceptions from Guzzle

Depending on your project, disabling exceptions for guzzle might be necessary. Sometimes coding rules disallow exceptions for flow control. You can disable exceptions for Guzzle 3 like this:

$client = new \Guzzle\Http\Client($httpBase, array(
  'request.options' => array(
     'exceptions' => false,
   )
));

This does not disable curl exceptions for something like timeouts, but now you can get every status code easily:

$request = $client->get($uri);
$response = $request->send();
$statuscode = $response->getStatusCode();

To check, if you got a valid code, you can use something like this:

if ($statuscode > 300) {
  // Do some error handling
}

... or better handle all expected codes:

if (200 === $statuscode) {
  // Do something
}
elseif (304 === $statuscode) {
  // Nothing to do
}
elseif (404 === $statuscode) {
  // Clean up DB or something like this
}
else {
  throw new MyException("Invalid response from api...");
}

For Guzzle 5.3

$client = new \GuzzleHttp\Client(['defaults' => [ 'exceptions' => false ]] );

Thanks to @mika

For Guzzle 6

$client = new \GuzzleHttp\Client(['http_errors' => false]);

How to make a div center align in HTML

how about something along these lines

<style type="text/css">
  #container {
    margin: 0 auto;
    text-align: center; /* for IE */
  }

  #yourdiv {
    width: 400px;
    border: 1px solid #000;
  }
</style>

....

<div id="container">
  <div id="yourdiv">
    weee
  </div>
</div>

SQL Query with Join, Count and Where

I have used sub-query and it worked great!

SELECT *,(SELECT count(*) FROM $this->tbl_news WHERE
$this->tbl_news.cat_id=$this->tbl_categories.cat_id) as total_news FROM
$this->tbl_categories

Constructor of an abstract class in C#

Normally constructors involve initializing the members of an object being created. In concept of inheritance, typically each class constructor in the inheritance hierarchy, is responsible for instantiating its own member variables. This makes sense because instantiation has to be done where the variables are defined.

Since an abstract class is not completely abstract (unlike interfaces), it is mix of both abstract and concrete members, and the members which are not abstract are needed to be initialized, which is done in abstract class's constructors, it is necessary to have constructors in the abstract class. Off course the abstract class's constructors can only be called from the constructors of derived class.

What is the difference between atan and atan2 in C++?

Another thing to mention is that atan2 is more stable when computing tangents using an expression like atan(y / x) and x is 0 or close to 0.

IF function with 3 conditions

Using INDEX and MATCH for binning. Easier to maintain if we have more bins.

=INDEX({"Text 1","Text 2","Text 3"},MATCH(A2,{0,5,21,100}))

enter image description here

How to disable Google Chrome auto update?

The simplest method on Windows 10 with recent versions of Chrome as of early 2020. No registry hack, Powershell or GPO required :

  1. Open the Computer Management app with elevated rights: type it in the taskbar search, then click Run as administrator on the menu
  2. Go to Service and Applications -> Services
  3. Find Google Update Service (gupdate) and Google Update Service (gupdatem)
  4. For both services, right-click, select Properties and set Startup type: to Disabled.

Tested and working on Google Chrome v 80, Win 10 / 1909 / 18363.592, as of March 2020.

Apply formula to the entire column

I think it's a more recent feature, but it works for me:

Double clicking the square on the bottom right of the highlighted cell copies the formula of the highlighted cell.

Hope it helps.

Starting with Zend Tutorial - Zend_DB_Adapter throws Exception: "SQLSTATE[HY000] [2002] No such file or directory"

This error because mysql is trying to connect via wrong socket file

try this command for MAMP servers

cd /var/mysql && sudo ln -s /Applications/MAMP/tmp/mysql/mysql.sock

or

cd /tmp && sudo ln -s /Applications/MAMP/tmp/mysql/mysql.sock

and this commands for XAMPP servers

    cd /var/mysql && sudo ln -s /Applications/XAMPP/tmp/mysql/mysql.sock

or

    cd /tmp && sudo ln -s /Applications/XAMPP/tmp/mysql/mysql.sock

Two div blocks on same line

What I would first is make the following CSS code:

#bloc1 {
   float: left
}

This will make #bloc2 be inline with #bloc1.

To make it central, I would add #bloc1 and #bloc2 in a separate div. For example:

<style type="text/css">
    #wrapper { margin: 0 auto; }
</style>
<div id="wrapper">
    <div id="bloc1"> ... </div>
    <div id="bloc2"> ... </div>
</div>

Scraping data from website using vba

This question asked long before. But I thought following information will useful for newbies. Actually you can easily get the values from class name like this.

Sub ExtractLastValue()

Set objIE = CreateObject("InternetExplorer.Application")

objIE.Top = 0
objIE.Left = 0
objIE.Width = 800
objIE.Height = 600

objIE.Visible = True

objIE.Navigate ("https://uk.investing.com/rates-bonds/financial-futures/")

Do
DoEvents
Loop Until objIE.readystate = 4

MsgBox objIE.document.getElementsByClassName("pid-8907-last")(0).innerText

End Sub

And if you are new to web scraping please read this blog post.

Web Scraping - Basics

And also there are various techniques to extract data from web pages. This article explain few of them with examples.

Web Scraping - Collecting Data From a Webpage

Mail multipart/alternative vs multipart/mixed

Great Answer Lain!

There were a couple things I did to make this work in a broader set of devices. At the end I will list the clients I tested on.

  1. I added a new build constructor that did not contain the parameter attachments and did not use MimeMultipart("mixed"). There is no need for mixed if you are sending only inline images.

    public Multipart build(String messageText, String messageHtml, List<URL> messageHtmlInline) throws MessagingException {
    
        final Multipart mpAlternative = new MimeMultipart("alternative");
        {
            //  Note: MUST RENDER HTML LAST otherwise iPad mail client only renders 
            //  the last image and no email
                addTextVersion(mpAlternative,messageText);
                addHtmlVersion(mpAlternative,messageHtml, messageHtmlInline);
        }
    
        return mpAlternative;
    }
    
  2. In addTextVersion method I added charset when adding content this probably could/should be passed in, but I just added it statically.

    textPart.setContent(messageText, "text/plain");
    to
    textPart.setContent(messageText, "text/plain; charset=UTF-8");
    
  3. The last item was adding to the addImagesInline method. I added setting the image filename to the header by the following code. If you don't do this then at least on Android default mail client it will have inline images that have a name of Unknown and will not automatically download them and present in email.

    for (URL img : embeded) {
        final MimeBodyPart htmlPartImg = new MimeBodyPart();
        DataSource htmlPartImgDs = new URLDataSource(img);
        htmlPartImg.setDataHandler(new DataHandler(htmlPartImgDs));
        String fileName = img.getFile();
        fileName = getFileName(fileName);
        String newFileName = cids.get(fileName);
        boolean imageNotReferencedInHtml = newFileName == null;
        if (imageNotReferencedInHtml) continue;
        htmlPartImg.setHeader("Content-ID", "<"+newFileName+">");
        htmlPartImg.setDisposition(BodyPart.INLINE);
        **htmlPartImg.setFileName(newFileName);**
        parent.addBodyPart(htmlPartImg);
    }
    

So finally, this is the list of clients I tested on. Outlook 2010, Outlook Web App, Internet Explorer 11, Firefox, Chrome, Outlook using Apple’s native app, Email going through Gmail - Browser mail client, Internet Explorer 11, Firefox, Chrome, Android default mail client, osx IPhone default mail client, Gmail mail client on Android, Gmail mail client on IPhone, Email going through Yahoo - Browser mail client, Internet Explorer 11, Firefox, Chrome, Android default mail client, osx IPhone default mail client.

Hope that helps anyone else.

How would I stop a while loop after n amount of time?

Try the following:

import time
timeout = time.time() + 60*5   # 5 minutes from now
while True:
    test = 0
    if test == 5 or time.time() > timeout:
        break
    test = test - 1

You may also want to add a short sleep here so this loop is not hogging CPU (for example time.sleep(1) at the beginning or end of the loop body).

How to fix "set SameSite cookie to none" warning?

For those can not create PHP session and working with live domain at local. You should delete live sites secure cookie first.

Full answer ; https://stackoverflow.com/a/64073275/1067434

Ant: How to execute a command for each file in directory?

Here is way to do this using javascript and the ant scriptdef task, you don't need ant-contrib for this code to work since scriptdef is a core ant task.

<scriptdef name="bzip2-files" language="javascript">
<element name="fileset" type="fileset"/>
<![CDATA[
  importClass(java.io.File);
  filesets = elements.get("fileset");

  for (i = 0; i < filesets.size(); ++i) {
    fileset = filesets.get(i);
    scanner = fileset.getDirectoryScanner(project);
    scanner.scan();
    files = scanner.getIncludedFiles();
    for( j=0; j < files.length; j++) {

        var basedir  = fileset.getDir(project);
        var filename = files[j];
        var src = new File(basedir, filename);
        var dest= new File(basedir, filename + ".bz2");

        bzip2 = self.project.createTask("bzip2");        
        bzip2.setSrc( src);
        bzip2.setDestfile(dest ); 
        bzip2.execute();
    }
  }
]]>
</scriptdef>

<bzip2-files>
    <fileset id="test" dir="upstream/classpath/jars/development">
            <include name="**/*.jar" />
    </fileset>
</bzip2-files>

How to build and run Maven projects after importing into Eclipse IDE

1.Update project

Right Click on your project maven > update project

2.Build project

Right Click on your project again. run as > Maven build

If you have not created a “Run configuration” yet, it will open a new configuration with some auto filled values.

You can change the name. "Base directory" will be a auto filled value for you. Keep it as it is. Give maven command to ”Goals” fields.

i.e, “clean install” for building purpose

Click apply

Click run.

3.Run project on tomcat

Right Click on your project again. run as > Run-Configuration. It will open Run-Configuration window for you.

Right Click on “Maven Build” from the right side column and Select “New”. It will open a blank configuration for you.

Change the name as you want. For the base directory field you can choose values using 3 buttons(workspace,FileSystem,Variables). You can also copy and paste the auto generated value from previously created Run-configuration. Give the Goals as “tomcat:run”. Click apply. Click run.

If you want to get more clear idea with snapshots use the following link.

Build and Run Maven project in Eclipse

(I hope this answer will help someone come after the topic of the question)

Install Android App Bundle on device

Installing the aab directly from the device, I couldn't find a way for that.

But there is a way to install it through your command line using the following documentation You can install apk to a device through BundleTool

According to "@Albert Vila Calvo" comment he noted that to install bundletools using HomeBrew use brew install bundletool

You can now install extract apks from aab file and install it to a device

Extracting apk files from through the next command

java -jar bundletool-all-0.3.3.jar build-apks --bundle=bundle.aab --output=app.apks --ks=my-release-key.keystore --ks-key-alias=alias --ks-pass=pass:password

Arguments:

  • --bundle -> Android Bundle .aab file
  • --output -> Destination and file name for the generated apk file
  • --ks -> Keystore file used to generate the Android Bundle
  • --ks-key-alias -> Alias for keystore file
  • --ks-pass -> Password for Alias file (Please note the 'pass' prefix before password value)

Then you will have a file with extension .apks So now you need to install it to a device

java -jar bundletool-all-0.6.0.jar install-apks --adb=/android-sdk/platform-tools/adb --apks=app.apks

Arguments:

  • --adb -> Path to adb file
  • --apks -> Apks file need to be installed

How can I write maven build to add resources to classpath?

If you place anything in src/main/resources directory, then by default it will end up in your final *.jar. If you are referencing it from some other project and it cannot be found on a classpath, then you did one of those two mistakes:

  1. *.jar is not correctly loaded (maybe typo in the path?)
  2. you are not addressing the resource correctly, for instance: /src/main/resources/conf/settings.properties is seen on classpath as classpath:conf/settings.properties

How to change the author and committer name and e-mail of multiple commits in Git?

This answer uses git-filter-branch, for which the docs now give this warning:

git filter-branch has a plethora of pitfalls that can produce non-obvious manglings of the intended history rewrite (and can leave you with little time to investigate such problems since it has such abysmal performance). These safety and performance issues cannot be backward compatibly fixed and as such, its use is not recommended. Please use an alternative history filtering tool such as git filter-repo. If you still need to use git filter-branch, please carefully read SAFETY (and PERFORMANCE) to learn about the land mines of filter-branch, and then vigilantly avoid as many of the hazards listed there as reasonably possible.

Changing the author (or committer) would require re-writing all of the history. If you're okay with that and think it's worth it then you should check out git filter-branch. The man page includes several examples to get you started. Also note that you can use environment variables to change the name of the author, committer, dates, etc. -- see the "Environment Variables" section of the git man page.

Specifically, you can fix all the wrong author names and emails for all branches and tags with this command (source: GitHub help):

#!/bin/sh

git filter-branch --env-filter '
OLD_EMAIL="[email protected]"
CORRECT_NAME="Your Correct Name"
CORRECT_EMAIL="[email protected]"
if [ "$GIT_COMMITTER_EMAIL" = "$OLD_EMAIL" ]
then
    export GIT_COMMITTER_NAME="$CORRECT_NAME"
    export GIT_COMMITTER_EMAIL="$CORRECT_EMAIL"
fi
if [ "$GIT_AUTHOR_EMAIL" = "$OLD_EMAIL" ]
then
    export GIT_AUTHOR_NAME="$CORRECT_NAME"
    export GIT_AUTHOR_EMAIL="$CORRECT_EMAIL"
fi
' --tag-name-filter cat -- --branches --tags

What is the difference between the operating system and the kernel?

The kernel is part of the operating system and closer to the hardware it provides low level services like:

  • device driver
  • process management
  • memory management
  • system calls

An operating system also includes applications like the user interface (shell, gui, tools, and services).

What is the difference between Sprint and Iteration in Scrum and length of each Sprint?

"___ is largely an organizational issue caused by long hours, little down time, and continual peer, customer, and superior surveillance"

No this is not the definition of scrum, it is the wikipedia excerpt on the definition of burnout.

Dont do too many short 10 days sprints. You will burnout your team eventually. Use short sprints where you really need them, and don't do too many in a row. Think long-term. A distance runner always paces themselves for the full race and does sprints in short distances only where it matters.

If you burnout your team you can toss out all them fancy scrum charts, they won't do a thing for your team's plummeting productivity.

How to vertically center a container in Bootstrap?

The Flexible box way

Vertical alignment is now very simple by the use of Flexible box layout. Nowadays, this method is supported in a wide range of web browsers except Internet Explorer 8 & 9. Therefore we'd need to use some hacks/polyfills or different approaches for IE8/9.

In the following I'll show you how to do that in only 3 lines of text (regardless of old flexbox syntax).

Note: it's better to use an additional class instead of altering .jumbotron to achieve the vertical alignment. I'd use vertical-center class name for instance.

Example Here (A Mirror on jsbin).

<div class="jumbotron vertical-center"> <!-- 
                      ^--- Added class  -->
  <div class="container">
    ...
  </div>
</div>
.vertical-center {
  min-height: 100%;  /* Fallback for browsers do NOT support vh unit */
  min-height: 100vh; /* These two lines are counted as one :-)       */

  display: flex;
  align-items: center;
}

Important notes (Considered in the demo):

  1. A percentage values of height or min-height properties is relative to the height of the parent element, therefore you should specify the height of the parent explicitly.

  2. Vendor prefixed / old flexbox syntax omitted in the posted snippet due to brevity, but exist in the online example.

  3. In some of old web browsers such as Firefox 9 (in which I've tested), the flex container - .vertical-center in this case - won't take the available space inside the parent, therefore we need to specify the width property like: width: 100%.

  4. Also in some of web browsers as mentioned above, the flex item - .container in this case - may not appear at the center horizontally. It seems the applied left/right margin of auto doesn't have any effect on the flex item.
    Therefore we need to align it by box-pack / justify-content.

For further details and/or vertical alignment of columns, you could refer to the topic below:


The traditional way for legacy web browsers

This is the old answer I wrote at the time I answered this question. This method has been discussed here and it's supposed to work in Internet Explorer 8 and 9 as well. I'll explain it in short:

In inline flow, an inline level element can be aligned vertically to the middle by vertical-align: middle declaration. Spec from W3C:

middle
Align the vertical midpoint of the box with the baseline of the parent box plus half the x-height of the parent.

In cases that the parent - .vertical-center element in this case - has an explicit height, by any chance if we could have a child element having the exact same height of the parent, we would be able to move the baseline of the parent to the midpoint of the full-height child and surprisingly make our desired in-flow child - the .container - aligned to the center vertically.

Getting all together

That being said, we could create a full-height element within the .vertical-center by ::before or ::after pseudo elements and also change the default display type of it and the other child, the .container to inline-block.

Then use vertical-align: middle; to align the inline elements vertically.

Here you go:

<div class="jumbotron vertical-center">
  <div class="container">
    ...
  </div>
</div>
.vertical-center {
  height:100%;
  width:100%;

  text-align: center;  /* align the inline(-block) elements horizontally */
  font: 0/0 a;         /* remove the gap between inline(-block) elements */
}

.vertical-center:before {    /* create a full-height inline block pseudo=element */
  content: " ";
  display: inline-block;
  vertical-align: middle;    /* vertical alignment of the inline element */
  height: 100%;
}

.vertical-center > .container {
  max-width: 100%;

  display: inline-block;
  vertical-align: middle;  /* vertical alignment of the inline element */
                           /* reset the font property */
  font: 16px/1 "Helvetica Neue", Helvetica, Arial, sans-serif;
}

WORKING DEMO.

Also, to prevent unexpected issues in extra small screens, you can reset the height of the pseudo-element to auto or 0 or change its display type to none if needed so:

@media (max-width: 768px) {
  .vertical-center:before {
    height: auto;
    /* Or */
    display: none;
  }
}

UPDATED DEMO

And one more thing:

If there are footer/header sections around the container, it's better to position that elements properly (relative, absolute? up to you.) and add a higher z-index value (for assurance) to keep them always on the top of the others.

ConfigurationManager.AppSettings - How to modify and save?

On how to change values in appSettings section in your app.config file:

config.AppSettings.Settings.Remove(key);
config.AppSettings.Settings.Add(key, value);

does the job.

Of course better practice is Settings class but it depends on what are you after.

How do I center list items inside a UL element?

ul {
    width: 100%;
    background: red;
    height: 20px;
    display: flex;
    justify-content: center;
    align-items: center;
}

li {
    background: blue;
    color: white;
    margin-right: 10px;
}

How to use conditional statement within child attribute of a Flutter Widget (Center Widget)

You can simply use a conditional statement a==b?c:d

For example :

Container(
  color: Colors.white,
  child: ('condition')
  ? Widget1(...)
  : Widget2(...)
)

I hope you got the idea.

Suppose if there is no else condition you can use a SizedBox.shrink()

Container(
      color: Colors.white,
      child: ('condition')
       ? Widget1(...)
       : SizedBox.shrink()
    )

If it is a column no need to write ?: operator

Column(
 children: <Widget>[
  if('condition')
    Widget1(...),
 ],
)

Java string split with "." (dot)

You need to escape the dot if you want to split on a literal dot:

String extensionRemoved = filename.split("\\.")[0];

Otherwise you are splitting on the regex ., which means "any character".
Note the double backslash needed to create a single backslash in the regex.


You're getting an ArrayIndexOutOfBoundsException because your input string is just a dot, ie ".", which is an edge case that produces an empty array when split on dot; split(regex) removes all trailing blanks from the result, but since splitting a dot on a dot leaves only two blanks, after trailing blanks are removed you're left with an empty array.

To avoid getting an ArrayIndexOutOfBoundsException for this edge case, use the overloaded version of split(regex, limit), which has a second parameter that is the size limit for the resulting array. When limit is negative, the behaviour of removing trailing blanks from the resulting array is disabled:

".".split("\\.", -1) // returns an array of two blanks, ie ["", ""]

ie, when filename is just a dot ".", calling filename.split("\\.", -1)[0] will return a blank, but calling filename.split("\\.")[0] will throw an ArrayIndexOutOfBoundsException.

What are the correct version numbers for C#?

C# language version history:

These are the versions of C# known about at the time of this writing:

In response to the OP's question:

What are the correct version numbers for C#? What came out when? Why can't I find any answers about C# 3.5?

There is no such thing as C# 3.5 - the cause of confusion here is that the C# 3.0 is present in .NET 3.5. The language and framework are versioned independently, however - as is the CLR, which is at version 2.0 for .NET 2.0 through 3.5, .NET 4 introducing CLR 4.0, service packs notwithstanding. The CLR in .NET 4.5 has various improvements, but the versioning is unclear: in some places it may be referred to as CLR 4.5 (this MSDN page used to refer to it that way, for example), but the Environment.Version property still reports 4.0.xxx.

As of May 3, 2017, the C# Language Team created a history of C# versions and features on their GitHub repository: Features Added in C# Language Versions. There is also a page that tracks upcoming and recently implemented language features.

Chrome violation : [Violation] Handler took 83ms of runtime

"Chrome violations" don't represent errors in either Chrome or your own web app. They are instead warnings to help you improve your app. In this case, Long running JavaScript and took 83ms of runtime are alerting you there's probably an opportunity to speed up your script.

("Violation" is not the best terminology; it's used here to imply the script "violates" a pre-defined guideline, but "warning" or similar would be clearer. These messages first appeared in Chrome in early 2017 and should ideally have a "More info" prompt to elaborate on the meaning and give suggested actions to the developer. Hopefully those will be added in the future.)

how to convert `content://media/external/images/media/Y` to `file:///storage/sdcard0/Pictures/X.jpg` in android?

If you just want the bitmap, This too works

InputStream inputStream = mContext.getContentResolver().openInputStream(uri);
Bitmap bmp = BitmapFactory.decodeStream(inputStream);
if( inputStream != null ) inputStream.close();

sample uri : content://media/external/images/media/12345

CSS hover vs. JavaScript mouseover

EDIT: This answer no longer holds true. CSS is well supportedand Javascript (read: JScript) is now pretty much required for any web experience, and few folks disable javascript.

The original answer, as my opinion in 2009.

Off the top of my head:

With CSS, you may have issues with browser support.

With JScript, people can disable jscript (thats what I do).

I believe the preferred method is to do content in HTML, Layout with CSS, and anything dynamic in JScript. So in this instance, you would probably want to take the CSS approach.

Different ways of clearing lists

There is a very simple way to clear a python list. Use del list_name[:].

For example:

>>> a = [1, 2, 3]
>>> b = a
>>> del a[:]
>>> print a, b
[] []

Quicker way to get all unique values of a column in VBA?

Use Excel's AdvancedFilter function to do this.

Using Excels inbuilt C++ is the fastest way with smaller datasets, using the dictionary is faster for larger datasets. For example:

Copy values in Column A and insert the unique values in column B:

Range("A1:A6").AdvancedFilter Action:=xlFilterCopy, CopyToRange:=Range("B1"), Unique:=True

It works with multiple columns too:

Range("A1:B4").AdvancedFilter Action:=xlFilterCopy, CopyToRange:=Range("D1:E1"), Unique:=True

Be careful with multiple columns as it doesn't always work as expected. In those cases I resort to removing duplicates which works by choosing a selection of columns to base uniqueness. Ref: MSDN - Find and remove duplicates

enter image description here

Here I remove duplicate columns based on the third column:

Range("A1:C4").RemoveDuplicates Columns:=3, Header:=xlNo

Here I remove duplicate columns based on the second and third column:

Range("A1:C4").RemoveDuplicates Columns:=Array(2, 3), Header:=xlNo

In Java, remove empty elements from a list of Strings

  1. If you were asking how to remove the empty strings, you can do it like this (where l is an ArrayList<String>) - this removes all null references and strings of length 0:

    Iterator<String> i = l.iterator();
    while (i.hasNext())
    {
        String s = i.next();
        if (s == null || s.isEmpty())
        {
            i.remove();
        }
    }
    
  2. Don't confuse an ArrayList with arrays, an ArrayList is a dynamic data-structure that resizes according to it's contents. If you use the code above, you don't have to do anything to get the result as you've described it -if your ArrayList was ["","Hi","","How","are","you"], after removing as above, it's going to be exactly what you need - ["Hi","How","are","you"].

    However, if you must have a 'sanitized' copy of the original list (while leaving the original as it is) and by 'store it back' you meant 'make a copy', then krmby's code in the other answer will serve you just fine.

How do I set the rounded corner radius of a color drawable using xml?

Use the <shape> tag to create a drawable in XML with rounded corners. (You can do other stuff with the shape tag like define a color gradient as well).

Here's a copy of a XML file I'm using in one of my apps to create a drawable with a white background, black border and rounded corners:

<?xml version="1.0" encoding="UTF-8"?> 
<shape xmlns:android="http://schemas.android.com/apk/res/android"> 
    <solid android:color="#ffffffff"/>    
             
    <stroke android:width="3dp"
            android:color="#ff000000" />

    <padding android:left="1dp"
             android:top="1dp"
             android:right="1dp"
             android:bottom="1dp" /> 
             
    <corners android:radius="7dp" /> 
</shape>

The server encountered an internal error or misconfiguration and was unable to complete your request

Check your servers error log, typically /var/log/apache2/error.log.

Add a prefix string to beginning of each line

If you have Perl:

perl -pe 's/^/PREFIX/' input.file

How to insert pandas dataframe via mysqldb into database?

df.to_sql(name = "owner", con= db_connection, schema = 'aws', if_exists='replace', index = >True, index_label='id')

Nested Recycler view height doesn't wrap its content

The code up above doesn't work well when you need to make your items "wrap_content", because it measures both items height and width with MeasureSpec.UNSPECIFIED. After some troubles I've modified that solution so now items can expand. The only difference is that it provides parents height or width MeasureSpec depends on layout orientation.

public class MyLinearLayoutManager extends LinearLayoutManager {

public MyLinearLayoutManager(Context context, int orientation, boolean reverseLayout)    {
    super(context, orientation, reverseLayout);
}

private int[] mMeasuredDimension = new int[2];

@Override
public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state,
                      int widthSpec, int heightSpec) {
    final int widthMode = View.MeasureSpec.getMode(widthSpec);
    final int heightMode = View.MeasureSpec.getMode(heightSpec);
    final int widthSize = View.MeasureSpec.getSize(widthSpec);
    final int heightSize = View.MeasureSpec.getSize(heightSpec);
    int width = 0;
    int height = 0;
    for (int i = 0; i < getItemCount(); i++) {


        if (getOrientation() == HORIZONTAL) {

            measureScrapChild(recycler, i,
                    View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
                    heightSpec,
                    mMeasuredDimension);

            width = width + mMeasuredDimension[0];
            if (i == 0) {
                height = mMeasuredDimension[1];
            }
        } else {
            measureScrapChild(recycler, i,
                    widthSpec,
                    View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
                    mMeasuredDimension);
            height = height + mMeasuredDimension[1];
            if (i == 0) {
                width = mMeasuredDimension[0];
            }
        }
    }
    switch (widthMode) {
        case View.MeasureSpec.EXACTLY:
            width = widthSize;
        case View.MeasureSpec.AT_MOST:
        case View.MeasureSpec.UNSPECIFIED:
    }

    switch (heightMode) {
        case View.MeasureSpec.EXACTLY:
            height = heightSize;
        case View.MeasureSpec.AT_MOST:
        case View.MeasureSpec.UNSPECIFIED:
    }

    setMeasuredDimension(width, height);
}

private void measureScrapChild(RecyclerView.Recycler recycler, int position, int widthSpec,
                               int heightSpec, int[] measuredDimension) {
    View view = recycler.getViewForPosition(position);
    recycler.bindViewToPosition(view, position);
    if (view != null) {
        RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) view.getLayoutParams();
        int childWidthSpec = ViewGroup.getChildMeasureSpec(widthSpec,
                getPaddingLeft() + getPaddingRight(), p.width);
        int childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec,
                getPaddingTop() + getPaddingBottom(), p.height);
        view.measure(childWidthSpec, childHeightSpec);
        measuredDimension[0] = view.getMeasuredWidth() + p.leftMargin + p.rightMargin;
        measuredDimension[1] = view.getMeasuredHeight() + p.bottomMargin + p.topMargin;
        recycler.recycleView(view);
    }
}
}

ASP.NET MVC5/IIS Express unable to debug - Code Not Running

I started to get this problem with Asp.Net Core Web Applications in Visual Studio 2017. It didn't matter if it was the .Net Core Standard version with .Net 4.5.2 or the Core version with 1.1 in my case. IISExpress crashed when I started debug.

Tried everything, nothing worked until I went into add/remove programs in Windows 10 and I uninstalled .net core 1.0 runtime (I had both 1.0 installed AND 1.1). Once that was uninstalled, I started Visual Studio 2017 and my .Net Core Web applications (both kinds) and they both started working again!

How to import a module given the full path?

For Python 3.5+ use:

import importlib.util
spec = importlib.util.spec_from_file_location("module.name", "/path/to/file.py")
foo = importlib.util.module_from_spec(spec)
spec.loader.exec_module(foo)
foo.MyClass()

For Python 3.3 and 3.4 use:

from importlib.machinery import SourceFileLoader

foo = SourceFileLoader("module.name", "/path/to/file.py").load_module()
foo.MyClass()

(Although this has been deprecated in Python 3.4.)

For Python 2 use:

import imp

foo = imp.load_source('module.name', '/path/to/file.py')
foo.MyClass()

There are equivalent convenience functions for compiled Python files and DLLs.

See also http://bugs.python.org/issue21436.

Path to Powershell.exe (v 2.0)

I believe it's in C:\Windows\System32\WindowsPowershell\v1.0\. In order to confuse the innocent, MS kept it in a directory labeled "v1.0". Running this on Windows 7 and checking the version number via $Host.Version (Determine installed PowerShell version) shows it's 2.0.

Another option is type $PSVersionTable at the command prompt. If you are running v2.0, the output will be:

Name                           Value
----                           -----
CLRVersion                     2.0.50727.4927
BuildVersion                   6.1.7600.16385
PSVersion                      2.0
WSManStackVersion              2.0
PSCompatibleVersions           {1.0, 2.0}
SerializationVersion           1.1.0.1
PSRemotingProtocolVersion      2.1

If you're running version 1.0, the variable doesn't exist and there will be no output.

Localization PowerShell version 1.0, 2.0, 3.0, 4.0:

  • 64 bits version: C:\Windows\System32\WindowsPowerShell\v1.0\
  • 32 bits version: C:\Windows\SysWOW64\WindowsPowerShell\v1.0\

Algorithm to calculate the number of divisors of a given number

There are a lot more techniques to factoring than the sieve of Atkin. For example suppose we want to factor 5893. Well its sqrt is 76.76... Now we'll try to write 5893 as a product of squares. Well (77*77 - 5893) = 36 which is 6 squared, so 5893 = 77*77 - 6*6 = (77 + 6)(77-6) = 83*71. If that hadn't worked we'd have looked at whether 78*78 - 5893 was a perfect square. And so on. With this technique you can quickly test for factors near the square root of n much faster than by testing individual primes. If you combine this technique for ruling out large primes with a sieve, you will have a much better factoring method than with the sieve alone.

And this is just one of a large number of techniques that have been developed. This is a fairly simple one. It would take you a long time to learn, say, enough number theory to understand the factoring techniques based on elliptic curves. (I know they exist. I don't understand them.)

Therefore unless you are dealing with small integers, I wouldn't try to solve that problem myself. Instead I'd try to find a way to use something like the PARI library that already has a highly efficient solution implemented. With that I can factor a random 40 digit number like 124321342332143213122323434312213424231341 in about .05 seconds. (Its factorization, in case you wondered, is 29*439*1321*157907*284749*33843676813*4857795469949. I am quite confident that it didn't figure this out using the sieve of Atkin...)

Generate full SQL script from EF 5 Code First Migrations

The API appears to have changed (or at least, it doesn't work for me).

Running the following in the Package Manager Console works as expected:

Update-Database -Script -SourceMigration:0

Integer.valueOf() vs. Integer.parseInt()

Integer.valueOf() returns an Integer object, while Integer.parseInt() returns an int primitive.

What does the keyword Set actually do in VBA?

Off the top of my head, Set is used to assign COM objects to variables. By doing a Set I suspect that under the hood it's doing an AddRef() call on the object to manage it's lifetime.

How can I add the sqlite3 module to Python?

You don't need to install sqlite3 module. It is included in the standard library (since Python 2.5).

Checking if a folder exists using a .bat file

I think the answer is here (possibly duplicate):

How to test if a file is a directory in a batch script?

IF EXIST %VAR%\NUL ECHO It's a directory

Replace %VAR% with your directory. Please read the original answer because includes details about handling white spaces in the folder name.

As foxidrive said, this might not be reliable on NT class windows. It works for me, but I know it has some limitations (which you can find in the referenced question)

if exist "c:\folder\" echo folder exists 

should be enough for modern windows.

wait() or sleep() function in jquery?

I found a function called sleep function on the internet and don't know who made it. Here it is.

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}

sleep(2000);

Select values from XML field in SQL Server 2008

Considering that XML data comes from a table 'table' and is stored in a column 'field': use the XML methods, extract values with xml.value(), project nodes with xml.nodes(), use CROSS APPLY to join:

SELECT 
    p.value('(./firstName)[1]', 'VARCHAR(8000)') AS firstName,
    p.value('(./lastName)[1]', 'VARCHAR(8000)') AS lastName
FROM table 
    CROSS APPLY field.nodes('/person') t(p)

You can ditch the nodes() and cross apply if each field contains exactly one element 'person'. If the XML is a variable you select FROM @variable.nodes(...) and you don't need the cross apply.

if statements matching multiple values

If you have a List, you can use .Contains(yourObject), if you're just looking for it existing (like a where). Otherwise look at Linq .Any() extension method.

Reset auto increment counter in postgres

Use this query to check what is the Sequence Key with Schema and Table,

SELECT pg_get_serial_sequence('"SchemaName"."TableName"', 'KeyColumnName'); // output: "SequenceKey"

Use this query increase increment value one by one,

SELECT nextval('"SchemaName"."SequenceKey"'::regclass); // output 110

When inserting to table next incremented value will be used as the key (111).

Use this query to set specific value as the incremented value

SELECT setval('"SchemaName"."SequenceKey"', 120);

When inserting to table next incremented value will be used as the key (121).

JavaScript Adding an ID attribute to another created Element

Since id is an attribute don't create an id element, just do this:

myPara.setAttribute("id", "id_you_like");

Get current user id in ASP.NET Identity 2.0

In order to get CurrentUserId in Asp.net Identity 2.0, at first import Microsoft.AspNet.Identity:

C#:

using Microsoft.AspNet.Identity;

VB.NET:

Imports Microsoft.AspNet.Identity


And then call User.Identity.GetUserId() everywhere you want:

strCurrentUserId = User.Identity.GetUserId()

This method returns current user id as defined datatype for userid in database (the default is String).

How to make an "alias" for a long path?

but an actual alias for a dir is also possible, try

 myScripts="~/Files/Scripts/Main"
 alias myScripts="cd $myScripts"

This way you have a common naming convention (for each dir/alias pair), and if you need to copy something from the current dir to myScripts, you don't have to think about it.

IHTH

Clean out Eclipse workspace metadata

The only way I know to deal with this is to create a new workspace, import projects from the polluted workspace, reconstructing all my settings (a major pain) and then delete the old workspace. Is there an easier way to deal with this?

For synchronizing or restoring all our settings we use Workspace Mechanic. Once all the settings are recorded its one click and all settings are restored... You can also setup a server which provides those settings for all users.

How to create a Custom Dialog box in android?

Another easy way to do this.

step 1) create a layout with proper id's.

step 2) use the following code wherever you desire.

LayoutInflater factory = LayoutInflater.from(this);
final View deleteDialogView = factory.inflate(R.layout.mylayout, null);
final AlertDialog deleteDialog = new AlertDialog.Builder(this).create();
deleteDialog.setView(deleteDialogView);
deleteDialogView.findViewById(R.id.yes).setOnClickListener(new OnClickListener() {    
    @Override
    public void onClick(View v) {
        //your business logic 
        deleteDialog.dismiss();
    }
});
deleteDialogView.findViewById(R.id.no).setOnClickListener(new OnClickListener() {    
    @Override
    public void onClick(View v) {
        deleteDialog.dismiss();    
    }
});

deleteDialog.show();

How to convert array to SimpleXML

function array2xml($array, $xml = false){

    if($xml === false){

        $xml = new SimpleXMLElement('<?xml version=\'1.0\' encoding=\'utf-8\'?><'.key($array).'/>');
        $array = $array[key($array)];

    }
    foreach($array as $key => $value){
        if(is_array($value)){
            $this->array2xml($value, $xml->addChild($key));
        }else{
            $xml->addChild($key, $value);
        }
    }
    return $xml->asXML();
}

Checking if my Windows application is running

public partial class App : System.Windows.Application
{
    public bool IsProcessOpen(string name)
    {
        foreach (Process clsProcess in Process.GetProcesses()) 
        {
            if (clsProcess.ProcessName.Contains(name))
            {
                return true;
            }
        }

        return false;
    }

    protected override void OnStartup(StartupEventArgs e)
    {
        // Get Reference to the current Process
        Process thisProc = Process.GetCurrentProcess();

        if (IsProcessOpen("name of application.exe") == false)
        {
            //System.Windows.MessageBox.Show("Application not open!");
            //System.Windows.Application.Current.Shutdown();
        }
        else
        {
            // Check how many total processes have the same name as the current one
            if (Process.GetProcessesByName(thisProc.ProcessName).Length > 1)
            {
                // If ther is more than one, than it is already running.
                System.Windows.MessageBox.Show("Application is already running.");
                System.Windows.Application.Current.Shutdown();
                return;
            }

            base.OnStartup(e);
        }
    }

Get Hard disk serial Number

Here's some code that may help:

ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT * FROM Win32_DiskDrive");

string serial_number="";

foreach (ManagementObject wmi_HD in searcher.Get())
{
    serial_number = wmi_HD["SerialNumber"].ToString();
}

MessageBox.Show(serial_number);

Can an Android App connect directly to an online mysql database

step 1 : make a web service on your server

step 2 : make your application make a call to the web service and receive result sets

How do I schedule jobs in Jenkins?

*/5 * * * * means every 5 minutes

5 * * * * means the 5th minute of every hour

Inverse of matrix in R

You can use the function ginv() (Moore-Penrose generalized inverse) in the MASS package

Where does SVN client store user authentication data?

  • On Unix, it's in $HOME/.subversion/auth.

  • On Windows, I think it's: %APPDATA%\Subversion\auth.

Why doesn't Python have multiline comments?

Besides, multiline comments are a bitch. Sorry to say, but regardless of the language, I don't use them for anything else than debugging purposes. Say you have code like this:

void someFunction()
{
    Something
    /*Some comments*/
    Something else
}

Then you find out that there is something in your code you can't fix with the debugger, so you start manually debugging it by commenting out smaller and smaller chuncks of code with theese multiline comments. This would then give the function:

void someFunction()
{ /*
    Something
   /* Comments */
   Something more*/
}

This is really irritating.

Google.com and clients1.google.com/generate_204

204 responses are sometimes used in AJAX to track clicks and page activity. In this case, the only information being passed to the server in the get request is a cookie and not specific information in request parameters, so this doesn't seem to be the case here.

It seems that clients1.google.com is the server behind google search suggestions. When you visit http://www.google.com, the cookie is passed to http://clients1.google.com/generate_204. Perhaps this is to start up some kind of session on the server? Whatever the use, I doubt it's a very standard use.

There isn't anything to compare. Nothing to compare, branches are entirely different commit histories

I got this error message, because I was migrating an application from SVN to GitHub and it's not enough to invoke a git init in the location of the source code checked out from SVN, but you need to invoke a git svn clone in order to have all the commit history. This way the two source codes on GitHub will have a mutual history and I was able to open pull requests.

Finding all possible combinations of numbers to reach a given sum

C++ version of the same algorithm

#include <iostream>
#include <list>
void subset_sum_recursive(std::list<int> numbers, int target, std::list<int> partial)
{
        int s = 0;
        for (std::list<int>::const_iterator cit = partial.begin(); cit != partial.end(); cit++)
        {
            s += *cit;
        }
        if(s == target)
        {
                std::cout << "sum([";

                for (std::list<int>::const_iterator cit = partial.begin(); cit != partial.end(); cit++)
                {
                    std::cout << *cit << ",";
                }
                std::cout << "])=" << target << std::endl;
        }
        if(s >= target)
            return;
        int n;
        for (std::list<int>::const_iterator ai = numbers.begin(); ai != numbers.end(); ai++)
        {
            n = *ai;
            std::list<int> remaining;
            for(std::list<int>::const_iterator aj = ai; aj != numbers.end(); aj++)
            {
                if(aj == ai)continue;
                remaining.push_back(*aj);
            }
            std::list<int> partial_rec=partial;
            partial_rec.push_back(n);
            subset_sum_recursive(remaining,target,partial_rec);

        }
}

void subset_sum(std::list<int> numbers,int target)
{
    subset_sum_recursive(numbers,target,std::list<int>());
}
int main()
{
    std::list<int> a;
    a.push_back (3); a.push_back (9); a.push_back (8);
    a.push_back (4);
    a.push_back (5);
    a.push_back (7);
    a.push_back (10);
    int n = 15;
    //std::cin >> n;
    subset_sum(a, n);
    return 0;
}

How to write MySQL query where A contains ( "a" or "b" )

I've used most of the times the LIKE option and it works just fine. I just like to share one of my latest experiences where I used INSTR function. Regardless of the reasons that made me consider this options, what's important here is that the use is similar: instr(A, 'text 1') > 0 or instr(A, 'text 2') > 0 Another option could be: (instr(A, 'text 1') + instr(A, 'text 2')) > 0

I'd go with the LIKE '%text1%' OR LIKE '%text2%' option... if not hope this other option helps

Entity Framework Migrations renaming tables and columns

Table names and column names can be specified as part of the mapping of DbContext. Then there is no need to do it in migrations.

public class MyContext : DbContext
{
    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Restaurant>()
            .HasMany(p => p.Cuisines)
            .WithMany(r => r.Restaurants)
            .Map(mc =>
            {
                mc.MapLeftKey("RestaurantId");
                mc.MapRightKey("CuisineId");
                mc.ToTable("RestaurantCuisines");
            });
     }
}

How do I write to the console from a Laravel Controller?

Here's another way to go about it:

$stdout = fopen('php://stdout', 'w');
fwrite($stdout, 'Hello, World!' . PHP_EOL);

The PHP_EOL adds new line.

How to get a random number in Ruby

Use rand(range)

From Ruby Random Numbers:

If you needed a random integer to simulate a roll of a six-sided die, you'd use: 1 + rand(6). A roll in craps could be simulated with 2 + rand(6) + rand(6).

Finally, if you just need a random float, just call rand with no arguments.


As Marc-André Lafortune mentions in his answer below (go upvote it), Ruby 1.9.2 has its own Random class (that Marc-André himself helped to debug, hence the 1.9.2 target for that feature).

For instance, in this game where you need to guess 10 numbers, you can initialize them with:

10.times.map{ 20 + Random.rand(11) } 
#=> [26, 26, 22, 20, 30, 26, 23, 23, 25, 22]

Note:

This is why the equivalent of Random.new.rand(20..30) would be 20 + Random.rand(11), since Random.rand(int) returns “a random integer greater than or equal to zero and less than the argument.” 20..30 includes 30, I need to come up with a random number between 0 and 11, excluding 11.

How to convert .pfx file to keystore with private key?

Using JDK 1.6 or later

It has been pointed out by Justin in the comments below that keytool alone is capable of doing this using the following command (although only in JDK 1.6 and later):

keytool -importkeystore -srckeystore mypfxfile.pfx -srcstoretype pkcs12 
-destkeystore clientcert.jks -deststoretype JKS

Using JDK 1.5 or below

OpenSSL can do it all. This answer on JGuru is the best method that I've found so far.

Firstly make sure that you have OpenSSL installed. Many operating systems already have it installed as I found with Mac OS X.

The following two commands convert the pfx file to a format that can be opened as a Java PKCS12 key store:

openssl pkcs12 -in mypfxfile.pfx -out mypemfile.pem
openssl pkcs12 -export -in mypemfile.pem -out mykeystore.p12 -name "MyCert"

NOTE that the name provided in the second command is the alias of your key in the new key store.

You can verify the contents of the key store using the Java keytool utility with the following command:

keytool -v -list -keystore mykeystore.p12 -storetype pkcs12

Finally if you need to you can convert this to a JKS key store by importing the key store created above into a new key store:

keytool -importkeystore -srckeystore mykeystore.p12 -destkeystore clientcert.jks -srcstoretype pkcs12 -deststoretype JKS

How to create a multiline UITextfield?

use UITextView instead of UITextField

How to create a fixed sidebar layout with Bootstrap 4?

I'm using the J.S. to fix a sidebar menu. I've tried a lot of solutions with CSS but it's the simplest way to solve it, just add J.S. adding and removing a native BootStrap class: "position-fixed".

The J.S.:

var lateral = false;
function fixar() {

            var element, name, arr;
            element = document.getElementById("minhasidebar");

            if (lateral) {
                element.className = element.className.replace(
                        /\bposition-fixed\b/g, "");
                lateral = false;
            } else {

                name = "position-fixed";
                arr = element.className.split(" ");
                if (arr.indexOf(name) == -1) {
                    element.className += " " + name;
                }
                lateral = true;
            }

        }

The HTML:

Sidebar:

<aside>
        <nav class="sidebar ">
             <div id="minhasidebar">
                 <ul class="nav nav-pills">
                     <li class="nav-item"><a class="nav-link active" 
                     th:href="@{/hoje/inicial}"> <i class="oi oi-clipboard"></i> 
                     <span>Hoje</span>
                     </a></li>
                 </ul>
             </div>
        </nav>            
</aside>

HTTP client timeout and server timeout

According to https://bugzilla.mozilla.org/show_bug.cgi?id=592284, the pref network.http.connection-retry-timeout controls the amount of time in ms (Milliseconds !) to wait for success on the initial connection before beginning the second one. Setting it to 0 disables the parallel connection.

Convert bytes to bits in python

Operations are much faster when you work at the integer level. In particular, converting to a string as suggested here is really slow.

If you want bit 7 and 8 only, use e.g.

val = (byte >> 6) & 3

(this is: shift the byte 6 bits to the right - dropping them. Then keep only the last two bits 3 is the number with the first two bits set...)

These can easily be translated into simple CPU operations that are super fast.

Call JavaScript function from C#

If you want to call JavaScript function in C#, this will help you:

public string functionname(arg)
{
    if (condition)
    {
        Page page = HttpContext.Current.CurrentHandler as Page;
        page.ClientScript.RegisterStartupScript(
            typeof(Page),
            "Test",
            "<script type='text/javascript'>functionname1(" + arg1 + ",'" + arg2 + "');</script>");
    }
}

is it possible to add colors to python output?

If your console (like your standard ubuntu console) understands ANSI color codes, you can use those.

Here an example:

print ('This is \x1b[31mred\x1b[0m.') 

Insert Unicode character into JavaScript

Although @ruakh gave a good answer, I will add some alternatives for completeness:

You could in fact use even var Omega = '&#937;' in JavaScript, but only if your JavaScript code is:

  • inside an event attribute, as in onclick="var Omega = '&#937'; alert(Omega)" or
  • in a script element inside an XHTML (or XHTML + XML) document served with an XML content type.

In these cases, the code will be first (before getting passed to the JavaScript interpreter) be parsed by an HTML parser so that character references like &#937; are recognized. The restrictions make this an impractical approach in most cases.

You can also enter the O character as such, as in var Omega = 'O', but then the character encoding must allow that, the encoding must be properly declared, and you need software that let you enter such characters. This is a clean solution and quite feasible if you use UTF-8 encoding for everything and are prepared to deal with the issues created by it. Source code will be readable, and reading it, you immediately see the character itself, instead of code notations. On the other hand, it may cause surprises if other people start working with your code.

Using the \u notation, as in var Omega = '\u03A9', works independently of character encoding, and it is in practice almost universal. It can however be as such used only up to U+FFFF, i.e. up to \uffff, but most characters that most people ever heard of fall into that area. (If you need “higher” characters, you need to use either surrogate pairs or one of the two approaches above.)

You can also construct a character using the String.fromCharCode() method, passing as a parameter the Unicode number, in decimal as in var Omega = String.fromCharCode(937) or in hexadecimal as in var Omega = String.fromCharCode(0x3A9). This works up to U+FFFF. This approach can be used even when you have the Unicode number in a variable.

Access iframe elements in JavaScript

Two ways

window.frames['myIFrame'].contentDocument.getElementById('myIFrameElemId')

OR

window.frames['myIFrame'].contentWindow.document.getElementById('myIFrameElemId')

How to enable file upload on React's Material UI simple input?

The API provides component for this purpose.

<Button
  variant="contained"
  component="label"
>
  Upload File
  <input
    type="file"
    hidden
  />
</Button>

cannot call member function without object

If you want to call them like that, you should declare them static.

Remove Safari/Chrome textinput/textarea glow

Sure! You can remove blue border also from all HTML elements using *

*{
    outline-color: transparent;
    outline-style: none;
  }

And

 *{
     outline: none;   
   }

Correct location of openssl.cnf file

/usr/local/ssl/openssl.cnf

This is a local installation. You downloaded and built OpenSSL taking the default prefix, of you configured with ./config --prefix=/usr/local/ssl or ./config --openssldir=/usr/local/ssl.

You will use this if you use the OpenSSL in /usr/local/ssl/bin. That is, /usr/local/ssl/openssl.cnf will be used when you issue:

/usr/local/ssl/bin/openssl s_client -connect localhost:443 -tls1 -servername localhost

/usr/lib/ssl/openssl.cnf

This is where Ubuntu places openssl.cnf for the OpenSSL they provide.

You will use this if you use the OpenSSL in /usr/bin. That is, /usr/lib/ssl/openssl.cnf will be used when you issue:

openssl s_client -connect localhost:443 -tls1 -servername localhost

/etc/ssl/openssl.cnf

I don't know when this is used. The stuff in /etc/ssl is usually certificates and private keys, and it sometimes contains a copy of openssl.cnf. But I've never seen it used for anything.


Which is the main/correct one that I should use to make changes?

From the sounds of it, you should probably add the engine to /usr/lib/ssl/openssl.cnf. That ensures most "off the shelf" gear will use the new engine.

After you do that, add it to /usr/local/ssl/openssl.cnf also because copy/paste is easy.


Here's how to see which openssl.cnf directory is associated with a OpenSSL installation. The library and programs look for openssl.cnf in OPENSSLDIR. OPENSSLDIR is a configure option, and its set with --openssldir.

I'm on a MacBook with 3 different OpenSSL's (Apple's, MacPort's and the one I build):

# Apple    
$ /usr/bin/openssl version -a | grep OPENSSLDIR
OPENSSLDIR: "/System/Library/OpenSSL"

# MacPorts
$ /opt/local/bin/openssl version -a | grep OPENSSLDIR
OPENSSLDIR: "/opt/local/etc/openssl"

# My build of OpenSSL
$ openssl version -a | grep OPENSSLDIR
OPENSSLDIR: "/usr/local/ssl/darwin"

I have an Ubuntu system and I have installed openssl.

Just bike shedding, but be careful of Ubuntu's version of OpenSSL. It disables TLSv1.1 and TLSv1.2, so you will only have clients capable of older cipher suites; and you will not be able to use newer ciphers like AES/CTR (to replace RC4) and elliptic curve gear (like ECDHE_ECDSA_* and ECDHE_RSA_*). See Ubuntu 12.04 LTS: OpenSSL downlevel version is 1.0.0, and does not support TLS 1.2 in Launchpad.

EDIT: Ubuntu enabled TLS 1.1 and TLS 1.2 recently. See Comment 17 on the bug report.

Android Design Support Library expandable Floating Action Button(FAB) menu

  • First create the menu layouts in the your Activity layout xml file. For e.g. a linear layout with horizontal orientation and include a TextView for label then a Floating Action Button beside the TextView.

  • Create the menu layouts as per your need and number.

  • Create a Base Floating Action Button and on its click of that change the visibility of the Menu Layouts.

Please check the below code for the reference and for more info checkout my project from github

Checkout project from Github

<android.support.constraint.ConstraintLayout
            android:id="@+id/activity_main"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            tools:context="com.app.fabmenu.MainActivity">

            <android.support.design.widget.FloatingActionButton
                android:id="@+id/baseFloatingActionButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="16dp"
                android:layout_marginEnd="16dp"
                android:layout_marginRight="16dp"
                android:clickable="true"
                android:onClick="@{FabHandler::onBaseFabClick}"
                android:tint="@android:color/white"
                app:fabSize="normal"
                app:layout_constraintBottom_toBottomOf="@+id/activity_main"
                app:layout_constraintRight_toRightOf="@+id/activity_main"
                app:srcCompat="@drawable/ic_add_black_24dp" />

            <LinearLayout
                android:id="@+id/shareLayout"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="12dp"
                android:layout_marginEnd="24dp"
                android:layout_marginRight="24dp"
                android:gravity="center_vertical"
                android:orientation="horizontal"
                android:visibility="invisible"
                app:layout_constraintBottom_toTopOf="@+id/createLayout"
                app:layout_constraintLeft_toLeftOf="@+id/createLayout"
                app:layout_constraintRight_toRightOf="@+id/activity_main">

                <TextView
                    android:id="@+id/shareLabelTextView"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginEnd="8dp"
                    android:layout_marginRight="8dp"
                    android:background="@drawable/shape_fab_label"
                    android:elevation="2dp"
                    android:fontFamily="sans-serif"
                    android:padding="5dip"
                    android:text="Share"
                    android:textColor="@android:color/white"
                    android:typeface="normal" />


                <android.support.design.widget.FloatingActionButton
                    android:id="@+id/shareFab"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:clickable="true"
                    android:onClick="@{FabHandler::onShareFabClick}"
                    android:tint="@android:color/white"
                    app:fabSize="mini"
                    app:srcCompat="@drawable/ic_share_black_24dp" />

            </LinearLayout>

            <LinearLayout
                android:id="@+id/createLayout"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginBottom="24dp"
                android:layout_marginEnd="24dp"
                android:layout_marginRight="24dp"
                android:gravity="center_vertical"
                android:orientation="horizontal"
                android:visibility="invisible"
                app:layout_constraintBottom_toTopOf="@+id/baseFloatingActionButton"
                app:layout_constraintRight_toRightOf="@+id/activity_main">

                <TextView
                    android:id="@+id/createLabelTextView"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_marginEnd="8dp"
                    android:layout_marginRight="8dp"
                    android:background="@drawable/shape_fab_label"
                    android:elevation="2dp"
                    android:fontFamily="sans-serif"
                    android:padding="5dip"
                    android:text="Create"
                    android:textColor="@android:color/white"
                    android:typeface="normal" />

                <android.support.design.widget.FloatingActionButton
                    android:id="@+id/createFab"
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:clickable="true"
                    android:onClick="@{FabHandler::onCreateFabClick}"
                    android:tint="@android:color/white"
                    app:fabSize="mini"
                    app:srcCompat="@drawable/ic_create_black_24dp" />

            </LinearLayout>

        </android.support.constraint.ConstraintLayout>

These are the animations-

Opening animation of FAB Menu:

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:fillAfter="true">
<scale
    android:duration="300"
    android:fromXScale="0"
    android:fromYScale="0"
    android:interpolator="@android:anim/linear_interpolator"
    android:pivotX="50%"
    android:pivotY="50%"
    android:toXScale="1"
    android:toYScale="1" />
<alpha
    android:duration="300"
    android:fromAlpha="0.0"
    android:interpolator="@android:anim/accelerate_interpolator"
    android:toAlpha="1.0" />

</set>

Closing animation of FAB Menu:

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
android:fillAfter="true">
<scale
    android:duration="300"
    android:fromXScale="1"
    android:fromYScale="1"
    android:interpolator="@android:anim/linear_interpolator"
    android:pivotX="50%"
    android:pivotY="50%"
    android:toXScale="0.0"
    android:toYScale="0.0" />
<alpha
    android:duration="300"
    android:fromAlpha="1.0"
    android:interpolator="@android:anim/accelerate_interpolator"
    android:toAlpha="0.0" />
</set>

Then in my Activity I've simply used the animations above to show and hide the FAB menu :

Show Fab Menu:

  private void expandFabMenu() {

    ViewCompat.animate(binding.baseFloatingActionButton).rotation(45.0F).withLayer().setDuration(300).setInterpolator(new OvershootInterpolator(10.0F)).start();
    binding.createLayout.startAnimation(fabOpenAnimation);
    binding.shareLayout.startAnimation(fabOpenAnimation);
    binding.createFab.setClickable(true);
    binding.shareFab.setClickable(true);
    isFabMenuOpen = true;

}

Close Fab Menu:

private void collapseFabMenu() {

    ViewCompat.animate(binding.baseFloatingActionButton).rotation(0.0F).withLayer().setDuration(300).setInterpolator(new OvershootInterpolator(10.0F)).start();
    binding.createLayout.startAnimation(fabCloseAnimation);
    binding.shareLayout.startAnimation(fabCloseAnimation);
    binding.createFab.setClickable(false);
    binding.shareFab.setClickable(false);
    isFabMenuOpen = false;

}

Here is the the Activity class -

package com.app.fabmenu;

import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.support.v4.view.ViewCompat;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.OvershootInterpolator;

import com.app.fabmenu.databinding.ActivityMainBinding;

public class MainActivity extends AppCompatActivity {

private ActivityMainBinding binding;
private Animation fabOpenAnimation;
private Animation fabCloseAnimation;
private boolean isFabMenuOpen = false;

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

    binding = DataBindingUtil.setContentView(this,    R.layout.activity_main);
    binding.setFabHandler(new FabHandler());

    getAnimations();


}

private void getAnimations() {

    fabOpenAnimation = AnimationUtils.loadAnimation(this, R.anim.fab_open);

    fabCloseAnimation = AnimationUtils.loadAnimation(this, R.anim.fab_close);

}

private void expandFabMenu() {

    ViewCompat.animate(binding.baseFloatingActionButton).rotation(45.0F).withLayer().setDuration(300).setInterpolator(new OvershootInterpolator(10.0F)).start();
    binding.createLayout.startAnimation(fabOpenAnimation);
    binding.shareLayout.startAnimation(fabOpenAnimation);
    binding.createFab.setClickable(true);
    binding.shareFab.setClickable(true);
    isFabMenuOpen = true;


}

private void collapseFabMenu() {

    ViewCompat.animate(binding.baseFloatingActionButton).rotation(0.0F).withLayer().setDuration(300).setInterpolator(new OvershootInterpolator(10.0F)).start();
    binding.createLayout.startAnimation(fabCloseAnimation);
    binding.shareLayout.startAnimation(fabCloseAnimation);
    binding.createFab.setClickable(false);
    binding.shareFab.setClickable(false);
    isFabMenuOpen = false;

}


public class FabHandler {

    public void onBaseFabClick(View view) {

        if (isFabMenuOpen)
            collapseFabMenu();
        else
            expandFabMenu();


    }

    public void onCreateFabClick(View view) {

        Snackbar.make(binding.coordinatorLayout, "Create FAB tapped", Snackbar.LENGTH_SHORT).show();

    }

    public void onShareFabClick(View view) {

        Snackbar.make(binding.coordinatorLayout, "Share FAB tapped", Snackbar.LENGTH_SHORT).show();

    }


}

@Override
public void onBackPressed() {

    if (isFabMenuOpen)
        collapseFabMenu();
    else
        super.onBackPressed();
}
}

Here are the screenshots

Floating Action Menu with Label Textview in new Cursive Font Family of Android

Floating Action Menu with Label Textview in new Roboto Font Family of Android

How to open the command prompt and insert commands using Java?

You have to set all \" (quotes) carefully. The parameter \k is used to leave the command prompt open after the execution.

1) to combine 2 commands use (for example pause and ipconfig)

Runtime.getRuntime()
  .exec("cmd /c start cmd.exe /k \"pause && ipconfig\"", null, selectedFile.getParentFile());

2) to show the content of a file use (MORE is a command line viewer on Windows)

File selectedFile = new File(pathToFile):
Runtime.getRuntime()
  .exec("cmd /c start cmd.exe /k \"MORE \"" + selectedFile.getName() + "\"\"", null, selectedFile.getParentFile());

One nesting quote \" is for the command and the file name, the second quote \" is for the filename itself, for spaces etc. in the name particularly.

HttpClient does not exist in .net 4.0: what can I do?

Agreeing with TrueWill's comment on a separate answer, the best way I've seen to use system.web.http on a .NET 4 targeted project under current Visual Studio is Install-Package Microsoft.AspNet.WebApi.Client -Version 4.0.30506

Convert wchar_t to char

assert is for ensuring that something is true in a debug mode, without it having any effect in a release build. Better to use an if statement and have an alternate plan for characters that are outside the range, unless the only way to get characters outside the range is through a program bug.

Also, depending on your character encoding, you might find a difference between the Unicode characters 0x80 through 0xff and their char version.

Using module 'subprocess' with timeout

Another option is to write to a temporary file to prevent the stdout blocking instead of needing to poll with communicate(). This worked for me where the other answers did not; for example on windows.

    outFile =  tempfile.SpooledTemporaryFile() 
    errFile =   tempfile.SpooledTemporaryFile() 
    proc = subprocess.Popen(args, stderr=errFile, stdout=outFile, universal_newlines=False)
    wait_remaining_sec = timeout

    while proc.poll() is None and wait_remaining_sec > 0:
        time.sleep(1)
        wait_remaining_sec -= 1

    if wait_remaining_sec <= 0:
        killProc(proc.pid)
        raise ProcessIncompleteError(proc, timeout)

    # read temp streams from start
    outFile.seek(0);
    errFile.seek(0);
    out = outFile.read()
    err = errFile.read()
    outFile.close()
    errFile.close()

Simple check for SELECT query empty result

Use @@ROWCOUNT:

SELECT * FROM service s WHERE s.service_id = ?;

IF @@ROWCOUNT > 0 
   -- do stuff here.....

According to SQL Server Books Online:

Returns the number of rows affected by the last statement. If the number of rows is more than 2 billion, use ROWCOUNT_BIG.

SQL to add column and comment in table in single command

You can use below query to update or create comment on already created table.

SYNTAX:

COMMENT ON COLUMN TableName.ColumnName IS 'comment text';

Example:

COMMENT ON COLUMN TAB_SAMBANGI.MY_COLUMN IS 'This is a comment on my column...';

The ScriptManager must appear before any controls that need it

The script manager must be put onto the page before it is used. This would be directly on the page itself, or alternatively, if you are using them, on the Master Page.

The markup would be;

 <asp:ScriptManager ID="ScriptManager1" runat="server" LoadScriptsBeforeUI="true"
            EnablePartialRendering="true" />

What does O(log n) mean exactly?

You can think of O(log N) intuitively by saying the time is proportional to the number of digits in N.

If an operation performs constant time work on each digit or bit of an input, the whole operation will take time proportional to the number of digits or bits in the input, not the magnitude of the input; thus, O(log N) rather than O(N).

If an operation makes a series of constant time decisions each of which halves (reduces by a factor of 3, 4, 5..) the size of the input to be considered, the whole will take time proportional to log base 2 (base 3, base 4, base 5...) of the size N of the input, rather than being O(N).

And so on.

Fixed page header overlaps in-page anchors

Updated on 2/2021

Correct but not cross-browser solution is:

h1 {
  scroll-margin-top: 50px
}

It is part of CSS Scroll Snap spec. Currently runs on all modern browsers except for Safari. It is fixed there and released in TP, but not as a stable yet.

List distinct values in a vector in R

Do you mean unique:

R> x = c(1,1,2,3,4,4,4)
R> x
[1] 1 1 2 3 4 4 4
R> unique(x)
[1] 1 2 3 4

Using Jquery AJAX function with datatype HTML

Here is a version that uses dataType html, but this is far less explicit, because i am returning an empty string to indicate an error.

Ajax call:

$.ajax({
  type : 'POST',
  url : 'post.php',
  dataType : 'html',
  data: {
      email : $('#email').val()
  },
  success : function(data){
      $('#waiting').hide(500);
      $('#message').removeClass().addClass((data == '') ? 'error' : 'success')
     .html(data).show(500);
      if (data == '') {
          $('#message').html("Format your email correcly");
          $('#demoForm').show(500);
      }
  },
  error : function(XMLHttpRequest, textStatus, errorThrown) {
      $('#waiting').hide(500);
      $('#message').removeClass().addClass('error')
      .text('There was an error.').show(500);
      $('#demoForm').show(500);
  }

});

post.php

<?php
sleep(1);

function processEmail($email) {
    if (preg_match("#^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$#", $email)) {
        // your logic here (ex: add into database)
        return true;
    }
    return false;
}

if (processEmail($_POST['email'])) {
    echo "<span>Your email is <strong>{$_POST['email']}</strong></span>";
}

HashMap get/put complexity

HashMap operation is dependent factor of hashCode implementation. For the ideal scenario lets say the good hash implementation which provide unique hash code for every object (No hash collision) then the best, worst and average case scenario would be O(1). Let's consider a scenario where a bad implementation of hashCode always returns 1 or such hash which has hash collision. In this case the time complexity would be O(n).

Now coming to the second part of the question about memory, then yes memory constraint would be taken care by JVM.

How to take backup of a single table in a MySQL database?

You can either use mysqldump from the command line:

mysqldump -u username -p password dbname tablename > "path where you want to dump"

You can also use MySQL Workbench:

Go to left > Data Export > Select Schema > Select tables and click on Export

What HTTP traffic monitor would you recommend for Windows?

I now use CharlesProxy for development, but previously I have used Fiddler

node.js: read a text file into an array. (Each line an item in the array.)

use readline (documentation). here's an example reading a css file, parsing for icons and writing them to json

var results = [];
  var rl = require('readline').createInterface({
    input: require('fs').createReadStream('./assets/stylesheets/_icons.scss')
  });


  // for every new line, if it matches the regex, add it to an array
  // this is ugly regex :)
  rl.on('line', function (line) {
    var re = /\.icon-icon.*:/;
    var match;
    if ((match = re.exec(line)) !== null) {
      results.push(match[0].replace(".",'').replace(":",''));
    }
  });


  // readline emits a close event when the file is read.
  rl.on('close', function(){
    var outputFilename = './icons.json';
    fs.writeFile(outputFilename, JSON.stringify(results, null, 2), function(err) {
        if(err) {
          console.log(err);
        } else {
          console.log("JSON saved to " + outputFilename);
        }
    });
  });

How to add /usr/local/bin in $PATH on Mac

Try placing $PATH at the end.

export PATH=/usr/local/git/bin:/usr/local/bin:$PATH

What does java.lang.Thread.interrupt() do?

For completeness, in addition to the other answers, if the thread is interrupted before it blocks on Object.wait(..) or Thread.sleep(..) etc., this is equivalent to it being interrupted immediately upon blocking on that method, as the following example shows.

public class InterruptTest {
    public static void main(String[] args) {

        Thread.currentThread().interrupt();

        printInterrupted(1);

        Object o = new Object();
        try {
            synchronized (o) {
                printInterrupted(2);
                System.out.printf("A Time %d\n", System.currentTimeMillis());
                o.wait(100);
                System.out.printf("B Time %d\n", System.currentTimeMillis());
            }
        } catch (InterruptedException ie) {
            System.out.printf("WAS interrupted\n");
        }
        System.out.printf("C Time %d\n", System.currentTimeMillis());

        printInterrupted(3);

        Thread.currentThread().interrupt();

        printInterrupted(4);

        try {
            System.out.printf("D Time %d\n", System.currentTimeMillis());
            Thread.sleep(100);
            System.out.printf("E Time %d\n", System.currentTimeMillis());
        } catch (InterruptedException ie) {
            System.out.printf("WAS interrupted\n");
        }
        System.out.printf("F Time %d\n", System.currentTimeMillis());

        printInterrupted(5);

        try {
            System.out.printf("G Time %d\n", System.currentTimeMillis());
            Thread.sleep(100);
            System.out.printf("H Time %d\n", System.currentTimeMillis());
        } catch (InterruptedException ie) {
            System.out.printf("WAS interrupted\n");
        }
        System.out.printf("I Time %d\n", System.currentTimeMillis());

    }
    static void printInterrupted(int n) {
        System.out.printf("(%d) Am I interrupted? %s\n", n,
                Thread.currentThread().isInterrupted() ? "Yes" : "No");
    }
}

Output:

$ javac InterruptTest.java 

$ java -classpath "." InterruptTest
(1) Am I interrupted? Yes
(2) Am I interrupted? Yes
A Time 1399207408543
WAS interrupted
C Time 1399207408543
(3) Am I interrupted? No
(4) Am I interrupted? Yes
D Time 1399207408544
WAS interrupted
F Time 1399207408544
(5) Am I interrupted? No
G Time 1399207408545
H Time 1399207408668
I Time 1399207408669

Implication: if you loop like the following, and the interrupt occurs at the exact moment when control has left Thread.sleep(..) and is going around the loop, the exception is still going to occur. So it is perfectly safe to rely on the InterruptedException being reliably thrown after the thread has been interrupted:

while (true) {
    try {
        Thread.sleep(10);
    } catch (InterruptedException ie) {
        break;
    }
}

How does numpy.newaxis work and when to use it?

newaxis object in the selection tuple serves to expand the dimensions of the resulting selection by one unit-length dimension.

It is not just conversion of row matrix to column matrix.

Consider the example below:

In [1]:x1 = np.arange(1,10).reshape(3,3)
       print(x1)
Out[1]: array([[1, 2, 3],
               [4, 5, 6],
               [7, 8, 9]])

Now lets add new dimension to our data,

In [2]:x1_new = x1[:,np.newaxis]
       print(x1_new)
Out[2]:array([[[1, 2, 3]],

              [[4, 5, 6]],

              [[7, 8, 9]]])

You can see that newaxis added the extra dimension here, x1 had dimension (3,3) and X1_new has dimension (3,1,3).

How our new dimension enables us to different operations:

In [3]:x2 = np.arange(11,20).reshape(3,3)
       print(x2)
Out[3]:array([[11, 12, 13],
              [14, 15, 16],
              [17, 18, 19]]) 

Adding x1_new and x2, we get:

In [4]:x1_new+x2
Out[4]:array([[[12, 14, 16],
               [15, 17, 19],
               [18, 20, 22]],

              [[15, 17, 19],
               [18, 20, 22],
               [21, 23, 25]],

              [[18, 20, 22],
               [21, 23, 25],
               [24, 26, 28]]])

Thus, newaxis is not just conversion of row to column matrix. It increases the dimension of matrix, thus enabling us to do more operations on it.

How many times does each value appear in a column?

You can use CountIf. Put the following code in B1 and drag down the whole column

=COUNTIF(A:A,A1)

It will look like this:

enter image description here

Populating a dictionary using for loops (python)

dicts = {}
keys = range(4)
values = ["Hi", "I", "am", "John"]
for i in keys:
        dicts[i] = values[i]
print(dicts)

alternatively

In [7]: dict(list(enumerate(values)))
Out[7]: {0: 'Hi', 1: 'I', 2: 'am', 3: 'John'}

Redirect From Action Filter Attribute

Set filterContext.Result

With the route name:

filterContext.Result = new RedirectToRouteResult("SystemLogin", routeValues);

You can also do something like:

filterContext.Result = new ViewResult
{
    ViewName = SharedViews.SessionLost,
    ViewData = filterContext.Controller.ViewData
};

If you want to use RedirectToAction:

You could make a public RedirectToAction method on your controller (preferably on its base controller) that simply calls the protected RedirectToAction from System.Web.Mvc.Controller. Adding this method allows for a public call to your RedirectToAction from the filter.

public new RedirectToRouteResult RedirectToAction(string action, string controller)
{
    return base.RedirectToAction(action, controller);
}

Then your filter would look something like:

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
    var controller = (SomeControllerBase) filterContext.Controller;
    filterContext.Result = controller.RedirectToAction("index", "home");
}

ValueError: Length of values does not match length of index | Pandas DataFrame.unique()

The error comes up when you are trying to assign a list of numpy array of different length to a data frame, and it can be reproduced as follows:

A data frame of four rows:

df = pd.DataFrame({'A': [1,2,3,4]})

Now trying to assign a list/array of two elements to it:

df['B'] = [3,4]   # or df['B'] = np.array([3,4])

Both errors out:

ValueError: Length of values does not match length of index

Because the data frame has four rows but the list and array has only two elements.

Work around Solution (use with caution): convert the list/array to a pandas Series, and then when you do assignment, missing index in the Series will be filled with NaN:

df['B'] = pd.Series([3,4])

df
#   A     B
#0  1   3.0
#1  2   4.0
#2  3   NaN          # NaN because the value at index 2 and 3 doesn't exist in the Series
#3  4   NaN

For your specific problem, if you don't care about the index or the correspondence of values between columns, you can reset index for each column after dropping the duplicates:

df.apply(lambda col: col.drop_duplicates().reset_index(drop=True))

#   A     B
#0  1   1.0
#1  2   5.0
#2  7   9.0
#3  8   NaN

How can I stop the browser back button using JavaScript?

This code was tested with the latest Chrome and Firefox browsers.

<script type="text/javascript">
    history.pushState(null, null, location.href);
    history.back();
    history.forward();
    window.onpopstate = function () { history.go(1); };
</script>

Populate unique values into a VBA array from Excel

If you don't mind using the Variant data type, then you can use the in-built worksheet function Unique as shown.

sub unique_results_to_array()
    dim rng_data as Range
    set rng_data = activesheet.range("A1:A10") 'enter the range of data here

    dim my_arr() as Variant
    my_arr = WorksheetFunction.Unique(rng_data)
    
    first_val  = my_arr(1,1)
    second_val = my_arr(2,1)
    third_val = my_arr(3,1)   'etc...    

end sub

How to read file binary in C#?

You can use BinaryReader to read each of the bytes, then use BitConverter.ToString(byte[]) to find out how each is represented in binary.

You can then use this representation and write it to a file.

"Prevent saving changes that require the table to be re-created" negative effects

SQL Server drops and recreates the tables only if you:

  • Add a new column
  • Change the Allow Nulls setting for a column
  • Change the column order in the table
  • Change the column data type

Using ALTER is safer, as in case the metadata is lost while you re-create the table, your data will be lost.

How to scroll to an element inside a div?

browser does scrolling automatically to an element that gets focus, so what you can also do it to wrap the element that you need to be scrolled to into <a>...</a> and then when you need scroll just set the focus on that a

Why use a ReentrantLock if one can use synchronized(this)?

Synchronized locks does not offer any mechanism of waiting queue in which after the execution of one thread any thread running in parallel can acquire the lock. Due to which the thread which is there in the system and running for a longer period of time never gets chance to access the shared resource thus leading to starvation.

Reentrant locks are very much flexible and has a fairness policy in which if a thread is waiting for a longer time and after the completion of the currently executing thread we can make sure that the longer waiting thread gets the chance of accessing the shared resource hereby decreasing the throughput of the system and making it more time consuming.

What is a predicate in c#?

Predicate<T> is a functional construct providing a convenient way of basically testing if something is true of a given T object.

For example suppose I have a class:

class Person {
    public string Name { get; set; }
    public int Age { get; set; }
}

Now let's say I have a List<Person> people and I want to know if there's anyone named Oscar in the list.

Without using a Predicate<Person> (or Linq, or any of that fancy stuff), I could always accomplish this by doing the following:

Person oscar = null;
foreach (Person person in people) {
    if (person.Name == "Oscar") {
        oscar = person;
        break;
    }
}

if (oscar != null) {
    // Oscar exists!
}

This is fine, but then let's say I want to check if there's a person named "Ruth"? Or a person whose age is 17?

Using a Predicate<Person>, I can find these things using a LOT less code:

Predicate<Person> oscarFinder = (Person p) => { return p.Name == "Oscar"; };
Predicate<Person> ruthFinder = (Person p) => { return p.Name == "Ruth"; };
Predicate<Person> seventeenYearOldFinder = (Person p) => { return p.Age == 17; };

Person oscar = people.Find(oscarFinder);
Person ruth = people.Find(ruthFinder);
Person seventeenYearOld = people.Find(seventeenYearOldFinder);

Notice I said a lot less code, not a lot faster. A common misconception developers have is that if something takes one line, it must perform better than something that takes ten lines. But behind the scenes, the Find method, which takes a Predicate<T>, is just enumerating after all. The same is true for a lot of Linq's functionality.

So let's take a look at the specific code in your question:

Predicate<int> pre = delegate(int a){ return a % 2 == 0; };

Here we have a Predicate<int> pre that takes an int a and returns a % 2 == 0. This is essentially testing for an even number. What that means is:

pre(1) == false;
pre(2) == true;

And so on. This also means, if you have a List<int> ints and you want to find the first even number, you can just do this:

int firstEven = ints.Find(pre);

Of course, as with any other type that you can use in code, it's a good idea to give your variables descriptive names; so I would advise changing the above pre to something like evenFinder or isEven -- something along those lines. Then the above code is a lot clearer:

int firstEven = ints.Find(evenFinder);

Unique constraint on multiple columns

By using the constraint definition on table creation, you can specify one or multiple constraints that span multiple columns. The syntax, simplified from technet's documentation, is in the form of:

CONSTRAINT constraint_name UNIQUE [ CLUSTERED | NONCLUSTERED ] 
(
    column [ ASC | DESC ] [ ,...n ]
)

Therefore, the resuting table definition would be:

CREATE TABLE [dbo].[user](
    [userID] [int] IDENTITY(1,1) NOT NULL,
    [fcode] [int] NULL,
    [scode] [int] NULL,
    [dcode] [int] NULL,
    [name] [nvarchar](50) NULL,
    [address] [nvarchar](50) NULL,
    CONSTRAINT [PK_user_1] PRIMARY KEY CLUSTERED 
    (
        [userID] ASC
    ),
    CONSTRAINT [UQ_codes] UNIQUE NONCLUSTERED
    (
        [fcode], [scode], [dcode]
    )
) ON [PRIMARY]

How to close <img> tag properly?

Unfortunately the above solutions did not work in my case - maybe because a put the button inside a form-tag. This code ...

<input class="button" type="submit" value=" ">
    <img src="../assets/logo.png" alt="test" />
</input>

... always leads to error (with or without the closing slash of the img tag):

error  Parsing error: x-invalid-end-tag  vue/no-parsing-error

? 1 problem (1 error, 0 warnings)

A kind of workaround that did work was to define the image as background-image by means of css.

The html snippet describes the button only. The value attribute contains a single blank in order to suppress some browsers presenting unwanted default text.

<input class="button" type="submit" value=" " />

the CSS defines the button's background image:

.button {
  display: block;
  width: 6em;
  height: 6em;
  color: white;
  background-color: #639f59;
  padding: 0.4em 1.2em;
  box-shadow: inset 0 -0.6em 1em -0.35em rgba(5, 122, 11, 0.30),
    inset 0 0.6em 2em -0.3em rgba(255, 255, 255, 0.30),
    inset 0 0 0em 0.05em rgba(255, 255, 255, 0.30);
  cursor: pointer;
  background: url("../assets/logo.png") ;
  background-repeat: no-repeat;
  background-size: 6em;
  background-position: center;
  border: 0;
  border-radius: 3em;
}

What does \0 stand for?

In C \0 is a character literal constant store into an int data type that represent the character with value of 0.

Since Objective-C is a strict superset of C this constant is retained.

What are the recommendations for html <base> tag?

Also, you should remember that if you run your web server at non-standard port you need to include port number at base href too:

<base href="//localhost:1234" />  // from base url
<base href="../" />  // for one step above

How to get tf.exe (TFS command line client)?

There is a Java TFS client in the Team Explorer Everywhere installation (together with an Eclipse plugin). Look at http://www.microsoft.com/en-us/download/details.aspx?id=30661

How do I check for vowels in JavaScript?

benchmark

I think you can safely say a for loop is faster.

I do admit that a regexp looks cleaner in terms of code. If it's a real bottleneck then use a for loop, otherwise stick with the regular expression for reasons of "elegance"

If you want to go for simplicity then just use

function isVowel(c) {
    return ['a', 'e', 'i', 'o', 'u'].indexOf(c.toLowerCase()) !== -1
}

how to use free cloud database with android app?

As Wingman said, Google App Engine is a great solution for your scenario.

You can get some information about GAE+Android here: https://developers.google.com/eclipse/docs/appengine_connected_android

And from this Google IO 2012 session: http://www.youtube.com/watch?v=NU_wNR_UUn4

How to set Grid row and column positions programmatically

Try this:

                Grid grid = new Grid(); //Define the grid
                for (int i = 0; i < 36; i++) //Add 36 rows
                {
                    ColumnDefinition columna = new ColumnDefinition()
                    {
                        Name = "Col_" + i,
                        Width = new GridLength(32.5),
                    };
                    grid.ColumnDefinitions.Add(columna);
                }

                for (int i = 0; i < 36; i++) //Add 36 columns
                {
                    RowDefinition row = new RowDefinition();
                    row.Height = new GridLength(40, GridUnitType.Pixel);
                    grid.RowDefinitions.Add(row);
                }

                for (int i = 0; i < 36; i++)
                {
                    for (int j = 0; j < 36; j++)
                    {
                        Label t1 = new Label()
                        {
                            FontSize = 10,
                            FontFamily = new FontFamily("consolas"),
                            FontWeight = FontWeights.SemiBold,
                            BorderBrush = Brushes.LightGray,
                            BorderThickness = new Thickness(2),
                            HorizontalContentAlignment = HorizontalAlignment.Center,
                            VerticalContentAlignment = VerticalAlignment.Center,
                        };
                        Grid.SetRow(t1, i);
                        Grid.SetColumn(t1, j);
                        grid.Children.Add(t1); //Add the Label Control to the Grid created
                    }
                }

How to split a file into equal parts, without breaking individual lines?

split was updated in coreutils release 8.8 (announced 22 Dec 2010) with the --number option to generate a specific number of files. The option --number=l/n generates n files without splitting lines.

http://www.gnu.org/software/coreutils/manual/html_node/split-invocation.html#split-invocation http://savannah.gnu.org/forum/forum.php?forum_id=6662

javascript createElement(), style problem

yourElement.setAttribute("style", "background-color:red; font-size:2em;");

Or you could write the element as pure HTML and use .innerHTML = [raw html code]... that's very ugly though.

In answer to your first question, first you use var myElement = createElement(...);, then you do document.body.appendChild(myElement);.

Laravel blank white screen

Got this from the Laravel forums, but if you recently upgraded Laravel versions AND PHP versions AND are running nginx, make sure you have changed your nginx configuration file to reflect the new PHP version. For instance:

In your nginx site config file (here: /etc/nginx/sites-available), change

fastcgi_pass unix:/var/run/php5-fpm.sock;

to

fastcgi_pass unix:/var/run/php/php5.6-fpm.sock;

Split String into an array of String

String[] result = "hi i'm paul".split("\\s+"); to split across one or more cases.

Or you could take a look at Apache Common StringUtils. It has StringUtils.split(String str) method that splits string using white space as delimiter. It also has other useful utility methods

How do I get the latest version of my code?

try this code

cd /go/to/path
git pull origin master

html vertical align the text inside input type button

Use the <button> tag instead. <button> labels are vertically centered by default.

How do I rename a column in a database table using SQL?

In MySQL, the syntax is ALTER TABLE ... CHANGE:

ALTER TABLE <table_name> CHANGE <column_name> <new_column_name> <data_type> ...

Note that you can't just rename and leave the type and constraints as is; you must retype the data type and constraints after the new name of the column.

Select from table by knowing only date without time (ORACLE)

You could use the between function to get all records between 2010-08-03 00:00:00:000 AND 2010-08-03 23:59:59:000

How to toggle boolean state of react component?

You should use this.state.check instead of check.value here:

this.setState({check: !this.state.check})

But anyway it is bad practice to do it this way. Much better to move it to separate method and don't write callbacks directly in markup.

How to determine programmatically the current active profile using Spring boot

It doesn't matter is your app Boot or just raw Spring. There is just enough to inject org.springframework.core.env.Environment to your bean.

@Autowired
private Environment environment;
....

this.environment.getActiveProfiles();

How to list all properties of a PowerShell object

I like

 Get-WmiObject Win32_computersystem | format-custom *

That seems to expand everything.

There's also a show-object command in the PowerShellCookbook module that does it in a GUI. Jeffrey Snover, the PowerShell creator, uses it in his unplugged videos (recommended).

Although most often I use

Get-WmiObject Win32_computersystem | fl *

It avoids the .format.ps1xml file that defines a table or list view for the object type, if there are any. The format file may even define column headers that don't match any property names.

Open popup and refresh parent page on close popup

You can reach main page with parent command (parent is the window) after the step you can make everything...

    function funcx() {
        var result = confirm('bla bla bla.!');
        if(result)
            //parent.location.assign("http://localhost:58250/Ekocc/" + document.getElementById('hdnLink').value + "");
            parent.location.assign("http://blabla.com/" + document.getElementById('hdnLink').value + "");
    } 

ssl.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:749)

On CentOS Linux, Python3.6, I edited this file (make a backup copy first)

/usr/lib/python3.6/site-packages/certifi/cacert.pem

to the end of the file, I added my public certificate from my .pem file. you should be able to obtain the .pem file from your ssl certificate provider.

how to check if input field is empty

As javascript is dynamically typed, rather than using the .length property as above you can simply treat the input value as a boolean:

var input = $.trim($("#spa").val());

if (input) {
    // Do Stuff
}

You can also extract the logic out into functions, then by assigning a class and using the each() method the code is more dynamic if, for example, in the future you wanted to add another input you wouldn't need to change any code.

So rather than hard coding the function call into the input markup, you can give the inputs a class, in this example it's test, and use:

$(".test").each(function () {
    $(this).keyup(function () {
        $("#submit").prop("disabled", CheckInputs());
    });
});

which would then call the following and return a boolean value to assign to the disabled property:

function CheckInputs() {
    var valid = false;
    $(".test").each(function () {
        if (valid) { return valid; }
        valid = !$.trim($(this).val());
    });
    return valid;
}

You can see a working example of everything I've mentioned in this JSFiddle.

toBe(true) vs toBeTruthy() vs toBeTrue()

As you read through the examples below, just keep in mind this difference

true === true // true
"string" === true // false
1 === true // false
{} === true // false

But

Boolean("string") === true // true
Boolean(1) === true // true
Boolean({}) === true // true

1. expect(statement).toBe(true)

Assertion passes when the statement passed to expect() evaluates to true

expect(true).toBe(true) // pass
expect("123" === "123").toBe(true) // pass

In all other cases cases it would fail

expect("string").toBe(true) // fail
expect(1).toBe(true); // fail
expect({}).toBe(true) // fail

Even though all of these statements would evaluate to true when doing Boolean():

So you can think of it as 'strict' comparison

2. expect(statement).toBeTrue()

This one does exactly the same type of comparison as .toBe(true), but was introduced in Jasmine recently in version 3.5.0 on Sep 20, 2019

3. expect(statement).toBeTruthy()

toBeTruthy on the other hand, evaluates the output of the statement into boolean first and then does comparison

expect(false).toBeTruthy() // fail
expect(null).toBeTruthy() // fail
expect(undefined).toBeTruthy() // fail
expect(NaN).toBeTruthy() // fail
expect("").toBeTruthy() // fail
expect(0).toBeTruthy() // fail

And IN ALL OTHER CASES it would pass, for example

expect("string").toBeTruthy() // pass
expect(1).toBeTruthy() // pass
expect({}).toBeTruthy() // pass

Detect if HTML5 Video element is playing

Best approach:

function playPauseThisVideo(this_video_id) {

  var this_video = document.getElementById(this_video_id);

  if (this_video.paused) {

    console.log("VIDEO IS PAUSED");

  } else {

    console.log("VIDEO IS PLAYING");

  }

}

How to resize array in C++?

You can do smth like this for 1D arrays. Here we use int*& because we want our pointer to be changeable.

#include<algorithm> // for copy

void resize(int*& a, size_t& n)
{
   size_t new_n = 2 * n;
   int* new_a = new int[new_n];
   copy(a, a + n, new_a);
   delete[] a;
   a = new_a;
   n = new_n;
}

For 2D arrays:

#include<algorithm> // for copy

void resize(int**& a, size_t& n)
{
   size_t new_n = 2 * n, i = 0;
   int** new_a = new int* [new_n];
   for (i = 0; i != new_n; ++i)
       new_a[i] = new int[100];
   for (i = 0; i != n; ++i)
   {
       copy(a[i], a[i] + 100, new_a[i]);
       delete[] a[i];
   }
   delete[] a;
   a = new_a;
   n = new_n;
}

Invoking of 1D array:

void myfn(int*& a, size_t& n)
{
   // do smth
   resize(a, n);
}

Invoking of 2D array:

void myfn(int**& a, size_t& n)
{
   // do smth
   resize(a, n);
}
  


   

How to connect to remote Oracle DB with PL/SQL Developer?

The problem is not the TNS file, in PLSQL Developer, if you don't have the oracle installation, you need to provide the location of the OCI.DLL file.

In PLSQL DEV app go to Tools-Preferences-Oracle/connections-OCI Library.

In my case I put the next address C:\Oracle\InstantClient-win32-11.2.0.1.0\oci.dll.

If have Weblogic app installed, I didnt tried but if you want try to put the next location

C:\Oracle\Middleware\wlserver_10.3\server\adr.

HTTP GET in VB.NET

The easiest way is System.Net.WebClient.DownloadFile or DownloadString.

Javascript - validation, numbers only

Regular expressions are great, but why not just make sure it's a number before trying to do something with it?

function addemup() {
var n1 = document.getElementById("num1");
var n2 = document.getElementById("num2");
sum = Number(n1.value) + Number(n2.value);
    if(Number(sum)) {
        alert(sum);
        } else {
            alert("Numbers only, please!");
        };
    };

Setting table column width

Add colgroup after your table tag. Define width and number of column here. and add tbody tag. Put your tr inside of tbody.

<table>
    <colgroup>
       <col span="1" style="width: 30%;">
       <col span="1" style="width: 70%;">
    </colgroup>


    <tbody>
        <tr>
            <td>First column</td>
            <td>Second column</td>
        </tr>
    </tbody>
</table>