Programs & Examples On #Maked textbox

org.hibernate.MappingException: Unknown entity: annotations.Users

Add the following code to hibernate.cfg.xml

  <property name="hibernate.c3p0.min_size">5</property>
  <property name="hibernate.c3p0.max_size">20</property>
  <property name="hibernate.c3p0.timeout">300</property>
  <property name="hibernate.c3p0.max_statements">50</property>
  <property name="hibernate.c3p0.idle_test_period">3000</property>

How to get text from each cell of an HTML table?

its

selenium.getTable("tablename".rowNumber.colNumber)

not

selenium.getTable("tablename".colNumber.rowNumber)

How to get city name from latitude and longitude coordinates in Google Maps?

You can use this if you have a list:

Address address = list.get(0);
String cityname = address.getLocality();

Parsing time string in Python

In [117]: datetime.datetime.strptime?
Type:           builtin_function_or_method
Base Class:     <type 'builtin_function_or_method'>
String Form:    <built-in method strptime of type object at 0x9a2520>
Namespace:      Interactive
Docstring:
    string, format -> new datetime parsed from a string (like time.strptime()).

How to go from one page to another page using javascript?

The correct solution that i get is

<html>
      <head>
        <script type="text/javascript" language="JavaScript">
                  function clickedButton()
            {

                window.location = 'new url'

            }
             </script>
      </head>

      <form name="login_form" method="post">
            ..................
            <input type="button" value="Login" onClick="clickedButton()"/>
      </form>
 </html>

Here the new url is given inside the single quote.

Change the name of a key in dictionary

To convert all the keys in the dictionary

Suppose this is your dictionary:

>>> sample = {'person-id': '3', 'person-name': 'Bob'}

To convert all the dashes to underscores in the sample dictionary key:

>>> sample = {key.replace('-', '_'): sample.pop(key) for key in sample.keys()}
>>> sample
>>> {'person_id': '3', 'person_name': 'Bob'}

How to alter SQL in "Edit Top 200 Rows" in SSMS 2008

Ctrl+3 in SQL Server 2012. Might work in 2008 too

Launch programs whose path contains spaces

You van use Exec

Dim objShell
Set objShell = WScript.CreateObject( "WScript.Shell" )
objShell.Exec("c:\Program Files\Mozilla Firefox\firefox.exe")
Set objShell = Nothing

How do you redirect to a page using the POST verb?

I would like to expand the answer of Jason Bunting

like this

ActionResult action = new SampelController().Index(2, "text");
return action;

And Eli will be here for something idea on how to make it generic variable

Can get all types of controller

Make a dictionary with duplicate keys in Python

If you want to have lists only when they are necessary, and values in any other cases, then you can do this:

class DictList(dict):
    def __setitem__(self, key, value):
        try:
            # Assumes there is a list on the key
            self[key].append(value)
        except KeyError: # If it fails, because there is no key
            super(DictList, self).__setitem__(key, value)
        except AttributeError: # If it fails because it is not a list
            super(DictList, self).__setitem__(key, [self[key], value])

You can then do the following:

dl = DictList()
dl['a']  = 1
dl['b']  = 2
dl['b'] = 3

Which will store the following {'a': 1, 'b': [2, 3]}.


I tend to use this implementation when I want to have reverse/inverse dictionaries, in which case I simply do:

my_dict = {1: 'a', 2: 'b', 3: 'b'}
rev = DictList()
for k, v in my_dict.items():
    rev_med[v] = k

Which will generate the same output as above: {'a': 1, 'b': [2, 3]}.


CAVEAT: This implementation relies on the non-existence of the append method (in the values you are storing). This might produce unexpected results if the values you are storing are lists. For example,

dl = DictList()
dl['a']  = 1
dl['b']  = [2]
dl['b'] = 3

would produce the same result as before {'a': 1, 'b': [2, 3]}, but one might expected the following: {'a': 1, 'b': [[2], 3]}.

How to add jQuery in JS file

If document.write('<\script ...') isn't working, try document.createElement('script')...

Other than that, you should be worried about the type of website you're making - do you really think its a good idea to include .js files from .js files?

How do I create an Excel chart that pulls data from multiple sheets?

Here's some code from Excel 2010 that may work. It has a couple specifics (like filtering bad-encode characters from titles) but it was designed to create multiple multi-series graphs from 4-dimensional data having both absolute and percentage-based data. Modify it how you like:

Sub createAllGraphs()

Const chartWidth As Integer = 260
Const chartHeight As Integer = 200




If Sheets.Count = 1 Then
    Sheets.Add , Sheets(1)
    Sheets(2).Name = "AllCharts"
ElseIf Sheets("AllCharts").ChartObjects.Count > 0 Then
    Sheets("AllCharts").ChartObjects.Delete
End If
Dim c As Variant
Dim c2 As Variant
Dim cs As Object
Set cs = Sheets("AllCharts")
Dim s As Object
Set s = Sheets(1)

Dim i As Integer


Dim chartX As Integer
Dim chartY As Integer

Dim r As Integer
r = 2

Dim curA As String
curA = s.Range("A" & r)
Dim curB As String
Dim curC As String
Dim startR As Integer
startR = 2

Dim lastTime As Boolean
lastTime = False

Do While s.Range("A" & r) <> ""

    If curC <> s.Range("C" & r) Then

        If r <> 2 Then
seriesAdd:
            c.SeriesCollection.Add s.Range("D" & startR & ":E" & (r - 1)), , False, True
            c.SeriesCollection(c.SeriesCollection.Count).Name = Replace(s.Range("C" & startR), "Â", "")
            c.SeriesCollection(c.SeriesCollection.Count).XValues = "='" & s.Name & "'!$D$" & startR & ":$D$" & (r - 1)
            c.SeriesCollection(c.SeriesCollection.Count).Values = "='" & s.Name & "'!$E$" & startR & ":$E$" & (r - 1)
            c.SeriesCollection(c.SeriesCollection.Count).HasErrorBars = True
            c.SeriesCollection(c.SeriesCollection.Count).ErrorBars.Select
            c.SeriesCollection(c.SeriesCollection.Count).ErrorBar Direction:=xlY, Include:=xlBoth, Type:=xlCustom, Amount:="='" & s.Name & "'!$F$" & startR & ":$F$" & (r - 1), minusvalues:="='" & s.Name & "'!$F$" & startR & ":$F$" & (r - 1)
            c.SeriesCollection(c.SeriesCollection.Count).ErrorBar Direction:=xlX, Include:=xlBoth, Type:=xlFixedValue, Amount:=0

            c2.SeriesCollection.Add s.Range("D" & startR & ":D" & (r - 1) & ",G" & startR & ":G" & (r - 1)), , False, True
            c2.SeriesCollection(c2.SeriesCollection.Count).Name = Replace(s.Range("C" & startR), "Â", "")
            c2.SeriesCollection(c2.SeriesCollection.Count).XValues = "='" & s.Name & "'!$D$" & startR & ":$D$" & (r - 1)
            c2.SeriesCollection(c2.SeriesCollection.Count).Values = "='" & s.Name & "'!$G$" & startR & ":$G$" & (r - 1)
            c2.SeriesCollection(c2.SeriesCollection.Count).HasErrorBars = True
            c2.SeriesCollection(c2.SeriesCollection.Count).ErrorBars.Select
            c2.SeriesCollection(c2.SeriesCollection.Count).ErrorBar Direction:=xlY, Include:=xlBoth, Type:=xlCustom, Amount:="='" & s.Name & "'!$H$" & startR & ":$H$" & (r - 1), minusvalues:="='" & s.Name & "'!$H$" & startR & ":$H$" & (r - 1)
            c2.SeriesCollection(c2.SeriesCollection.Count).ErrorBar Direction:=xlX, Include:=xlBoth, Type:=xlFixedValue, Amount:=0
            If lastTime = True Then GoTo postLoop
        End If

        If curB <> s.Range("B" & r).Value Then

            If curA <> s.Range("A" & r).Value Then
                chartX = chartX + chartWidth * 2
                chartY = 0
                curA = s.Range("A" & r)
            End If

            Set c = cs.ChartObjects.Add(chartX, chartY, chartWidth, chartHeight)
            Set c = c.Chart
            c.ChartWizard , xlXYScatterSmooth, , , , , True, Replace(s.Range("B" & r), "Â", "") & " " & s.Range("A" & r), s.Range("D1"), s.Range("E1")

            Set c2 = cs.ChartObjects.Add(chartX + chartWidth, chartY, chartWidth, chartHeight)
            Set c2 = c2.Chart
            c2.ChartWizard , xlXYScatterSmooth, , , , , True, Replace(s.Range("B" & r), "Â", "") & " " & s.Range("A" & r) & " (%)", s.Range("D1"), s.Range("G1")

            chartY = chartY + chartHeight
            curB = s.Range("B" & r)
            curC = s.Range("C" & r)
        End If

        curC = s.Range("C" & r)
        startR = r
    End If

    If s.Range("A" & r) <> "" Then oneMoreTime = False ' end the loop for real this time
    r = r + 1
Loop

lastTime = True
GoTo seriesAdd
postLoop:
cs.Activate

End Sub

using jQuery .animate to animate a div from right to left?

This worked for me

$("div").css({"left":"2000px"}).animate({"left":"0px"}, "slow");

How to make exe files from a node.js app?

I did find any of these solutions met my requirements, so made my own version of node called node2exe that does this. It's available from https://github.com/areve/node2exe

Total memory used by Python process?

On Windows, you can use WMI (home page, cheeseshop):


def memory():
    import os
    from wmi import WMI
    w = WMI('.')
    result = w.query("SELECT WorkingSet FROM Win32_PerfRawData_PerfProc_Process WHERE IDProcess=%d" % os.getpid())
    return int(result[0].WorkingSet)

