Programs & Examples On #Libpcap

Libpcap, a portable C/C++ library for network traffic capture. Unix-like systems implement pcap, whereas Windows use a port of libpcap - Winpcap. It is now developed by the same tcpdump.org group that develops tcpdump.

How do you make a LinearLayout scrollable?

<ScrollView 
      xmlns:android="http://schemas.android.com/apk/res/android"
      android:id="@+id/scroll" 
      android:layout_width="match_parent"
      android:layout_height="wrap_content">

      <LinearLayout 
            android:id="@+id/container"
            android:orientation="vertical" 
            android:layout_width="match_parent"
            android:layout_height="wrap_content">
      </LinearLayout>

 </ScrollView>

How to blur background images in Android

This is an easy way to blur Images Efficiently with Android's RenderScript that I found on this article

  1. Create a Class called BlurBuilder

    public class BlurBuilder {
      private static final float BITMAP_SCALE = 0.4f;
      private static final float BLUR_RADIUS = 7.5f;
    
      public static Bitmap blur(Context context, Bitmap image) {
        int width = Math.round(image.getWidth() * BITMAP_SCALE);
        int height = Math.round(image.getHeight() * BITMAP_SCALE);
    
        Bitmap inputBitmap = Bitmap.createScaledBitmap(image, width, height, false);
        Bitmap outputBitmap = Bitmap.createBitmap(inputBitmap);
    
        RenderScript rs = RenderScript.create(context);
        ScriptIntrinsicBlur theIntrinsic = ScriptIntrinsicBlur.create(rs, Element.U8_4(rs));
        Allocation tmpIn = Allocation.createFromBitmap(rs, inputBitmap);
        Allocation tmpOut = Allocation.createFromBitmap(rs, outputBitmap);
        theIntrinsic.setRadius(BLUR_RADIUS);
        theIntrinsic.setInput(tmpIn);
        theIntrinsic.forEach(tmpOut);
        tmpOut.copyTo(outputBitmap);
    
        return outputBitmap;
      }
    }
    
  2. Copy any image to your drawable folder

  3. Use BlurBuilder in your activity like this:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
                WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_login);
    
        mContainerView = (LinearLayout) findViewById(R.id.container);
        Bitmap originalBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.background);
        Bitmap blurredBitmap = BlurBuilder.blur( this, originalBitmap );
        mContainerView.setBackground(new BitmapDrawable(getResources(), blurredBitmap));
    
  4. Renderscript is included into support v8 enabling this answer down to api 8. To enable it using gradle include these lines into your gradle file (from this answer)

    defaultConfig {
        ...
        renderscriptTargetApi *your target api*
        renderscriptSupportModeEnabled true
    }
    
  5. Result

enter image description here

Zip folder in C#

There's an article over on MSDN that has a sample application for zipping and unzipping files and folders purely in C#. I've been using some of the classes in that successfully for a long time. The code is released under the Microsoft Permissive License, if you need to know that sort of thing.

EDIT: Thanks to Cheeso for pointing out that I'm a bit behind the times. The MSDN example I pointed to is in fact using DotNetZip and is really very fully-featured these days. Based on my experience of a previous version of this I'd happily recommend it.

SharpZipLib is also quite a mature library and is highly rated by people, and is available under the GPL license. It really depends on your zipping needs and how you view the license terms for each of them.

Rich

Python: Best way to add to sys.path relative to the current running script

You can run the script with python -m from the relevant root dir. And pass the "modules path" as argument.

Example: $ python -m module.sub_module.main # Notice there is no '.py' at the end.


Another example:

$ tree  # Given this file structure
.
+-- bar
¦   +-- __init__.py
¦   +-- mod.py
+-- foo
    +-- __init__.py
    +-- main.py

$ cat foo/main.py
from bar.mod import print1
print1()

$ cat bar/mod.py
def print1():
    print('In bar/mod.py')

$ python foo/main.py  # This gives an error
Traceback (most recent call last):
  File "foo/main.py", line 1, in <module>
    from bar.mod import print1
ImportError: No module named bar.mod

$ python -m foo.main  # But this succeeds
In bar/mod.py

Conditional Count on a field

I would need to display the jobid, jobname and 5 fields called Priority1, Priority2, Priority3, Priority4. Priority5.

Something's wrong with your query design. You're showing a specific job in each row as well, and so you'll either have a situation where ever row has four priority columns with a '0' and one priority column with a '1' (the priority for that job) or you'll end up repeating the count for all priorities on every row.

What do you really want to show here?

Is it possible to access to google translate api for free?

Yes, you can use GT for free. See the post with explanation. And look at repo on GitHub.

UPD 19.03.2019 Here is a version for browser on GitHub.

Error Dropping Database (Can't rmdir '.test\', errno: 17)

just go to data directory in my case path is "wamp\bin\mysql\mysql5.6.17\data" here you will see all databases folder just delete this your database folder the db will automatically drooped :)

CSS disable hover effect

I tried the following and it works for me better

Code:

.unstyled-link{ 
  color: inherit;
  text-decoration: inherit;
  &:link,
  &:hover {
    color: inherit;
    text-decoration: inherit;
  }
}

How do I make a <div> move up and down when I'm scrolling the page?

Just for a more animated and cute solution:

$(window).scroll(function(){
  $("#div").stop().animate({"marginTop": ($(window).scrollTop()) + "px", "marginLeft":($(window).scrollLeft()) + "px"}, "slow" );
});

And a pen for those who want to see: http://codepen.io/think123/full/mAxlb, and fork: http://codepen.io/think123/pen/mAxlb

Update: and a non-animated jQuery solution:

$(window).scroll(function(){
  $("#div").css({"margin-top": ($(window).scrollTop()) + "px", "margin-left":($(window).scrollLeft()) + "px"});
});

How to get first 5 characters from string

An alternative way to get only one character.

$str = 'abcdefghij';
echo $str{5};

I would particularly not use this, but for the purpose of education. We can use that to answer the question:

$newString = '';
for ($i = 0; $i < 5; $i++) {
    $newString .= $str{$i};
}
echo $newString;

For anyone using that. Bear in mind curly brace syntax for accessing array elements and string offsets is deprecated from PHP 7.4

More information: https://wiki.php.net/rfc/deprecate_curly_braces_array_access

c++ string array initialization

Prior to C++11, you cannot initialise an array using type[]. However the latest c++11 provides(unifies) the initialisation, so you can do it in this way:

string* pStr = new string[3] { "hi", "there"};

See http://www2.research.att.com/~bs/C++0xFAQ.html#uniform-init

how to open an URL in Swift3

I'm using macOS Sierra (v10.12.1) Xcode v8.1 Swift 3.0.1 and here's what worked for me in ViewController.swift:

//
//  ViewController.swift
//  UIWebViewExample
//
//  Created by Scott Maretick on 1/2/17.
//  Copyright © 2017 Scott Maretick. All rights reserved.
//

import UIKit
import WebKit

class ViewController: UIViewController {

    //added this code
    @IBOutlet weak var webView: UIWebView!

    override func viewDidLoad() {
        super.viewDidLoad()
        // Your webView code goes here
        let url = URL(string: "https://www.google.com")
        if UIApplication.shared.canOpenURL(url!) {
            UIApplication.shared.open(url!, options: [:], completionHandler: nil)
            //If you want handle the completion block than
            UIApplication.shared.open(url!, options: [:], completionHandler: { (success) in
                print("Open url : \(success)")
            })
        }
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


};

Rounding to 2 decimal places in SQL

Try this...

SELECT TO_CHAR(column_name,'99G999D99MI')
as format_column
FROM DUAL;

The intel x86 emulator accelerator (HAXM installer) revision 6.0.5 is showing not compatible with windows

You likely have Hyper-V enabled. The manual installer provides this detailed notice when it refuses to install on a Windows with it on.

This computer does not support Intel Virtualization Technology (VT-x) or it is being exclusively used by Hyper-V. HAXM cannot be installed. Please ensure Hyper-V is disabled in Windows Features, or refer to the Intel HAXM documentation for more information.

How to format LocalDate to string?

A pretty nice way to do this is to use SimpleDateFormat I'll show you how:

SimpleDateFormat sdf = new SimpleDateFormat("d MMMM YYYY");
Date d = new Date();
sdf.format(d);

I see that you have the date in a variable:

sdf.format(variable_name);

Cheers.

Where is database .bak file saved from SQL Server Management Studio?

If the backup wasn't created in the default location, you can use this T-SQL (run this in SSMS) to find the file path for the most recent backup for all DBs on your SQL Server instance:

SELECT  DatabaseName = x.database_name,
        LastBackupFileName = x.physical_device_name,
        LastBackupDatetime = x.backup_start_date
FROM (  SELECT  bs.database_name,
                bs.backup_start_date,
                bmf.physical_device_name,
                  Ordinal = ROW_NUMBER() OVER( PARTITION BY bs.database_name ORDER BY bs.backup_start_date DESC )
          FROM  msdb.dbo.backupmediafamily bmf
                  JOIN msdb.dbo.backupmediaset bms ON bmf.media_set_id = bms.media_set_id
                  JOIN msdb.dbo.backupset bs ON bms.media_set_id = bs.media_set_id
          WHERE   bs.[type] = 'D'
                  AND bs.is_copy_only = 0 ) x
WHERE x.Ordinal = 1
ORDER BY DatabaseName;

scatter plot in matplotlib

Maybe something like this:

import matplotlib.pyplot
import pylab

x = [1,2,3,4]
y = [3,4,8,6]

matplotlib.pyplot.scatter(x,y)

matplotlib.pyplot.show()

EDIT:

Let me see if I understand you correctly now:

You have:

       test1 | test2 | test3
test3 |   1   |   0  |  1

test4 |   0   |   1  |  0

test5 |   1   |   1  |  0

Now you want to represent the above values in in a scatter plot, such that value of 1 is represented by a dot.

Let's say you results are stored in a 2-D list:

results = [[1, 0, 1], [0, 1, 0], [1, 1, 0]]

We want to transform them into two variables so we are able to plot them.

And I believe this code will give you what you are looking for:

import matplotlib
import pylab


results = [[1, 0, 1], [0, 1, 0], [1, 1, 0]]

x = []
y = []

for ind_1, sublist in enumerate(results):
    for ind_2, ele in enumerate(sublist):
        if ele == 1:
            x.append(ind_1)
            y.append(ind_2)       


matplotlib.pyplot.scatter(x,y)

matplotlib.pyplot.show()

Notice that I do need to import pylab, and you would have play around with the axis labels. Also this feels like a work around, and there might be (probably is) a direct method to do this.

Ant if else condition?

The if attribute does not exist for <copy>. It should be applied to the <target>.

Below is an example of how you can use the depends attribute of a target and the if and unless attributes to control execution of dependent targets. Only one of the two should execute.

<target name="prepare-copy" description="copy file based on condition"
    depends="prepare-copy-true, prepare-copy-false">
</target>

<target name="prepare-copy-true" description="copy file based on condition"
    if="copy-condition">
    <echo>Get file based on condition being true</echo>
    <copy file="${some.dir}/true" todir="." />
</target>

<target name="prepare-copy-false" description="copy file based on false condition" 
    unless="copy-condition">
    <echo>Get file based on condition being false</echo>
    <copy file="${some.dir}/false" todir="." />
</target>

If you are using ANT 1.8+, then you can use property expansion and it will evaluate the value of the property to determine the boolean value. So, you could use if="${copy-condition}" instead of if="copy-condition".

In ANT 1.7.1 and earlier, you specify the name of the property. If the property is defined and has any value (even an empty string), then it will evaluate to true.

Numpy, multiply array with scalar

You can multiply numpy arrays by scalars and it just works.

>>> import numpy as np
>>> np.array([1, 2, 3]) * 2
array([2, 4, 6])
>>> np.array([[1, 2, 3], [4, 5, 6]]) * 2
array([[ 2,  4,  6],
       [ 8, 10, 12]])

This is also a very fast and efficient operation. With your example:

>>> a_1 = np.array([1.0, 2.0, 3.0])
>>> a_2 = np.array([[1., 2.], [3., 4.]])
>>> b = 2.0
>>> a_1 * b
array([2., 4., 6.])
>>> a_2 * b
array([[2., 4.],
       [6., 8.]])

#define macro for debug printing in C?

I would do something like

#ifdef DEBUG
#define debug_print(fmt, ...) fprintf(stderr, fmt, __VA_ARGS__)
#else
#define debug_print(fmt, ...) do {} while (0)
#endif

I think this is cleaner.

How can I open a link in a new window?

this solution also considered the case that url is empty and disabled(gray) the empty link.

_x000D_
_x000D_
$(function() {_x000D_
  changeAnchor();_x000D_
});_x000D_
_x000D_
function changeAnchor() {_x000D_
  $("a[name$='aWebsiteUrl']").each(function() { // you can write your selector here_x000D_
    $(this).css("background", "none");_x000D_
    $(this).css("font-weight", "normal");_x000D_
_x000D_
    var url = $(this).attr('href').trim();_x000D_
    if (url == " " || url == "") { //disable empty link_x000D_
      $(this).attr("class", "disabled");_x000D_
      $(this).attr("href", "javascript:void(0)");_x000D_
    } else {_x000D_
      $(this).attr("target", "_blank");// HERE set the non-empty links, open in new window_x000D_
    }_x000D_
  });_x000D_
}
_x000D_
a.disabled {_x000D_
  text-decoration: none;_x000D_
  pointer-events: none;_x000D_
  cursor: default;_x000D_
  color: grey;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>_x000D_
<a name="aWebsiteUrl" href="http://www.baidu.com" class='#'>[website]</a>_x000D_
<a name="aWebsiteUrl" href=" " class='#'>[website]</a>_x000D_
<a name="aWebsiteUrl" href="http://www.alibaba.com" class='#'>[website]</a>_x000D_
<a name="aWebsiteUrl" href="http://www.qq.com" class='#'>[website]</a>
_x000D_
_x000D_
_x000D_

z-index not working with fixed positioning

This question can be solved in a number of ways, but really, knowing the stacking rules allows you to find the best answer that works for you.

Solutions

The <html> element is your only stacking context, so just follow the stacking rules inside a stacking context and you will see that elements are stacked in this order

  1. The stacking context’s root element (the <html> element in this case)
  2. Positioned elements (and their children) with negative z-index values (higher values are stacked in front of lower values; elements with the same value are stacked according to appearance in the HTML)
  3. Non-positioned elements (ordered by appearance in the HTML)
  4. Positioned elements (and their children) with a z-index value of auto (ordered by appearance in the HTML)
  5. Positioned elements (and their children) with positive z-index values (higher values are stacked in front of lower values; elements with the same value are stacked according to appearance in the HTML)

So you can

  1. set a z-index of -1, for #under positioned -ve z-index appear behind non-positioned #over element
  2. set the position of #over to relative so that rule 5 applies to it

The Real Problem

Developers should know the following before trying to change the stacking order of elements.

  1. When a stacking context is formed
    • By default, the <html> element is the root element and is the first stacking context
  2. Stacking order within a stacking context

The Stacking order and stacking context rules below are from this link

When a stacking context is formed

  • When an element is the root element of a document (the <html> element)
  • When an element has a position value other than static and a z-index value other than auto
  • When an element has an opacity value less than 1
  • Several newer CSS properties also create stacking contexts. These include: transforms, filters, css-regions, paged media, and possibly others. https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Positioning/Understanding_z_index/The_stacking_context
  • As a general rule, it seems that if a CSS property requires rendering in an offscreen context, it must create a new stacking context.

Stacking Order within a Stacking Context

The order of elements:

  1. The stacking context’s root element (the <html> element is the only stacking context by default, but any element can be a root element for a stacking context, see rules above)
    • You cannot put a child element behind a root stacking context element
  2. Positioned elements (and their children) with negative z-index values (higher values are stacked in front of lower values; elements with the same value are stacked according to appearance in the HTML)
  3. Non-positioned elements (ordered by appearance in the HTML)
  4. Positioned elements (and their children) with a z-index value of auto (ordered by appearance in the HTML)
  5. Positioned elements (and their children) with positive z-index values (higher values are stacked in front of lower values; elements with the same value are stacked according to appearance in the HTML)

What's the idiomatic syntax for prepending to a short python list?

In my opinion, the most elegant and idiomatic way of prepending an element or list to another list, in Python, is using the expansion operator * (also called unpacking operator),

# Initial list
l = [4, 5, 6]

# Modification
l = [1, 2, 3, *l]

Where the resulting list after the modification is [1, 2, 3, 4, 5, 6]

I also like simply combining two lists with the operator +, as shown,

# Prepends [1, 2, 3] to l
l = [1, 2, 3] + l

# Prepends element 42 to l
l = [42] + l

I don't like the other common approach, l.insert(0, value), as it requires a magic number. Moreover, insert() only allows prepending a single element, however the approach above has the same syntax for prepending a single element or multiple elements.

Android: Difference between onInterceptTouchEvent and dispatchTouchEvent?

The main difference :

•Activity.dispatchTouchEvent(MotionEvent) - This allows your Activity to intercept all touch events before they are dispatched to the window.
•ViewGroup.onInterceptTouchEvent(MotionEvent) - This allows a ViewGroup to watch events as they are dispatched to child Views.

Looping from 1 to infinity in Python

Using itertools.count:

import itertools
for i in itertools.count(start=1):
    if there_is_a_reason_to_break(i):
        break

In Python 2, range() and xrange() were limited to sys.maxsize. In Python 3 range() can go much higher, though not to infinity:

import sys
for i in range(sys.maxsize**10):  # you could go even higher if you really want
    if there_is_a_reason_to_break(i):
        break

So it's probably best to use count().

How to export DataTable to Excel

Purely sample code (in case it might help someone with some ideas), based on Tomasz Wisniewski answer from here: https://stackoverflow.com/a/21079709/2717521

MainWindow ExportButton:

public int counter;

public void SaveToExcel(object sender, RoutedEventArgs e)
{
    counter = 1;
    CountChecker();
}

public void CountChecker()
{
    string filename = GlobalStrings.building_house_address;
    string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\";


    if (CurrentID != 0)
    {
        if (!File.Exists(path + filename + ".xlsx"))
        {
            DataGridParts.Export(path + filename);
            MessageBoxEx.Show(this, "Shranjeno na namizje");
        }
        else
        {
            if (!File.Exists(path + "\\" + filename + " (" + (counter) + ")" + ".xlsx"))
            {
                DataGridParts.Export(path + filename + " (" + (counter) + ")");
                MessageBoxEx.Show(this, "Shranjeno na namizje");
            }
            else
            {
                counter++;
                CountChecker();
            }
        }
    }
    else
    {
        MessageBoxEx.Show(this, "Izbran ni noben naslov!");
    }
}

ExportToExcel Class:

using Microsoft.Office.Interop.Excel;
using System.Runtime.InteropServices;

namespace CBUGIS
{
    public static class ExportToExcel
    {
        /// <summary>
        /// Export DataTable to Excel file
        /// </summary>
        /// <param name="DataTable">Source DataTable</param>
        /// <param name="ExcelFilePath">Path to result file name</param>
        public static void Export(this System.Data.DataTable DataTable, string ExcelFilePath = null)
        {
            int ColumnsCount;
            int RowShift = 5;

            ColumnsCount = DataTable.Columns.Count;

            // load excel, and create a new workbook
            Application Excel = new Application();
            Excel.Workbooks.Add();

            // single worksheet
            _Worksheet Worksheet = Excel.ActiveSheet;
            Excel.Sheets[1].Name = "CBUGIS";

            Worksheet.Columns.NumberFormat = "@";
            Worksheet.Columns.HorizontalAlignment = XlHAlign.xlHAlignLeft;

            object[,] Title = new object[3, 1]; // Array Size

            if (GlobalStrings.building_alterantive_addresses.Length == 0)
            {
                if (GlobalStrings.building_postcode.Length != 0)
                {
                    Title[0, 0] = "NASLOV: " + GlobalStrings.building_house_street + " " + GlobalStrings.building_house_number + GlobalStrings.building_house_id + ", " + GlobalStrings.building_postcode + " " + GlobalStrings.building_area;
                    Title[1, 0] = "K.O.: " + GlobalStrings.building_cadastral_community + ", ŠT.STAVBE: " + GlobalStrings.building_building_number + ", ŠT.PARCELE: " + GlobalStrings.building_plot_number;
                }
                else
                {
                    Title[0, 0] = "NASLOV: " + GlobalStrings.building_house_street + " " + GlobalStrings.building_house_number + GlobalStrings.building_house_id;
                    Title[1, 0] = "K.O.: " + GlobalStrings.building_cadastral_community + ", ŠT.STAVBE: " + GlobalStrings.building_building_number + ", " + GlobalStrings.building_plot_number;
                }
            }
            else
            {
                if (GlobalStrings.building_postcode.Length != 0)
                {
                    Title[0, 0] = "NASLOV: " + GlobalStrings.building_house_street + " " + GlobalStrings.building_house_number + GlobalStrings.building_house_id + ", " + GlobalStrings.building_postcode + " " + GlobalStrings.building_area;
                    Title[1, 0] = "K.O.: " + GlobalStrings.building_cadastral_community + ", ŠT.STAVBE: " + GlobalStrings.building_building_number + ", ŠT.PARCELE: " + GlobalStrings.building_plot_number;
                    Title[2, 0] = "GLEJ TUDI: " + GlobalStrings.building_alterantive_addresses;
                }
                else
                {
                    Title[0, 0] = "NASLOV: " + GlobalStrings.building_house_street + " " + GlobalStrings.building_house_number + GlobalStrings.building_house_id;
                    Title[1, 0] = "K.O.: " + GlobalStrings.building_cadastral_community + ", ŠT.STAVBE: " + GlobalStrings.building_building_number + ", ŠT.PARCELE: " + GlobalStrings.building_plot_number;
                    Title[2, 0] = "GLEJ TUDI: " + GlobalStrings.building_alterantive_addresses;
                }
            }

            Range TitleRange = Worksheet.get_Range((Range)(Worksheet.Cells[3, 1]), (Range)(Worksheet.Cells[1, 1]));
            TitleRange.Value = Title;
            TitleRange.Font.Bold = true;
            TitleRange.Font.Size = 10;


            object[] Header = new object[11]; // Number of Columns

            Header[0] = "DEL";
            Header[1] = "DELEŽ";
            Header[2] = "CRP";
            Header[3] = "LASTNIK";
            Header[4] = "NASLOV";
            Header[5] = "P.Š";
            Header[6] = "OBMOCJE";
            Header[7] = "DRŽAVA";
            Header[8] = "EMŠO/MAT. ŠT.";
            Header[9] = "OPIS";
            Header[10] = "OPOMBA";

            Range HeaderRange = Worksheet.get_Range((Range)(Worksheet.Cells[RowShift, 2]), (Range)(Worksheet.Cells[RowShift, 12]));
            HeaderRange.Value = Header;
            HeaderRange.Font.Bold = true;
            HeaderRange.Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.LightGray);

            // DataCells
            int RowsCount = DataTable.Rows.Count;

            object[,] Cells = new object[RowsCount, ColumnsCount];

            for (int j = 0; j < RowsCount; j++)
                for (int i = 0; i < ColumnsCount - 1; i++)
                    if (i > 1)
                    {
                        Cells[j, i - 2] = DataTable.Rows[j][i];
                    }

            Range CellRange = Worksheet.get_Range((Range)(Worksheet.Cells[RowShift +1, 2]), (Range)(Worksheet.Cells[RowShift + RowsCount, 12]));
            CellRange.Value = Cells;
            CellRange.Borders.LineStyle = XlLineStyle.xlContinuous;

            Worksheet.Columns.NumberFormat = "@";
            Worksheet.Columns[1].ColumnWidth = 0.1;
            for (int b = 1; b < 12; b++)
            {
                if (b > 1)
                {
                    Worksheet.Columns[b].AutoFit();
                }
            }

            Worksheet.PageSetup.Orientation = XlPageOrientation.xlLandscape;
            Worksheet.PageSetup.TopMargin = 0.5;
            Worksheet.PageSetup.BottomMargin = 0.5;
            Worksheet.PageSetup.RightMargin = 0.5;
            Worksheet.PageSetup.LeftMargin = 0.5;

            // check fielpath
            if (ExcelFilePath != null && ExcelFilePath != "")
            {
                Worksheet.SaveAs(ExcelFilePath);
                Excel.Quit();
                Marshal.FinalReleaseComObject(Worksheet);
                Marshal.FinalReleaseComObject(TitleRange);
                Marshal.FinalReleaseComObject(HeaderRange);
                Marshal.FinalReleaseComObject(CellRange);
                Marshal.FinalReleaseComObject(Excel);
            }
            else

            // no filepath is given
            {
                Excel.Visible = true;
            }      
        }
    }
}

CSS centred header image

If you set the margin to be margin:0 auto the image will be centered.

This will give top + bottom a margin of 0, and left and right a margin of 'auto'. Since the div has a width (200px), the image will be 200px wide and the browser will auto set the left and right margin to half of what is left on the page, which will result in the image being centered.

mysql-python install error: Cannot open include file 'config-win.h'

you can try to install another package:

pip install mysql-connector-python

This package worked fine for me and I got no issues to install.

How to cast an Object to an int

Refer This code:

public class sample 
{
  public static void main(String[] args) 
  {
    Object obj=new Object();
    int a=10,b=0;
    obj=a;
    b=(int)obj;

    System.out.println("Object="+obj+"\nB="+b);
  }
}

JavaScript: Parsing a string Boolean value?

I would be inclined to do a one liner with a ternary if.

var bool_value = value == "true" ? true : false

Edit: Even quicker would be to simply avoid using the a logical statement and instead just use the expression itself:

var bool_value = value == 'true';

This works because value == 'true' is evaluated based on whether the value variable is a string of 'true'. If it is, that whole expression becomes true and if not, it becomes false, then that result gets assigned to bool_value after evaluation.

How to print third column to last column?

awk '{a=match($0, $3); print substr($0,a)}'

First you find the position of the start of the third column. With substr you will print the whole line ($0) starting at the position(in this case a) to the end of the line.

Bootstrap 3 navbar active li not changing background-color

Did you include "bootstrap-theme.css" files on your code?

In "bootstrap-theme.min.css" files, background-image about ".active" is existed for "navbar" (check this screenshot: http://i.imgur.com/1etLIyY.png).

It will re-declare your style code, and then it will be effected on your code.

So after you delete or re-declare them (background-image), you can use your background color style about the ".active" tag.

Getting a HeadlessException: No X11 DISPLAY variable was set

This appears to be a more general SWING/AWT/JDK problem that just the JBOSS installer:

The accepted answer below solved the issue for me :

Unable to run java gui programs with ubuntu

("sudo apt-get install openjdk-6-jdk")

How to make flutter app responsive according to different screen size?

An Another approach :) easier for flutter web

class SampleView extends StatelessWidget {
@override
Widget build(BuildContext context) {
 return Center(
  child: Container(
    width: 200,
    height: 200,
    color: Responsive().getResponsiveValue(
        forLargeScreen: Colors.red,
        forMediumScreen: Colors.green,
        forShortScreen: Colors.yellow,
        forMobLandScapeMode: Colors.blue,
        context: context),
    // You dodn't need to provide the values for every 
    //parameter(except shortScreen & context)
    // but default its provide the value as ShortScreen for Larger and 
    //mediumScreen
    ),
   );
 }
}



 // utility 
          class Responsive {
            // function reponsible for providing value according to screensize
            getResponsiveValue(
                {dynamic forShortScreen,
                dynamic forMediumScreen,
                dynamic forLargeScreen,
                dynamic forMobLandScapeMode,
                BuildContext context}) {

              if (isLargeScreen(context)) {

                return forLargeScreen ?? forShortScreen;
              } else if (isMediumScreen(context)) {

                return forMediumScreen ?? forShortScreen;
              } 
           else if (isSmallScreen(context) && isLandScapeMode(context)) {

                return forMobLandScapeMode ?? forShortScreen;
              } else {
                return forShortScreen;
              }
            }
          
            isLandScapeMode(BuildContext context) {
              if (MediaQuery.of(context).orientation == Orientation.landscape) {
                return true;
              } else {
                return false;
              }
            }
          
            static bool isLargeScreen(BuildContext context) {
              return getWidth(context) > 1200;
            }
          
            static bool isSmallScreen(BuildContext context) {
              return getWidth(context) < 800;
            }
          
            static bool isMediumScreen(BuildContext context) {
              return getWidth(context) > 800 && getWidth(context) < 1200;
            }
          
            static double getWidth(BuildContext context) {
              return MediaQuery.of(context).size.width;
            }
          }

CSS 3 slide-in from left transition

You can use CSS3 transitions or maybe CSS3 animations to slide in an element.

For browser support: http://caniuse.com/

I made two quick examples just to show you how I mean.

CSS transition (on hover)

Demo One

Relevant Code

.wrapper:hover #slide {
    transition: 1s;
    left: 0;
}

In this case, Im just transitioning the position from left: -100px; to 0; with a 1s. duration. It's also possible to move the element using transform: translate();

CSS animation

Demo Two

#slide {
    position: absolute;
    left: -100px;
    width: 100px;
    height: 100px;
    background: blue;
    -webkit-animation: slide 0.5s forwards;
    -webkit-animation-delay: 2s;
    animation: slide 0.5s forwards;
    animation-delay: 2s;
}

@-webkit-keyframes slide {
    100% { left: 0; }
}

@keyframes slide {
    100% { left: 0; }
}

Same principle as above (Demo One), but the animation starts automatically after 2s, and in this case I've set animation-fill-mode to forwards, which will persist the end state, keeping the div visible when the animation ends.

Like I said, two quick example to show you how it could be done.

EDIT: For details regarding CSS Animations and Transitions see:

Animations

https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Using_CSS_animations

Transitions

https://developer.mozilla.org/en-US/docs/Web/Guide/CSS/Using_CSS_transitions

Hope this helped.

HTML inside Twitter Bootstrap popover

This is a slight modification on Jack's excellent answer.

The following makes sure simple popovers, without HTML content, remain unaffected.

JavaScript:

$(function(){
    $('[data-toggle=popover]:not([data-popover-content])').popover();
    $('[data-toggle=popover][data-popover-content]').popover({
        html : true,
        content: function() {
          var content = $(this).attr("data-popover-content");
          return $(content).children(".popover-body").html();
        },
        title: function() {
          var title = $(this).attr("data-popover-content");
          return $(title).children(".popover-heading").html();
        }
    });
});

Enforcing the type of the indexed members of a Typescript object?

A quick update: since Typescript 2.1 there is a built in type Record<T, K> that acts like a dictionary.

In this case you could declare stuff like so:

var stuff: Record<string, any> = {};

You could also limit/specify potential keys by unioning literal types:

var stuff: Record<'a'|'b'|'c', string|boolean> = {};

Here's a more generic example using the record type from the docs:

// For every properties K of type T, transform it to U
function mapObject<K extends string, T, U>(obj: Record<K, T>, f: (x: T) => U): Record<K, U>

const names = { foo: "hello", bar: "world", baz: "bye" };
const lengths = mapObject(names, s => s.length);  // { foo: number, bar: number, baz: number }

TypeScript 2.1 Documentation on Record<T, K>

The only disadvantage I see to using this over {[key: T]: K} is that you can encode useful info on what sort of key you are using in place of "key" e.g. if your object only had prime keys you could hint at that like so: {[prime: number]: yourType}.

Here's a regex I wrote to help with these conversions. This will only convert cases where the label is "key". To convert other labels simply change the first capturing group:

Find: \{\s*\[(key)\s*(+\s*:\s*(\w+)\s*\]\s*:\s*([^\}]+?)\s*;?\s*\}

Replace: Record<$2, $3>

How to convert numbers to alphabet?

If you have a number, for example 65, and if you want to get the corresponding ASCII character, you can use the chr function, like this

>>> chr(65)
'A'

similarly if you have 97,

>>> chr(97)
'a'

EDIT: The above solution works for 8 bit characters or ASCII characters. If you are dealing with unicode characters, you have to specify unicode value of the starting character of the alphabet to ord and the result has to be converted using unichr instead of chr.

>>> print unichr(ord(u'\u0B85'))
?

>>> print unichr(1 + ord(u'\u0B85'))
?

NOTE: The unicode characters used here are of the language called "Tamil", my first language. This is the unicode table for the same http://www.unicode.org/charts/PDF/U0B80.pdf

Remove privileges from MySQL database