On Linux (from python cookbook http://code.activestate.com/recipes/286222/:

import os
_proc_status = '/proc/%d/status' % os.getpid()

_scale = {'kB': 1024.0, 'mB': 1024.0*1024.0,
          'KB': 1024.0, 'MB': 1024.0*1024.0}

def _VmB(VmKey):
    '''Private.
    '''
    global _proc_status, _scale
     # get pseudo file  /proc/<pid>/status
    try:
        t = open(_proc_status)
        v = t.read()
        t.close()
    except:
        return 0.0  # non-Linux?
     # get VmKey line e.g. 'VmRSS:  9999  kB\n ...'
    i = v.index(VmKey)
    v = v[i:].split(None, 3)  # whitespace
    if len(v) < 3:
        return 0.0  # invalid format?
     # convert Vm value to bytes
    return float(v[1]) * _scale[v[2]]


def memory(since=0.0):
    '''Return memory usage in bytes.
    '''
    return _VmB('VmSize:') - since


def resident(since=0.0):
    '''Return resident memory usage in bytes.
    '''
    return _VmB('VmRSS:') - since


def stacksize(since=0.0):
    '''Return stack size in bytes.
    '''
    return _VmB('VmStk:') - since

The performance impact of using instanceof in Java

Answering your very last question: Unless a profiler tells you, that you spend ridiculous amounts of time in an instanceof: Yes, you're nitpicking.

Before wondering about optimizing something that never needed to be optimized: Write your algorithm in the most readable way and run it. Run it, until the jit-compiler gets a chance to optimize it itself. If you then have problems with this piece of code, use a profiler to tell you, where to gain the most and optimize this.

In times of highly optimizing compilers, your guesses about bottlenecks will be likely to be completely wrong.

And in true spirit of this answer (which I wholeheartly believe): I absolutely don't know how instanceof and == relate once the jit-compiler got a chance to optimize it.

I forgot: Never measure the first run.

When you use 'badidea' or 'thisisunsafe' to bypass a Chrome certificate/HSTS error, does it only apply for the current site?

I'm a PHP developer and to be able to work on my development environment with a certificate, I was able to do the same by finding the real SSL HTTPS/HTTP Certificate and deleting it.

The steps are :

  1. In the address bar, type "chrome://net-internals/#hsts".
  2. Type the domain name in the text field below "Delete domain".
  3. Click the "Delete" button.
  4. Type the domain name in the text field below "Query domain".
  5. Click the "Query" button.
  6. Your response should be "Not found".

You can find more information at : http://classically.me/blogs/how-clear-hsts-settings-major-browsers

Although this solution is not the best, Chrome currently does not have any good solution for the moment. I have escalated this situation with their support team to help improve user experience.

Edit : you have to repeat the steps every time you will go on the production site.

How to pass a callback as a parameter into another function

Yes of course, function are objects and can be passed, but of course you must declare it:

function firstFunction(){
    //some code
    var callbackfunction = function(data){
       //do something with the data returned from the ajax request
     }
    //a callback function is written for $.post() to execute
    secondFunction("var1","var2",callbackfunction);
}

an interesting thing is that your callback function has also access to every variable you might have declared inside firstFunction() (variables in javascript have local scope).

How to Correctly Check if a Process is running and Stop it

@jmp242 - the generic System.Object type does not contain the CloseMainWindow method, but statically casting the System.Diagnostics.Process type when collecting the ProcessList variable works for me. Updated code (from this answer) with this casting (and looping changed to use ForEach-Object) is below.

function Stop-Processes {
    param(
        [parameter(Mandatory=$true)] $processName,
                                     $timeout = 5
    )
    [System.Diagnostics.Process[]]$processList = Get-Process $processName -ErrorAction SilentlyContinue

    ForEach ($Process in $processList) {
        # Try gracefully first
        $Process.CloseMainWindow() | Out-Null
    }

    # Check the 'HasExited' property for each process
    for ($i = 0 ; $i -le $timeout; $i++) {
        $AllHaveExited = $True
        $processList | ForEach-Object {
            If (-NOT $_.HasExited) {
                $AllHaveExited = $False
            }                    
        }
        If ($AllHaveExited -eq $true){
            Return
        }
        Start-Sleep 1
    }
    # If graceful close has failed, loop through 'Stop-Process'
    $processList | ForEach-Object {
        If (Get-Process -ID $_.ID -ErrorAction SilentlyContinue) {
            Stop-Process -Id $_.ID -Force -Verbose
        }
    }
}

How to prune local tracking branches that do not exist on remote anymore

There's a neat NPM package that does it for you (and it should work cross platform).

Install it with: npm install -g git-removed-branches

And then git removed-branches will show you all the stale local branches, and git removed-branches --prune to actually delete them.

More info here.

How to Convert string "07:35" (HH:MM) to TimeSpan

While correct that this will work:

TimeSpan time = TimeSpan.Parse("07:35");

And if you are using it for validation...

TimeSpan time;
if (!TimeSpan.TryParse("07:35", out time))
{
    // handle validation error
}

Consider that TimeSpan is primarily intended to work with elapsed time, rather than time-of-day. It will accept values larger than 24 hours, and will accept negative values also.

If you need to validate that the input string is a valid time-of-day (>= 00:00 and < 24:00), then you should consider this instead:

DateTime dt;
if (!DateTime.TryParseExact("07:35", "HH:mm", CultureInfo.InvariantCulture, 
                                              DateTimeStyles.None, out dt))
{
    // handle validation error
}
TimeSpan time = dt.TimeOfDay;

As an added benefit, this will also parse 12-hour formatted times when an AM or PM is included, as long as you provide the appropriate format string, such as "h:mm tt".

How to get some values from a JSON string in C#?

Following code is working for me.

Usings:

using System.IO;
using System.Net;
using Newtonsoft.Json.Linq;

Code:

 using (HttpWebResponse response = (HttpWebResponse)request.GetResponse())
                {
                    using (Stream responseStream = response.GetResponseStream())
                    {
                        using (StreamReader responseReader = new StreamReader(responseStream))
                        {
                            string json = responseReader.ReadToEnd();
                            string data = JObject.Parse(json)["id"].ToString();
                        }
                    }
                }

//json = {"kind": "ALL", "id": "1221455", "longUrl": "NewURL"}

How to wrap text around an image using HTML/CSS

With CSS Shapes you can go one step further than just float text around a rectangular image.

You can actually wrap text such that it takes the shape of the edge of the image or polygon that you are wrapping it around.

DEMO FIDDLE (Currently working on webkit - caniuse)

_x000D_
_x000D_
.oval {_x000D_
  width: 400px;_x000D_
  height: 250px;_x000D_
  color: #111;_x000D_
  border-radius: 50%;_x000D_
  text-align: center;_x000D_
  font-size: 90px;_x000D_
  float: left;_x000D_
  shape-outside: ellipse();_x000D_
  padding: 10px;_x000D_
  background-color: MediumPurple;_x000D_
  background-clip: content-box;_x000D_
}_x000D_
span {_x000D_
  padding-top: 70px;_x000D_
  display: inline-block;_x000D_
}
_x000D_
<div class="oval"><span>PHP</span>_x000D_
</div>_x000D_
<p>Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has_x000D_
  survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing_x000D_
  software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley_x000D_
  of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing_x000D_
  Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy_x000D_
  text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised_x000D_
  in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
_x000D_
_x000D_
_x000D_

Also, here is a good list apart article on CSS Shapes

Java: Detect duplicates in ArrayList?

private boolean isDuplicate() {
    for (int i = 0; i < arrayList.size(); i++) {
        for (int j = i + 1; j < arrayList.size(); j++) {
            if (arrayList.get(i).getName().trim().equalsIgnoreCase(arrayList.get(j).getName().trim())) {
                return true;
            }
        }
    }

    return false;
}

How to print a string in C++

#include <iostream>
std::cout << someString << "\n";

or

printf("%s\n",someString.c_str());

How to calculate the number of days between two dates?

Adjusted to allow for daylight saving differences. try this:

  function daysBetween(date1, date2) {

 // adjust diff for for daylight savings
 var hoursToAdjust = Math.abs(date1.getTimezoneOffset() /60) - Math.abs(date2.getTimezoneOffset() /60);
 // apply the tz offset
 date2.addHours(hoursToAdjust); 

    // The number of milliseconds in one day
    var ONE_DAY = 1000 * 60 * 60 * 24

    // Convert both dates to milliseconds
    var date1_ms = date1.getTime()
    var date2_ms = date2.getTime()

    // Calculate the difference in milliseconds
    var difference_ms = Math.abs(date1_ms - date2_ms)

    // Convert back to days and return
    return Math.round(difference_ms/ONE_DAY)

}

// you'll want this addHours function too 

Date.prototype.addHours= function(h){
    this.setHours(this.getHours()+h);
    return this;
}

Regular Expression For Duplicate Words

This is the regex I use to remove duplicate phrases in my twitch bot:

(\S+\s*)\1{2,}

(\S+\s*) looks for any string of characters that isn't whitespace, followed whitespace.

\1{2,} then looks for more than 2 instances of that phrase in the string to match. If there are 3 phrases that are identical, it matches.

How to write a CSS hack for IE 11?

So I found my own solution to this problem in the end.

After searching through Microsoft documentation I managed to find a new IE11 only style msTextCombineHorizontal

In my test, I check for IE10 styles and if they are a positive match, then I check for the IE11 only style. If I find it, then it's IE11+, if I don't, then it's IE10.

Code Example: Detect IE10 and IE11 by CSS Capability Testing (JSFiddle)

I will update the code example with more styles when I discover them.

NOTE: This will almost certainly identify IE12 and IE13 as "IE11", as those styles will probably carry forward. I will add further tests as new versions roll out, and hopefully be able to rely again on Modernizr.

I'm using this test for fallback behavior. The fallback behavior is just less glamorous styling, it doesn't have reduced functionality.

jQuery 1.9 .live() is not a function

The jQuery API documentation lists live() as deprecated as of version 1.7 and removed as of version 1.9: link.

version deprecated: 1.7, removed: 1.9

Furthermore it states:

As of jQuery 1.7, the .live() method is deprecated. Use .on() to attach event handlers. Users of older versions of jQuery should use .delegate() in preference to .live()

Response.Redirect with POST instead of Get?

Something new in ASP.Net 3.5 is this "PostBackUrl" property of ASP buttons. You can set it to the address of the page you want to post directly to, and when that button is clicked, instead of posting back to the same page like normal, it instead posts to the page you've indicated. Handy. Be sure UseSubmitBehavior is also set to TRUE.

ImageView - have height match width?

In Android 26.0.0 PercentRelativeLayout has been deprecated.

The best way to solve it is now with ConstraintLayout like this:

<android.support.constraint.ConstraintLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">

    <ImageView android:layout_width="match_parent"
               android:layout_height="0dp"
               android:scaleType="centerCrop"
               android:src="@drawable/you_image"                       
               app:layout_constraintDimensionRatio="1:1"/>


</android.support.constraint.ConstraintLayout>


Here is a tutorial on how to add ConstraintLayout to your project.

input file appears to be a text format dump. Please use psql

In order to create a backup using pg_dump that is compatible with pg_restore you must use the --format=custom / -Fc when creating your dump.

From the docs:

Output a custom-format archive suitable for input into pg_restore.

So your pg_dump command might look like:

pg_dump --file /tmp/db.dump --format=custom --host localhost --dbname my-source-database --username my-username --password

And your pg_restore command:

pg_restore --verbose --clean --no-acl --no-owner --host localhost --dbname my-destination-database /tmp/db.dump

Regex pattern to match at least 1 number and 1 character in a string

While the accepted answer is correct, I find this regex a lot easier to read:

REGEX = "([A-Za-z]+[0-9]|[0-9]+[A-Za-z])[A-Za-z0-9]*"

What is an alternative to execfile in Python 3?

Here's what I had (file is already assigned to the path to the file with the source code in both examples):

execfile(file)

Here's what I replaced it with:

exec(compile(open(file).read(), file, 'exec'))

My favorite part: the second version works just fine in both Python 2 and 3, meaning it's not necessary to add in version dependent logic.

Display Python datetime without time

If you need the result to be timezone-aware, you can use the replace() method of datetime objects. This preserves timezone, so you can do

>>> from django.utils import timezone
>>> now = timezone.now()
>>> now
datetime.datetime(2018, 8, 30, 14, 15, 43, 726252, tzinfo=<UTC>)
>>> now.replace(hour=0, minute=0, second=0, microsecond=0)
datetime.datetime(2018, 8, 30, 0, 0, tzinfo=<UTC>)

Note that this returns a new datetime object -- now remains unchanged.

PyLint "Unable to import" error - how to set PYTHONPATH?

The solution to alter path in init-hook is good, but I dislike the fact that I had to add absolute path there, as result I can not share this pylintrc file among the developers of the project. This solution using relative path to pylintrc file works better for me:

[MASTER]
init-hook="from pylint.config import find_pylintrc; import os, sys; sys.path.append(os.path.dirname(find_pylintrc()))"

Note that pylint.config.PYLINTRC also exists and has the same value as find_pylintrc().

How do I select child elements of any depth using XPath?

If you are using the XmlDocument and XmlNode.

Say:

XmlNode f = root.SelectSingleNode("//form[@id='myform']");

Use:

XmlNode s = f.SelectSingleNode(".//input[@type='submit']");

It depends on the tool that you use. But .// will select any child, any depth from a reference node.

Maintain/Save/Restore scroll position when returning to a ListView

I'm using FirebaseListAdapter and couldn't get any of the solutions to work. I ended up doing this. I'm guessing there are more elegant ways but this is a complete and working solution.

Before onCreate:

private int reset;
private int top;
private int index;

Inside of the FirebaseListAdapter:

@Override
public void onDataChanged() {
     super.onDataChanged();

     // Only do this on first change, when starting
     // activity or coming back to it.
     if(reset == 0) {
          mListView.setSelectionFromTop(index, top);
          reset++;
     }

 }

onStart:

@Override
protected void onStart() {
    super.onStart();
    if(adapter != null) {
        adapter.startListening();
        index = 0;
        top = 0;
        // Get position from SharedPrefs
        SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
        top = sharedPref.getInt("TOP_POSITION", 0);
        index = sharedPref.getInt("INDEX_POSITION", 0);
        // Set reset to 0 to allow change to last position
        reset = 0;
    }
}

onStop:

@Override
protected void onStop() {
    super.onStop();
    if(adapter != null) {
        adapter.stopListening();
        // Set position
        index = mListView.getFirstVisiblePosition();
        View v = mListView.getChildAt(0);
        top = (v == null) ? 0 : (v.getTop() - mListView.getPaddingTop());
        // Save position to SharedPrefs
        SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
        sharedPref.edit().putInt("TOP_POSITION" + "", top).apply();
        sharedPref.edit().putInt("INDEX_POSITION" + "", index).apply();
    }
}

Since I also had to solve this for FirebaseRecyclerAdapter I'm posting the solution here for that too:

Before onCreate:

private int reset;
private int top;
private int index;

Inside of the FirebaseRecyclerAdapter:

@Override
public void onDataChanged() {
    // Only do this on first change, when starting
    // activity or coming back to it.
    if(reset == 0) {
        linearLayoutManager.scrollToPositionWithOffset(index, top);
        reset++;
    }
}

onStart:

@Override
protected void onStart() {
    super.onStart();
    if(adapter != null) {
        adapter.startListening();
        index = 0;
        top = 0;
        // Get position from SharedPrefs
        SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
        top = sharedPref.getInt("TOP_POSITION", 0);
        index = sharedPref.getInt("INDEX_POSITION", 0);
        // Set reset to 0 to allow change to last position
        reset = 0;
    }
}

onStop:

@Override
protected void onStop() {
    super.onStop();
    if(adapter != null) {
        adapter.stopListening();
        // Set position
        index = linearLayoutManager.findFirstVisibleItemPosition();
        View v = linearLayoutManager.getChildAt(0);
        top = (v == null) ? 0 : (v.getTop() - linearLayoutManager.getPaddingTop());
        // Save position to SharedPrefs
        SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this);
        sharedPref.edit().putInt("TOP_POSITION" + "", top).apply();
        sharedPref.edit().putInt("INDEX_POSITION" + "", index).apply();
    }
}

Javascript wait() function

Javascript isn't threaded, so a "wait" would freeze the entire page (and probably cause the browser to stop running the script entirely).

To specifically address your problem, you should remove the brackets after donothing in your setTimeout call, and make waitsecs a number not a string:

console.log('before');
setTimeout(donothing,500); // run donothing after 0.5 seconds
console.log('after');

But that won't stop execution; "after" will be logged before your function runs.

To wait properly, you can use anonymous functions:

console.log('before');
setTimeout(function(){
    console.log('after');
},500);

All your variables will still be there in the "after" section. You shouldn't chain these - if you find yourself needing to, you need to look at how you're structuring the program. Also you may want to use setInterval / clearInterval if it needs to loop.

How to set div width using ng-style

ngStyle accepts a map:

$scope.myStyle = {
    "width" : "900px",
    "background" : "red"
};

Fiddle

Passing multiple argument through CommandArgument of Button in Asp.net

A little more elegant way of doing the same adding on to the above comment ..

<asp:GridView ID="grdParent" runat="server" BackColor="White" BorderColor="#DEDFDE"
                           AutoGenerateColumns="false"
                            OnRowDeleting="deleteRow"
                         GridLines="Vertical">
      <asp:BoundField DataField="IdTemplate" HeaderText="IdTemplate" />
      <asp:BoundField DataField="EntityId" HeaderText="EntityId"  />
    <asp:TemplateField ShowHeader="false">
        <ItemTemplate>
           <asp:LinkButton ID="lnkCustomize" Text="Delete"  CommandName="Delete"  CommandArgument='<%#Eval("IdTemplate") + ";" +Eval("EntityId")%>'  runat="server"> 
           </asp:LinkButton>   
        </ItemTemplate>   
    </asp:TemplateField>
     </asp:GridView>

And on the server side:

protected void deleteRow(object sender, GridViewDeleteEventArgs e)
{
    string IdTemplate= e.Values["IdTemplate"].ToString();
    string EntityId = e.Values["EntityId"].ToString();

   // Do stuff..
}

How can query string parameters be forwarded through a proxy_pass with nginx?

you have to use rewrite to pass params using proxy_pass here is example I did for angularjs app deployment to s3

S3 Static Website Hosting Route All Paths to Index.html

adopted to your needs would be something like

location /service/ {
    rewrite ^\/service\/(.*) /$1 break;
    proxy_pass http://apache;
}

if you want to end up in http://127.0.0.1:8080/query/params/

if you want to end up in http://127.0.0.1:8080/service/query/params/ you'll need something like

location /service/ {
    rewrite ^\/(.*) /$1 break;
    proxy_pass http://apache;
}

How can I delete using INNER JOIN with SQL Server?

This is a simple query to delete the records from two table at a time.

DELETE table1.* ,
       table2.* 
FROM table1 
INNER JOIN table2 ON table1.id= table2.id where table1.id ='given_id'

Effective way to find any file's Encoding

The StreamReader.CurrentEncoding property rarely returns the correct text file encoding for me. I've had greater success determining a file's endianness, by analyzing its byte order mark (BOM). If the file does not have a BOM, this cannot determine the file's encoding.

*UPDATED 4/08/2020 to include UTF-32LE detection and return correct encoding for UTF-32BE

/// <summary>
/// Determines a text file's encoding by analyzing its byte order mark (BOM).
/// Defaults to ASCII when detection of the text file's endianness fails.
/// </summary>
/// <param name="filename">The text file to analyze.</param>
/// <returns>The detected encoding.</returns>
public static Encoding GetEncoding(string filename)
{
    // Read the BOM
    var bom = new byte[4];
    using (var file = new FileStream(filename, FileMode.Open, FileAccess.Read))
    {
        file.Read(bom, 0, 4);
    }

    // Analyze the BOM
    if (bom[0] == 0x2b && bom[1] == 0x2f && bom[2] == 0x76) return Encoding.UTF7;
    if (bom[0] == 0xef && bom[1] == 0xbb && bom[2] == 0xbf) return Encoding.UTF8;
    if (bom[0] == 0xff && bom[1] == 0xfe && bom[2] == 0 && bom[3] == 0) return Encoding.UTF32; //UTF-32LE
    if (bom[0] == 0xff && bom[1] == 0xfe) return Encoding.Unicode; //UTF-16LE
    if (bom[0] == 0xfe && bom[1] == 0xff) return Encoding.BigEndianUnicode; //UTF-16BE
    if (bom[0] == 0 && bom[1] == 0 && bom[2] == 0xfe && bom[3] == 0xff) return new UTF32Encoding(true, true);  //UTF-32BE

    // We actually have no idea what the encoding is if we reach this point, so
    // you may wish to return null instead of defaulting to ASCII
    return Encoding.ASCII;
}

Bootstrap Carousel image doesn't align properly

Insert this on the css parent div class where your carousel is.

<div class="parent_div">
     <div id="myCarousel" class="carousel slide">
            <div class="carousel-inner">
              <div class="item active">
                <img src="assets/img/slider_1.png" alt="">
                <div class="carousel-caption">
                </div>
              </div>
            </div>
     </div>      
</div>

CSS

.parent_div { 
margin: 0 auto;
min-width: [desired width];
max-width: [desired width];
}

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

Always build with at least minimal optimization. With -O0, all analysis that the compiler could use to determine that execution cannot reach the end of the function has been disabled. This is why you're seeing the warning. The only time you should ever use -O0 is for step-by-line debugging, which is usually not a good debugging approach anyway, but it's what most people who got started with MSVC learned on...

Saving excel worksheet to CSV files with filename+worksheet name using VB

I think this is what you want...

Sub SaveWorksheetsAsCsv()

Dim WS As Excel.Worksheet
Dim SaveToDirectory As String

Dim CurrentWorkbook As String
Dim CurrentFormat As Long

CurrentWorkbook = ThisWorkbook.FullName
CurrentFormat = ThisWorkbook.FileFormat
' Store current details for the workbook
SaveToDirectory = "H:\test\"

For Each WS In Application.ActiveWorkbook.Worksheets
    WS.SaveAs SaveToDirectory & WS.Name, xlCSV
Next

Application.DisplayAlerts = False
ThisWorkbook.SaveAs Filename:=CurrentWorkbook, FileFormat:=CurrentFormat
Application.DisplayAlerts = True
' Temporarily turn alerts off to prevent the user being prompted
'  about overwriting the original file.

End Sub

Create numpy matrix filled with NaNs

Another option is to use numpy.full, an option available in NumPy 1.8+

a = np.full([height, width, 9], np.nan)

This is pretty flexible and you can fill it with any other number that you want.

Get integer value of the current year in Java

You can do the whole thing using Integer math without needing to instantiate a calendar:

return (System.currentTimeMillis()/1000/3600/24/365.25 +1970);

May be off for an hour or two at new year but I don't get the impression that is an issue?

How to set Angular 4 background image?

In Html

<div [style.background]="background"></div>

In Typescript

this.background= 
this.sanitization.bypassSecurityTrustStyle(`url(${this.section.backgroundSrc}) no-repeat`);

A working solution.

What is the recommended way to dynamically set background image in Angular 4

set initial viewcontroller in appdelegate - swift

Here is a good way to approach it. This example places a navigation controller as the root view controller, and puts the view controller of your choice within it at the bottom of the navigation stack, ready for you to push whatever you need to from it.

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool
{
    // mainStoryboard
    let mainStoryboard = UIStoryboard(name: "MainStoryboard", bundle: nil)

    // rootViewController
    let rootViewController = mainStoryboard.instantiateViewControllerWithIdentifier("MainViewController") as? UIViewController

    // navigationController
    let navigationController = UINavigationController(rootViewController: rootViewController!)

    navigationController.navigationBarHidden = true // or not, your choice.

    // self.window
    self.window = UIWindow(frame: UIScreen.mainScreen().bounds)

    self.window!.rootViewController = navigationController

    self.window!.makeKeyAndVisible()
}

To make this example work you would set "MainViewController" as the Storyboard ID on your main view controller, and the storyboard's file name in this case would be "MainStoryboard.storyboard". I rename my storyboards this way because Main.storyboard to me is not a proper name, particularly if you ever go to subclass it.

Set new id with jQuery

What happens when you set all of the attributes in one attr() command like so

$(this).attr({
               id : this.id + '_' + new_id,
               name: this.name + '_' + new_id,
               value: 'test' 
             });

Passing an array as a function parameter in JavaScript

Function arguments may also be Arrays:

_x000D_
_x000D_
function foo([a,b,c], d){
  console.log(a,b,c,d);
}

foo([1,2,3], 4)
_x000D_
_x000D_
_x000D_

of-course one can also use spread:

_x000D_
_x000D_
function foo(a, b, c, d){
  console.log(a, b, c, d);
}

foo(...[1, 2, 3], 4)
_x000D_
_x000D_
_x000D_

.trim() in JavaScript not working in IE

Unfortunately there is not cross browser JavaScript support for trim().

If you aren't using jQuery (which has a .trim() method) you can use the following methods to add trim support to strings:

String.prototype.trim = function() {
    return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
    return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
    return this.replace(/\s+$/,"");
}

Align Div at bottom on main Div

Give your parent div position: relative, then give your child div position: absolute, this will absolute position the div inside of its parent, then you can give the child bottom: 0px;

See example here:

http://jsfiddle.net/PGMqs/1/

How do I completely uninstall Node.js, and reinstall from beginning (Mac OS X)

@lfender6445 answer worked just fine for me to uninstall

Now to reinstall, I had problems installing the last version instead of the most stable one, so to install a specific node version you should do:

brew install node@10 // 10 is the version I want
brew link node@10

UnicodeDecodeError when reading CSV file in Pandas with Python

This answer seems to be the catch-all for CSV encoding issues. If you are getting a strange encoding problem with your header like this:

>>> f = open(filename,"r")
>>> reader = DictReader(f)
>>> next(reader)
OrderedDict([('\ufeffid', '1'), ... ])

Then you have a byte order mark (BOM) character at the beginning of your CSV file. This answer addresses the issue:

Python read csv - BOM embedded into the first key

The solution is to load the CSV with encoding="utf-8-sig":

>>> f = open(filename,"r", encoding="utf-8-sig")
>>> reader = DictReader(f)
>>> next(reader)
OrderedDict([('id', '1'), ... ])

Hopefully this helps someone.

What is the best way to detect a mobile device?

I do this for my .NET applications.

In my shared _Layout.cshtml Page, I add this.

@{
    var isMobileDevice = HttpContext.Current.Request.Browser.IsMobileDevice;
}

<html lang="en" class="@((isMobileDevice)?"ismobiledevice":"")">

Then to check on any page in your site (jQuery):

<script>
var isMobile = $('html').hasClass('ismobiledevice');
</script>

How do I find the value of $CATALINA_HOME?

Tomcat can tell you in several ways. Here's the easiest:

 $ /path/to/catalina.sh version
Using CATALINA_BASE:   /usr/local/apache-tomcat-7.0.29
Using CATALINA_HOME:   /usr/local/apache-tomcat-7.0.29
Using CATALINA_TMPDIR: /usr/local/apache-tomcat-7.0.29/temp
Using JRE_HOME:        /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home
Using CLASSPATH:       /usr/local/apache-tomcat-7.0.29/bin/bootstrap.jar:/usr/local/apache-tomcat-7.0.29/bin/tomcat-juli.jar
Server version: Apache Tomcat/7.0.29
Server built:   Jul 3 2012 11:31:52
Server number:  7.0.29.0
OS Name:        Mac OS X
OS Version:     10.7.4
Architecture:   x86_64
JVM Version:    1.6.0_33-b03-424-11M3720
JVM Vendor:     Apple Inc.

If you don't know where catalina.sh is (or it never gets called), you can usually find it via ps:

$ ps aux | grep catalina
chris            930   0.0  3.1  2987336 258328 s000  S    Wed01PM   2:29.43 /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home/bin/java -Dnop -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager -Djava.library.path=/usr/local/apache-tomcat-7.0.29/lib -Djava.endorsed.dirs=/usr/local/apache-tomcat-7.0.29/endorsed -classpath /usr/local/apache-tomcat-7.0.29/bin/bootstrap.jar:/usr/local/apache-tomcat-7.0.29/bin/tomcat-juli.jar -Dcatalina.base=/Users/chris/blah/blah -Dcatalina.home=/usr/local/apache-tomcat-7.0.29 -Djava.io.tmpdir=/Users/chris/blah/blah/temp org.apache.catalina.startup.Bootstrap start

From the ps output, you can see both catalina.home and catalina.base. catalina.home is where the Tomcat base files are installed, and catalina.base is where the running configuration of Tomcat exists. These are often set to the same value unless you have configured your Tomcat for multiple (configuration) instances to be launched from a single Tomcat base install.

You can also interrogate the JVM directly if you can't find it in a ps listing:

$ jinfo -sysprops 930 | grep catalina
Attaching to process ID 930, please wait...
Debugger attached successfully.
Server compiler detected.
JVM version is 20.8-b03-424
catalina.base = /Users/chris/blah/blah
[...]
catalina.home = /usr/local/apache-tomcat-7.0.29

If you can't manage that, you can always try to write a JSP that dumps the values of the two system properties catalina.home and catalina.base.

How to ignore the first line of data when processing CSV data?

Because this is related to something I was doing, I'll share here.

What if we're not sure if there's a header and you also don't feel like importing sniffer and other things?

If your task is basic, such as printing or appending to a list or array, you could just use an if statement:

# Let's say there's 4 columns
with open('file.csv') as csvfile:
     csvreader = csv.reader(csvfile)
# read first line
     first_line = next(csvreader)
# My headers were just text. You can use any suitable conditional here
     if len(first_line) == 4:
          array.append(first_line)
# Now we'll just iterate over everything else as usual:
     for row in csvreader:
          array.append(row)

The Response content must be a string or object implementing __toString(), "boolean" given after move to psql

I got this issue when I used an ajax call to retrieve data from the database. When the controller returned the array it converted it to a boolean. The problem was that I had "invalid characters" like ú (u with accent).

Why is "forEach not a function" for this object?

Object does not have forEach, it belongs to Array prototype. If you want to iterate through each key-value pair in the object and take the values. You can do this:

Object.keys(a).forEach(function (key){
    console.log(a[key]);
});

Usage note: For an object v = {"cat":"large", "dog": "small", "bird": "tiny"};, Object.keys(v) gives you an array of the keys so you get ["cat","dog","bird"]

Instantiate and Present a viewController in Swift

I created a library that will handle this much more easier with better syntax:

https://github.com/Jasperav/Storyboardable

Just change Storyboard.swift and let the ViewControllers conform to Storyboardable.

Why are the Level.FINE logging messages not showing?

why is my java logging not working

provides a jar file that will help you work out why your logging in not working as expected. It gives you a complete dump of what loggers and handlers have been installed and what levels are set and at which level in the logging hierarchy.

jquery-ui-dialog - How to hook into dialog close event

I have found it!

You can catch the close event using the following code:

 $('div#popup_content').on('dialogclose', function(event) {
     alert('closed');
 });

Obviously I can replace the alert with whatever I need to do.
Edit: As of Jquery 1.7, the bind() has become on()

When a 'blur' event occurs, how can I find out which element focus went *to*?

I am also trying to make Autocompleter ignore blurring if a specific element clicked and have a working solution, but for only Firefox due to explicitOriginalTarget

Autocompleter.Base.prototype.onBlur = Autocompleter.Base.prototype.onBlur.wrap( 
        function(origfunc, ev) {
            if ($(this.options.ignoreBlurEventElement)) {
                var newTargetElement = (ev.explicitOriginalTarget.nodeType == 3 ? ev.explicitOriginalTarget.parentNode : ev.explicitOriginalTarget);
                if (!newTargetElement.descendantOf($(this.options.ignoreBlurEventElement))) {
                    return origfunc(ev);
                }
            }
        }
    );

This code wraps default onBlur method of Autocompleter and checks if ignoreBlurEventElement parameters is set. if it is set, it checks everytime to see if clicked element is ignoreBlurEventElement or not. If it is, Autocompleter does not cal onBlur, else it calls onBlur. The only problem with this is that it only works in Firefox because explicitOriginalTarget property is Mozilla specific . Now I am trying to find a different way than using explicitOriginalTarget. The solution you have mentioned requires you to add onclick behaviour manually to the element. If I can't manage to solve explicitOriginalTarget issue, I guess I will follow your solution.

Yarn install command error No such file or directory: 'install'

Also had this issue (windows), the fix was a complete closure of all terminal instances, then retry.

Extract a part of the filepath (a directory) in Python

All you need is parent part if you use pathlib.

from pathlib import Path
p = Path(r'C:\Program Files\Internet Explorer\iexplore.exe')
print(p.parent) 

Will output:

C:\Program Files\Internet Explorer    

Case you need all parts (already covered in other answers) use parts:

p = Path(r'C:\Program Files\Internet Explorer\iexplore.exe')
print(p.parts) 

Then you will get a list:

('C:\\', 'Program Files', 'Internet Explorer', 'iexplore.exe')

Saves tone of time.

Assign static IP to Docker container

Easy with Docker version 1.10.1, build 9e83765.

First you need to create your own docker network (mynet123)

docker network create --subnet=172.18.0.0/16 mynet123

then, simply run the image (I'll take ubuntu as example)

docker run --net mynet123 --ip 172.18.0.22 -it ubuntu bash

then in ubuntu shell

ip addr

Additionally you could use

  • --hostname to specify a hostname
  • --add-host to add more entries to /etc/hosts

Docs (and why you need to create a network) at https://docs.docker.com/engine/reference/commandline/network_create/

Convert objective-c typedef to its string equivalent

I had a large enumerated type I wanted to convert it into an NSDictionary lookup. I ended up using sed from OSX terminal as:

$ sed -E 's/^[[:space:]]{1,}([[:alnum:]]{1,}).*$/  @(\1) : @"\1",/g' ObservationType.h

which can be read as: 'capture the first word on the line and output @(word) : @"word",'

This regex converts the enum in a header file named 'ObservationType.h' which contains:

typedef enum : int { 
    ObservationTypePulse = 1,
    ObservationTypeRespRate = 2,
    ObservationTypeTemperature = 3,
    .
    .
}

into something like:

    @(ObservationTypePulse) : @"ObservationTypePulse",
    @(ObservationTypeRespRate) : @"ObservationTypeRespRate",
    @(ObservationTypeTemperature) : @"ObservationTypeTemperature",
    .
    .

which can then be wrapped in a method using modern objective-c syntax @{ } (as explained by @yar1vn above) to create a NSDictionary lookup :

-(NSDictionary *)observationDictionary
{
    static NSDictionary *observationDictionary;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        observationDictionary = [[NSDictionary alloc] initWithDictionary:@{
                                 @(ObservationTypePulse) : @"ObservationTypePulse",
                                 @(ObservationTypeRespRate) : @"ObservationTypeRespRate",
                                 .
                                 .
                                 }];
    });
    return observationDictionary;
}

The dispatch_once boiler-plate is just to ensure that the static variable is initialised in a thread-safe manner.

Note: I found the sed regex expression on OSX odd - when I tried to use + to match 'one or more' it didn't work and had to resort to using {1,} as a replacement

How to recover MySQL database from .myd, .myi, .frm files

I just discovered to solution for this. I am using MySQL 5.1 or 5.6 on Windows 7.

  1. Copy the .frm file and ibdata1 from the old file which was located on "C:\Program Data\MySQL\MSQLServer5.1\Data"
  2. Stop the SQL server instance in the current SQL instance
  3. Go to the datafolder located at "C:\Program Data\MySQL\MSQLServer5.1\Data"
  4. Paste the ibdata1 and the folder of your database which contains the .frm file from the file you want to recover.
  5. Start the MySQL instance.

No need to locate the .MYI and .MYD file for this recovery.

Regex: match word that ends with "Id"

How about \A[a-z]*Id\z? [This makes characters before Id optional. Use \A[a-z]+Id\z if there needs to be one or more characters preceding Id.]

MySQL "CREATE TABLE IF NOT EXISTS" -> Error 1050

You can use the following query to create a table to a particular database in MySql.

create database if not exists `test`;

USE `test`;

SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0;

/*Table structure for table `test` */

CREATE TABLE IF NOT EXISTS `tblsample` (

  `id` int(11) NOT NULL auto_increment,   
  `recid` int(11) NOT NULL default '0',       
  `cvfilename` varchar(250)  NOT NULL default '',     
  `cvpagenumber`  int(11) NULL,     
  `cilineno` int(11)  NULL,    
  `batchname`  varchar(100) NOT NULL default '',
  `type` varchar(20) NOT NULL default '',    
  `data` varchar(100) NOT NULL default '',
   PRIMARY KEY  (`id`)

);

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

merge into t2 t2 
using (select * from t1) t1
on (t2.user_id = t1.user_id)
when matched then update
set
   t2.c1 = t1.c1
,  t2.c2 = t1.c2

How to post data in PHP using file_get_contents?

$sUrl = 'http://www.linktopage.com/login/';
$params = array('http' => array(
    'method'  => 'POST',
    'content' => 'username=admin195&password=d123456789'
));

$ctx = stream_context_create($params);
$fp = @fopen($sUrl, 'rb', false, $ctx);
if(!$fp) {
    throw new Exception("Problem with $sUrl, $php_errormsg");
}

$response = @stream_get_contents($fp);
if($response === false) {
    throw new Exception("Problem reading data from $sUrl, $php_errormsg");
}

Produce a random number in a range using C#

Something like:

var rnd = new Random(DateTime.Now.Millisecond);
int ticks = rnd.Next(0, 3000);

Remove Project from Android Studio

File > Close Project

move your mouse cursor on the project and press Delete keyboard button :)

EDIT try this solution, works for me

Android ImageView Animation

One way - split you image into N rotating it slightly every time. I'd say 5 is enough. then create something like this in drawable

<animation-list   android:id="@+id/handimation" android:oneshot="false" 
    xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/progress1" android:duration="150" />
    <item android:drawable="@drawable/progress2" android:duration="150" />
    <item android:drawable="@drawable/progress3" android:duration="150" />
 </animation-list> 

code start

progress.setVisibility(View.VISIBLE);
AnimationDrawable frameAnimation = (AnimationDrawable)progress.getDrawable();
frameAnimation.setCallback(progress);
frameAnimation.setVisible(true, true);

code stop

AnimationDrawable frameAnimation = (AnimationDrawable)progress.getDrawable();
frameAnimation.stop();
frameAnimation.setCallback(null);
frameAnimation = null;
progress.setVisibility(View.GONE);

more here

round a single column in pandas

No need to use for loop. It can be directly applied to a column of a dataframe

sleepstudy['Reaction'] = sleepstudy['Reaction'].round(1)

How to programmatically get iOS status bar height

Try this:

CGFloat statusBarHeight = [[UIApplication sharedApplication] statusBarFrame].size.height;

Index was out of range. Must be non-negative and less than the size of the collection parameter name:index

This error is caused when you have enabled paging in Grid view. If you want to delete a record from grid then you have to do something like this.

int index = Convert.ToInt32(e.CommandArgument);
int i = index % 20;
// Here 20 is my GridView's Page Size.
GridViewRow row = gvMainGrid.Rows[i];
int id = Convert.ToInt32(gvMainGrid.DataKeys[i].Value);
new GetData().DeleteRecord(id);
GridView1.DataSource = RefreshGrid();
GridView1.DataBind();

Hope this answers the question.

How can you create pop up messages in a batch script?

msg * "Enter Your Message"

Does this help ?

Upload file to FTP using C#

This works for me,this method will SFTP a file to a location within your network. It uses SSH.NET.2013.4.7 library.One can just download it for free.

    //Secure FTP
    public void SecureFTPUploadFile(string destinationHost,int port,string username,string password,string source,string destination)

    {
        ConnectionInfo ConnNfo = new ConnectionInfo(destinationHost, port, username, new PasswordAuthenticationMethod(username, password));

        var temp = destination.Split('/');
        string destinationFileName = temp[temp.Count() - 1];
        string parentDirectory = destination.Remove(destination.Length - (destinationFileName.Length + 1), destinationFileName.Length + 1);


        using (var sshclient = new SshClient(ConnNfo))
        {
            sshclient.Connect();
            using (var cmd = sshclient.CreateCommand("mkdir -p " + parentDirectory + " && chmod +rw " + parentDirectory))
            {
                cmd.Execute();
            }
            sshclient.Disconnect();
        }


        using (var sftp = new SftpClient(ConnNfo))
        {
            sftp.Connect();
            sftp.ChangeDirectory(parentDirectory);
            using (var uplfileStream = System.IO.File.OpenRead(source))
            {
                sftp.UploadFile(uplfileStream, destinationFileName, true);
            }
            sftp.Disconnect();
        }
    }

Removing duplicate objects with Underscore for Javascript

The lodash 4.6.1 docs have this as an example for object key equality:

_.uniqWith(objects, _.isEqual);

https://lodash.com/docs#uniqWith

Two Page Login with Spring Security 3.2.x

There should be three pages here:

  1. Initial login page with a form that asks for your username, but not your password.
  2. You didn't mention this one, but I'd check whether the client computer is recognized, and if not, then challenge the user with either a CAPTCHA or else a security question. Otherwise the phishing site can simply use the tendered username to query the real site for the security image, which defeats the purpose of having a security image. (A security question is probably better here since with a CAPTCHA the attacker could have humans sitting there answering the CAPTCHAs to get at the security images. Depends how paranoid you want to be.)
  3. A page after that that displays the security image and asks for the password.

I don't see this short, linear flow being sufficiently complex to warrant using Spring Web Flow.

I would just use straight Spring Web MVC for steps 1 and 2. I wouldn't use Spring Security for the initial login form, because Spring Security's login form expects a password and a login processing URL. Similarly, Spring Security doesn't provide special support for CAPTCHAs or security questions, so you can just use Spring Web MVC once again.

You can handle step 3 using Spring Security, since now you have a username and a password. The form login page should display the security image, and it should include the user-provided username as a hidden form field to make Spring Security happy when the user submits the login form. The only way to get to step 3 is to have a successful POST submission on step 1 (and 2 if applicable).

Check for column name in a SqlDataReader object

Hashtable ht = new Hashtable();
    Hashtable CreateColumnHash(SqlDataReader dr)
    {
        ht = new Hashtable();
        for (int i = 0; i < dr.FieldCount; i++)
        {
            ht.Add(dr.GetName(i), dr.GetName(i));
        }
        return ht;
    }

    bool ValidateColumn(string ColumnName)
    {
        return ht.Contains(ColumnName);
    }

How to add spacing between UITableViewCell

I was in the same boat. At first I tried switching to sections, but in my case it ended up being more of a headache than I originally thought, so I've been looking for an alternative. To keep using rows (and not mess with how you access your model data), here's what worked for me just by using a mask:

func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath)
{
    let verticalPadding: CGFloat = 8

    let maskLayer = CALayer()
    maskLayer.cornerRadius = 10    //if you want round edges
    maskLayer.backgroundColor = UIColor.black.cgColor
    maskLayer.frame = CGRect(x: cell.bounds.origin.x, y: cell.bounds.origin.y, width: cell.bounds.width, height: cell.bounds.height).insetBy(dx: 0, dy: verticalPadding/2)
    cell.layer.mask = maskLayer
}

All you have left to do is make the cell's height bigger by the same value as your desired verticalPadding, and then modify your inner layout so that any views that had spacing to the edges of the cell have that same spacing increased by verticalPadding/2. Minor downside: you get verticalPadding/2 padding on both the top and bottom of the tableView, but you can quickly fix this by setting tableView.contentInset.bottom = -verticalPadding/2 and tableView.contentInset.top = -verticalPadding/2. Hope this helps somebody!

Error: The processing instruction target matching "[xX][mM][lL]" is not allowed

Another reason of the above error is corrupted jar file. I got the same error but for Junit when running unit tests. Removing jar and downloading it again fixed the issue.

What is the role of "Flatten" in Keras?

I came across this recently, it certainly helped me understand: https://www.cs.ryerson.ca/~aharley/vis/conv/

So there's an input, a Conv2D, MaxPooling2D etc, the Flatten layers are at the end and show exactly how they are formed and how they go on to define the final classifications (0-9).

Environment variable in Jenkins Pipeline

To avoid problems of side effects after changing env, especially using multiple nodes, it is better to set a temporary context.

One safe way to alter the environment is:

 withEnv(['MYTOOL_HOME=/usr/local/mytool']) {
    sh '$MYTOOL_HOME/bin/start'
 }

This approach does not poison the env after the command execution.

JCheckbox - ActionListener and ItemListener?

The difference is that ActionEvent is fired when the action is performed on the JCheckBox that is its state is changed either by clicking on it with the mouse or with a space bar or a mnemonic. It does not really listen to change events whether the JCheckBox is selected or deselected.

For instance, if JCheckBox c1 (say) is added to a ButtonGroup. Changing the state of other JCheckBoxes in the ButtonGroup will not fire an ActionEvent on other JCheckBox, instead an ItemEvent is fired.

Final words: An ItemEvent is fired even when the user deselects a check box by selecting another JCheckBox (when in a ButtonGroup), however ActionEvent is not generated like that instead ActionEvent only listens whether an action is performed on the JCheckBox (to which the ActionListener is registered only) or not. It does not know about ButtonGroup and all other selection/deselection stuff.

How to convert an image to base64 encoding?

Here is an example using a cURL call.. This is better than the file_get_contents() function. Of course, use base64_encode()

$url = "http://example.com";

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_URL, $url); 
curl_setopt($ch, CURLOPT_HEADER, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);
?>

<img src="data:image/png;base64,<?php echo base64_encode($output);?>">  

MongoDB inserts float when trying to insert integer

If the value type is already double, then update the value with $set command can not change the value type double to int when using NumberInt() or NumberLong() function. So, to Change the value type, it must update the whole record.

var re = db.data.find({"name": "zero"})
re['value']=NumberInt(0)
db.data.update({"name": "zero"}, re)

Github Push Error: RPC failed; result=22, HTTP code = 413

The error occurs in 'libcurl', which is the underlying protocol for https upload. Solution is to somehow updgrade libcurl. To get more details about the error, set GIT_CURL_VERBOSE=1

https://confluence.atlassian.com/pages/viewpage.action?pageId=306348908

Meaning of error, as per libcurl doc: CURLE_HTTP_RETURNED_ERROR (22)

This is returned if CURLOPT_FAILONERROR is set TRUE and the HTTP server returns an error code that is >= 400.

http://curl.haxx.se/libcurl/c/libcurl-errors.html

Select columns from result set of stored procedure

I'd cut and paste the original SP and delete all columns except the 2 you want. Or. I'd bring the result set back, map it to a proper business object, then LINQ out the two columns.

RegEx to extract all matches from string using RegExp.exec

Here is my answer:

var str = '[me nombre es] : My name is. [Yo puedo] is the right word'; 

var reg = /\[(.*?)\]/g;

var a = str.match(reg);

a = a.toString().replace(/[\[\]]/g, "").split(','));

How to throw RuntimeException ("cannot find symbol")

You need to create the instance of the RuntimeException, using new the same way you would to create an instance of most other classes:

throw new RuntimeException(msg);

How to create JSON string in JavaScript?

I think this way helps you...

var name=[];
var age=[];
name.push('sulfikar');
age.push('24');
var ent={};
for(var i=0;i<name.length;i++)
{
ent.name=name[i];
ent.age=age[i];
}
JSON.Stringify(ent);

jQuery: enabling/disabling datepicker

This is what worked for me

$("#from").attr("disabled", true);

Consider defining a bean of type 'service' in your configuration [Spring boot]

I resolved by replacing the corrupted jar files.

But to find those corrupted jar files, I have to run my application in three IDE- 1) Intellij Idea 2)NetBeans 3) Eclipse.

Netbeans given me information for maximum number of corrupted jar. In Netbeans along with the run, I use the build option(after right clicking on project) to know more about corrupted jars.

It took me more than 15 hours to find out the root cause for these errors. Hope it help anyone.

Why can't I duplicate a slice with `copy()`?

The builtin copy(dst, src) copies min(len(dst), len(src)) elements.

So if your dst is empty (len(dst) == 0), nothing will be copied.

Try tmp := make([]int, len(arr)) (Go Playground):

arr := []int{1, 2, 3}
tmp := make([]int, len(arr))
copy(tmp, arr)
fmt.Println(tmp)
fmt.Println(arr)

Output (as expected):

[1 2 3]
[1 2 3]

Unfortunately this is not documented in the builtin package, but it is documented in the Go Language Specification: Appending to and copying slices:

The number of elements copied is the minimum of len(src) and len(dst).

Edit:

Finally the documentation of copy() has been updated and it now contains the fact that the minimum length of source and destination will be copied:

Copy returns the number of elements copied, which will be the minimum of len(src) and len(dst).

Java - No enclosing instance of type Foo is accessible

Lets understand it with the following simple example. This happens because this is NON-STATIC INNER CLASS. You should need the instance of outer class.

 public class PQ {

    public static void main(String[] args) {

        // create dog object here
        Dog dog = new PQ().new Dog();
        //OR
        PQ pq = new PQ();
        Dog dog1 = pq.new Dog();
    }

    abstract class Animal {
        abstract void checkup();
    }

    class Dog extends Animal {
        @Override
        void checkup() {
            System.out.println("Dog checkup");

        }
    }

    class Cat extends Animal {
        @Override
        void checkup() {
            System.out.println("Cat Checkup");

        }
    }
}

How can I show a message box with two buttons?

The VBScript Messagebox is fairly limited as to the labels you can apply to the buttons, your choices are pretty much limited to:

  • OK
  • Cancel
  • Retry
  • Abort
  • Ignore
  • Yes
  • No

So you are going to have to build your own form if you want "ON"/"OFF"

Better yet, why not rephrase the prompt in the box so one of the above options works.

For example:

Do you want the light on? 
[Yes] [No]

And for God's sake don't do one of these UI monstrosities!

Switch setting? (Click "yes" for ON and "No" for Off)
[Yes] [No]

.NET Core vs Mono

Necromancing.
Providing an actual answer.

What is the difference between .Net Core and Mono?