The USAGE-privilege in mysql simply means that there are no privileges for the user 'phpadmin'@'localhost' defined on global level *.*. Additionally the same user has ALL-privilege on database phpmyadmin phpadmin.*.

So if you want to remove all the privileges and start totally from scratch do the following:

  • Revoke all privileges on database level:

    REVOKE ALL PRIVILEGES ON phpmyadmin.* FROM 'phpmyadmin'@'localhost';

  • Drop the user 'phpmyadmin'@'localhost'

    DROP USER 'phpmyadmin'@'localhost';

Above procedure will entirely remove the user from your instance, this means you can recreate him from scratch.

To give you a bit background on what described above: as soon as you create a user the mysql.user table will be populated. If you look on a record in it, you will see the user and all privileges set to 'N'. If you do a show grants for 'phpmyadmin'@'localhost'; you will see, the allready familliar, output above. Simply translated to "no privileges on global level for the user". Now your grant ALL to this user on database level, this will be stored in the table mysql.db. If you do a SELECT * FROM mysql.db WHERE db = 'nameofdb'; you will see a 'Y' on every priv.

Above described shows the scenario you have on your db at the present. So having a user that only has USAGE privilege means, that this user can connect, but besides of SHOW GLOBAL VARIABLES; SHOW GLOBAL STATUS; he has no other privileges.

Detect element content changes with jQuery

I wrote a snippet that will check for the change of an element on an event.

So if you are using third party javascript code or something and you need to know when something appears or changes when you have clicked then you can.

For the below snippet, lets say you need to know when a table content changes after you clicked a button.

$('.button').live('click', function() {

            var tableHtml = $('#table > tbody').html();
            var timeout = window.setInterval(function(){

                if (tableHtml != $('#table > tbody').
                    console.log('no change');
                } else {
                    console.log('table changed!');
                    clearInterval(timeout);
                }

            }, 10);
        });

Pseudo Code:

  • Once you click a button
  • the html of the element you are expecting to change is captured
  • we then continually check the html of the element
  • when we find the html to be different we stop the checking

Find the line number where a specific word appears with "grep"

You can call tail +[line number] [file] and pipe it to grep -n which shows the line number:

tail +[line number] [file] | grep -n /regex/

The only problem with this method is the line numbers reported by grep -n will be [line number] - 1 less than the actual line number in [file].

What's the difference between passing by reference vs. passing by value?

It's a way how to pass arguments to functions. Passing by reference means the called functions' parameter will be the same as the callers' passed argument (not the value, but the identity - the variable itself). Pass by value means the called functions' parameter will be a copy of the callers' passed argument. The value will be the same, but the identity - the variable - is different. Thus changes to a parameter done by the called function in one case changes the argument passed and in the other case just changes the value of the parameter in the called function (which is only a copy). In a quick hurry:

  • Java only supports pass by value. Always copies arguments, even though when copying a reference to an object, the parameter in the called function will point to the same object and changes to that object will be see in the caller. Since this can be confusing, here is what Jon Skeet has to say about this.
  • C# supports pass by value and pass by reference (keyword ref used at caller and called function). Jon Skeet also has a nice explanation of this here.
  • C++ supports pass by value and pass by reference (reference parameter type used at called function). You will find an explanation of this below.

Codes

Since my language is C++, i will use that here

// passes a pointer (called reference in java) to an integer
void call_by_value(int *p) { // :1
    p = NULL;
}

// passes an integer
void call_by_value(int p) { // :2
    p = 42;
}

// passes an integer by reference
void call_by_reference(int & p) { // :3
    p = 42;
}

// this is the java style of passing references. NULL is called "null" there.
void call_by_value_special(int *p) { // :4
    *p = 10; // changes what p points to ("what p references" in java)
    // only changes the value of the parameter, but *not* of 
    // the argument passed by the caller. thus it's pass-by-value:
    p = NULL;
}

int main() {
    int value = 10;
    int * pointer = &value;

    call_by_value(pointer); // :1
    assert(pointer == &value); // pointer was copied

    call_by_value(value); // :2
    assert(value == 10); // value was copied

    call_by_reference(value); // :3
    assert(value == 42); // value was passed by reference

    call_by_value_special(pointer); // :4
    // pointer was copied but what pointer references was changed.
    assert(value == 10 && pointer == &value);
}

And an example in Java won't hurt:

class Example {
    int value = 0;

    // similar to :4 case in the c++ example
    static void accept_reference(Example e) { // :1
        e.value++; // will change the referenced object
        e = null; // will only change the parameter
    }

    // similar to the :2 case in the c++ example
    static void accept_primitive(int v) { // :2
        v++; // will only change the parameter
    }        

    public static void main(String... args) {
        int value = 0;
        Example ref = new Example(); // reference

        // note what we pass is the reference, not the object. we can't 
        // pass objects. The reference is copied (pass-by-value).
        accept_reference(ref); // :1
        assert ref != null && ref.value == 1;

        // the primitive int variable is copied
        accept_primitive(value); // :2
        assert value == 0;
    }
}

Wikipedia

http://en.wikipedia.org/wiki/Pass_by_reference#Call_by_value

http://en.wikipedia.org/wiki/Pass_by_reference#Call_by_reference

This guy pretty much nails it:

http://javadude.com/articles/passbyvalue.htm

How to get a value of an element by name instead of ID

Use the name attribute selector:

$("input[name='nameGoesHere']").val();

It is a mandatory requirement to include quotes around the value, see: http://api.jquery.com/attribute-equals-selector/

Get-WmiObject : The RPC server is unavailable. (Exception from HRESULT: 0x800706BA)

I was doing this mistake

ForEach ($server in $servers) {
$OS = Get-WmiObject win32_operatingsystem -ComputerName $server
}

Which, of course, couldn't be passed, because output of the server in a csv file was @{Name=hv1g.contoso.com}

I had to call the property from csv file like this $server.Name

ForEach ($server in $servers) {
$OS = Get-WmiObject win32_operatingsystem -ComputerName $server.Name
}

It fixed my issue.

How to overwrite existing files in batch?

If the copy command is run from within a batch job you do not need to use the /Y switch: it will overwrite existing files.

How to get UTF-8 working in Java webapps?