.NET Core now officially is the future of .NET. It started for most part with a re-write of the ASP.NET MVC framework and console applications, which of course includes server applications. (Since it's Turing-complete and supports interop with C dlls, you could, if you absolutely wanted to, also write your own desktop applications with it, for example through 3rd-party libraries like Avalonia, which were a bit very basic at the time I first wrote this, which meant you were pretty much limited to web or server stuff.) Over time, many APIs have been added to .NET Core, so much so that after version 3.1, .NET Core will jump to version 5.0, be known as .NET 5.0 without the "Core", and that then will be the future of the .NET Framework. What used to be the full .NET Framework will linger around in maintenance mode as Full .NET Framework 4.8.x for a few decades, until it will die (maybe there are still going to be some upgrades, but I doubt it). In other words, .NET Core is the future of .NET, and Full .NET Framework will go the way of the Dodo/Silverlight/WindowsPhone.

The main point of .NET Core, apart from multi-platform support, is to improve performance, and to enable "native compilation"/self-contained-deployment (so you don't need .NET framework/VM installed on the target machine.
On the one hand, this means docker.io support on Linux, and on the other, self-contained deployment is useful in "cloud-computing", since then you can just use whatever version of the dotnet-CORE framework you like, and you don't have to worry about which version(s) of the .NET framework the sysadmin has actually installed.

While the .NET Core runtime supports multiple operating systems and processors, the SDK is a different story. And while the SDK supports multiple OS, ARM support for the SDK is/was still work in progress. .NET Core is supported by Microsoft. Dotnet-Core did not come with WinForms or WPF or anything like that.

  • As of version 3.0, WinForms and WPF is also supported by .NET Core, but only on Windows, and only by C#. Not by VB.NET (VB.NET support planned for v5 in 2020). And there is no Forms Designer in .NET Core: it's being shipped with a Visual Studio update later, at an unspecified time.
  • WebForms are still not supported by .NET Core, and there are no plans to support them, ever (Blazor is the new kid in town for that).
  • .NET Core also comes with System.Runtime, which replaces mscorelib.
  • Oftentimes, .NET Core is mixed up with NetStandard, which is a bit of a wrapper around System.Runtime/mscorelib (and some others), that allows you to write libraries that target .NET Core, Full .NET Framework and Xamarin (iOS/Android), all at the same time.
  • the .NET Core SDK does not/did not work on ARM, at least not last time I checked.

"The Mono Project" is much older than .NET Core.
Mono is Spanish and means Monkey, and as a side-remark, the name has nothing to do with mononucleosis (hint: you could get a list of staff under http://primates.ximian.com/).
Mono was started in 2005 by Miguel de Icaza (the guy that started GNOME - and a few others) as an implementation of the .NET Framework for Linux (Ximian/SuSe/Novell). Mono includes Web-Forms, Winforms, MVC, Olive, and an IDE called MonoDevelop (also knows as Xamarin Studio or Visual Studio Mac). Basically the equivalent of (OpenJDK) JVM and (OpenJDK) JDK/JRE (as opposed to SUN/Oracle JDK). You can use it to get ASP.NET-WebForms + WinForms + ASP.NET-MVC applications to work on Linux.

Mono is supported by Xamarin (the new company name of what used to be Ximian, when they focused on the Mobile market, instead of the Linux market), and not by Microsoft.
(since Xamarin was bought by Microsoft, that's technically [but not culturally] Microsoft.)
You will usually get your C# stuff to compile on mono, but not the VB.NET stuff.
Mono misses some advanced features, like WSE/WCF and WebParts.
Many of the Mono implementations are incomplete (e.g. throw NotImplementedException in ECDSA encryption), buggy (e.g. ODBC/ADO.NET with Firebird), behave differently than on .NET (for example XML-serialization) or otherwise unstable (ASP.NET MVC) and unacceptably slow (Regex). On the upside, the Mono toolchain also works on ARM.

As far as .NET Core is concerned, when they say cross-platform, don't expect that cross-platform means that you could actually just apt-get install .NET Core on ARM-Linux, like you can with ElasticSearch. You'll have to compile the entire framework from source.
That is, if you have that space (e.g. on a Chromebook, which has a 16 to 32 GB total HD).
It also used to have issues of incompatibility with OpenSSL 1.1 and libcurl.
Those have been rectified in the latest version of .NET Core Version 2.2.
So much for cross-platform.

I found a statement on the official site that said, "Code written for it is also portable across application stacks, such as Mono".

As long as that code doesn't rely on WinAPI-calls, Windows-dll-pinvokes, COM-Components, a case-insensitive file system, the default-system-encoding (codepage) and doesn't have directory separator issues, that's correct. However, .NET Core code runs on .NET Core, and not on Mono. So mixing the two will be difficult. And since Mono is quite unstable and slow (for web applications), I wouldn't recommend it anyway. Try image-processing on .NET core, e.g. WebP or moving GIF or multipage-tiff or writing text on an image, you'll be nastily surprised.

Note:
As of .NET Core 2.0, there is System.Drawing.Common (NuGet), which contains most of the functionality of System.Drawing. It should be more or less feature-complete in .NET-Core 2.1. However, System.Drawing.Common uses GDI+, and therefore won't work on Azure (System.Drawing libraries are available in Azure Cloud Service [basically just a VM], but not in Azure Web App [basically shared hosting?])
So far, System.Drawing.Common works fine on Linux/Mac, but has issues on iOS/Android - if it works at all, there.
Prior to .NET Core 2.0, that is to say sometime mid-February 2017, you could use SkiaSharp for imaging (example) (you still can).
Post .net-core 2.0, you'll notice that SixLabors ImageSharp is the way to go, since System.Drawing is not necessarely secure, and has a lot of potential or real memory leaks, which is why you shouldn't use GDI in web-applications; Note that SkiaSharp is a lot faster than ImageSharp, because it uses native-libraries (which can also be a drawback). Also, note that while GDI+ works on Linux & Mac, that doesn't mean it works on iOS/Android.

Code not written for .NET (non-Core) is not portable to .NET Core.
Meaning, if you want a non-GPL C# library like PDFSharp to create PDF-documents (very commonplace), you're out of luck (at the moment) (not anymore). Never mind ReportViewer control, which uses Windows-pInvokes (to encrypt, create mcdf documents via COM, and to get font, character, kerning, font embedding information, measure strings and do line-breaking, and for actually drawing tiffs of acceptable quality), and doesn't even run on Mono on Linux
(I'm working on that).

Also, code written in .NET Core is not portable to Mono, because Mono lacks the .NET Core runtime libraries (so far).

My goal is to use C#, LINQ, EF7, visual studio to create a website that can be ran/hosted in linux.

EF in any version that I tried so far was so goddamn slow (even on such simple things like one table with one left-join), I wouldn't recommend it ever - not on Windows either.
I would particularly not recommend EF if you have a database with unique-constrains, or varbinary/filestream/hierarchyid columns. (Not for schema-update either.)
And also not in a situation where DB-performance is critical (say 10+ to 100+ concurrent users).
Also, running a website/web-application on Linux will sooner or later mean you'll have to debug it.
There is no debugging support for .NET Core on Linux. (Not anymore, but requires JetBrains Rider.)
MonoDevelop does not (yet) support debugging .NET Core projects.
If you have problems, you're on your own. You'll have to use extensive logging.
Be careful, be advised extensive logging will fill your disk in no time, particularly if your program enters an infinite loop or recursion.
This is especially dangerous if your web-app runs as root, because log-in requires logfile-space - if there's no free space left, you won't be able to login anymore.
(Normally, about 5% of diskspace is reserved for user root [aka administrator on Windows], so at least the administrator can still log in if the disk is almost full. But if your applications run as root, that restriction does not apply for their disk usage, and so their logfiles can use 100% of the remaining free space, so not even the administrator can log in any more.)
It's therefore better not to encrypt that disk, that is, if you value your data/system.

Someone told me that he wanted it to be "in Mono", but I don't know what that means.

It either means he doesn't want to use .NET Core, or he just wants to use C# on Linux/Mac. My guess is he just wants to use C# for a Web-App on Linux. .NET Core is the way to go for that, if you absolutely want to do it in C#. Don't go with "Mono proper"; on the surface, it would seem to work at first - but believe me you will regret it because Mono's ASP.NET MVC isn't stable when your server runs long-term (longer than 1 day) - you have now been warned. See also the "did not complete" references when measuring Mono performance on the techempower benchmarks.

fortunes

I know I want to use the .Net Core 1.0 framework with the technologies I listed above. He also said he wanted to use "fast cgi". I don't know what that means either.

It means he wants to use a high-performance full-featured WebServer like nginx (Engine-X), possibly Apache.
Then he can run mono/dotnetCore with virtual name based hosting (multiple domain names on the same IP) and/or load-balancing. He can also run other websites with other technologies, without requiring a different port-number on the web-server. It means your website runs on a fastcgi-server, and nginx forwards all web-requests for a certain domain via the fastcgi-protocol to that server. It also means your website runs in a fastcgi-pipeline, and you have to be careful what you do, e.g. you can't use HTTP 1.1 when transmitting files.
Otherwise, files will be garbled at the destination.
See also here and here.

To conclude:
.NET Core at present (2016-09-28) is not really portable, nor is is really cross-platform (in particular the debug-tools).
Nor is native-compilation easy, especially for ARM.
And to me, it also does not look like its development is "really finished", yet.
For example, System.Data.DataTable/DataAdaper.Update is missing... (not anymore with .NET Core 2.0)
Together with the System.Data.Common.IDB* interfaces. (not anymore with .NET Core 1.1)
if there ever was one class that is often used, DataTable/DataAdapter would be it...
Also, the Linux-installer (.deb) fails, at least on my machine, and I'm sure I'm not the only one that has that problem.
Debug, maybe with Visual Studio Code, if you can build it on ARM (I managed to do that - do NOT follow Scott Hanselman's blog-post if you do that - there's a howto in the wiki of VS-Code on github), because they don't offer the executable.
Yeoman also fails. (I guess it has something to do with the nodejs version you installed - VS Code requires one version, Yeoman another... but it should run on the same computer. pretty lame
Never mind that it should run on the node version shipped by default on the OS.
Never mind that there should be no dependency on NodeJS in the first place.
The kestell server is also work in progress.
And judging by my experience with the mono-project, I highly doubt they ever tested .NET Core on FastCGI, or that they have any idea what FastCGI-support means for their framework, let alone that they tested it to make sure "everything works". In fact, I just tried making a fastcgi-application with .NET Core and just realized there is no FastCGI library for .NET Core "RTM"...

So when you're going to run .NET Core "RTM" behind nginx, you can only do it by proxying requests to kestrell (that semi-finished nodeJS-derived web-server) - there's no fastcgi support at present in .NET Core "RTM", AFAIK. Since there is no .net core fastcgi library, and no samples, it's also highly unlikely that anybody did any testing on the framework to make sure fastcgi works as expected.

I also question the performance.
In the (preliminary) techempower-benchmark (round 13), aspnetcore-linux ranks on 25% relative to the best performance, while comparable frameworks like Go (golang) rank at 96.9% of peak performance (and that is when returning plaintext without file-system access only). .NET Core does a little better on JSON-serialization, but it does not look compelling either (go reaches 98.5% of peak, .NET core 65%). That said, it can't possibly be worse than "mono proper".

Also, since it's still relatively new, not all of the major libraries have been ported (yet), and I doubt that some of them will ever be ported.
Imaging support is also questionable at best.
For anything encryption, use BouncyCastle instead.

Can you help me make sense of all these terms and if my expectations are realistic?

I hope i helped you making more sense with all these terms.
As far as your expecations go:
Developing a Linux application without knowing anything about Linux is a really stupid idea in the first place, and it's also bound to fail in some horrible way one way or the other. That said, because Linux comes at no licensing costs, it's a good idea in principle, BUT ONLY IF YOU KNOW WHAT YOU DO.
Developing an application for a platform where you can't debug your application on is another really bad idea.
Developing for fastcgi without knowing what consequences there are is yet another really bad idea.

Doing all these things on a "experimental" platform without any knowledge of that platform's specifics and without debugging support is suicide, if your project is more than just a personal homepage. On the other hand, I guess doing it with your personal homepage for learning purposes would probably be a very good experience - then you get to know what the framework and what the non-framework problems are.
You can for example (programmatically) loop-mount a case-insensitive fat32, hfs or JFS for your application, to get around the case-sensitivity issues (loop-mount not recommended in production).

To summarize
At present (2016-09-28), I would stay away from .NET Core (for production usage). Maybe in one to two years, you can take another look, but probably not before.
If you have a new web-project that you develop, start it in .NET Core, not mono.

If you want a framework that works on Linux (x86/AMD64/ARMhf) and Windows and Mac, that has no dependencies, i.e. only static linking and no dependency on .NET, Java or Windows, use Golang instead. It's more mature, and its performance is proven (Baidu uses it with 1 million concurrent users), and golang has a significantly lower memory footprint. Also golang is in the repositories, the .deb installs without problems, the sourcecode compiles - without requiring changes - and golang (in the meantime) has debugging support with delve and JetBrains Gogland on Linux (and Windows and Mac). Golang's build process (and runtime) also doesn't depend on NodeJS, which is yet another plus.

As far as mono goes, stay away from it.
It is nothing short of amazing how far mono has come, but unfortunately that's no substitute for its performance/scalability and stability issues for production applications.
Also, mono-development is quite dead, they largely only develop the parts relevant to Android and iOS anymore, because that's where Xamarin makes their money.
Don't expect Web-Development to be a first-class Xamarin/mono citizen.
.NET Core might be worth it, if you start a new project, but for existing large web-forms projects, porting over is largely out of the question, the changes required are huge. If you have a MVC-project, the amount of changes might be manageable, if your original application design was sane, which is mostly not the case for most existing so-called "historically grown" applications.

December 2016 Update:
Native compilation has been removed from .NET Core preview, as it is not yet ready...

Seems like they have improved pretty heavily on the raw text-file benchmark, but on the other hand, it's gotten pretty buggy. Also, it further deteriorated in the JSON benchmarks. Curious also that entity framework shall be faster for updates than Dapper - although both at record slowness. This is very unlikely to be true. Looks like there still are more than just a few bugs to hunt.

Also, there seems to be relief coming on the Linux IDE front.
JetBrains released "Project Rider", an early access preview of a C#/.NET Core IDE for Linux (and Mac and Windows), that can handle Visual Studio Project files. Finally a C# IDE that is usable & that isn't slow as hell.

Conclusion: .NET Core still is pre-release quality software as we march into 2017. Port your libraries, but stay away from it for production usage, until framework quality stabilizes.
And keep an eye on Project Rider.

buggy .net core

2017 Update
Have migrated my (brother's) homepage to .NET Core for now.
So far, the runtime on Linux seems to be stable enough (at least for small projects) - it survived a load test with ease - mono never did.
Also, it looks like I mixed up .NET-Core-native and .NET-Core-self-contained-deployment. Self-contained deployment works, but it is a bit underdocumented, although it's super easy (the build/publish tools are a bit unstable, yet - if you encounter "Positive number required. - Build FAILED." - run the same command again, and it works).

You can run

dotnet restore -r win81-x64
dotnet build -r win81-x64
dotnet publish -f netcoreapp1.1 -c Release -r win81-x64

Note: As per .NET Core 3, you can publish everything minified as a single file:

dotnet publish -r win-x64 -c Release /p:PublishSingleFile=true
dotnet publish -r linux-x64 -c Release /p:PublishSingleFile=true

However, unlike go, it's not a statically linked executable, but a self-extracting zip file, so when deploying, you might run into problems, especially if the temp directory is locked down by group policy, or some other issues. Works fine for a hello-world program, though. And if you don't minify, the executable size will clock in at something around 100 MB.

And you get a self-contained .exe-file (in the publish directory), which you can move to a Windows 8.1 machine without .NET framework installed and let it run. Nice. It's here that dotNET-Core just starts to get interesting. (mind the gaps, SkiaSharp doesn't work on Windows 8.1 / Windows Server 2012 R2, [yet] - the ecosystem has to catch up first - but interestingly, the Skia-dll-load-fail doesn't crash the entire server/application - so everything else works)

(Note: SkiaSharp on Windows 8.1 is missing the appropriate VC runtime files - msvcp140.dll and vcruntime140.dll. Copy them into the publish-directory, and Skia will work on Windows 8.1.)

August 2017 Update
.NET Core 2.0 released.
Be careful - comes with (huge breaking) changes in authentication...
On the upside, it brought the DataTable/DataAdaper/DataSet classes back, and many more.
Realized .NET Core is still missing support for Apache SparkSQL, because Mobius isn't yet ported. That's bad, because that means no SparkSQL support for my IoT Cassandra Cluster, so no joins...
Experimental ARM support (runtime only, not SDK - too bad for devwork on my Chromebook - looking forward to 2.1 or 3.0).
PdfSharp is now experimentally ported to .NET Core.
JetBrains Rider left EAP. You can now use it to develop & debug .NET Core on Linux - though so far only .NET Core 1.1 until the update for .NET Core 2.0 support goes live.

May 2018 Update
.NET Core 2.1 release imminent. Maybe this will fix NTLM-authentication on Linux (NTLM authentication doesn't work on Linux {and possibly Mac} in .NET-Core 2.0 with multiple authenticate headers, such as negotiate, commonly sent with ms-exchange, and they're apparently only fixing it in v2.1, no bugfix release for 2.0).
But I'm not installing preview releases on my machine. So waiting.
v2.1 is also said to greatly reduce compile times. That would be good.

Also, note that on Linux, .NET Core is 64-Bit only !
There is no, and there will be no, x86-32 version of .NET Core on Linux.
And the ARM port is ARM-32 only. No ARM-64, yet.
And on ARM, you (at present) only have the runtime, not the dotnet-SDK.

And one more thing:
Because .NET-Core uses OpenSSL 1.0, .NET Core on Linux doesn't run on Arch Linux, and by derivation not on Manjaro (the most popular Linux distro by far at this point in time), because Arch Linux uses OpenSSL 1.1. So if you're using Arch Linux, you're out of luck (with Gentoo, too).

Edit:

Latest version of .NET Core 2.2+ supports OpenSSL 1.1. So you can use it on Arch or (k)Ubuntu 19.04+. You might have to use the .NET-Core install script though, because there are no packages, yet.

On the upside, performance has definitely improved: fortunes

plaintext

.NET Core 3:
.NET-Core v 3.0 is said to bring WinForms and WPF to .NET-Core.
However, while WinForms and WPF will be .NET Core, WinForms and WPF in .NET-Core will run on Windows only, because WinForms/WPF will use the Windows-API.

Note:
.NET Core 3.0 is now out (RTM), and there is WinForms and WPF support, but only for C# (on Windows). There is no WinForms-Core-Designer. The designer will, eventually, come with a Visual Studio update, somewhen. WinForms support for VB.NET is not supported, but is planned for .NET 5.0 somewhen in 2020.

PS:

echo "DOTNET_CLI_TELEMETRY_OPTOUT=1" >> /etc/environment
export DOTNET_CLI_TELEMETRY_OPTOUT=1 

If you've used it on windows, you probably never saw this:

The .NET Core tools collect usage data in order to improve your experience.
The data is anonymous and does not include command-line arguments.
The data is collected by Microsoft and shared with the community.
You can opt out of telemetry by setting a DOTNET_CLI_TELEMETRY_OPTOUT environment variable to 1 using your favorite shell.
You can read more about .NET Core tools telemetry @ https://aka.ms/dotnet-cli-telemetry.

I thought I'd mention that I think monodevelop (aka Xamarin Studio, the Mono IDE, or Visual Studio Mac as it is now called on Mac) has evolved quite nicely, and is - in the meantime - largely usable.
However, JetBrains Rider (2018 EAP at this point in time) is definitely a lot nicer and more reliable (and the included decompiler is a life-safer), that is to say, if you develop .NET-Core on Linux or Mac. MonoDevelop does not support Debug-StepThrough on Linux in .NET Core, though, since MS does not license their debugging API dll (except for VisualStudio Mac ... ). However, you can use the Samsung debugger for .NET Core through the .NET Core debugger extension for Samsung Debugger for MonoDevelop

Disclaimer:
I don't use Mac, so I can't say if what I wrote here applies to FreeBSD-Unix based Mac as well. I am refering to the Linux (Debian/Ubuntu/Mint) version of JetBrains Rider, mono, MonoDevelop/VisualStudioMac/XamarinStudio and .NET-Core. Also, Apple is contemplating a move from Intel-processors to self-manufactured ARM(ARM-64?)-based processors, so much of what applies to Mac right now might not apply to Mac in the future (2020+).

Also, when I write "mono is quite unstable and slow", the unstable relates to WinFroms & WebForms applications, specifically executing web-applications via fastcgi or with XSP (on the 4.x version of mono), as well as XML-serialization-handling peculiarities, and the quite-slow relates to WinForms, and regular expressions in particular (ASP.NET-MVC uses regular expressions for routing as well).

When I write about my experience about mono 2.x, 3.x and 4.x, that also does not necessarely mean these issues haven't been resolved by now, or by the time you are reading this, nor that if they are fixed now, that there can't be a regression later that reintroduces any of these bugs/features. Nor does that mean that if you embed the mono-runtime, you'll get the same results as when you use the (dev) system's mono runtime. It also doesn't mean that embedding the mono-runtime (anywhere) is necessarely free.

All that doesn't necessarely mean mono is ill-suited for iOS or Android, or that it has the same issues there. I don't use mono on Android or IOS, so I'm in no positon to say anything about stability, usability, costs and performance on these platforms. Obviously, if you use .NET on Android, you have some other costs considerations to do as well, such as weighting xamarin-costs vs. costs and time for porting existing code to Java. One hears mono on Android and IOS shall be quite good. Take it with a grain of salt. For one, don't expect the default-system-encoding to be the same on android/ios vs. Windows, and don't expect the android filesystem to be case-insensitive, and don't expect any windows fonts to be present.

geom_smooth() what are the methods available?

The method argument specifies the parameter of the smooth statistic. You can see stat_smooth for the list of all possible arguments to the method argument.

Does Google Chrome work with Selenium IDE (as Firefox does)?

If you want to harness Selenium IDE record & playback capabilities for Chrome browser there is an equivalent extension for Chrome called Scirocco. You can add it to Chrome by visiting here using your Chrome browser https://chrome.google.com/webstore/search/scirocco

Scirocco is created by Sonix Asia and is not as polished as Selenium IDE for Firefox. It is in fact quite buggy in places. But it does what you ask.

Output grep results to text file, need cleaner output

grep -n "YOUR SEARCH STRING" * > output-file

The -n will print the line number and the > will redirect grep-results to the output-file.
If you want to "clean" the results you can filter them using pipe | for example:
grep -n "test" * | grep -v "mytest" > output-file will match all the lines that have the string "test" except the lines that match the string "mytest" (that's the switch -v) - and will redirect the result to an output file.
A few good grep-tips can be found on this post

Body of Http.DELETE request in Angular2

Below is the relevant code example for Angular 2/4/5 projects:

let headers = new Headers({
  'Content-Type': 'application/json'
});

let options = new RequestOptions({
  headers: headers,
  body: {
    id: 123
  }
});

return this.http.delete("http//delete.example.com/delete", options)
  .map((response: Response) => {
    return response.json()
  })
  .catch(err => {
    return err;
  });

Notice that body is passed through RequestOptions

Python Remove last char from string and return it

The precise wording of the question makes me think it's impossible.

return to me means you have a function, which you have passed a string as a parameter.

You cannot change this parameter. Assigning to it will only change the value of the parameter within the function, not the passed in string. E.g.

>>> def removeAndReturnLastCharacter(a):
        c = a[-1]
        a = a[:-1]
        return c

>>> b = "Hello, Gaukler!"
>>> removeAndReturnLastCharacter(b)
!

>>> b    # b has not been changed
Hello, Gaukler!

How to search a string in multiple files and return the names of files in Powershell?

I modified one of the answers above to give me a bit more information. This spared me a second query later on. It was something like this:

Get-ChildItem `
        -Path "C:\data\path" -Filter "Example*.dat" -recurse | `
    Select-String -pattern "dummy" | `
    Select-Object -Property Path,LineNumber,Line | `
    Export-CSV "C:\ResultFile.csv"

I can specify the path and file wildcards with this structures, and it saves the filename, line number and relevant line to an output file.

How to update a pull request from forked repo?

Updating a pull request in GitHub is as easy as committing the wanted changes into existing branch (that was used with pull request), but often it is also wanted to squash the changes into single commit:

git checkout yourbranch
git rebase -i origin/master

# Edit command names accordingly
  pick   1fc6c95 My pull request
  squash 6b2481b Hack hack - will be discarded
  squash dd1475d Also discarded

git push -f origin yourbranch

...and now the pull request contains only one commit.


Related links about rebasing:

Read a text file line by line in Qt

Here's the example from my code. So I will read a text from 1st line to 3rd line using readLine() and then store to array variable and print into textfield using for-loop :

QFile file("file.txt");

    if(!file.open(QIODevice::ReadOnly | QIODevice::Text))
        return;

    QTextStream in(&file);
    QString line[3] = in.readLine();
    for(int i=0; i<3; i++)
    {
        ui->textEdit->append(line[i]);
    }

How to find third or n?? maximum salary from salary table?

Optimized way,

;With CTE as
(
select salary 
        ,RANK(order by salary desc) as Rnk
from table
)
select * from CTE where Rnk = @yourVariable

Second Opinion,

Declare @yourVariable int = 2
Select top 1 * from 
(
select distinct top(@yourVariable)  salary 
from Employees
order by salary desc
)as a
order by a.salary asc
select * from Employees
order by salary desc

How to make phpstorm display line numbers by default?

File -> Settings -> Editor -> General -> Appearance check "Show Line Numbers"

This is the current location as of phpStorm 8.0.2 on Ubuntu 14.04

how do I set height of container DIV to 100% of window height?

I've been thinking over this and experimenting with height of the elements: html, body and div. Finally I came up with the code:

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<meta charset="utf-8" />_x000D_
<title>Height question</title>_x000D_
<style>_x000D_
 html {height: 50%; border: solid red 3px; }_x000D_
 body {height: 70vh; border: solid green 3px; padding: 12pt; }_x000D_
 div {height: 90vh; border: solid blue 3px; padding: 24pt; }_x000D_
 _x000D_
</style>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
 <div id="container">_x000D_
  <p>&lt;html&gt; is red</p>_x000D_
  <p>&lt;body&gt; is green</p>_x000D_
  <p>&lt;div&gt; is blue</p>_x000D_
 </div>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

With my browser (Firefox 65@mint 64), all three elements are of 1) different height, 2) every one is longer, than the previous (html is 50%, body is 70vh, and div 90vh). I also checked the styles without the height with respect to the html and body tags. Worked fine, too.

About CSS units: w3schools: CSS units

A note about the viewport: " Viewport = the browser window size. If the viewport is 50cm wide, 1vw = 0.5cm."

ImageView in circular through xml

I hope this will help you.

1) CircleImageView

enter image description here

 <de.hdodenhof.circleimageview.CircleImageView
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/profile_image"
    android:layout_width="96dp"
    android:layout_height="96dp"
    android:src="@drawable/profile"
    app:civ_border_width="2dp"
    app:civ_border_color="#FF000000"/>

Don't forget implementation: Gradle Scripts > build.gradle (Module: app) > dependencies

     implementation 'de.hdodenhof:circleimageview:3.1.0'   

For complete description please check here : The Source here.

2) CircularImageView

enter image description here

<com.mikhaellopez.circularimageview.CircularImageView
    android:layout_width="250dp"
    android:layout_height="250dp"
    android:src="@drawable/image"
    app:civ_border_color="#3f51b5"
    app:civ_border_width="4dp"
    app:civ_shadow="true"
    app:civ_shadow_radius="10"
    app:civ_shadow_color="#3f51b5"/>

Don't forget implementation: Gradle Scripts > build.gradle (Module: app) > dependencies

     implementation 'com.mikhaellopez:circularimageview:4.2.0'   

For complete description please check here : The Source here.

error LNK2019: unresolved external symbol _WinMain@16 referenced in function ___tmainCRTStartup

Your tried to turn that source file into an executable, which obviously isn't possible, because the mandatory entry point, the main function, isn't defined. Add a file main.cpp and define a main function. If you're working on the commandline (which I doubt), you can add /c to only compile and not link. This will produce an object file only, which needs to be linked into either a static or shared lib or an application (in which case you'll need an oject file with main defined).

_WinMain is Microsoft's name for main when linking.

Also: you're not running the code yet, you are compiling (and linking) it. C++ is not an interpreted language.

How to prevent ENTER keypress to submit a web form?

Add this tag to your form - onsubmit="return false;" Then you can only submit your form with some JavaScript function.

Method to Add new or update existing item in Dictionary

The only problem could be if one day

map[key] = value

will transform to -

map[key]++;

and that will cause a KeyNotFoundException.

ScriptManager.RegisterStartupScript code not working - why?

I came across a similar issue. However this issue was caused because of the way i designed the pages to bring the requests in. I placed all of my .js files as the last thing to be applied to the page, therefore they are at the end of my document. The .js files have all my functions include. The script manager seems that to be able to call this function it needs the js file already present with the function being called at the time of load. Hope this helps anyone else.

connecting to phpMyAdmin database with PHP/MySQL

$db = new mysqli('Server_Name', 'Name', 'password', 'database_name');

Creating a JSON dynamically with each input value using jquery

I don't think you can turn JavaScript objects into JSON strings using only jQuery, assuming you need the JSON string as output.

Depending on the browsers you are targeting, you can use the JSON.stringify function to produce JSON strings.

See http://www.json.org/js.html for more information, there you can also find a JSON parser for older browsers that don't support the JSON object natively.

In your case:

var array = [];
$("input[class=email]").each(function() {
    array.push({
        title: $(this).attr("title"),
        email: $(this).val()
    });
});
// then to get the JSON string
var jsonString = JSON.stringify(array);

Error:Cannot fit requested classes in a single dex file.Try supplying a main-dex list. # methods: 72477 > 65536

In build:app

apply plugin: 'com.android.application'
android {
compileSdkVersion 28
defaultConfig {
    applicationId "com.proyecto.marketdillo"
    minSdkVersion 14
    targetSdkVersion 28
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    multiDexEnabled true
}
buildTypes {
    release {
        minifyEnabled false
        proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
    }
  }
}
dependencies {
implementation fileTree(dir: 'libs', include: ['*.jar'])
implementation 'com.android.support:appcompat-v7:28.0.0-rc02'
implementation 'com.google.firebase:firebase-core:16.0.7'
implementation 'com.android.support.constraint:constraint-layout:1.1.3'
implementation 'com.android.support:support-v4:28.0.0-rc02'
implementation 'com.android.support:design:28.0.0-rc02'
implementation 'com.google.firebase:firebase-auth:16.1.0'
implementation 'com.squareup.picasso:picasso:2.5.2'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'
implementation 'com.google.firebase:firebase-firestore:17.1.5'
implementation 'com.android.support:multidex:1.0.3'
}
apply plugin: 'com.google.gms.google-services'

How to negate a method reference predicate

Predicate.not( … )

offers a new method Predicate#not

So you can negate the method reference:

Stream<String> s = ...;
long nonEmptyStrings = s.filter(Predicate.not(String::isEmpty)).count();

Why std::cout instead of simply cout?

It seems possible your class may have been using pre-standard C++. An easy way to tell, is to look at your old programs and check, do you see:

#include <iostream.h>

or

#include <iostream>

The former is pre-standard, and you'll be able to just say cout as opposed to std::cout without anything additional. You can get the same behavior in standard C++ by adding

using std::cout;

or

using namespace std;

Just one idea, anyway.

How do I create a folder in VB if it doesn't exist?

(imports System.IO)

if Not Directory.Exists(Path) then
  Directory.CreateDirectory(Path)
end if

JavaScript/jQuery to download file via POST with JSON data

Solution

Content-Disposition attachment seems to work for me:

self.set_header("Content-Type", "application/json")
self.set_header("Content-Disposition", 'attachment; filename=learned_data.json')

Workaround

application/octet-stream

I had something similar happening to me with a JSON, for me on the server side I was setting the header to self.set_header("Content-Type", "application/json") however when i changed it to:

self.set_header("Content-Type", "application/octet-stream")

It automatically downloaded it.

Also know that in order for the file to still keep the .json suffix you will need to it on filename header:

self.set_header("Content-Disposition", 'filename=learned_data.json')

Change Bootstrap input focus blue glow

In the end I changed the following css entry in bootstrap.css

textarea:focus,
input[type="text"]:focus,
input[type="password"]:focus,
input[type="datetime"]:focus,
input[type="datetime-local"]:focus,
input[type="date"]:focus,
input[type="month"]:focus,
input[type="time"]:focus,
input[type="week"]:focus,
input[type="number"]:focus,
input[type="email"]:focus,
input[type="url"]:focus,
input[type="search"]:focus,
input[type="tel"]:focus,
input[type="color"]:focus,
.uneditable-input:focus {   
  border-color: rgba(126, 239, 104, 0.8);
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.075) inset, 0 0 8px rgba(126, 239, 104, 0.6);
  outline: 0 none;
}

Find out how much memory is being used by an object in Python

I haven't any personal experience with either of the following, but a simple search for a "Python [memory] profiler" yield:

  • PySizer, "a memory profiler for Python," found at http://pysizer.8325.org/. However the page seems to indicate that the project hasn't been updated for a while, and refers to...

  • Heapy, "support[ing] debugging and optimization regarding memory related issues in Python programs," found at http://guppy-pe.sourceforge.net/#Heapy.

Hope that helps.

mysql query result in php variable

I personally use prepared statements.

Why is it important?

Well it's important because of security. It's very easy to do an SQL injection on someone who use variables in the query.

Instead of using this code:

$query = "SELECT username,userid FROM user WHERE username = 'admin' ";
$result=$conn->query($query);

You should use this

$stmt = $this->db->query("SELECT * FROM users WHERE username = ? AND password = ?");
$stmt->bind_param("ss", $username, $password); //You need the variables to do something as well.
$stmt->execute();

Learn more about prepared statements on:

http://php.net/manual/en/mysqli.quickstart.prepared-statements.php MySQLI

http://php.net/manual/en/pdo.prepared-statements.php PDO

How to remove old Docker containers

These two lines of Bash will filter containers by some keywords before deleting them:

containers_to_keep=$(docker ps -a | grep 'keep\|Up\|registry:latest\|nexus' | awk '{ print $1 }')
containers_to_delete=$(docker ps -a | grep Exited | grep -Fv "$containers_to_keep" | awk '{ print $1 }')
docker rm $containers_to_delete

From this post.

How to list all the files in android phone by using adb shell?

Some Android phones contain Busybox. Was hard to find.

To see if busybox was around:

ls -lR / | grep busybox

If you know it's around. You need some read/write space. Try you flash drive, /sdcard

cd /sdcard
ls -lR / >lsoutput.txt

upload to your computer. Upload the file. Get some text editor. Search for busybox. Will see what directory the file was found in.

busybox find /sdcard -iname 'python*'

to make busybox easier to access, you could:

cd /sdcard
ln -s /where/ever/busybox/is  busybox
/sdcard/busybox find /sdcard -iname 'python*'

Or any other place you want. R

Set formula to a range of cells

Range("C1:C10").Formula = "=A1+B1"

Simple as that.

It autofills (FillDown) the range with the formula.

Progress during large file copy (Copy-Item & Write-Progress?)

This recursive function copies files and directories recursively from source path to destination path

If file already exists on destination path, it copies them only with newer files.

Function Copy-FilesBitsTransfer(
        [Parameter(Mandatory=$true)][String]$sourcePath, 
        [Parameter(Mandatory=$true)][String]$destinationPath, 
        [Parameter(Mandatory=$false)][bool]$createRootDirectory = $true)
{
    $item = Get-Item $sourcePath
    $itemName = Split-Path $sourcePath -leaf
    if (!$item.PSIsContainer){ #Item Is a file

        $clientFileTime = Get-Item $sourcePath | select LastWriteTime -ExpandProperty LastWriteTime

        if (!(Test-Path -Path $destinationPath\$itemName)){
            Start-BitsTransfer -Source $sourcePath -Destination $destinationPath -Description "$sourcePath >> $destinationPath" -DisplayName "Copy Template file" -Confirm:$false
            if (!$?){
                return $false
            }
        }
        else{
            $serverFileTime = Get-Item $destinationPath\$itemName | select LastWriteTime -ExpandProperty LastWriteTime

            if ($serverFileTime -lt $clientFileTime)
            {
                Start-BitsTransfer -Source $sourcePath -Destination $destinationPath -Description "$sourcePath >> $destinationPath" -DisplayName "Copy Template file" -Confirm:$false
                if (!$?){
                    return $false
                }
            }
        }
    }
    else{ #Item Is a directory
        if ($createRootDirectory){
            $destinationPath = "$destinationPath\$itemName"
            if (!(Test-Path -Path $destinationPath -PathType Container)){
                if (Test-Path -Path $destinationPath -PathType Leaf){ #In case item is a file, delete it.
                    Remove-Item -Path $destinationPath
                }

                New-Item -ItemType Directory $destinationPath | Out-Null
                if (!$?){
                    return $false
                }

            }
        }
        Foreach ($fileOrDirectory in (Get-Item -Path "$sourcePath\*"))
        {
            $status = Copy-FilesBitsTransfer $fileOrDirectory $destinationPath $true
            if (!$status){
                return $false
            }
        }
    }

    return $true
}

Looping through rows in a DataView

The DataView object itself is used to loop through DataView rows.

DataView rows are represented by the DataRowView object. The DataRowView.Row property provides access to the original DataTable row.

C#

foreach (DataRowView rowView in dataView)
{
    DataRow row = rowView.Row;
    // Do something //
}

VB.NET

For Each rowView As DataRowView in dataView
    Dim row As DataRow = rowView.Row
    ' Do something '
Next

Scanner doesn't read whole sentence - difference between next() and nextLine() of scanner class

Instead of using System.in and System.out directly, use the Console class - it allows you to display a prompt and read an entire line (thereby fixing your problem) of input in one call:

String address = System.console().readLine("Enter your Address: ");

HTTP response header content disposition for attachments

Problems

The code has the following issues:

  • An Ajax call (<a4j:commandButton .../>) does not work with attachments.
  • Creating the output content must happen first.
  • Displaying the error messages also cannot use Ajax-based a4j tags.

Solution

  1. Change <a4j:commandButton .../> to <h:commandButton .../>.
  2. Update the source code:
    1. Change bw.write( getDomainDocument() ); to bw.write( document );.
    2. Add String document = getDomainDocument(); to the first line of the try/catch.
  3. Change the <a4j:outputPanel.../> (not shown) to <h:messages showDetail="false"/>.

Essentially, remove all the Ajax facilities related to the commandButton. It is still possible to display error messages and leverage the RichFaces UI style.

References

What is the Swift equivalent of isEqualToString in Objective-C?

With Swift you don't need anymore to check the equality with isEqualToString

You can now use ==

Example:

let x = "hello"
let y = "hello"
let isEqual = (x == y)

now isEqual is true.

JavaScript: set dropdown selected item based on option text

var textToFind = 'Google';

var dd = document.getElementById('MyDropDown');
for (var i = 0; i < dd.options.length; i++) {
    if (dd.options[i].text === textToFind) {
        dd.selectedIndex = i;
        break;
    }
}

Can't push image to Amazon ECR - fails with "no basic auth credentials"

if you run $(aws ecr get-login --region us-east-1) it will be all done for you

How to convert BigInteger to String in java

You want to use BigInteger.toByteArray()

String msg = "Hello there!";
BigInteger bi = new BigInteger(msg.getBytes());
System.out.println(new String(bi.toByteArray())); // prints "Hello there!"

The way I understand it is that you're doing the following transformations:

  String  -----------------> byte[] ------------------> BigInteger
          String.getBytes()         BigInteger(byte[])

And you want the reverse:

  BigInteger ------------------------> byte[] ------------------> String
             BigInteger.toByteArray()          String(byte[])

Note that you probably want to use overloads of String.getBytes() and String(byte[]) that specifies an explicit encoding, otherwise you may run into encoding issues.

XPath: difference between dot and text()

There is a difference between . and text(), but this difference might not surface because of your input document.

If your input document looked like (the simplest document one can imagine given your XPath expressions)

Example 1

<html>
  <a>Ask Question</a>
</html>

Then //a[text()="Ask Question"] and //a[.="Ask Question"] indeed return exactly the same result. But consider a different input document that looks like

Example 2

<html>
  <a>Ask Question<other/>
  </a>
</html>

where the a element also has a child element other that follows immediately after "Ask Question". Given this second input document, //a[text()="Ask Question"] still returns the a element, while //a[.="Ask Question"] does not return anything!


This is because the meaning of the two predicates (everything between [ and ]) is different. [text()="Ask Question"] actually means: return true if any of the text nodes of an element contains exactly the text "Ask Question". On the other hand, [.="Ask Question"] means: return true if the string value of an element is identical to "Ask Question".

In the XPath model, text inside XML elements can be partitioned into a number of text nodes if other elements interfere with the text, as in Example 2 above. There, the other element is between "Ask Question" and a newline character that also counts as text content.

To make an even clearer example, consider as an input document:

Example 3

<a>Ask Question<other/>more text</a>

Here, the a element actually contains two text nodes, "Ask Question" and "more text", since both are direct children of a. You can test this by running //a/text() on this document, which will return (individual results separated by ----):

Ask Question
-----------------------
more text

So, in such a scenario, text() returns a set of individual nodes, while . in a predicate evaluates to the string concatenation of all text nodes. Again, you can test this claim with the path expression //a[.='Ask Questionmore text'] which will successfully return the a element.


Finally, keep in mind that some XPath functions can only take one single string as an input. As LarsH has pointed out in the comments, if such an XPath function (e.g. contains()) is given a sequence of nodes, it will only process the first node and silently ignore the rest.

Regular expression - starting and ending with a character string

^wp.*\.php$ Should do the trick.

The .* means "any character, repeated 0 or more times". The next . is escaped because it's a special character, and you want a literal period (".php"). Don't forget that if you're typing this in as a literal string in something like C#, Java, etc., you need to escape the backslash because it's a special character in many literal strings.

find vs find_by vs where

The accepted answer generally covers it all, but I'd like to add something, just incase you are planning to work with the model in a way like updating, and you are retrieving a single record(whose id you do not know), Then find_by is the way to go, because it retrieves the record and does not put it in an array

irb(main):037:0> @kit = Kit.find_by(number: "3456")
  Kit Load (0.9ms)  SELECT "kits".* FROM "kits" WHERE "kits"."number" = 
 '3456' LIMIT 1
=> #<Kit id: 1, number: "3456", created_at: "2015-05-12 06:10:56",   
updated_at: "2015-05-12 06:10:56", job_id: nil>

irb(main):038:0> @kit.update(job_id: 2)
(0.2ms)  BEGIN Kit Exists (0.4ms)  SELECT 1 AS one FROM "kits" WHERE  
("kits"."number" = '3456' AND "kits"."id" != 1) LIMIT 1 SQL (0.5ms)   
UPDATE "kits" SET "job_id" = $1, "updated_at" = $2 WHERE  "kits"."id" = 
1  [["job_id", 2], ["updated_at", Tue, 12 May 2015 07:16:58 UTC +00:00]] 
(0.6ms)  COMMIT => true

but if you use where then you can not update it directly

irb(main):039:0> @kit = Kit.where(number: "3456")
Kit Load (1.2ms)  SELECT "kits".* FROM "kits" WHERE "kits"."number" =  
'3456' => #<ActiveRecord::Relation [#<Kit id: 1, number: "3456", 
created_at: "2015-05-12 06:10:56", updated_at: "2015-05-12 07:16:58", 
job_id: 2>]>

irb(main):040:0> @kit.update(job_id: 3)
ArgumentError: wrong number of arguments (1 for 2)

in such a case you would have to specify it like this

irb(main):043:0> @kit[0].update(job_id: 3)
(0.2ms)  BEGIN Kit Exists (0.6ms)  SELECT 1 AS one FROM "kits" WHERE 
("kits"."number" = '3456' AND "kits"."id" != 1) LIMIT 1 SQL (0.6ms)   
UPDATE "kits" SET "job_id" = $1, "updated_at" = $2 WHERE "kits"."id" = 1  
[["job_id", 3], ["updated_at", Tue, 12 May 2015 07:28:04 UTC +00:00]]
(0.5ms)  COMMIT => true

SQL Server replace, remove all after certain character

Could use CASE WHEN to leave those with no ';' alone.

    SELECT
    CASE WHEN CHARINDEX(';', MyText) > 0 THEN
    LEFT(MyText, CHARINDEX(';', MyText)-1) ELSE
    MyText END
    FROM MyTable

Is it possible to return empty in react render function?

for those developers who came to this question about checking where they can return null from component instead of checking in ternary mode to render or not render the component, the answer is YES, You Can!

i mean instead of this junk ternary condition inside your jsx in render part of your component:

// some component body
return(
  <section>
   {/* some ui */}
   
   { someCondition && <MyComponent /> }
   or
   { someCondition ? <MyComponent /> : null }

   {/* more ui */}
  </section>
)

you can check than condition inside your component like:

const MyComponent:React.FC = () => {
  
  // get someCondition from context at here before any thing


  if(someCondition) return null; // i mean this part , checking inside component! 
  
  return (
    <section>   
     // some ui...
    </section>
  )
}

Just Consider that in my case i provide the someCondition variable from a context in upper level component ( for example, just consider in your mind ) and i don't need to prop drill the someCondition inside MyComponent.

Just look how clean view your code gets after that, i mean you don't need to user ternary operator inside your JSX, and your parent component would like below:

// some component body
return(
  <section>
   {/* some ui */}
   
   <MyComponent />

   {/* more ui */}
  </section>
)

and MyComponent would handle the rest for you!

Telling gcc directly to link a library statically

You can add .a file in the linking command:

  gcc yourfiles /path/to/library/libLIBRARY.a

But this is not talking with gcc driver, but with ld linker as options like -Wl,anything are.

When you tell gcc or ld -Ldir -lLIBRARY, linker will check both static and dynamic versions of library (you can see a process with -Wl,--verbose). To change order of library types checked you can use -Wl,-Bstatic and -Wl,-Bdynamic. Here is a man page of gnu LD: http://linux.die.net/man/1/ld

To link your program with lib1, lib3 dynamically and lib2 statically, use such gcc call:

gcc program.o -llib1 -Wl,-Bstatic -llib2 -Wl,-Bdynamic -llib3

Assuming that default setting of ld is to use dynamic libraries (it is on Linux).

How do I create a comma delimited string from an ArrayList?

string.Join(" ,", myArrayList.ToArray()); This will work with .net framework 4.5

How to change the color of a SwitchCompat from AppCompat library

My working example of using style and android:theme simultaneously (API >= 21)

<android.support.v7.widget.SwitchCompat
    android:id="@+id/wan_enable_nat_switch"
    style="@style/Switch"
    app:layout_constraintBaseline_toBaselineOf="@id/wan_enable_nat_label"
    app:layout_constraintEnd_toEndOf="parent" />

<style name="Switch">
    <item name="android:layout_width">wrap_content</item>
    <item name="android:layout_height">wrap_content</item>
    <item name="android:paddingEnd">16dp</item>
    <item name="android:focusableInTouchMode">true</item>
    <item name="android:theme">@style/ThemeOverlay.MySwitchCompat</item>
</style>

<style name="ThemeOverlay.MySwitchCompat" parent="">
    <item name="colorControlActivated">@color/colorPrimaryDark</item>
    <item name="colorSwitchThumbNormal">@color/text_outline_not_active</item>
    <item name="android:colorForeground">#42221f1f</item>
</style>

How to embed image or picture in jupyter notebook, either from a local machine or from a web resource?

Alternatively, you can use a plain HTML <img src>, which allows you to change height and width and is still read by the markdown interpreter:

<img src="subdirectory/MyImage.png" width=60 height=60 />

How to download Javadoc to read offline?

For the download of latest java documentation(jdk-8u77) API

Navigate to http://www.oracle.com/technetwork/java/javase/downloads/index.html

Under Addition Resources and Under Java SE 8 Documentation
Click Download button

Under Java SE Development Kit 8 Documentation > Java SE Development Kit 8u77 Documentation

Accept the License Agreement and click on the download zip file

Unzip the downloaded file Start the API docs from jdk-8u77-docs-all\docs\api\index.html

For the other java versions api download, follow the following steps.

Navigate to http://docs.oracle.com/javase/

From Release dropdown select either of Java SE 7/6/5

In corresponding JAVA SE page and under Downloads left side menu Click JDK 7/6/5 Documentation or Java SE Documentation

Now in next page select the appropriate Java SE Development Kit 7uXX Documentation.

Accept License Agreement and click on Download zip file

Unzip the file and Start the API docs from
jdk-7uXX-docs-all\docs\api\index.html

Facebook share link - can you customize the message body text?

You can't do this using sharer.php, but you can do something similar using the Dialog API. http://developers.facebook.com/docs/reference/dialogs/

http://www.facebook.com/dialog/feed?  
app_id=123050457758183&  
link=http://developers.facebook.com/docs/reference/dialogs/&
picture=http://fbrell.com/f8.jpg&  
name=Facebook%20Dialogs&  
caption=Reference%20Documentation& 
description=Dialogs%20provide%20a%20simple,%20consistent%20interface%20for%20applications%20to%20interact%20with%20users.&
message=Facebook%20Dialogs%20are%20so%20easy!&
redirect_uri=http://www.example.com/response

Facebook dialog example

The catch is you must create a dummy Facebook application just to have an app_id. Note that your Facebook application doesn't have to do ANYTHING at all. Just be sure that it is properly configured, and you should be all set.

Checking out Git tag leads to "detached HEAD state"

Yes, it is normal. This is because you checkout a single commit, that doesnt have a head. Especially it is (sooner or later) not a head of any branch.

But there is usually no problem with that state. You may create a new branch from the tag, if this makes you feel safer :)

Import Error: No module named numpy

I think there are something wrong with the installation of numpy. Here are my steps to solve this problem.

  1. go to this website to download correct package: http://sourceforge.net/projects/numpy/files/
  2. unzip the package
  3. go to the document
  4. use this command to install numpy: python setup.py install

Error:(23, 17) Failed to resolve: junit:junit:4.12

You should to address Java to windows.

  1. Open this address: 'control panel\system and security\system'
  2. From left side choose 'Advanced system settings'
  3. In the advanced tab, choose 'Environment Variables'
  4. In opened window, below "system variables", choose 'New'.
  5. Set variable name to JAVA_HOME, and the variable value to the address you installed Java. For example, for me it is C:\ProgramFiles\Java\jdk1.8.0_66. After that, click the okay button.
  6. Restart Android Studio

Check if list<t> contains any of another list

Here is a sample to find if there are match elements in another list

List<int> nums1 = new List<int> { 2, 4, 6, 8, 10 };
List<int> nums2 = new List<int> { 1, 3, 6, 9, 12};

if (nums1.Any(x => nums2.Any(y => y == x)))
{
    Console.WriteLine("There are equal elements");
}
else
{
    Console.WriteLine("No Match Found!");
}

How to break lines in PowerShell?

I think I found it. All you have to do is type in "`n" (WITH THE QUOTATION MARKS!)