Faced the same issue on Spring MVC 5 + Tomcat 9 + JSP.
After the long research, came to an elegant solution (no need filters and no need changes in the Tomcat server.xml (starting from 8.0.0-RC3 version))

  1. In the WebMvcConfigurer implementation set default encoding for messageSource (for reading data from messages source files in the UTF-8 encoding.

    @Configuration
    @EnableWebMvc
    @ComponentScan("{package.with.components}")
    public class WebApplicationContextConfig implements WebMvcConfigurer {
    
        @Bean
        public MessageSource messageSource() {
            final ResourceBundleMessageSource messageSource = new ResourceBundleMessageSource();
    
            messageSource.setBasenames("messages");
            messageSource.setDefaultEncoding("UTF-8");
    
            return messageSource;
        }
    
        /* other beans and methods */
    
    }
    
  2. In the DispatcherServletInitializer implementation @Override the onStartup method and set request and resource character encoding in it.

    public class DispatcherServletInitializer extends AbstractAnnotationConfigDispatcherServletInitializer {
    
        @Override
        public void onStartup(final ServletContext servletContext) throws ServletException {
    
            // https://wiki.apache.org/tomcat/FAQ/CharacterEncoding
            servletContext.setRequestCharacterEncoding("UTF-8");
            servletContext.setResponseCharacterEncoding("UTF-8");
    
            super.onStartup(servletContext);
        }
    
        /* servlet mappings, root and web application configs, other methods */
    
    }
    
  3. Save all message source and view files in UTF-8 encoding.

  4. Add <%@ page contentType="text/html;charset=UTF-8" %> or <%@ page pageEncoding="UTF-8" %> in each *.jsp file or add jsp-config descriptor to web.xml

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee"
     xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
     id="WebApp_ID" version="3.0">
        <display-name>AppName</display-name>
    
        <jsp-config>
            <jsp-property-group>
                <url-pattern>*.jsp</url-pattern>
                <page-encoding>UTF-8</page-encoding>
            </jsp-property-group>
        </jsp-config>
    </web-app>
    

How to clone ArrayList and also clone its contents?

I have used this option always:

ArrayList<Dog> clonedList = new ArrayList<Dog>(name_of_arraylist_that_you_need_to_Clone);

Responsive Image full screen and centered - maintain aspect ratio, not exceed window

To center it, you can use the technique shown here: Absolute centering.

To make it as big as possible, give it max-width and max-height of 100%.

To maintain the aspect ratio (even when the width is specifically set like in the snippet below), use object-fit as explained here.

_x000D_
_x000D_
.className {
    max-width: 100%;
    max-height: 100%;
    bottom: 0;
    left: 0;
    margin: auto;
    overflow: auto;
    position: fixed;
    right: 0;
    top: 0;
    -o-object-fit: contain;
    object-fit: contain;
}
_x000D_
<img src="https://i.imgur.com/HmezgW6.png" class="className" />

<!-- Slider to control the image width, only to make demo clearer !-->
<input type="range" min="10" max="2000" value="276" step="10" oninput="document.querySelector('img').style.width = (this.value +'px')" style="width: 90%; position: absolute; z-index: 2;" >
_x000D_
_x000D_
_x000D_

Difference between a Seq and a List in Scala

In Java terms, Scala's Seq would be Java's List, and Scala's List would be Java's LinkedList.

Note that Seq is a trait, which is equivalent to Java's interface, but with the equivalent of up-and-coming defender methods. Scala's List is an abstract class that is extended by Nil and ::, which are the concrete implementations of List.

So, where Java's List is an interface, Scala's List is an implementation.

Beyond that, Scala's List is immutable, which is not the case of LinkedList. In fact, Java has no equivalent to immutable collections (the read only thing only guarantees the new object cannot be changed, but you still can change the old one, and, therefore, the "read only" one).

Scala's List is highly optimized by compiler and libraries, and it's a fundamental data type in functional programming. However, it has limitations and it's inadequate for parallel programming. These days, Vector is a better choice than List, but habit is hard to break.

Seq is a good generalization for sequences, so if you program to interfaces, you should use that. Note that there are actually three of them: collection.Seq, collection.mutable.Seq and collection.immutable.Seq, and it is the latter one that is the "default" imported into scope.

There's also GenSeq and ParSeq. The latter methods run in parallel where possible, while the former is parent to both Seq and ParSeq, being a suitable generalization for when parallelism of a code doesn't matter. They are both relatively newly introduced, so people doesn't use them much yet.

How do I set specific environment variables when debugging in Visual Studio?

As environments are inherited from the parent process, you could write an add-in for Visual Studio that modifies its environment variables before you perform the start. I am not sure how easy that would be to put into your process.

Check string for palindrome

import java.io.*;
import java.util.*;

public class Solution {

    public static void main(String[] args) {

        Scanner sc=new Scanner(System.in);
        String A=sc.next();
        char[] array = A.toCharArray();
        String str = "";
        for(int i=A.length()-1;i>=0;i--){
            str = str + array[i];
        }
        if(A.equalsIgnoreCase(str))System.out.println("Yes");
        else System.out.println("No");
    }
}

How to create a hidden <img> in JavaScript?

Try setting the style to display=none:

<img src="a.gif" style="display:none">

Python function attributes - uses and abuses

I've used them as static variables for a function. For example, given the following C code:

int fn(int i)
{
    static f = 1;
    f += i;
    return f;
}

I can implement the function similarly in Python:

def fn(i):
    fn.f += i
    return fn.f
fn.f = 1

This would definitely fall into the "abuses" end of the spectrum.

Regex: Use start of line/end of line signs (^ or $) in different context

You can't use ^ and $ in character classes in the way you wish - they will be interpreted literally, but you can use an alternation to achieve the same effect:

(^|,)garp(,|$)

How to delete items from a dictionary while iterating over it?

With python3, iterate on dic.keys() will raise the dictionary size error. You can use this alternative way:

Tested with python3, it works fine and the Error "dictionary changed size during iteration" is not raised:

my_dic = { 1:10, 2:20, 3:30 }
# Is important here to cast because ".keys()" method returns a dict_keys object.
key_list = list( my_dic.keys() )

# Iterate on the list:
for k in key_list:
    print(key_list)
    print(my_dic)
    del( my_dic[k] )


print( my_dic )
# {}

Can an angular directive pass arguments to functions in expressions specified in the directive's attributes?

In directive (myDirective):

...
directive.scope = {  
    boundFunction: '&',
    model: '=',
};
...
return directive;

In directive template:

<div 
data-ng-repeat="item in model"  
data-ng-click='boundFunction({param: item})'>
{{item.myValue}}
</div>

In source:

<my-directive 
model='myData' 
bound-function='myFunction(param)'>
</my-directive>

...where myFunction is defined in the controller.

Note that param in the directive template binds neatly to param in the source, and is set to item.


To call from within the link property of a directive ("inside" of it), use a very similar approach:

...
directive.link = function(isolatedScope) {
    isolatedScope.boundFunction({param: "foo"});
};
...
return directive;

Set windows environment variables with a batch file

@ECHO OFF

:: %HOMEDRIVE% = C:
:: %HOMEPATH% = \Users\Ruben
:: %system32% ??
:: No spaces in paths
:: Program Files > ProgramFiles
:: cls = clear screen
:: CMD reads the system environment variables when it starts. To re-read those variables you need to restart CMD
:: Use console 2 http://sourceforge.net/projects/console/


:: Assign all Path variables
SET PHP="%HOMEDRIVE%\wamp\bin\php\php5.4.16"
SET SYSTEM32=";%HOMEDRIVE%\Windows\System32"
SET ANT=";%HOMEDRIVE%%HOMEPATH%\Downloads\apache-ant-1.9.0-bin\apache-ant-1.9.0\bin"
SET GRADLE=";%HOMEDRIVE%\tools\gradle-1.6\bin;"
SET ADT=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\eclipse\jre\bin"
SET ADTTOOLS=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\sdk\tools"
SET ADTP=";%HOMEDRIVE%\tools\adt-bundle-windows-x86-20130219\sdk\platform-tools"
SET YII=";%HOMEDRIVE%\wamp\www\yii\framework"
SET NODEJS=";%HOMEDRIVE%\ProgramFiles\nodejs"
SET CURL=";%HOMEDRIVE%\tools\curl_734_0_ssl"
SET COMPOSER=";%HOMEDRIVE%\ProgramData\ComposerSetup\bin"
SET GIT=";%HOMEDRIVE%\Program Files\Git\cmd"

:: Set Path variable
setx PATH "%PHP%%SYSTEM32%%NODEJS%%COMPOSER%%YII%%GIT%" /m

:: Set Java variable
setx JAVA_HOME "%HOMEDRIVE%\ProgramFiles\Java\jdk1.7.0_21" /m

PAUSE

MaxJsonLength exception in ASP.NET MVC during JavaScriptSerializer

this worked for me

        JsonSerializerSettings json = new JsonSerializerSettings
        {
            ReferenceLoopHandling = ReferenceLoopHandling.Ignore
        };
        var result = JsonConvert.SerializeObject(list, Formatting.Indented, json);
        return new JsonResult { Data = result, MaxJsonLength = int.MaxValue };

How could others, on a local network, access my NodeJS app while it's running on my machine?

I had the same question and solved the problem. In my case, the Windows Firewall (not the router) was blocking the V8 machine I/O on the hosting machine.

  1. Go to windows button
  2. Search "Firewall"
  3. Choose "Allow programs to communicate through Firewall"
  4. Click Change Setup
  5. Tick all of "Evented I/O for V8 Javascript" OR "Node.js: Server-side Javascript"

My guess is that "Evented I/O for V8 Javascript" is the I/O process that node.js communicates to outside world and we need to free it before it can send packets outside of the local computer. After enabling this program to communicate over Windows firewall, I could use any port numbers to listen.

Byte Array in Python

Dietrich's answer is probably just the thing you need for what you describe, sending bytes, but a closer analogue to the code you've provided for example would be using the bytearray type.

>>> key = bytearray([0x13, 0x00, 0x00, 0x00, 0x08, 0x00])
>>> bytes(key)
b'\x13\x00\x00\x00\x08\x00'
>>> 

When is "java.io.IOException:Connection reset by peer" thrown?

There are lot of factors , first see whether server returns the result, then check between server and client.

rectify them from server side first,then check the writing condition between server and client !

server side rectify the time outs between the datalayer and server from client side rectify the time out and number of available connections !

Searching a list of objects in Python

You should add a __eq__ and a __hash__ method to your Data class, it could check if the __dict__ attributes are equal (same properties) and then if their values are equal, too.

If you did that, you can use

test = Data()
test.n = 5

found = test in myList

The in keyword checks if test is in myList.

If you only want to a a n property in Data you could use:

class Data(object):
    __slots__ = ['n']
    def __init__(self, n):
        self.n = n
    def __eq__(self, other):
        if not isinstance(other, Data):
            return False
        if self.n != other.n:
            return False
        return True
    def __hash__(self):
        return self.n

    myList = [ Data(1), Data(2), Data(3) ]
    Data(2) in myList  #==> True
    Data(5) in myList  #==> False

Reading/Writing a MS Word file in PHP

Reading binary Word documents would involve creating a parser according to the published file format specifications for the DOC format. I think this is no real feasible solution.

You could use the Microsoft Office XML formats for reading and writing Word files - this is compatible with the 2003 and 2007 version of Word. For reading you have to ensure that the Word documents are saved in the correct format (it's called Word 2003 XML-Document in Word 2007). For writing you just have to follow the openly available XML schema. I've never used this format for writing out Office documents from PHP, but I'm using it for reading in an Excel worksheet (naturally saved as XML-Spreadsheet 2003) and displaying its data on a web page. As the files are plainly XML data it's no problem to navigate within and figure out how to extract the data you need.

The other option - a Word 2007 only option (if the OpenXML file formats are not installed in your Word 2003) - would be to ressort to OpenXML. As databyss pointed out here the DOCX file format is just a ZIP archive with XML files included. There are a lot of resources on MSDN regarding the OpenXML file format, so you should be able to figure out how to read the data you want. Writing will be much more complicated I think - it just depends on how much time you'll invest.

Perhaps you can have a look at PHPExcel which is a library able to write to Excel 2007 files and read from Excel 2007 files using the OpenXML standard. You could get an idea of the work involved when trying to read and write OpenXML Word documents.

What does 'wb' mean in this code, using Python?

The wb indicates that the file is opened for writing in binary mode.

When writing in binary mode, Python makes no changes to data as it is written to the file. In text mode (when the b is excluded as in just w or when you specify text mode with wt), however, Python will encode the text based on the default text encoding. Additionally, Python will convert line endings (\n) to whatever the platform-specific line ending is, which would corrupt a binary file like an exe or png file.

Text mode should therefore be used when writing text files (whether using plain text or a text-based format like CSV), while binary mode must be used when writing non-text files like images.

References:

https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files https://docs.python.org/3/library/functions.html#open

Passing on command line arguments to runnable JAR

You can also set a Java property, i.e. environment variable, on the command line and easily use it anywhere in your code.

The command line would be done this way:

c:/> java -jar -Dmyvar=enwiki-20111007-pages-articles.xml wiki2txt

and the java code accesses the value like this:

String context = System.getProperty("myvar"); 

See this question about argument passing in Java.

How can I get the Google cache age of any URL or web page?

its too simple, you can just type "cache:" before the URL of the page. for example if you want to check the last webcache of this page simply type on URL bar cache:http://stackoverflow.com/questions/4560400/how-can-i-get-the-google-cache-age-of-any-url-or-web-page

this will show you the last webcache of the page.see here:

enter image description here

But remember, the caching of a webpage will only show if the page is already indexed on search engine(Google). for this you need to check the meta robot tag of that page.

Append an array to another array in JavaScript

If you want to modify the original array instead of returning a new array, use .push()...

array1.push.apply(array1, array2);
array1.push.apply(array1, array3);

I used .apply to push the individual members of arrays 2 and 3 at once.

or...

array1.push.apply(array1, array2.concat(array3));

To deal with large arrays, you can do this in batches.

for (var n = 0, to_add = array2.concat(array3); n < to_add.length; n+=300) {
    array1.push.apply(array1, to_add.slice(n, n+300));
}

If you do this a lot, create a method or function to handle it.

var push_apply = Function.apply.bind([].push);
var slice_call = Function.call.bind([].slice);

Object.defineProperty(Array.prototype, "pushArrayMembers", {
    value: function() {
        for (var i = 0; i < arguments.length; i++) {
            var to_add = arguments[i];
            for (var n = 0; n < to_add.length; n+=300) {
                push_apply(this, slice_call(to_add, n, n+300));
            }
        }
    }
});

and use it like this:

array1.pushArrayMembers(array2, array3);

_x000D_
_x000D_
var push_apply = Function.apply.bind([].push);_x000D_
var slice_call = Function.call.bind([].slice);_x000D_
_x000D_
Object.defineProperty(Array.prototype, "pushArrayMembers", {_x000D_
    value: function() {_x000D_
        for (var i = 0; i < arguments.length; i++) {_x000D_
            var to_add = arguments[i];_x000D_
            for (var n = 0; n < to_add.length; n+=300) {_x000D_
                push_apply(this, slice_call(to_add, n, n+300));_x000D_
            }_x000D_
        }_x000D_
    }_x000D_
});_x000D_
_x000D_
var array1 = ['a','b','c'];_x000D_
var array2 = ['d','e','f'];_x000D_
var array3 = ['g','h','i'];_x000D_
_x000D_
array1.pushArrayMembers(array2, array3);_x000D_
_x000D_
document.body.textContent = JSON.stringify(array1, null, 4);
_x000D_
_x000D_
_x000D_

Cron job every three days

It would be simpler if you configured it to just run e.g. on monday and thursdays, which would give it a 3 and 4 day break.

Otherwise configure it to run daily, but make your php cron script exit early with:

if (! (date("z") % 3)) {
     exit;
}

Executing an EXE file using a PowerShell script

Not being a developer I found a solution in running multiple ps commands in one line. E.g:

powershell "& 'c:\path with spaces\to\executable.exe' -arguments ; second command ; etc

By placing a " (double quote) before the & (ampersand) it executes the executable. In none of the examples I have found this was mentioned. Without the double quotes the ps prompt opens and waits for input.

How do I get my Python program to sleep for 50 milliseconds?

You can also do it by using the Timer() function.

Code:

from threading import Timer

def hello():
  print("Hello")

t = Timer(0.05, hello)
t.start()  # After 0.05 seconds, "Hello" will be printed

How do I alter the position of a column in a PostgreSQL database table?

I use Django and it requires id column in each table if you don't want to have a headache. Unfortunately, I was careless and my table bp.geo_location_vague didn't contain this field. I initialed little trick. Step 1:

CREATE VIEW bp.geo_location_vague_vw AS
    SELECT 
        a.id, -- I change order of id column here. 
        a.in_date,
        etc
    FROM bp.geo_location_vague a

Step 2: (without create table - table will create automaticaly!)

SELECT * into bp.geo_location_vague_cp2 FROM bp.geo_location_vague_vw

Step 3:

CREATE SEQUENCE bp.tbl_tbl_id_seq;
ALTER TABLE bp.geo_location_vague_cp2 ALTER COLUMN id SET DEFAULT nextval('tbl_tbl_id_seq');
ALTER SEQUENCE bp.tbl_tbl_id_seq OWNED BY bp.geo_location_vague_cp2.id;
SELECT setval('tbl_tbl_id_seq', COALESCE(max(id), 0)) FROM bp.geo_location_vague_cp2;

Because I need have bigserial pseudotype in the table. After SELECT * into pg will create bigint type insetad bigserial.

step 4: Now we can drop the view, drop source table and rename the new table in the old name. The trick was ended successfully.

Simple Popup by using Angular JS

Built a modal popup example using syarul's jsFiddle link. Here is the updated fiddle.

Created an angular directive called modal and used in html. Explanation:-

HTML

<div ng-controller="MainCtrl" class="container">
  <button ng-click="toggleModal('Success')" class="btn btn-default">Success</button>
  <button ng-click="toggleModal('Remove')" class="btn btn-default">Remove</button>
  <button ng-click="toggleModal('Deny')" class="btn btn-default">Deny</button>
  <button ng-click="toggleModal('Cancel')" class="btn btn-default">Cancel</button>
  <modal visible="showModal">
      Any additional data / buttons
  </modal>
</div>

On button click toggleModal() function is called with the button message as parameter. This function toggles the visibility of popup. Any tags that you put inside will show up in the popup as content since ng-transclude is placed on modal-body in the directive template.

JS

var mymodal = angular.module('mymodal', []);

mymodal.controller('MainCtrl', function ($scope) {
    $scope.showModal = false;
    $scope.buttonClicked = "";
    $scope.toggleModal = function(btnClicked){
        $scope.buttonClicked = btnClicked;
        $scope.showModal = !$scope.showModal;
    };
  });

mymodal.directive('modal', function () {
    return {
      template: '<div class="modal fade">' + 
          '<div class="modal-dialog">' + 
            '<div class="modal-content">' + 
              '<div class="modal-header">' + 
                '<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>' + 
                '<h4 class="modal-title">{{ buttonClicked }} clicked!!</h4>' + 
              '</div>' + 
              '<div class="modal-body" ng-transclude></div>' + 
            '</div>' + 
          '</div>' + 
        '</div>',
      restrict: 'E',
      transclude: true,
      replace:true,
      scope:true,
      link: function postLink(scope, element, attrs) {
        scope.title = attrs.title;

        scope.$watch(attrs.visible, function(value){
          if(value == true)
            $(element).modal('show');
          else
            $(element).modal('hide');
        });

        $(element).on('shown.bs.modal', function(){
          scope.$apply(function(){
            scope.$parent[attrs.visible] = true;
          });
        });

        $(element).on('hidden.bs.modal', function(){
          scope.$apply(function(){
            scope.$parent[attrs.visible] = false;
          });
        });
      }
    };
  });

UPDATE

<!doctype html>
<html ng-app="mymodal">


<body>

<div ng-controller="MainCtrl" class="container">
  <button ng-click="toggleModal('Success')" class="btn btn-default">Success</button>
  <button ng-click="toggleModal('Remove')" class="btn btn-default">Remove</button>
  <button ng-click="toggleModal('Deny')" class="btn btn-default">Deny</button>
  <button ng-click="toggleModal('Cancel')" class="btn btn-default">Cancel</button>
  <modal visible="showModal">
      Any additional data / buttons
  </modal>
</div>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.1/css/bootstrap.min.css">
        <!-- Scripts -->
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/js/bootstrap.min.js"></script>

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>

    <!-- App -->
    <script>
        var mymodal = angular.module('mymodal', []);

mymodal.controller('MainCtrl', function ($scope) {
    $scope.showModal = false;
    $scope.buttonClicked = "";
    $scope.toggleModal = function(btnClicked){
        $scope.buttonClicked = btnClicked;
        $scope.showModal = !$scope.showModal;
    };
  });

mymodal.directive('modal', function () {
    return {
      template: '<div class="modal fade">' + 
          '<div class="modal-dialog">' + 
            '<div class="modal-content">' + 
              '<div class="modal-header">' + 
                '<button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>' + 
                '<h4 class="modal-title">{{ buttonClicked }} clicked!!</h4>' + 
              '</div>' + 
              '<div class="modal-body" ng-transclude></div>' + 
            '</div>' + 
          '</div>' + 
        '</div>',
      restrict: 'E',
      transclude: true,
      replace:true,
      scope:true,
      link: function postLink(scope, element, attrs) {
          scope.$watch(attrs.visible, function(value){
          if(value == true)
            $(element).modal('show');
          else
            $(element).modal('hide');
        });

        $(element).on('shown.bs.modal', function(){
          scope.$apply(function(){
            scope.$parent[attrs.visible] = true;
          });
        });

        $(element).on('hidden.bs.modal', function(){
          scope.$apply(function(){
            scope.$parent[attrs.visible] = false;
          });
        });
      }
    };
  });

    </script>
</body>
</html>

UPDATE 2 restrict : 'E' : directive to be used as an HTML tag (element). Example in our case is

<modal>

Other values are 'A' for attribute

<div modal>

'C' for class (not preferable in our case because modal is already a class in bootstrap.css)

<div class="modal">

How to send cookies in a post request with the Python Requests library?

The latest release of Requests will build CookieJars for you from simple dictionaries.

import requests

cookies = {'enwiki_session': '17ab96bd8ffbe8ca58a78657a918558'}

r = requests.post('http://wikipedia.org', cookies=cookies)

Enjoy :)

Android - How to download a file from a webserver

use AsyncTask and

put your download file code in doinbackground of it..

android don't allow anymore to do heavy tasks on main thread to avoid ANR(Application not responding) error

how to redirect to home page

document.location.href="/";

Extract a single (unsigned) integer from a string

You can use preg_match:

$s = "In My Cart : 11 items";
preg_match("|\d+|", $s, $m);
var_dump($m);

How can I find the first occurrence of a sub-string in a python string?

to implement this in algorithmic way, by not using any python inbuilt function . This can be implemented as

def find_pos(string,word):

    for i in range(len(string) - len(word)+1):
        if string[i:i+len(word)] == word:
            return i
    return 'Not Found'

string = "the dude is a cool dude"
word = 'dude1'
print(find_pos(string,word))
# output 4

SQL Server Case Statement when IS NULL

Your hyphen in your ELSE statement isn't accepted in the column which is being defined under the datetime data type. You could either:

a) Wrap a CAST around your [stat] field to convert it to a varchar representation of a date

b) Use a datetime like 9999-12-31 for your ELSE value.

Should I use string.isEmpty() or "".equals(string)?

It doesn't really matter. "".equals(str) is more clear in my opinion.

isEmpty() returns count == 0;

Failed to start component [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/JDBC_DBO]]

Check your application is building successfully by running mvn clean install over your project and correct all the errors

Usually this error comes when you have dependencies which are not present on your classpath.

If you are using tomcat maven plugin then try deploying your war using following command

tomcat7:run-war-only

Loop through array of values with Arrow Function

One statement can be written as such:

someValues.forEach(x => console.log(x));

or multiple statements can be enclosed in {} like this:

someValues.forEach(x => { let a = 2 + x; console.log(a); });

Find duplicates and delete all in notepad++

You could use

Click TextFX ? Click TextFX Tools ? Click Sort lines case insensitive (at column) Duplicates and blank lines have been removed and the data has been sorted alphabetically.

as indicated above. However, the way I did it because I need to replace the duplicates by blank lines and not just remove the lines, once sorted alphabetically:

REPLACE:
((^.*$)(\n))(?=\k<1>)

by

$3

This will convert:

Shorts
Shorts
Shorts
Shorts
Shorts
Shorts Two Pack
Shorts Two Pack
Signature Braces
Signature Braces
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers
Signature Cotton Trousers

to:

Shorts

Shorts Two Pack

Signature Braces










Signature Cotton Trousers

That's how I did it because I specifically needed those lines.

Run CRON job everyday at specific time

you can write multiple lines in case of different minutes, for example you want to run at 10:01 AM and 2:30 PM

1 10 * * * php -f /var/www/package/index.php controller function

30 14 * * * php -f /var/www/package/index.php controller function

but the following is the best solution for running cron multiple times in a day as minutes are same, you can mention hours like 10,30 .

30 10,14 * * * php -f /var/www/package/index.php controller function

How can I sanitize user input with PHP?

You never sanitize input.

You always sanitize output.

The transforms you apply to data to make it safe for inclusion in an SQL statement are completely different from those you apply for inclusion in HTML are completely different from those you apply for inclusion in Javascript are completely different from those you apply for inclusion in LDIF are completely different from those you apply to inclusion in CSS are completely different from those you apply to inclusion in an Email....

By all means validate input - decide whether you should accept it for further processing or tell the user it is unacceptable. But don't apply any change to representation of the data until it is about to leave PHP land.

A long time ago someone tried to invent a one-size fits all mechanism for escaping data and we ended up with "magic_quotes" which didn't properly escape data for all output targets and resulted in different installation requiring different code to work.

PhpMyAdmin "Wrong permissions on configuration file, should not be world writable!"

all you need is to

  1. open terminal type

    opt/lampp/lampp start

to start it and then

  1. sudo chmod 755 /opt/lampp/phpmyadmin/config.inc.php

then visit in your browser

localhost/phpmyadmin

it will work fine.

Error launching Eclipse 4.4 "Version 1.6.0_65 of the JVM is not suitable for this product."

Here's how to fix this error when launching Eclipse:

Version 1.6.0_65 of the JVM is not suitable for this product. Version: 1.7 or greater is required.

  1. Go and install latest JDK

  2. Make sure you have installed 64 bit Eclipse

How to convert ISO8859-15 to UTF8?

We have this problem and to solve

Create a script file called to-utf8.sh

#!/bin/bash
TO="UTF-8"; FILE=$1
FROM=$(file -i $FILE | cut -d'=' -f2)
if [[ $FROM = "binary" ]]; then
 echo "Skipping binary $FILE..."
 exit 0
fi
iconv -f $FROM -t $TO -o $FILE.tmp $FILE; ERROR=$?
if [[ $ERROR -eq 0 ]]; then
  echo "Converting $FILE..."
  mv -f $FILE.tmp $FILE
else
  echo "Error on $FILE"
fi

Set the executable bit

chmod +x to-utf8.sh

Do a conversion

./to-utf8.sh MyFile.txt

If you want to convert all files under a folder, do

find /your/folder/here | xargs -n 1 ./to-utf8.sh

Hope it's help.

Share data between AngularJS controllers

A simple solution is to have your factory return an object and let your controllers work with a reference to the same object:

JS:

// declare the app with no dependencies
var myApp = angular.module('myApp', []);

// Create the factory that share the Fact
myApp.factory('Fact', function(){
  return { Field: '' };
});

// Two controllers sharing an object that has a string in it
myApp.controller('FirstCtrl', function( $scope, Fact ){
  $scope.Alpha = Fact;
});

myApp.controller('SecondCtrl', function( $scope, Fact ){
  $scope.Beta = Fact;
});

HTML:

<div ng-controller="FirstCtrl">
    <input type="text" ng-model="Alpha.Field">
    First {{Alpha.Field}}
</div>

<div ng-controller="SecondCtrl">
<input type="text" ng-model="Beta.Field">
    Second {{Beta.Field}}
</div>

Demo: http://jsfiddle.net/HEdJF/

When applications get larger, more complex and harder to test you might not want to expose the entire object from the factory this way, but instead give limited access for example via getters and setters:

myApp.factory('Data', function () {

    var data = {
        FirstName: ''
    };

    return {
        getFirstName: function () {
            return data.FirstName;
        },
        setFirstName: function (firstName) {
            data.FirstName = firstName;
        }
    };
});

With this approach it is up to the consuming controllers to update the factory with new values, and to watch for changes to get them:

myApp.controller('FirstCtrl', function ($scope, Data) {

    $scope.firstName = '';

    $scope.$watch('firstName', function (newValue, oldValue) {
        if (newValue !== oldValue) Data.setFirstName(newValue);
    });
});

myApp.controller('SecondCtrl', function ($scope, Data) {

    $scope.$watch(function () { return Data.getFirstName(); }, function (newValue, oldValue) {
        if (newValue !== oldValue) $scope.firstName = newValue;
    });
});

HTML:

<div ng-controller="FirstCtrl">
  <input type="text" ng-model="firstName">
  <br>Input is : <strong>{{firstName}}</strong>
</div>
<hr>
<div ng-controller="SecondCtrl">
  Input should also be here: {{firstName}}
</div>

Demo: http://jsfiddle.net/27mk1n1o/

Creating a Custom Event

Yes you can do like this :

Creating advanced C# custom events

or

The Simplest C# Events Example Imaginable

public class Metronome
{
    public event TickHandler Tick;
    public EventArgs e = null;
    public delegate void TickHandler(Metronome m, EventArgs e);
    public void Start()
    {
        while (true)
        {
            System.Threading.Thread.Sleep(3000);
            if (Tick != null)
            {
                Tick(this, e);
            }
        }
    }
}
public class Listener
{
    public void Subscribe(Metronome m)
    {
        m.Tick += new Metronome.TickHandler(HeardIt);
    }

    private void HeardIt(Metronome m, EventArgs e)
    {
        System.Console.WriteLine("HEARD IT");
    }
}
class Test
{
    static void Main()
    {
        Metronome m = new Metronome();
        Listener l = new Listener();
        l.Subscribe(m);
        m.Start();
    }
}

POST string to ASP.NET Web Api application - returns null

Darrel is of course right on with his response. One thing to add is that the reason why attempting to bind to a body containing a single token like "hello".

is that it isn’t quite URL form encoded data. By adding “=” in front like this:

=hello

it becomes a URL form encoding of a single key value pair with an empty name and value of “hello”.

However, a better solution is to use application/json when uploading a string:

POST /api/sample HTTP/1.1
Content-Type: application/json; charset=utf-8
Host: host:8080
Content-Length: 7

"Hello"

Using HttpClient you can do it as follows:

HttpClient client = new HttpClient();
HttpResponseMessage response = await client.PostAsJsonAsync(_baseAddress + "api/json", "Hello");
string result = await response.Content.ReadAsStringAsync();
Console.WriteLine(result);

Henrik

remove duplicates from sql union

If you are using T-SQL you could use a temporary table in a stored procedure and update or insert the records of your query accordingly.

How to get Exception Error Code in C#

You should look at the members of the thrown exception, particularly .Message and .InnerException.

I would also see whether or not the documentation for InvokeMethod tells you whether it throws some more specialized Exception class than Exception - such as the Win32Exception suggested by @Preet. Catching and just looking at the Exception base class may not be particularly useful.

Set the space between Elements in Row Flutter

There are many ways of doing it, I'm listing a few here:

  1. Use SizedBox if you want to set some specific space

    Row(
      children: <Widget>[
        Text("1"),
        SizedBox(width: 50), // give it width
        Text("2"),
      ],
    )
    

    enter image description here


  1. Use Spacer if you want both to be as far apart as possible.

    Row(
      children: <Widget>[
        Text("1"),
        Spacer(), // use Spacer
        Text("2"),
      ],
    )
    

    enter image description here


  1. Use mainAxisAlignment according to your needs:

    Row(
      mainAxisAlignment: MainAxisAlignment.spaceEvenly, // use whichever suits your need
      children: <Widget>[
        Text("1"),
        Text("2"),
      ],
    )
    

    enter image description here


  1. Use Wrap instead of Row and give some spacing

    Wrap(
      spacing: 100, // set spacing here
      children: <Widget>[
        Text("1"),
        Text("2"),
      ],
    )
    

    enter image description here


  1. Use Wrap instead of Row and give it alignment

    Wrap(
      alignment: WrapAlignment.spaceAround, // set your alignment
      children: <Widget>[
        Text("1"),
        Text("2"),
      ],
    )
    

    enter image description here

Reading a text file with SQL Server

Just discovered this:

SELECT * FROM OPENROWSET(BULK N'<PATH_TO_FILE>', SINGLE_CLOB) AS Contents

It'll pull in the contents of the file as varchar(max). Replace SINGLE_CLOB with:

SINGLE_NCLOB for nvarchar(max) SINGLE_BLOB for varbinary(max)

Thanks to http://www.mssqltips.com/sqlservertip/1643/using-openrowset-to-read-large-files-into-sql-server/ for this!

How to generate unique id in MySQL?

If you use MySQL with version higher than 5.7.4, you can use the newly added RANDOM_BYTES function:

 SELECT TO_BASE64(RANDOM_BYTES(16));

This will result in a random string such as GgwEvafNLWQ3+ockEST00A==.

Is an entity body allowed for an HTTP DELETE request?

In case anyone is running into this issue testing, No it is not universally supported.

I am currently testing with Sahi Pro and it is very apparent a http DELETE call strips any provided body data (a large list of id's to delete in bulk as per endpoint design).

I have been in contact with them several times as well as sent in three separate packages of scrips, images, logs for them to review and they still have not confirmed this. A failed patch, and a missed conference calls by their support later and I still haven't gotten a solid answer.

I am certain Sahi does not support this, and I would imagine many other tools follow suite.

How to make flexbox items the same size?

You need to add width: 0 to make columns equal if contents of the items make it grow bigger.

.item {
  flex: 1 1 0;
  width: 0;
}

Can't connect Nexus 4 to adb: unauthorized

I think it has an error when the device tries to display the screen asking for permission, so it does not appear.

This works for me (commands are given in the adb shell):

  1. rm /data/misc/adb/adb_keys;
  2. I sent the public key (adbkey.pub in ~/.android/) from my computer to my device via email;
  3. Invoke stop adbd;
  4. cat adbkey.pub >> /data/misc/adb/adb_keys (authorize myself);
  5. start adbd (restart adb with new keys).

Best Free Text Editor Supporting *More Than* 4GB Files?

HxD -- it's a hexeditor, but it allows in place edits, and doesn't barf on large files.

How do I get the currently-logged username from a Windows service in .NET?

Completing the answer from @xanblax

private static string getUserName()
    {
        SelectQuery query = new SelectQuery(@"Select * from Win32_Process");
        using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query))
        {
            foreach (System.Management.ManagementObject Process in searcher.Get())
            {
                if (Process["ExecutablePath"] != null &&
                    string.Equals(Path.GetFileName(Process["ExecutablePath"].ToString()), "explorer.exe", StringComparison.OrdinalIgnoreCase))
                {
                    string[] OwnerInfo = new string[2];
                    Process.InvokeMethod("GetOwner", (object[])OwnerInfo);

                    return OwnerInfo[0];
                }
            }
        }
        return "";
    }

Java String split removed empty values

you may have multiple separators, including whitespace characters, commas, semicolons, etc. take those in repeatable group with []+, like:

 String[] tokens = "a , b,  ,c; ;d,      ".split( "[,; \t\n\r]+" );

you'll have 4 tokens -- a, b, c, d

leading separators in the source string need to be removed before applying this split.

as answer to question asked:

String data = "5|6|7||8|9||";
String[] split = data.split("[\\| \t\n\r]+");

whitespaces added just in case if you'll have those as separators along with |

vue.js 2 how to watch store values from vuex

The best way to watch store changes is to use mapGetters as Gabriel said. But there is a case when you can't do it through mapGetters e.g. you want to get something from store using parameter:

getters: {
  getTodoById: (state, getters) => (id) => {
    return state.todos.find(todo => todo.id === id)
  }
}

in that case you can't use mapGetters. You may try to do something like this instead:

computed: {
    todoById() {
        return this.$store.getters.getTodoById(this.id)
    }
}

But unfortunately todoById will be updated only if this.id is changed

If you want you component update in such case use this.$store.watch solution provided by Gong. Or handle your component consciously and update this.id when you need to update todoById.

How do you cast a List of supertypes to a List of subtypes?

Since this is a widely referenced question, and the current answers mainly explain why it does not work (or propose hacky, dangerous solutions that I would never ever like to see in production code), I think it is appropriate to add another answer, showing the pitfalls, and a possible solution.


The reason why this does not work in general has already been pointed out in other answers: Whether or not the conversion is actually valid depends on the types of the objects that are contained in the original list. When there are objects in the list whose type is not of type TestB, but of a different subclass of TestA, then the cast is not valid.


Of course, the casts may be valid. You sometimes have information about the types that is not available for the compiler. In these cases, it is possible to cast the lists, but in general, it is not recommended:

One could either...

  • ... cast the whole list or
  • ... cast all elements of the list

The implications of the first approach (which corresponds to the currently accepted answer) are subtle. It might seem to work properly at the first glance. But if there are wrong types in the input list, then a ClassCastException will be thrown, maybe at a completely different location in the code, and it may be hard to debug this and to find out where the wrong element slipped into the list. The worst problem is that someone might even add the invalid elements after the list has been casted, making debugging even more difficult.

The problem of debugging these spurious ClassCastExceptions can be alleviated with the Collections#checkedCollection family of methods.


Filtering the list based on the type

A more type-safe way of converting from a List<Supertype> to a List<Subtype> is to actually filter the list, and create a new list that contains only elements that have certain type. There are some degrees of freedom for the implementation of such a method (e.g. regarding the treatment of null entries), but one possible implementation may look like this:

/**
 * Filter the given list, and create a new list that only contains
 * the elements that are (subtypes) of the class c
 * 
 * @param listA The input list
 * @param c The class to filter for
 * @return The filtered list
 */
private static <T> List<T> filter(List<?> listA, Class<T> c)
{
    List<T> listB = new ArrayList<T>();
    for (Object a : listA)
    {
        if (c.isInstance(a))
        {
            listB.add(c.cast(a));
        }
    }
    return listB;
}

This method can be used in order to filter arbitrary lists (not only with a given Subtype-Supertype relationship regarding the type parameters), as in this example:

// A list of type "List<Number>" that actually 
// contains Integer, Double and Float values
List<Number> mixedNumbers = 
    new ArrayList<Number>(Arrays.asList(12, 3.4, 5.6f, 78));

// Filter the list, and create a list that contains
// only the Integer values:
List<Integer> integers = filter(mixedNumbers, Integer.class);

System.out.println(integers); // Prints [12, 78]

Line Break in XML?

In XML a line break is a normal character. You can do this:

<xml>
  <text>some text
with
three lines</text>
</xml>

and the contents of <text> will be

some text
with
three lines

If this does not work for you, you are doing something wrong. Special "workarounds" like encoding the line break are unnecessary. Stuff like \n won't work, on the other hand, because XML has no escape sequences*.


* Note that &#xA; is the character entity that represents a line break in serialized XML. "XML has no escape sequences" means the situation when you interact with a DOM document, setting node values through the DOM API.

This is where neither &#xA; nor things like \n will work, but an actual newline character will. How this character ends up in the serialized document (i.e. "file") is up to the API and should not concern you.


Since you seem to wonder where your line breaks go in HTML: Take a look into your source code, there they are. HTML ignores line breaks in source code. Use <br> tags to force line breaks on screen.

Here is a JavaScript function that inserts <br> into a multi-line string:

function nl2br(s) { return s.split(/\r?\n/).join("<br>"); }

Alternatively you can force line breaks at new line characters with CSS:

div.lines {
    white-space: pre-line;
}

How to find if a native DLL file is compiled as x64 or x86?

The Magic field of the IMAGE_OPTIONAL_HEADER (though there is nothing optional about the header in Windows executable images (DLL/EXE files)) will tell you the architecture of the PE.

Here's an example of grabbing the architecture from a file.

public static ushort GetImageArchitecture(string filepath) {
    using (var stream = new System.IO.FileStream(filepath, System.IO.FileMode.Open, System.IO.FileAccess.Read))
    using (var reader = new System.IO.BinaryReader(stream)) {
        //check the MZ signature to ensure it's a valid Portable Executable image
        if (reader.ReadUInt16() != 23117) 
            throw new BadImageFormatException("Not a valid Portable Executable image", filepath);

        // seek to, and read, e_lfanew then advance the stream to there (start of NT header)
        stream.Seek(0x3A, System.IO.SeekOrigin.Current); 
        stream.Seek(reader.ReadUInt32(), System.IO.SeekOrigin.Begin);

        // Ensure the NT header is valid by checking the "PE\0\0" signature
        if (reader.ReadUInt32() != 17744)
            throw new BadImageFormatException("Not a valid Portable Executable image", filepath);

        // seek past the file header, then read the magic number from the optional header
        stream.Seek(20, System.IO.SeekOrigin.Current); 
        return reader.ReadUInt16();
    }
}

The only two architecture constants at the moment are:

0x10b - PE32
0x20b - PE32+

Cheers

UPDATE It's been a while since I posted this answer, yet I still see that it gets a few upvotes now and again so I figured it was worth updating. I wrote a way to get the architecture of a Portable Executable image, which also checks to see if it was compiled as AnyCPU. Unfortunately the answer is in C++, but it shouldn't be too hard to port to C# if you have a few minutes to look up the structures in WinNT.h. If people are interested I'll write a port in C#, but unless people actually want it I wont spend much time stressing about it.

#include <Windows.h>

#define MKPTR(p1,p2) ((DWORD_PTR)(p1) + (DWORD_PTR)(p2))

typedef enum _pe_architecture {
    PE_ARCHITECTURE_UNKNOWN = 0x0000,
    PE_ARCHITECTURE_ANYCPU  = 0x0001,
    PE_ARCHITECTURE_X86     = 0x010B,
    PE_ARCHITECTURE_x64     = 0x020B
} PE_ARCHITECTURE;