Thanks!

What to gitignore from the .idea folder?

The official support page should answer your question.

So in your .gitignore you might ignore the files ending with .iws, and the workspace.xml and tasks.xml files.

How can I convert a char to int in Java?

The ASCII table is arranged so that the value of the character '9' is nine greater than the value of '0'; the value of the character '8' is eight greater than the value of '0'; and so on.

So you can get the int value of a decimal digit char by subtracting '0'.

char x = '9';
int y = x - '0'; // gives the int value 9

filter out multiple criteria using excel vba

Replace Operator:=xlOr with Operator:=xlAnd between your criteria. See below the amended script

myRange.AutoFilter Field:=1, Criteria1:="<>A", Operator:=xlAnd, Criteria2:="<>B", Operator:=xlAnd, Criteria3:="<>C"

How to get the index of an item in a list in a single step?

  1. Simple solution to find index for any string value in the List.

Here is code for List Of String:

int indexOfValue = myList.FindIndex(a => a.Contains("insert value from list"));
  1. Simple solution to find index for any Integer value in the List.

Here is Code for List Of Integer:

    int indexOfNumber = myList.IndexOf(/*insert number from list*/);

ip address validation in python using regex

Why not use a library function to validate the ip address?

>>> ip="241.1.1.112343434" 
>>> socket.inet_aton(ip)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
socket.error: illegal IP address string passed to inet_aton

How to open a local disk file with JavaScript?

The HTML5 fileReader facility does allow you to process local files, but these MUST be selected by the user, you cannot go rooting about the users disk looking for files.

I currently use this with development versions of Chrome (6.x). I don't know what other browsers support it.

How can I create a dynamically sized array of structs?

If you want to dynamically allocate arrays, you can use malloc from stdlib.h.

If you want to allocate an array of 100 elements using your words struct, try the following:

words* array = (words*)malloc(sizeof(words) * 100);

The size of the memory that you want to allocate is passed into malloc and then it will return a pointer of type void (void*). In most cases you'll probably want to cast it to the pointer type you desire, which in this case is words*.

The sizeof keyword is used here to find out the size of the words struct, then that size is multiplied by the number of elements you want to allocate.

Once you are done, be sure to use free() to free up the heap memory you used in order to prevent memory leaks:

free(array);

If you want to change the size of the allocated array, you can try to use realloc as others have mentioned, but keep in mind that if you do many reallocs you may end up fragmenting the memory. If you want to dynamically resize the array in order to keep a low memory footprint for your program, it may be better to not do too many reallocs.

Disable submit button on form submit

The following worked for me:

var form_enabled = true;
$().ready(function(){
       // allow the user to submit the form only once each time the page loads
       $('#form_id').on('submit', function(){
               if (form_enabled) {
                       form_enabled = false;
                       return true;
               }

               return false;
        });
});

This cancels the submit event if the user tries to submit the form multiple times (by clicking a submit button, pressing Enter, etc.)

Control the dashed border stroke length and distance between strokes

Css render is browser specific and I don't know any fine tuning on it, you should work with images as recommended by Ham. Reference: http://www.w3.org/TR/CSS2/box.html#border-style-properties

Push commits to another branch

when you pushing code to another branch just follow the below git command. Remember demo is my other branch name you can replace with your branch name.

git push origin master:demo

How do I output an ISO 8601 formatted string in JavaScript?

There is a '+' missing after the 'T'

isoDate: function(msSinceEpoch) {
  var d = new Date(msSinceEpoch);
  return d.getUTCFullYear() + '-' + (d.getUTCMonth() + 1) + '-' + d.getUTCDate() + 'T'
         + d.getUTCHours() + ':' + d.getUTCMinutes() + ':' + d.getUTCSeconds();
}

should do it.

For the leading zeros you could use this from here:

function PadDigits(n, totalDigits) 
{ 
    n = n.toString(); 
    var pd = ''; 
    if (totalDigits > n.length) 
    { 
        for (i=0; i < (totalDigits-n.length); i++) 
        { 
            pd += '0'; 
        } 
    } 
    return pd + n.toString(); 
} 

Using it like this:

PadDigits(d.getUTCHours(),2)

Form inside a form, is that alright?

No. HTML explicitly forbids nested forms.

From the HTML 5 draft:

Content model: Flow content, but with no form element descendants.

From the HTML 4.01 Recommendation:

<!ELEMENT FORM - - (%block;|SCRIPT)+ -(FORM) -- interactive form -->

(Note the -(FORM) section).

How do I pass command-line arguments to a WinForms application?

static void Main(string[] args)
{
  // For the sake of this example, we're just printing the arguments to the console.
  for (int i = 0; i < args.Length; i++) {
    Console.WriteLine("args[{0}] == {1}", i, args[i]);
  }
}

The arguments will then be stored in the args string array:

$ AppB.exe firstArg secondArg thirdArg
args[0] == firstArg
args[1] == secondArg
args[2] == thirdArg

Convert pandas Series to DataFrame

One line answer would be

myseries.to_frame(name='my_column_name')

Or

myseries.reset_index(drop=True, inplace=True)  # As needed

"Permission Denied" trying to run Python on Windows 10

May be you can try opening command prompt with Administrator privileges. (Run As Administrator). Works for me most of the time.

C/C++ check if one bit is set in, i.e. int variable

There is, namely the _bittest intrinsic instruction.

if else in a list comprehension

Make a list from items in an iterable

It seems best to first generalize all the possible forms rather than giving specific answers to questions. Otherwise, the reader won't know how the answer was determined. Here are a few generalized forms I thought up before I got a headache trying to decide if a final else' clause could be used in the last form.

[expression1(item)                                        for item in iterable]

[expression1(item) if conditional1                        for item in iterable]

[expression1(item) if conditional1 else expression2(item) for item in iterable]

[expression1(item) if conditional1 else expression2(item) for item in iterable if conditional2]

The value of item doesn't need to be used in any of the conditional clauses. A conditional3 can be used as a switch to either add or not add a value to the output list.

For example, to create a new list that eliminates empty strings or whitespace strings from the original list of strings:

newlist = [s for s in firstlist if s.strip()]

How to set border on jPanel?

Possibly the problem is your two constructor overloads, one that sets the border, the other that doesn't:

public GoBoard(){
    this.linien = 9;
    this.setBorder(BorderFactory.createEmptyBorder(0,10,10,10)); 
}

public GoBoard(int pLinien){
    this.linien = pLinien;

}

If you create a GoBoard object with the second constructor and pass an int parameter, the empty border will not be created. To fix this, consider changing this so both constructors set the border:

// default constructor
public GoBoard(){
    this(9);  // calls other constructor
}

public GoBoard(int pLinien){
    this.linien = pLinien;
    this.setBorder(BorderFactory.createEmptyBorder(0,10,10,10)); 
}

edit 1: The border you've added is more for controlling how components are added to your JPanel. If you want to draw in your one JPanel but have a border around the drawing, consider placing this JPanel into another JPanel, a holding JPanel that has the border. For e.g.,

class GoTest {
   private static final int JB_WIDTH = 400;
   private static final int JB_HEIGHT = JB_WIDTH;

   private static void initGui() {
      JFrame frame = new JFrame("GoBoard");
      GoBoard jboard = new GoBoard();
      jboard.setLayout(new BorderLayout(10, 10));

      JPanel holdingPanel = new JPanel(new BorderLayout());
      int eb = 20;
      holdingPanel.setBorder(BorderFactory.createEmptyBorder(0, eb, eb, eb));
      holdingPanel.add(jboard, BorderLayout.CENTER);
      frame.add(holdingPanel, BorderLayout.CENTER);
      jboard.setPreferredSize(new Dimension(JB_WIDTH, JB_HEIGHT));

      frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
      //!! frame.setSize(400, 400);
      frame.pack();
      frame.setVisible(true);
   }

// .... etc....

How to handle an IF STATEMENT in a Mustache template?

I have a simple and generic hack to perform key/value if statement instead of boolean-only in mustache (and in an extremely readable fashion!) :

function buildOptions (object) {
    var validTypes = ['string', 'number', 'boolean'];
    var value;
    var key;
    for (key in object) {
        value = object[key];
        if (object.hasOwnProperty(key) && validTypes.indexOf(typeof value) !== -1) {
            object[key + '=' + value] = true;
        }
    }
    return object;
}

With this hack, an object like this:

var contact = {
  "id": 1364,
  "author_name": "Mr Nobody",
  "notified_type": "friendship",
  "action": "create"
};

Will look like this before transformation:

var contact = {
  "id": 1364,
  "id=1364": true,
  "author_name": "Mr Nobody",
  "author_name=Mr Nobody": true,
  "notified_type": "friendship",
  "notified_type=friendship": true,
  "action": "create",
  "action=create": true
};

And your mustache template will look like this:

{{#notified_type=friendship}}
    friendship…
{{/notified_type=friendship}}

{{#notified_type=invite}}
    invite…
{{/notified_type=invite}}

Import SQL file by command line in Windows 7

To import database from dump file use:

mysql -u UserName -p Password DatabaseName < FileName.sql 

In wamp

C:\wamp\bin\mysql\mysql5.0.51b\bin>mysql mysql -uroot -p DatabaseName < FileName.sql 

Eclipse change project files location

If you have your project saved as a local copy of a repository, it may be better to import from git. Select local, and then browse to your git repository folder. That worked better for me than importing it as an existing project. Attempting the latter did not allow me to "finish".

jQuery replace one class with another

you could have both of them use a "corpo_button" class, or something like that, and then in $(".corpo_button").click(...) just call $(this).toggleClass("corpo_buttons_asia corpo_buttons_global");

Is it possible to decompile an Android .apk file?

Download this jadx tool https://sourceforge.net/projects/jadx/files/

Unzip it and than in lib folder run jadx-gui-0.6.1.jar file now browse your apk file. It's done. Automatically apk will decompile and save it by pressing save button. Hope it will work for you. Thanks

Bootstrap Columns Not Working

Try this:

DEMO

<div class="container-fluid"> <!-- If Needed Left and Right Padding in 'md' and 'lg' screen means use container class -->
            <div class="row">
                <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4">
                    <a href="#">About</a>
                </div>
                <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4">
                    <img src="image.png" />
                </div>
                <div class="col-xs-4 col-sm-4 col-md-4 col-lg-4">
                    <a href="#myModal1" data-toggle="modal">SHARE</a>
                </div>
            </div>
        </div>

How to add the JDBC mysql driver to an Eclipse project?

you haven't loaded driver into memory. use this following in init()

Class.forName("com.mysql.jdbc.Driver");

Also, you missed a colon (:) in url, use this

String mySqlUrl = "jdbc:mysql://localhost:3306/mysql";

What is the difference between a Shared Project and a Class Library in Visual Studio 2015?

In-Short Differences are

1) PCL is not going to have Full Access to .NET Framework , where as SharedProject has.

2) #ifdef for platform specific code - you can not write in PCL (#ifdef option isn’t available to you in a PCL because it’s compiled separately, as its own DLL, so at compile time (when the #ifdef is evaluated) it doesn’t know what platform it will be part of. ) where as Shared project you can.

3) Platform specific code is achieved using Inversion Of Control in PCL , where as using #ifdef statements you can achieve the same in Shared Project.

An excellent article which illustrates differences between PCL vs Shared Project can be found at the following link

http://hotkrossbits.com/2015/05/03/xamarin-forms-pcl-vs-shared-project/

concatenate two database columns into one resultset column

If you are having a problem with NULL values, use the COALESCE function to replace the NULL with the value of your choice. Your query would then look like this:

SELECT (COALESCE(field1, '') + '' + COALESCE(field2, '') + '' + COALESCE(field3,'')) FROM table1

http://www.codeproject.com/KB/database/DataCrunching.aspx

Sun JSTL taglib declaration fails with "Can not find the tag library descriptor"

I was getting this problem with a maven project using the eclipse IDE. I changed the 'Order and Export' in the project's build path putting the Maven dependencies first and the error disappeared. I guess it's because the eclipse IDE was initially building my application source before loading the Maven libraries.

How to use OUTPUT parameter in Stored Procedure

You need to close the connection before you can use the output parameters. Something like this

con.Close();
MessageBox.Show(cmd.Parameters["@code"].Value.ToString());

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

I've used py2exe in the past and have been very happy with it. I didn't particularly enjoy using cx-freeze as much, though

Equivalent of Super Keyword in C#

C# equivalent of your code is

  class Imagedata : PDFStreamEngine
  {
     // C# uses "base" keyword whenever Java uses "super" 
     // so instead of super(...) in Java we should call its C# equivalent (base):
     public Imagedata()
       : base(ResourceLoader.loadProperties("org/apache/pdfbox/resources/PDFTextStripper.properties", true)) 
     { }

     // Java methods are virtual by default, when C# methods aren't.
     // So we should be sure that processOperator method in base class 
     // (that is PDFStreamEngine)
     // declared as "virtual"
     protected override void processOperator(PDFOperator operations, List arguments)
     {
        base.processOperator(operations, arguments);
     }
  }

Find which rows have different values for a given column in Teradata SQL

This works for PL/SQL:

select count(*), id,address from table group by id,address having count(*)<2

How do I create a circle or square with just CSS - with a hollow center?

In case of circle all you need is one div, but in case of hollow square you need to have 2 divs. The divs are having a display of inline-block which you can change accordingly. Live Codepen link: Click Me

In case of circle all you need to change is the border properties and the dimensions(width and height) of circle. If you want to change color just change the border color of hollow-circle.

In case of the square background-color property needs to be changed depending upon the background of page or the element upon which you want to place the hollow-square. Always keep the inner-circle dimension small as compared to the hollow-square. If you want to change color just change the background-color of hollow-square. The inner-circle is centered upon the hollow-square using the position, top, left, transform properties just don't mess with them.

Code is as follows:

_x000D_
_x000D_
/* CSS Code */_x000D_
_x000D_
.hollow-circle {_x000D_
  width: 4rem;_x000D_
  height: 4rem;_x000D_
  background-color: transparent;_x000D_
  border-radius: 50%;_x000D_
  display: inline-block;_x000D_
  _x000D_
  /* Use this */_x000D_
  border-color: black;_x000D_
  border-width: 5px;_x000D_
  border-style: solid;_x000D_
  /* or */_x000D_
  /* Shorthand Property */_x000D_
  /* border: 5px solid #000; */_x000D_
}_x000D_
_x000D_
.hollow-square {_x000D_
  position: relative;_x000D_
  width: 4rem;_x000D_
  height: 4rem;_x000D_
  display: inline-block;_x000D_
  background-color: black;_x000D_
}_x000D_
_x000D_
.inner-circle {_x000D_
  position: absolute;_x000D_
  top: 50%;_x000D_
  left: 50%;_x000D_
  transform: translate(-50%, -50%);_x000D_
  width: 3rem;_x000D_
  height: 3rem;_x000D_
  border-radius: 50%;_x000D_
  background-color: white;_x000D_
}
_x000D_
<!-- HTML Code -->_x000D_
_x000D_
<div class="hollow-circle">_x000D_
</div>_x000D_
_x000D_
<br/><br/><br/>_x000D_
_x000D_
<div class="hollow-square">_x000D_
  <div class="inner-circle"></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Basic HTML - how to set relative path to current folder?

Just dot is working. The doctype makes a difference however as sometimes the ./ is fine as well.

<a href=".">Link to this folder</a>

Nested attributes unpermitted parameters

Actually there is a way to just white-list all nested parameters.

params.require(:widget).permit(:name, :description).tap do |whitelisted|
  whitelisted[:position] = params[:widget][:position]
  whitelisted[:properties] = params[:widget][:properties]
end

This method has advantage over other solutions. It allows to permit deep-nested parameters.

While other solutions like:

params.require(:person).permit(:name, :age, pets_attributes: [:id, :name, :category])

Don't.


Source:

https://github.com/rails/rails/issues/9454#issuecomment-14167664

How to make bootstrap column height to 100% row height?

You can solve that using display table.

Here is the updated JSFiddle that solves your problem.

CSS

.body {
    display: table;
    background-color: green;
}

.left-side {
    background-color: blue;
    float: none;
    display: table-cell;
    border: 1px solid;
}

.right-side {
    background-color: red;
    float: none;
    display: table-cell;
    border: 1px solid;
}

HTML

<div class="row body">
        <div class="col-xs-9 left-side">
            <p>sdfsdf</p>
            <p>sdfsdf</p>
            <p>sdfsdf</p>
            <p>sdfsdf</p>
            <p>sdfsdf</p>
            <p>sdfsdf</p>
        </div>
        <div class="col-xs-3 right-side">
            asdfdf
        </div>
    </div>

Hive Alter table change Column Name

Change Column Name/Type/Position/Comment:

ALTER TABLE table_name CHANGE [COLUMN] col_old_name col_new_name column_type [COMMENT col_comment] [FIRST|AFTER column_name]

Example:

CREATE TABLE test_change (a int, b int, c int);

// will change column a's name to a1
ALTER TABLE test_change CHANGE a a1 INT;

Git: how to reverse-merge a commit?

git reset --hard HEAD^ 

Use the above command to revert merge changes.

Removing duplicates from a String in Java

StringBuilder builderWord = new StringBuilder(word);
 for(int index=0; index < builderWord.length(); index++) {
   for(int reverseIndex=builderWord.length()-1; reverseIndex > index;reverseIndex--) {
     if (builderWord.charAt(reverseIndex) == builderWord.charAt(index)) {
       builderWord.deleteCharAt(reverseIndex);
     }
   }
}
return builderWord.toString();

Use C# HttpWebRequest to send json to web service

First of all you missed ScriptService attribute to add in webservice.

[ScriptService]

After then try following method to call webservice via JSON.

        var webAddr = "http://Domain/VBRService.asmx/callJson";
        var httpWebRequest = (HttpWebRequest)WebRequest.Create(webAddr);
        httpWebRequest.ContentType = "application/json; charset=utf-8";
        httpWebRequest.Method = "POST";            

        using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
        {
            string json = "{\"x\":\"true\"}";

            streamWriter.Write(json);
            streamWriter.Flush();
        }

        var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();
        using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
        {
            var result = streamReader.ReadToEnd();
            return result;
        }