LPVOID GetOffsetFromRva(IMAGE_DOS_HEADER *pDos, IMAGE_NT_HEADERS *pNt, DWORD rva) {
    IMAGE_SECTION_HEADER *pSecHd = IMAGE_FIRST_SECTION(pNt);
    for(unsigned long i = 0; i < pNt->FileHeader.NumberOfSections; ++i, ++pSecHd) {
        // Lookup which section contains this RVA so we can translate the VA to a file offset
        if (rva >= pSecHd->VirtualAddress && rva < (pSecHd->VirtualAddress + pSecHd->Misc.VirtualSize)) {
            DWORD delta = pSecHd->VirtualAddress - pSecHd->PointerToRawData;
            return (LPVOID)MKPTR(pDos, rva - delta);
        }
    }
    return NULL;
}

PE_ARCHITECTURE GetImageArchitecture(void *pImageBase) {
    // Parse and validate the DOS header
    IMAGE_DOS_HEADER *pDosHd = (IMAGE_DOS_HEADER*)pImageBase;
    if (IsBadReadPtr(pDosHd, sizeof(pDosHd->e_magic)) || pDosHd->e_magic != IMAGE_DOS_SIGNATURE)
        return PE_ARCHITECTURE_UNKNOWN;

    // Parse and validate the NT header
    IMAGE_NT_HEADERS *pNtHd = (IMAGE_NT_HEADERS*)MKPTR(pDosHd, pDosHd->e_lfanew);
    if (IsBadReadPtr(pNtHd, sizeof(pNtHd->Signature)) || pNtHd->Signature != IMAGE_NT_SIGNATURE)
        return PE_ARCHITECTURE_UNKNOWN;

    // First, naive, check based on the 'Magic' number in the Optional Header.
    PE_ARCHITECTURE architecture = (PE_ARCHITECTURE)pNtHd->OptionalHeader.Magic;

    // If the architecture is x86, there is still a possibility that the image is 'AnyCPU'
    if (architecture == PE_ARCHITECTURE_X86) {
        IMAGE_DATA_DIRECTORY comDirectory = pNtHd->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_COM_DESCRIPTOR];
        if (comDirectory.Size) {
            IMAGE_COR20_HEADER *pClrHd = (IMAGE_COR20_HEADER*)GetOffsetFromRva(pDosHd, pNtHd, comDirectory.VirtualAddress);
            // Check to see if the CLR header contains the 32BITONLY flag, if not then the image is actually AnyCpu
            if ((pClrHd->Flags & COMIMAGE_FLAGS_32BITREQUIRED) == 0)
                architecture = PE_ARCHITECTURE_ANYCPU;
        }
    }

    return architecture;
}

The function accepts a pointer to an in-memory PE image (so you can choose your poison on how to get it their; memory-mapping or reading the whole thing into memory...whatever).

Entity Framework rollback and remove bad migration

As of .NET Core 2.2, TargetMigration seems to be gone:

get-help Update-Database

NAME
    Update-Database

SYNOPSIS
    Updates the database to a specified migration.


SYNTAX
    Update-Database [[-Migration] <String>] [-Context <String>] [-Project <String>] [-StartupProject <String>] [<CommonParameters>]


DESCRIPTION
    Updates the database to a specified migration.


RELATED LINKS
    Script-Migration
    about_EntityFrameworkCore 

REMARKS
    To see the examples, type: "get-help Update-Database -examples".
    For more information, type: "get-help Update-Database -detailed".
    For technical information, type: "get-help Update-Database -full".
    For online help, type: "get-help Update-Database -online"

So this works for me now:

Update-Database -Migration 20180906131107_xxxx_xxxx

As well as (no -Migration switch):

Update-Database 20180906131107_xxxx_xxxx

On an added note, you can no longer cleanly delete migration folders without putting your Model Snapshot out of sync. So if you learn this the hard way and wind up with an empty migration where you know there should be changes, you can run (no switches needed for the last migration):

Remove-migration

It will clean up the mess and put you back where you need to be, even though the last migration folder was deleted manually.

jQuery to loop through elements with the same class

you can do it this way

$('.testimonial').each(function(index, obj){
    //you can use this to access the current item
});

How to resolve "Server Error in '/' Application" error?

vs2017 just added in these lines to csproj.user file

    <IISExpressAnonymousAuthentication>enabled</IISExpressAnonymousAuthentication>
    <IISExpressWindowsAuthentication>enabled</IISExpressWindowsAuthentication>
    <IISExpressUseClassicPipelineMode>false</IISExpressUseClassicPipelineMode>

with these lines in Web.config

<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" maxRequestLength="1048576" />
<identity impersonate="false" />
<authentication mode="Windows" />
<authorization>
  <allow users="yourNTusername" />
  <deny users="?" />
</authorization>

And it worked

Defined Edges With CSS3 Filter Blur

Here is a solution I came up with keeps 100% of the image and no crop is needed:

Basically I mirror tile the image in 3x3 grid then blur everything and then zoom in at the center image effectively creating like a repeat edges when blurring in after effects, it a bit strange that css3 don't have like a repeat edges built in.

Link to the method / code: How to blur an image using CSS3 without cropping or fading the edges?

How can I make a checkbox readonly? not disabled?

There is no property to make the checkbox readonly. But you can try this trick.

<input type="checkbox" onclick="return false" />

DEMO

Multiple Forms or Multiple Submits in a Page?

Best practice: one form per product is definitely the way to go.

Benefits:

  • It will save you the hassle of having to parse the data to figure out which product was clicked
  • It will reduce the size of data being posted

In your specific situation

If you only ever intend to have one form element, in this case a submit button, one form for all should work just fine.


My recommendation Do one form per product, and change your markup to something like:

<form method="post" action="">
    <input type="hidden" name="product_id" value="123">
    <button type="submit" name="action" value="add_to_cart">Add to Cart</button>
</form>

This will give you a much cleaner and usable POST. No parsing. And it will allow you to add more parameters in the future (size, color, quantity, etc).

Note: There's no technical benefit to using <button> vs. <input>, but as a programmer I find it cooler to work with action=='add_to_cart' than action=='Add to Cart'. Besides, I hate mixing presentation with logic. If one day you decide that it makes more sense for the button to say "Add" or if you want to use different languages, you could do so freely without having to worry about your back-end code.

receiving error: 'Error: SSL Error: SELF_SIGNED_CERT_IN_CHAIN' while using npm

Turning off SSL seems like a profoundly bad idea. npm's blog explains that they no longer support their self-signed cert. They suggest upgrading npm via npm install npm -g, but I of course got the same SELF_SIGNED_CERT_IN_CHAIN error. So I just updated node, which updated npm along with it. Exact procedure depends on how you installed node in the first place.

PHP - Check if two arrays are equal

Short solution that works even with arrays which keys are given in different order:

public static function arrays_are_equal($array1, $array2)
{
    array_multisort($array1);
    array_multisort($array2);
    return ( serialize($array1) === serialize($array2) );
}

Remove git mapping in Visual Studio 2015

You cant delete local git repository when its already connected. so close the solution, open another solution and then remove the local git repository. dont forget to delete .git hidden folder works for me

Text that shows an underline on hover

You just need to specify text-decoration: underline; with pseudo-class :hover.

HTML

<span class="underline-on-hover">Hello world</span>

CSS

.underline-on-hover:hover {
    text-decoration: underline;
}

I have whipped up a working Code Pen Demo.

How can you find the height of text on an HTML canvas?

Isn't the height of the text in pixels equal to the font size (in pts) if you define the font using context.font ?

How is OAuth 2 different from OAuth 1?

Note there are serious security arguments against using Oauth 2:

one bleak article

and a more technical one

Note these are coming from Oauth 2's lead author.

Key points:

  • Oauth 2 offers no security on top of SSL while Oauth 1 is transport-independent.

  • in a sense SSL isn't secure in that the server does not verify the connection and the common client libraries make it easy to ignore failures.

    The problem with SSL/TLS, is that when you fail to verify the certificate on the client side, the connection still works. Any time ignoring an error leads to success, developers are going to do just that. The server has no way of enforcing certificate verification, and even if it could, an attacker will surely not.

  • you can fat-finger away all of your security, which is much harder to do in OAuth 1.0:

    The second common potential problem are typos. Would you consider it a proper design when omitting one character (the ‘s’ in ‘https’) voids the entire security of the token? Or perhaps sending the request (over a valid and verified SSL/TLS connection) to the wrong destination (say ‘http://gacebook.com’?). Remember, being able to use OAuth bearer tokens from the command line was clearly a use case bearer tokens advocates promoted.

AngularJS does not send hidden field value

Directly assign the value to model in data-ng-value attribute. Since Angular interpreter doesn't recognize hidden fields as part of ngModel.

<input type="hidden" name="pfuserid" data-ng-value="newPortfolio.UserId = data.Id"/>

get dictionary value by key

          private void button2_Click(object sender, EventArgs e)
            {
                Dictionary<string, string> Data_Array = new Dictionary<string, string>();
                Data_Array.Add("XML_File", "Settings.xml");

                XML_Array(Data_Array);
            }
          static void XML_Array(Dictionary<string, string> Data_Array)
            {
                String xmlfile = Data_Array["XML_File"];
            }

How to iterate over a column vector in Matlab?

for i=1:length(list)
  elm = list(i);
  //do something with elm.

How to edit hosts file via CMD?

echo 0.0.0.0 websitename.com >> %WINDIR%\System32\Drivers\Etc\Hosts

the >> appends the output of echo to the file.

Note that there are two reasons this might not work like you want it to. You may be aware of these, but I mention them just in case.

First, it won't affect a web browser, for example, that already has the current, "real" IP address resolved. So, it won't always take effect right away.

Second, it requires you to add an entry for every host name on a domain; just adding websitename.com will not block www.websitename.com, for example.

How to convert an iterator to a stream?

Great suggestion! Here's my reusable take on it:

public class StreamUtils {

    public static <T> Stream<T> asStream(Iterator<T> sourceIterator) {
        return asStream(sourceIterator, false);
    }

    public static <T> Stream<T> asStream(Iterator<T> sourceIterator, boolean parallel) {
        Iterable<T> iterable = () -> sourceIterator;
        return StreamSupport.stream(iterable.spliterator(), parallel);
    }
}

And usage (make sure to statically import asStream):

List<String> aPrefixedStrings = asStream(sourceIterator)
                .filter(t -> t.startsWith("A"))
                .collect(toList());

Php artisan make:auth command is not defined

Update for Laravel 6

Now that Laravel 6 is released you need to install laravel/ui.

composer require laravel/ui --dev
php artisan ui vue --auth

You can change vue with react if you use React in your project (see Using React).

And then you need to perform the migrations and compile the frontend

php artisan migrate
npm install && npm run dev

Source : Laravel Documentation for authentication

Want to get started fast? Install the laravel/ui Composer package and run php artisan ui vue --auth in a fresh Laravel application. After migrating your database, navigate your browser to http://your-app.test/register or any other URL that is assigned to your application. These commands will take care of scaffolding your entire authentication system!

Note: That's only if you want to use scaffolding, you can use the default User model and the Eloquent authentication driver.

Angular 5, HTML, boolean on checkbox is checked

Work with checkboxes using observables

You could even choose to use a behaviourSubject to utilize the power of observables so you can start a certain chain of reaction starting at the isChecked$ observable.

In your component.ts:

public isChecked$ = new BehaviorSubject(false);
toggleChecked() {
  this.isChecked$.next(!this.isChecked$.value)
}

In your template

<input type="checkbox" [checked]="isChecked$ | async" (change)="toggleChecked()">

Comparing two vectors in an if statement

Are they identical?

> identical(A,C)
[1] FALSE

Which elements disagree:

> which(A != C)
[1] 2 4

HTML.ActionLink vs Url.Action in ASP.NET Razor

Html.ActionLink generates an <a href=".."></a> tag automatically.

Url.Action generates only an url.

For example:

@Html.ActionLink("link text", "actionName", "controllerName", new { id = "<id>" }, null)

generates:

<a href="/controllerName/actionName/<id>">link text</a>

and

@Url.Action("actionName", "controllerName", new { id = "<id>" }) 

generates:

/controllerName/actionName/<id>

Best plus point which I like is using Url.Action(...)

You are creating anchor tag by your own where you can set your own linked text easily even with some other html tag.

<a href="@Url.Action("actionName", "controllerName", new { id = "<id>" })">

   <img src="<ImageUrl>" style"width:<somewidth>;height:<someheight> />

   @Html.DisplayFor(model => model.<SomeModelField>)
</a>

How to read the last row with SQL Server

SELECT * from Employees where [Employee ID] = ALL (SELECT MAX([Employee ID]) from Employees)

Where do I put my php files to have Xampp parse them?

in XAMPP the default root is "htdocs" inside the XAMPP folder, if you followed the instructions on the xampp homepage it would be "/opt/lampp/htdocs"

Adding 'serial' to existing column in Postgres

TL;DR

Here's a version where you don't need a human to read a value and type it out themselves.

CREATE SEQUENCE foo_a_seq OWNED BY foo.a;
SELECT setval('foo_a_seq', coalesce(max(a), 0) + 1, false) FROM foo;
ALTER TABLE foo ALTER COLUMN a SET DEFAULT nextval('foo_a_seq'); 

Another option would be to employ the reusable Function shared at the end of this answer.


A non-interactive solution

Just adding to the other two answers, for those of us who need to have these Sequences created by a non-interactive script, while patching a live-ish DB for instance.

That is, when you don't wanna SELECT the value manually and type it yourself into a subsequent CREATE statement.

In short, you can not do:

CREATE SEQUENCE foo_a_seq
    START WITH ( SELECT max(a) + 1 FROM foo );

... since the START [WITH] clause in CREATE SEQUENCE expects a value, not a subquery.

Note: As a rule of thumb, that applies to all non-CRUD (i.e.: anything other than INSERT, SELECT, UPDATE, DELETE) statements in pgSQL AFAIK.

However, setval() does! Thus, the following is absolutely fine:

SELECT setval('foo_a_seq', max(a)) FROM foo;

If there's no data and you don't (want to) know about it, use coalesce() to set the default value:

SELECT setval('foo_a_seq', coalesce(max(a), 0)) FROM foo;
--                         ^      ^         ^
--                       defaults to:       0

However, having the current sequence value set to 0 is clumsy, if not illegal.
Using the three-parameter form of setval would be more appropriate:

--                                             vvv
SELECT setval('foo_a_seq', coalesce(max(a), 0) + 1, false) FROM foo;
--                                                  ^   ^
--                                                is_called

Setting the optional third parameter of setval to false will prevent the next nextval from advancing the sequence before returning a value, and thus:

the next nextval will return exactly the specified value, and sequence advancement commences with the following nextval.

— from this entry in the documentation

On an unrelated note, you also can specify the column owning the Sequence directly with CREATE, you don't have to alter it later:

CREATE SEQUENCE foo_a_seq OWNED BY foo.a;

In summary:

CREATE SEQUENCE foo_a_seq OWNED BY foo.a;
SELECT setval('foo_a_seq', coalesce(max(a), 0) + 1, false) FROM foo;
ALTER TABLE foo ALTER COLUMN a SET DEFAULT nextval('foo_a_seq'); 

Using a Function

Alternatively, if you're planning on doing this for multiple columns, you could opt for using an actual Function.

CREATE OR REPLACE FUNCTION make_into_serial(table_name TEXT, column_name TEXT) RETURNS INTEGER AS $$
DECLARE
    start_with INTEGER;
    sequence_name TEXT;
BEGIN
    sequence_name := table_name || '_' || column_name || '_seq';
    EXECUTE 'SELECT coalesce(max(' || column_name || '), 0) + 1 FROM ' || table_name
            INTO start_with;
    EXECUTE 'CREATE SEQUENCE ' || sequence_name ||
            ' START WITH ' || start_with ||
            ' OWNED BY ' || table_name || '.' || column_name;
    EXECUTE 'ALTER TABLE ' || table_name || ' ALTER COLUMN ' || column_name ||
            ' SET DEFAULT nextVal(''' || sequence_name || ''')';
    RETURN start_with;
END;
$$ LANGUAGE plpgsql VOLATILE;

Use it like so:

INSERT INTO foo (data) VALUES ('asdf');
-- ERROR: null value in column "a" violates not-null constraint

SELECT make_into_serial('foo', 'a');
INSERT INTO foo (data) VALUES ('asdf');
-- OK: 1 row(s) affected

foreach loop in angularjs

The angular.forEach() will iterate through your json object.

First iteration,

key = 0, value = { "name" : "Thomas", "password" : "thomasTheKing"}

Second iteration,

key = 1, value = { "name" : "Linda", "password" : "lindatheQueen" }

To get the value of your name, you can use value.name or value["name"]. Same with your password, you use value.password or value["password"].

The code below will give you what you want:

   angular.forEach(json, function (value, key)
         {
                //console.log(key);
                //console.log(value);
                if (value.password == "thomasTheKing") {
                    console.log("username is thomas");
                }
         });

Why not use Double or Float to represent currency?

I'm troubled by some of these responses. I think doubles and floats have a place in financial calculations. Certainly, when adding and subtracting non-fractional monetary amounts there will be no loss of precision when using integer classes or BigDecimal classes. But when performing more complex operations, you often end up with results that go out several or many decimal places, no matter how you store the numbers. The issue is how you present the result.

If your result is on the borderline between being rounded up and rounded down, and that last penny really matters, you should be probably be telling the viewer that the answer is nearly in the middle - by displaying more decimal places.

The problem with doubles, and more so with floats, is when they are used to combine large numbers and small numbers. In java,

System.out.println(1000000.0f + 1.2f - 1000000.0f);

results in

1.1875

Maven: how to override the dependency added by a library

Alternatively, you can just exclude the dependency that you don't want. STAX is included in JDK 1.6, so if you're using 1.6 you can just exclude it entirely.

My example below is slightly wrong for you - you only need one of the two exclusions but I'm not quite sure which one. There are other versions of Stax floating about, in my example below I was importing A which imported B which imported C & D which each (through yet more transitive dependencies) imported different versions of Stax. So in my dependency on 'A', I excluded both versions of Stax.

<dependency>
  <groupId>a.group</groupId>
  <artifactId>a.artifact</artifactId>
  <version>a.version</version>
  <exclusions>
    <!--  STAX comes with Java 1.6 -->
    <exclusion>
      <artifactId>stax-api</artifactId>
      <groupId>javax.xml.stream</groupId>
    </exclusion>
    <exclusion>
      <artifactId>stax-api</artifactId>
      <groupId>stax</groupId>
    </exclusion>
  </exclusions>
<dependency>

How to redirect to action from JavaScript method?

Maybe better to make an anchor with DeleteJob url instead of button?

<a href="<%=Url.Action("DeleteJob", "YourController", new {selectedObject="someObject"})%>" onclick="return DeleteJob()">Löschen</a>

and use your javascript you wrote already:

function DeleteJob() {

        if (confirm("Do you really want to delete selected job/s?"))
            return true;
        else
            return false;
    }

So if function return true - you will be redirected. If function return false - you still stay on the page.

Check if file is already open

If file is in use FileOutputStream fileOutputStream = new FileOutputStream(file); returns java.io.FileNotFoundException with 'The process cannot access the file because it is being used by another process' in the exception message.

How to use PHP to connect to sql server

I've been having the same problem (well I hope the same). Anyways it turned out to be my version of ntwdblib.dll, which was out of date in my PHP folder.

http://dba.fyicenter.com/faq/sql_server_2/Finding_ntwdblib_dll_Version_2000_80_194_0.html

What is the difference between square brackets and parentheses in a regex?

These regexes are equivalent (for matching purposes):

  • /^(7|8|9)\d{9}$/
  • /^[789]\d{9}$/
  • /^[7-9]\d{9}$/

The explanation:

  • (a|b|c) is a regex "OR" and means "a or b or c", although the presence of brackets, necessary for the OR, also captures the digit. To be strictly equivalent, you would code (?:7|8|9) to make it a non capturing group.

  • [abc] is a "character class" that means "any character from a,b or c" (a character class may use ranges, e.g. [a-d] = [abcd])

The reason these regexes are similar is that a character class is a shorthand for an "or" (but only for single characters). In an alternation, you can also do something like (abc|def) which does not translate to a character class.

Python memory usage of numpy arrays

The field nbytes will give you the size in bytes of all the elements of the array in a numpy.array:

size_in_bytes = my_numpy_array.nbytes

Notice that this does not measures "non-element attributes of the array object" so the actual size in bytes can be a few bytes larger than this.

Reverting to a specific commit based on commit id with Git?

git reset c14809fafb08b9e96ff2879999ba8c807d10fb07 is what you're after...

Decode JSON with unknown structure

You really just need a single struct, and as mentioned in the comments the correct annotations on the field will yield the desired results. JSON is not some extremely variant data format, it is well defined and any piece of json, no matter how complicated and confusing it might be to you can be represented fairly easily and with 100% accuracy both by a schema and in objects in Go and most other OO programming languages. Here's an example;

package main

import (
    "fmt"
    "encoding/json"
)

type Data struct {
    Votes *Votes `json:"votes"`
    Count string `json:"count,omitempty"`
}

type Votes struct {
    OptionA string `json:"option_A"`
}

func main() {
    s := `{ "votes": { "option_A": "3" } }`
    data := &Data{
        Votes: &Votes{},
    }
    err := json.Unmarshal([]byte(s), data)
    fmt.Println(err)
    fmt.Println(data.Votes)
    s2, _ := json.Marshal(data)
    fmt.Println(string(s2))
    data.Count = "2"
    s3, _ := json.Marshal(data)
    fmt.Println(string(s3))
}

https://play.golang.org/p/ScuxESTW5i

Based on your most recent comment you could address that by using an interface{} to represent data besides the count, making the count a string and having the rest of the blob shoved into the interface{} which will accept essentially anything. That being said, Go is a statically typed language with a fairly strict type system and to reiterate, your comments stating 'it can be anything' are not true. JSON cannot be anything. For any piece of JSON there is schema and a single schema can define many many variations of JSON. I advise you take the time to understand the structure of your data rather than hacking something together under the notion that it cannot be defined when it absolutely can and is probably quite easy for someone who knows what they're doing.

Resize an Array while keeping current elements in Java?

Not nice, but works:

    int[] a = {1, 2, 3};
    // make a one bigger
    a = Arrays.copyOf(a, a.length + 1);
    for (int i : a)
        System.out.println(i);

as stated before, go with ArrayList

How to get root directory in yii2

To get the base URL you can use this (would return "http:// localhost/yiistore2/upload")

Yii::app()->baseUrl

The following Code would return just "localhost/yiistore2/upload" without http[s]://

Yii::app()->getBaseUrl(true)

Or you could get the webroot path (would return "d:\wamp\www\yii2store")

Yii::getPathOfAlias('webroot')

Can I draw rectangle in XML?

Use this code

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

    <corners
        android:bottomLeftRadius="5dp"
        android:bottomRightRadius="5dp"
        android:radius="0.1dp"
        android:topLeftRadius="5dp"
        android:topRightRadius="5dp" />

    <solid android:color="#Efffff" />

    <stroke
        android:width="2dp"
        android:color="#25aaff" />

</shape>

How to change Apache Tomcat web server port number

Simple !!... you can do it easily via server.xml

  • Go to tomcat>conf folder
  • Edit server.xml
  • Search "Connector port"
  • Replace "8080" by your port number
  • Restart tomcat server.

You are done!.

What is the difference between a schema and a table and a database?

schema : database : table :: floor plan : house : room

Which passwordchar shows a black dot (•) in a winforms textbox?

One more solution to use this Unicode black circle >>

Start >> All Programs >> Accessories >> System Tools >> Character Map

Then select Arial font and choose the Black circle copy it and paste it into PasswordChar property of the textbox.

That's it....

Adding Counter in shell script

Here's how you might implement a counter:

counter=0
while true; do
  if /home/hadoop/latest/bin/hadoop fs -ls /apps/hdtech/bds/quality-rt/dt=$DATE_YEST_FORMAT2 then
       echo "Files Present" | mailx -s "File Present"  -r [email protected] [email protected]
       exit 0
  elif [[ "$counter" -gt 20 ]]; then
       echo "Counter: $counter times reached; Exiting loop!"
       exit 1
  else
       counter=$((counter+1))
       echo "Counter: $counter time(s); Sleeping for another half an hour" | mailx -s "Time to Sleep Now"  -r [email protected] [email protected]
       sleep 1800
  fi
done

Some Explanations:

  • counter=$((counter+1)) - this is how you can increment a counter. The $ for counter is optional inside the double parentheses in this case.
  • elif [[ "$counter" -gt 20 ]]; then - this checks whether $counter is not greater than 20. If so, it outputs the appropriate message and breaks out of your while loop.

Execute command without keeping it in history

You might consider using a shell without history, like perhaps

/bin/sh << END
   your commands without history
END

(perhaps /bin/dash or /bin/sash could be more appropriate than /bin/sh)

or even better use the batch utility e.g

batch << EOB
   your commands
EOB

The history would then contain sh or batch which is not very meaningful

Detect click inside/outside of element with single event handler

Using jQuery, and assuming that you have <div id="foo">:

jQuery(function($){
  $('#foo').click(function(e){
    console.log( 'clicked on div' );
    e.stopPropagation(); // Prevent bubbling
  });
  $('body').click(function(e){
    console.log( 'clicked outside of div' );
  });
});

Edit: For a single handler:

jQuery(function($){
  $('body').click(function(e){
    var clickedOn = $(e.target);
    if (clickedOn.parents().andSelf().is('#foo')){
      console.log( "Clicked on", clickedOn[0], "inside the div" );
    }else{
      console.log( "Clicked outside the div" );
  });
});

unknown type name 'uint8_t', MinGW

I had to include "PROJECT_NAME/osdep.h" and that includes the os specific configurations.

I would look in other files using the types you are interested in and find where/how they are defined (by looking at includes).

Why does JavaScript only work after opening developer tools in IE once?

I guess this could help, adding this before any tag of javascript:

try{
  console
}catch(e){
   console={}; console.log = function(){};
}

ERROR Error: No value accessor for form control with unspecified name attribute on switch

In my case, it's happening in my shared module and I had to add the following into @NgModule:

...
  imports: [
    CommonModule,
    FormsModule,
    ReactiveFormsModule,
    IonicModule
  ],
...

Maven error: Could not find or load main class org.codehaus.plexus.classworlds.launcher.Launcher

I was having this same problem and was able to resolve it by carefully redoing the Environment Variables:

  • M2_HOME
  • M2
  • JAVA_HOME

Also, I made them all System Variables, not User Variables like the Maven instructions say. When you

echo %Path%

Make sure you can see the %M2% and %JAVA_HOME% variables completely expanded, i.e. :

C:\Users\afairchild>echo %Path%
C:\Program Files\Apache Software Foundation\apache-maven-3.0.4\bin;C:\Program Files\Java\jdk1.7.0_09\bin; [etc]

how do I check in bash whether a file was created more than x time ago?

Using the stat to figure out the last modification date of the file, date to figure out the current time and a liberal use of bashisms, one can do the test that you want based on the file's last modification time1.

if [ "$(( $(date +"%s") - $(stat -c "%Y" $somefile) ))" -gt "7200" ]; then
   echo "$somefile is older then 2 hours"
fi

While the code is a bit less readable then the find approach, I think its a better approach then running find to look at a file you already "found". Also, date manipulation is fun ;-)


  1. As Phil correctly noted creation time is not recorded, but use %Z instead of %Y below to get "change time" which may be what you want.

[Update]

For mac users, use stat -f "%m" $somefile instead of the Linux specific syntax above

How to convert int[] to Integer[] in Java?

Rather than write your own code you can use an IntBuffer to wrap the existing int[] without having to copy the data into an Integer array

int[] a = {1,2,3,4};
IntBuffer b = IntBuffer.wrap(a);

IntBuffer implements comparable so you are able to use the code you already have written. Formally maps compare keys such that a.equals(b) is used to say two keys are equal, so two IntBuffers with array 1,2,3 - even if the arrays are in different memory locations - are said to be equal and so will work for your frequency code.

ArrayList<int[]> data = ... // load a dataset`

Map<IntBuffer, Double> frequencies = new HashMap<IntBuffer, Double>();

for(int[] a : data) {

    IntBuffer q = IntBuffer.wrap(a);

    if(frequencies.containsKey(q)) {
        frequencies.put(q, tfs.get(q) + p);
    } else {
        frequencies.put(q, p);
    }

}

Hope that helps

What is the use of adding a null key or value to a HashMap in Java?

I'm not positive what you're asking, but if you're looking for an example of when one would want to use a null key, I use them often in maps to represent the default case (i.e. the value that should be used if a given key isn't present):

Map<A, B> foo;
A search;
B val = foo.containsKey(search) ? foo.get(search) : foo.get(null);

HashMap handles null keys specially (since it can't call .hashCode() on a null object), but null values aren't anything special, they're stored in the map like anything else

nodejs mysql Error: Connection lost The server closed the connection

Creating and destroying the connections in each query maybe complicated, i had some headaches with a server migration when i decided to install MariaDB instead MySQL. For some reason in the file etc/my.cnf the parameter wait_timeout had a default value of 10 sec (it causes that the persistence can't be implemented). Then, the solution was set it in 28800, that's 8 hours. Well, i hope help somebody with this "güevonada"... excuse me for my bad english.

Work on a remote project with Eclipse via SSH

I'm in the same spot myself (or was), FWIW I ended up checking out to a samba share on the Linux host and editing that share locally on the Windows machine with notepad++, then I compiled on the Linux box via PuTTY. (We weren't allowed to update the ten y/o versions of the editors on the Linux host and it didn't have Java, so I gave up on X11 forwarding)

Now... I run modern Linux in a VM on my Windows host, add all the tools I want (e.g. CDT) to the VM and then I checkout and build in a chroot jail that closely resembles the RTE.

It's a clunky solution but I thought I'd throw it in to the mix.

Passing parameter via url to sql server reporting service

I've just solved this problem myself. I found the solution on MSDN: http://msdn.microsoft.com/en-us/library/ms155391.aspx.

The format basically is

http://<server>/reportserver?/<path>/<report>&rs:Command=Render&<parameter>=<value>

How do I skip an iteration of a `foreach` loop?

Another approach is to filter using LINQ before the loop executes:

foreach ( int number in numbers.Where(n => n >= 0) )
{
    // process number
}

fstream won't create a file

This will do:

#include <fstream>
#include <iostream>
using std::fstream;

int main(int argc, char *argv[]) {
    fstream file;
    file.open("test.txt",std::ios::out);
    file << fflush;
    file.close();
}

Could not autowire field:RestTemplate in Spring boot application

Error points directly that RestTemplate bean is not defined in context and it cannot load the beans.

  1. Define a bean for RestTemplate and then use it
  2. Use a new instance of the RestTemplate

If you are sure that the bean is defined for the RestTemplate then use the following to print the beans that are available in the context loaded by spring boot application

ApplicationContext ctx = SpringApplication.run(Application.class, args);
String[] beanNames = ctx.getBeanDefinitionNames();
Arrays.sort(beanNames);
for (String beanName : beanNames) {
    System.out.println(beanName);
}

If this contains the bean by the name/type given, then all good. Or else define a new bean and then use it.

What is the difference between URI, URL and URN?

Below I sum up Prateek Joshi's awesome explanation.

The theory:

  • URI (uniform resource identifier) identifies a resource (text document, image file, etc)
  • URL (uniform resource locator) is a subset of the URIs that include a network location
  • URN (uniform resource name) is a subset of URIs that include a name within a given space, but no location

That is:

enter image description here

And for an example:

enter image description here

Also, if you haven't already, I suggest reading Roger Pate's answer.

WCF on IIS8; *.svc handler mapping doesn't work

We managed to solve the error under Windows Server 2012 by:

  1. Removing from "Remove Roles and Features Wizard" .NET Framework 4.5 Features/ASP.NET 4.5 and all its dependent features
  2. Re-installing the removed features.

It seems the order of installation is the cause.

Also, make sure you have HTTP Activation installed under WCF Services.

Use the auto keyword in C++ STL

This is new item in the language which I think we are going to be struggling with for years to come. The 'auto' of the start presents not only readability problem , from now on when you encounter it you will have to spend considerable time trying to figure out wtf it is(just like the time that intern named all variables xyz :)), but you also will spend considerable time cleaning after easily excitable programmers , like the once who replied before me. Example from above , I can bet $1000 , will be written "for (auto it : s)", not "for (auto& it : s)", as a result invoking move semantics where you list expecting it, modifying your collection underneath .

Another example of the problem is your question itself. You clearly don't know much about stl iterators and you trying to overcome that gap through usage of the magic of 'auto', as a result you create the code that might be problematic later on

Locate the nginx.conf file my nginx is actually using

which nginx

will give you the path of the nginx being used


EDIT (2017-Jan-18)

Thanks to Will Palmer's comment on this answer, I have added the following...

If you've installed nginx via a package manager such as HomeBrew...

which nginx

may not give you the EXACT path to the nginx being used. You can however find it using

realpath $(which nginx)

and as mentioned by @Daniel Li

you can get configuration of nginx via his method

alternatively you can use this:

nginx -V

Angularjs $http post file and form data

You can also upload using HTML5. You can use this AJAX uploader.

The JS code is basically:

  $scope.doPhotoUpload = function () {
    // ..
    var myUploader = new uploader(document.getElementById('file_upload_element_id'), options);
    myUploader.send();
    // ..
  }

Which reads from an HTML input element

<input id="file_upload_element_id" type="file" onchange="angular.element(this).scope().doPhotoUpload()">

Save internal file in my own internal folder in Android

Save:

public boolean saveFile(Context context, String mytext){
    Log.i("TESTE", "SAVE");
    try {
        FileOutputStream fos = context.openFileOutput("file_name"+".txt",Context.MODE_PRIVATE);
        Writer out = new OutputStreamWriter(fos);
        out.write(mytext);
        out.close();
        return true;
    } catch (IOException e) {
        e.printStackTrace();
        return false;
    }
}

Load:

public String load(Context context){
    Log.i("TESTE", "FILE");
    try {
        FileInputStream fis = context.openFileInput("file_name"+".txt");
        BufferedReader r = new BufferedReader(new InputStreamReader(fis));
        String line= r.readLine();
        r.close();
        return line;
    } catch (IOException e) {
        e.printStackTrace();
        Log.i("TESTE", "FILE - false");
        return null;
    }
}

datatable jquery - table header width not aligned with body width

I was facing the same issue. I added the scrollX: true property for the dataTable and it worked. There is no need to change the CSS for datatable

jQuery('#myTable').DataTable({
                            "fixedHeader":true,
                            "scrollY":"450px",
                            "scrollX":true,
                            "paging":   false,
                            "ordering": false,
                            "info":     false,
                            "searching": false,
                            "scrollCollapse": true
                            });

How can I check if a URL exists via PHP?

the simple way is curl (and FASTER too)

<?php
$mylinks="http://site.com/page.html";
$handlerr = curl_init($mylinks);
curl_setopt($handlerr,  CURLOPT_RETURNTRANSFER, TRUE);
$resp = curl_exec($handlerr);
$ht = curl_getinfo($handlerr, CURLINFO_HTTP_CODE);


if ($ht == '404')
     { echo 'OK';}
else { echo 'NO';}

?>

List file names based on a filename pattern and file content?

grep LMN20113456 LMN2011*

or if you want to search recursively through subdirectories:

find . -type f -name 'LMN2011*' -exec grep LMN20113456 {} \;

Generate random numbers with a given (numerical) distribution

from __future__ import division
import random
from collections import Counter


def num_gen(num_probs):
    # calculate minimum probability to normalize
    min_prob = min(prob for num, prob in num_probs)
    lst = []
    for num, prob in num_probs:
        # keep appending num to lst, proportional to its probability in the distribution
        for _ in range(int(prob/min_prob)):
            lst.append(num)
    # all elems in lst occur proportional to their distribution probablities
    while True:
        # pick a random index from lst
        ind = random.randint(0, len(lst)-1)
        yield lst[ind]

Verification:

gen = num_gen([(1, 0.1),
               (2, 0.05),
               (3, 0.05),
               (4, 0.2),
               (5, 0.4),
               (6, 0.2)])
lst = []
times = 10000
for _ in range(times):
    lst.append(next(gen))
# Verify the created distribution:
for item, count in Counter(lst).iteritems():
    print '%d has %f probability' % (item, count/times)

1 has 0.099737 probability
2 has 0.050022 probability
3 has 0.049996 probability 
4 has 0.200154 probability
5 has 0.399791 probability
6 has 0.200300 probability

How to write logs in text file when using java.util.logging.Logger

Hope people find this helpful

public static void writeLog(String info) {
    String filename = "activity.log";
    String FILENAME = "C:\\testing\\" + filename;
    BufferedWriter bw = null;
    FileWriter fw = null;
    try {
        fw = new FileWriter(FILENAME, true);
        bw = new BufferedWriter(fw);
        bw.write(info);
        bw.write("\n");
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (bw != null)
                bw.close();
            if (fw != null)
                fw.close();
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }
}

Include another JSP file

You can use Include Directives

<%
 if(request.getParameter("p")!=null)
 { 
   String p = request.getParameter("p");
%>    

<%@include file="<%="includes/" + p +".jsp"%>"%>

<% 
 }
%>

or JSP Include Action

<%
 if(request.getParameter("p")!=null)
 { 
   String p = request.getParameter("p");
%>    

<jsp:include page="<%="includes/"+p+".jsp"%>"/>

<% 
 }
%>

the different is include directive includes a file during the translation phase. while JSP Include Action includes a file at the time the page is requested

I recommend Spring MVC Framework as your controller to manipulate things. use url pattern instead of parameter.

example:

www.yourwebsite.com/products

instead of

www.yourwebsite.com/?p=products

Watch this video Spring MVC Framework

Writing binary number system in C code

Prefix you literal with 0b like in

int i = 0b11111111;

See here.

how to set textbox value in jquery

I would like to point out to you that .val() also works with selects to select the current selected value.

When tracing out variables in the console, How to create a new line?

You need to add the new line character \n:

console.log('line one \nline two')

would display:

line one

line two

Pass multiple arguments into std::thread

You literally just pass them in std::thread(func1,a,b,c,d); that should have compiled if the objects existed, but it is wrong for another reason. Since there is no object created you cannot join or detach the thread and the program will not work correctly. Since it is a temporary the destructor is immediately called, since the thread is not joined or detached yet std::terminate is called. You could std::join or std::detach it before the temp is destroyed, like std::thread(func1,a,b,c,d).join();//or detach .

This is how it should be done.

std::thread t(func1,a,b,c,d);
t.join();  

You could also detach the thread, read-up on threads if you don't know the difference between joining and detaching.

Append values to query string

This is even more frustrating because now (.net 5) MS have marked many (all) of their methods that take a string instead of a Uri as obsolete.

Anyway, probably a better way to manipulate relative Uris is to give it what it wants:

var requestUri = new Uri("x://x").MakeRelativeUri(
   new UriBuilder("x://x") { Path = path, Query = query }.Uri);

You can use the other answers to actually build the query string.

Beginner Python Practice?

You could also try CheckIO which is kind of a quest where you have to post solutions in Python 2.7 or 3.3 to move up in the game. Fun and has quite a big community for questions and support.

From their Main Wiki Page:

Welcome to CheckIO – a service that has united all levels of Python developers – from beginners up to the real experts!

Here you can learn Python coding, try yourself in solving various kinds of problems and share your ideas with others. Moreover, you can consider original solutions of other users, exchange opinions and find new friends.

If you are just starting with Python – CheckIO is a great chance for you to learn the basics and get a rich practice in solving different tasks. If you’re an experienced coder, here you’ll find an exciting opportunity to perfect your skills and learn new alternative logics from others. On CheckIO you can not only resolve the existing tasks, but also provide your own ones and even get points for them. Enjoy the possibility of playing logical games, participating in exciting competitions and share your success with friends in CheckIO.org!

Change background color of selected item on a ListView

I know this is a old question, but i give a simple solution for this need (without loops!):

//On your adapter create a variable:
private View lastSelectedItem;

//Define the folowing method:
private void toggleBackgroundItem(View view) {
    if (lastSelectedItem != null) {
        lastSelectedItem.setBackgroundColor(Color.TRANSPARENT);
    }
    view.setBackgroundColor(getResources().getColor(R.color.colorPrimaryDark));
    lastSelectedItem = view;

}
//finally invoque the method onItemClick
lvSac.setOnItemClickListener(new AdapterView.OnItemClickListener()

{
    @Override
    public void onItemClick (AdapterView < ? > adapterView, View view,int i, long l){

    toggleBackgroundItem(view);
}
}

MySQL - how to front pad zip code with "0"?

LPAD works with VARCHAR2 as it does not put spaces for left over bytes. LPAD changes leftover/null bytes to zeros on LHS SO datatype should be VARCHAR2

Spaces cause split in path with PowerShell

Simply put the path in double quotes in front of cd, Like this:

cd "C:\Users\MyComputer\Documents\Visual Studio 2019\Projects"

@synthesize vs @dynamic, what are the differences?

One thing want to add is that if a property is declared as @dynamic it will not occupy memory (I confirmed with allocation instrument). A consequence is that you can declare property in class category.

Java List.add() UnsupportedOperationException

instead of using add() we can use addall()

{ seeAlso.addall(groupDn); }

add adds a single item, while addAll adds each item from the collection one by one. In the end, both methods return true if the collection has been modified. In case of ArrayList this is trivial, because the collection is always modified, but other collections, such as Set, may return false if items being added are already there.

How long is the SHA256 hash?

Encoding options for SHA256's 256 bits:

  1. Base64: 6 bits per char = CHAR(44) including padding character
  2. Hex: 4 bits per char = CHAR(64)
  3. Binary: 8 bits per byte = BINARY(32)

incompatible character encodings: ASCII-8BIT and UTF-8

i had a similiar problem and the gem string-scrub automagically fixed it for me. https://github.com/hsbt/string-scrub If the given string contains an invalid byte sequence then that invalid byte sequence is replaced with the unicode replacement character (?) and a new string is returned.

Angular2: Cannot read property 'name' of undefined

You were getting this error because you followed the poorly-written directions on the Heroes tutorial. I ran into the same thing.

Specifically, under the heading Display hero names in a template, it states:

To display the hero names in an unordered list, insert the following chunk of HTML below the title and above the hero details.

followed by this code block:

<h2>My Heroes</h2>
<ul class="heroes">
  <li>
    <!-- each hero goes here -->
  </li>
</ul>

It does not instruct you to replace the previous detail code, and it should. This is why we are left with:

<h2>{{hero.name}} details!</h2>

outside of our *ngFor.

However, if you scroll further down the page, you will encounter the following:

The template for displaying heroes should look like this:

<h2>My Heroes</h2>
<ul class="heroes">
  <li *ngFor="let hero of heroes">
    <span class="badge">{{hero.id}}</span> {{hero.name}}
  </li>
</ul>

Note the absence of the detail elements from previous efforts.

An error like this by the author can result in quite a wild goose-chase. Hopefully, this post helps others avoid that.

Android Studio: Unable to start the daemon process

Check your project folder. You may have there a file called gradle.properties and in there, check to see if you don't have this line:

org.gradle.jvmargs=-Xmx2048m -XX:+HeapDumpOnOutOfMemoryError -Dfile.encoding=UTF-8

In my case, I just deleted the file, but check the contents to see if you don't actually want to keep some of the settings.

Getting URL parameter in java and extract a specific text from that URL

I have something like this:

import org.apache.http.NameValuePair;
import org.apache.http.client.utils.URIBuilder;

private String getParamValue(String link, String paramName) throws URISyntaxException {
        List<NameValuePair> queryParams = new URIBuilder(link).getQueryParams();
        return queryParams.stream()
                .filter(param -> param.getName().equalsIgnoreCase(paramName))
                .map(NameValuePair::getValue)
                .findFirst()
                .orElse("");
    }

How to initialize an array in one step using Ruby?

Oneliner:

array = [] << 1 << 2 << 3   #this is for fixnums.

or

 a = %w| 1 2 3 4 5 |

or

 a = [*'1'..'3']

or

 a = Array.new(3, '1')

or

 a = Array[*'1'..'3']

How to calculate growth with a positive and negative number?

Let me draw the scenario.
From: -303 To 183, what is the percentage change?

-303, -100%                0        183, 60.396%       303, 100%

|_________________ ||||||||||||||||||||||||________|

(183 - -303) / |-303| * 100 = 160.396%
Total Percent Change is approximately 160%

Note: No matter how negative the value is, it is treated as -100%.

Provisioning Profiles menu item missing from Xcode 5

For me, the refresh in xcode 5 prefs->accounts was doing nothing. At one point it showed me three profiles so I thought I was one refresh away, but after the next refresh it went back to just one profile, so I abandoned this method.

If anyone gets this far and is still struggling, here's what I did:

  1. Close xcode 5
  2. Open xcode 4.6.2
  3. Go to Window->Organizer->Provisioning Profiles
  4. Press Refresh arrow on bottom right

When I did this, everything synced up perfectly. It even told me what it was downloading each step of the way like good software does. After the sync completed, I closed xcode 4.6.2, re-opened xcode 5 and went to preferences->accounts and voila, all of my profiles are now available in xocde 5.

Getting Chrome to accept self-signed localhost certificate

For Fedora, Ubuntu, Linux, if you're getting example.com Not a Certification authority error when adding the certificate using the gui to add a new root authority. If you want to trust a server self signed certificate, it cannot make mention of an invalid authority... even if that's itself. I've only managed to make it work by trusting my authority and using that authorities key to sign server certificates.

Here's the self signed CA certificate that it accepted. This is the only way that I found works to get around cert_authority_invalid, I tried for hours to get it to accept a self signed end point certificate, no cigar. The UI will accept self signed authorities, as long as it's declared CA:TRUE. After that, all certs signed by that key with the correct DN will be accepted by chrome without needing to add them independently.

openssl req -new -x509 -extensions v3_req -days 8440 -config ca.conf -key rockstor.key -out rockstor.cert

[req]
distinguished_name=dn
req_extensions=v3_req
prompt = no

[v3_req]
basicConstraints=CA:TRUE,pathlen:0
keyUsage = keyEncipherment, dataEncipherment
extendedKeyUsage = serverAuth, clientAuth
subjectAltName=@alt_names

[alt_names]
DNS.1 = ca.tdpowerskills.com

[dn]
C = US
ST = LA
L = Alexandria
O = TDPS Certification Authority
OU = LEARNOPS
CN = ca.tdpowerskills.com

openssl req -new -x509 -extensions v3_req -days 8440 -config config.conf -key rockstor.key -out rockstor.cert

[req]
distinguished_name=dn
req_extensions=v3_req
prompt = no

[v3_req]
basicConstraints=CA:FALSE
keyUsage = keyEncipherment, dataEncipherment
extendedKeyUsage = serverAuth, clientAuth
subjectAltName=@alt_names
issuerAltName=DNS:ca.tdpowerskills.com

[alt_names]
DNS.1 = big.tdps.app

[dn]
C = US
ST = LA
L = Alexandria
O = TDPS Certification Authority
OU = LEARNOPS
CN = ca.tdpowerskills.com

If that doesn't work:

  • chrome://restart to actually restart

  • Try to get more details on the error using firefox, it tends to explain errors better... while chrome will say, ERR_CERTIFICATE_INVALID, firefox will throw: MOZILLA_PKIX_ERROR_CA_CERT_USED_AS_END_ENTITY.

  • Remember that chrome now requires Subject Alternate Name and nearly ignores CN.

For others:

  • certutil -d sql:$HOME/.pki/nssdb -A -t "P,," -n <nickname> -i <my.crt> // For server sertificates

  • certutil -d sql:$HOME/.pki/nssdb -A -t "C,," -n <nickname> -i <my.crt> for CA's https://blogs.oracle.com/meena/about-trust-flags-of-certificates-in-nss-database-that-can-be-modified-by-certutil

  • For Firefox, the UI adding an exception certificate does work and it will trust it once you do that.

  • Perhaps you have funky settings in /etc/pki/tls/openssl.cnf which get merged with your config.

  • perhaps you're no adding an extension to the config or command line, such as v3_req

  • Note, my method bypasses the need for a CSR by just signing the certificates with the authority key and adding details for the dev servers. CSR's allow more keys for actual security.

  • I tried everything, but chrome requires an authority with basicconstraints CA:true set. And server certificates must all be singed by a valid Authority... even if that's just another certificate that the signed themselves with CA:true.

How to replace substrings in windows batch file

To avoid blank line skipping just replace this:

echo !modified! >> %OUTTEXTFILE%

with this:

echo.!modified! >> %OUTTEXTFILE%