Programs & Examples On #Indy 9

Indy 9 is a reference to a specific version of Indy.

How to sort 2 dimensional array by column value?

As my usecase involves dozens of columns, I expanded @jahroy's answer a bit. (also just realized @charles-clayton had the same idea.)
I pass the parameter I want to sort by, and the sort function is redefined with the desired index for the comparison to take place on.

var ID_COLUMN=0
var URL_COLUMN=1

findings.sort(compareByColumnIndex(URL_COLUMN))

function compareByColumnIndex(index) {
  return function(a,b){
    if (a[index] === b[index]) {
        return 0;
    }
    else {
        return (a[index] < b[index]) ? -1 : 1;
    }
  }
}

Declaring & Setting Variables in a Select Statement

The SET command is TSQL specific - here's the PLSQL equivalent to what you posted:

v_date1 DATE := TO_DATE('03-AUG-2010', 'DD-MON-YYYY');

SELECT u.visualid
  FROM USAGE u 
 WHERE u.usetime > v_date1;

There's also no need for prefixing variables with "@"; I tend to prefix variables with "v_" to distinguish between variables & columns/etc.

See this thread about the Oracle equivalent of NOLOCK...

Select objects based on value of variable in object using jq

I had a similar related question: What if you wanted the original object format back (with key names, e.g. FOO, BAR)?

Jq provides to_entries and from_entries to convert between objects and key-value pair arrays. That along with map around the select

These functions convert between an object and an array of key-value pairs. If to_entries is passed an object, then for each k: v entry in the input, the output array includes {"key": k, "value": v}.

from_entries does the opposite conversion, and with_entries(foo) is a shorthand for to_entries | map(foo) | from_entries, useful for doing some operation to all keys and values of an object. from_entries accepts key, Key, name, Name, value and Value as keys.

jq15 < json 'to_entries | map(select(.value.location=="Stockholm")) | from_entries'

{
  "FOO": {
    "name": "Donald",
    "location": "Stockholm"
  },
  "BAR": {
    "name": "Walt",
    "location": "Stockholm"
  }
}

Using the with_entries shorthand, this becomes:

jq15 < json 'with_entries(select(.value.location=="Stockholm"))'
{
  "FOO": {
    "name": "Donald",
    "location": "Stockholm"
  },
  "BAR": {
    "name": "Walt",
    "location": "Stockholm"
  }
}

What is the return value of os.system() in Python?

Based on the answer of @AlokThakur (thanks!):

def run_system_command(command):
    return_value = os.system(command)
    # Calculate the return value code
    return_value = int(bin(return_value).replace("0b", "").rjust(16, '0')[:8], 2)
    if return_value != 0:
        raise RuntimeError(f'The system command\n{command}\nexited with return code {return_value}')

java: ArrayList - how can I check if an index exists?

a simple way to do this:

try {
  list.get( index ); 
} 
catch ( IndexOutOfBoundsException e ) {
  if(list.isEmpty() || index >= list.size()){
    // Adding new item to list.
  }
}

Kotlin: How to get and set a text to TextView in Android using Kotlin?

import kotlinx.android.synthetic.main.MainActivity.*

class Mainactivity : AppCompatActivity() {


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.MainActivity)

        txt.setText("hello Kotlin")

    }

}

How to sort a data frame by alphabetic order of a character variable in R?

The arrange function in the plyr package makes it easy to sort by multiple columns. For example, to sort DF by ID first and then decreasing by num, you can write

plyr::arrange(DF, ID, desc(num))

How do I convert the date from one format to another date object in another format without using any deprecated classes?

    //Convert input format 19-FEB-16 01.00.00.000000000 PM to 2016-02-19 01.00.000 PM
    SimpleDateFormat inFormat = new SimpleDateFormat("dd-MMM-yy hh.mm.ss.SSSSSSSSS aaa");
    Date today = new Date();        

    Date d1 = inFormat.parse("19-FEB-16 01.00.00.000000000 PM");

    SimpleDateFormat outFormat = new SimpleDateFormat("yyyy-MM-dd hh.mm.ss.SSS aaa");

    System.out.println("Out date ="+outFormat.format(d1));

How to play a sound using Swift?

import AVFoundation

import AudioToolbox

public final class MP3Player : NSObject {
    
    // Singleton class
    static let shared:MP3Player = MP3Player()
    
    private var player: AVAudioPlayer? = nil
    
    // Play only mp3 which are stored in the local
    public func playLocalFile(name:String) {
        guard let url = Bundle.main.url(forResource: name, withExtension: "mp3") else { return }

        do {
            try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback)
            try AVAudioSession.sharedInstance().setActive(true)
            player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue)
            guard let player = player else { return }

            player.play()
        }catch let error{
            print(error.localizedDescription)
        }
    }
}

To call this function

MP3Player.shared.playLocalFile(name: "JungleBook")

How to list records with date from the last 10 days?

http://www.postgresql.org/docs/current/static/functions-datetime.html shows operators you can use for working with dates and times (and intervals).

So you want

SELECT "date"
FROM "Table"
WHERE "date" > (CURRENT_DATE - INTERVAL '10 days');

The operators/functions above are documented in detail:

How can I create database tables from XSD files?

hyperjaxb (versions 2 and 3) actually generates hibernate mapping files and related entity objects and also does a round trip test for a given XSD and sample XML file. You can capture the log output and see the DDL statements for yourself. I had to tweak them a little bit, but it gives you a basic blue print to start with.

Variable length (Dynamic) Arrays in Java

You can't change the size of an array. You can, however, create a new array with the right size and copy the data from the old array to the new.

But your best option is to use IntList from jacarta commons. (here)

It works just like a List but takes less space and is more efficient than that, because it stores int's instead of storing wrapper objects over int's (that's what the Integer class is).

Does Visual Studio Code have box select/multi-line edit?

On Windows it's holding down Alt while box selecting. Once you have your selection then attempt your edit.

PHP Array to JSON Array using json_encode();

If you don't specify indexes on your initial array, you get the regular numric ones. Arrays must have some form of unique index

Angular-Material DateTime Picker Component?

For as long as there is no official date and time picker from angular itself, I would advise to make a combination of the default angular date picker and this Angular Material Timepicker. I've chosen that one because all the other ones I found at this time lack support for issues, are outdated or are not functioning well in the most recent angular versions. This guy seems to be very responsive.

I've wrapped them both in one component so that it looks like it is one unit. You just have to make sure to do a few things:

When no input has been given yet, I would advise:

  • On-click of the component, the datepicker should always be triggered first.
  • After the datepicker closes, have the timepicker automatically popup.
  • Use touchUi = true on the datepicker, so that both the datepicker and the timepicker come as a dialog after each other.
  • Make sure the datepicker also shows up when clicking on the form (instead of only on the icon which is the default).
  • Use this solution to use the timepicker also in a material form, when placing them behind each other, it looks like it is one form.

After a value has been given, it is clear that one part contains the time and the other part contains the date. At that moment it is clear that the user has to click on the time to change the time, and on the date to change the date. But before that, so when both fields are empty (and 'attached' to each other as one field) you should make sure the user cannot be confused by doing above recommendations.

My component is not complete yet, I will try to remember myself to share the code later. Shoot a comment if this question is more then a month old or so.

Edit: Result

enter image description here

<div fxLayout="row">
  <div *ngIf="!dateOnly" [formGroup]="timeFormGroup">
    <mat-form-field>
      <input matInput [ngxTimepicker]="endTime" [format]="24"  placeholder="{{placeholderTime}}" formControlName="endTime" />
    </mat-form-field>
    <ngx-material-timepicker #endTime (timeSet)="timeChange($event)" [minutesGap]="10"></ngx-material-timepicker>
  </div>
  <div>
    <mat-form-field>
      <input id="pickerId" matInput [matDatepicker]="datepicker" placeholder="{{placeholderDate}}" [formControl]="dateForm"
             [min]="config.minDate" [max]="config.maxDate" (dateChange)="dateChange($event)">
      <mat-datepicker-toggle matSuffix [for]="datepicker"></mat-datepicker-toggle>
      <mat-datepicker #datepicker [disabled]="disabled" [touchUi]="config.touchUi" startView="{{config.startView}}"></mat-datepicker>
    </mat-form-field>
  </div>
</div>
import { Component, OnInit, Input, EventEmitter, Output } from '@angular/core';
import { FormControl, FormGroup } from '@angular/forms';
import { DateAdapter, MatDatepickerInputEvent } from '@angular/material';

import * as moment_ from 'moment';

const moment = moment_;

import { MAT_MOMENT_DATE_ADAPTER_OPTIONS } from '@angular/material-moment-adapter';

class DateConfig {
  startView: 'month' | 'year' | 'multi-year';
  touchUi: boolean;
  minDate: moment_.Moment;
  maxDate: moment_.Moment;
}

@Component({
  selector: 'cb-datetimepicker',
  templateUrl: './cb-datetimepicker.component.html',
  styleUrls: ['./cb-datetimepicker.component.scss'],
})
export class DatetimepickerComponent implements OnInit {

  @Input() disabled: boolean;
  @Input() placeholderDate: string;
  @Input() placeholderTime: string;
  @Input() model: Date;
  @Input() purpose: string;
  @Input() dateOnly: boolean;

  @Output() dateUpdate = new EventEmitter<Date>();

  public pickerId: string = "_" + Math.random().toString(36).substr(2, 9);

  public dateForm: FormControl;
  public timeFormGroup: FormGroup;
  public endTime: FormControl;

  public momentDate: moment_.Moment;
  public config: DateConfig;

  //myGroup: FormGroup;


  constructor(private adapter : DateAdapter<any>) { }

  ngOnInit() {

    this.adapter.setLocale("nl-NL");//todo: configurable
    this.config = new DateConfig();
    if (this.purpose === "birthday") {
      this.config.startView = 'multi-year';
      this.config.maxDate = moment().add('year', -15);
      this.config.minDate = moment().add('year', -90);
      this.dateOnly = true;
    } //add more configurations
    else {
      this.config.startView = 'month';
      this.config.maxDate = moment().add('year', 100);
      this.config.minDate = moment().add('year', -100);
    }


    if (window.screen.width < 767) {
      this.config.touchUi = true;
    }



    if (this.model) {
      var mom = moment(this.model);
      if (mom.isBefore(moment('1900-01-01'))) {
        this.momentDate = moment();
      } else {
        this.momentDate = mom;
      }
    } else {
      this.momentDate = moment();
    }

    this.dateForm = new FormControl(this.momentDate);
    if (this.disabled) {
      this.dateForm.disable();
    }
    this.endTime = new FormControl(this.momentDate.format("HH:mm"));

    this.timeFormGroup = new FormGroup({
      endTime: this.endTime
    });


  }


  public dateChange(date: MatDatepickerInputEvent<any>) {

    if (moment.isMoment(date.value)) {
      this.momentDate = moment(date.value);
      if (this.dateOnly) {
        this.momentDate = this.momentDate.utc(true);
      } 
      var newDate = this.momentDate.toDate();
      this.model = newDate;
      this.dateUpdate.emit(newDate);
    }

    console.log("datechange",date);
  }

  public timeChange(time: string) {

    var splitted = time.split(':');
    var hour = splitted[0];
    var minute = splitted[1];

    console.log("time change", time);
   this.momentDate = this.momentDate.set('hour', parseInt(hour));
    this.momentDate = this.momentDate.set('minute', parseInt(minute));

    var newDate = this.momentDate.toDate();
    this.model = newDate;
    this.dateUpdate.emit(newDate);
  }
}

One important source: https://github.com/Agranom/ngx-material-timepicker/issues/126

I think it still deserves some tweaks, as I think it can work a bit better when I would have more time creating this. Most importantly I tried to solve the UTC issue as well, so all dates should be shown in local time but should be sent to the server in UTC format (or at least saved with the correct timezone added to it).

Eclipse Optimize Imports to Include Static Imports

Not exactly what I wanted, but I found a workaround. In Eclipse 3.4 (Ganymede), go to

Window->Preferences->Java->Editor->Content Assist

and check the checkbox for Use static imports (only 1.5 or higher).

This will not bring in the import on an Optimize Imports, but if you do a Quick Fix (CTRL + 1) on the line it will give you the option to add the static import which is good enough.

mysql update column with value from another table

If you have common field in both table then it's so easy !....

Table-1 = table where you want to update. Table-2 = table where you from take data.

  1. make query in Table-1 and find common field value.
  2. make a loop and find all data from Table-2 according to table 1 value.
  3. again make update query in table 1.

$qry_asseet_list = mysql_query("SELECT 'primary key field' FROM `table-1`");

$resultArray = array();
while ($row = mysql_fetch_array($qry_asseet_list)) {
$resultArray[] = $row;
}



foreach($resultArray as $rec) {

    $a = $rec['primary key field'];

    $cuttable_qry = mysql_query("SELECT * FROM `Table-2` WHERE `key field name` = $a");

    $cuttable = mysql_fetch_assoc($cuttable_qry);



    echo $x= $cuttable['Table-2 field']; echo " ! ";
    echo $y= $cuttable['Table-2 field'];echo " ! ";
    echo $z= $cuttable['Table-2 field'];echo " ! ";


    $k = mysql_query("UPDATE `Table-1` SET `summary_style` = '$x', `summary_color` = '$y', `summary_customer` = '$z' WHERE `summary_laysheet_number` = $a;");

    if ($k) {
        echo "done";
    } else {
        echo mysql_error();
    }


}

What's "P=NP?", and why is it such a famous question?

P stands for polynomial time. NP stands for non-deterministic polynomial time.

Definitions:

  • Polynomial time means that the complexity of the algorithm is O(n^k), where n is the size of your data (e. g. number of elements in a list to be sorted), and k is a constant.

  • Complexity is time measured in the number of operations it would take, as a function of the number of data items.

  • Operation is whatever makes sense as a basic operation for a particular task. For sorting, the basic operation is a comparison. For matrix multiplication, the basic operation is multiplication of two numbers.

Now the question is, what does deterministic vs. non-deterministic mean? There is an abstract computational model, an imaginary computer called a Turing machine (TM). This machine has a finite number of states, and an infinite tape, which has discrete cells into which a finite set of symbols can be written and read. At any given time, the TM is in one of its states, and it is looking at a particular cell on the tape. Depending on what it reads from that cell, it can write a new symbol into that cell, move the tape one cell forward or backward, and go into a different state. This is called a state transition. Amazingly enough, by carefully constructing states and transitions, you can design a TM, which is equivalent to any computer program that can be written. This is why it is used as a theoretical model for proving things about what computers can and cannot do.

There are two kinds of TM's that concern us here: deterministic and non-deterministic. A deterministic TM only has one transition from each state for each symbol that it is reading off the tape. A non-deterministic TM may have several such transition, i. e. it is able to check several possibilities simultaneously. This is sort of like spawning multiple threads. The difference is that a non-deterministic TM can spawn as many such "threads" as it wants, while on a real computer only a specific number of threads can be executed at a time (equal to the number of CPUs). In reality, computers are basically deterministic TMs with finite tapes. On the other hand, a non-deterministic TM cannot be physically realized, except maybe with a quantum computer.

It has been proven that any problem that can be solved by a non-deterministic TM can be solved by a deterministic TM. However, it is not clear how much time it will take. The statement P=NP means that if a problem takes polynomial time on a non-deterministic TM, then one can build a deterministic TM which would solve the same problem also in polynomial time. So far nobody has been able to show that it can be done, but nobody has been able to prove that it cannot be done, either.

NP-complete problem means an NP problem X, such that any NP problem Y can be reduced to X by a polynomial reduction. That implies that if anyone ever comes up with a polynomial-time solution to an NP-complete problem, that will also give a polynomial-time solution to any NP problem. Thus that would prove that P=NP. Conversely, if anyone were to prove that P!=NP, then we would be certain that there is no way to solve an NP problem in polynomial time on a conventional computer.

An example of an NP-complete problem is the problem of finding a truth assignment that would make a boolean expression containing n variables true.
For the moment in practice any problem that takes polynomial time on the non-deterministic TM can only be done in exponential time on a deterministic TM or on a conventional computer.
For example, the only way to solve the truth assignment problem is to try 2^n possibilities.

How to resolve Error : Showing a modal dialog box or form when the application is not running in UserInteractive mode is not a valid operation

For Vb.Net Framework 4.0, U can use:

Alert("your message here", Boolean)

The Boolean here can be True or False. True If you want to close the window right after, False If you want to keep the window open.

How to get the IP address of the docker host from inside a docker container

Here is another option for those running Docker in AWS. This option avoids having using apk to add the curl package and saves the precious 7mb of space. Use the built-in wget (part of the monolithic BusyBox binary):

wget -q -O - http://169.254.169.254/latest/meta-data/local-ipv4

Optimal way to concatenate/aggregate strings

Are methods using FOR XML PATH like below really that slow? Itzik Ben-Gan writes that this method has good performance in his T-SQL Querying book (Mr. Ben-Gan is a trustworthy source, in my view).

create table #t (id int, name varchar(20))

insert into #t
values (1, 'Matt'), (1, 'Rocks'), (2, 'Stylus')

select  id
        ,Names = stuff((select ', ' + name as [text()]
        from #t xt
        where xt.id = t.id
        for xml path('')), 1, 2, '')
from #t t
group by id

Is there a way to view two blocks of code from the same file simultaneously in Sublime Text?

In the nav go View => Layout => Columns:2 (alt+shift+2) and open your file again in the other pane (i.e. click the other pane and use ctrl+p filename.py)

It appears you can also reopen the file using the command File -> New View into File which will open the current file in a new tab

How can I get a user's media from Instagram without authenticating as a user?

Here is a php script that downloads the images and creates an html file with links on the images. Credit 350D for php version, this is just elaborated..I would suggest putting this is a cron job and firing however often you need. Verified working as of May 2019.

<?
$user = 'smena8m';
$igdata = file_get_contents('https://instagram.com/'.$user.'/');
preg_match('/_sharedData = ({.*);<\/script>/',$igdata,$matches);
$profile_data = json_decode($matches[1])->entry_data->ProfilePage[0]->graphql->user;
$html = '<div class="instagramBox" style="display:inline-grid;grid-template-columns:auto auto auto;">';
$i = 0;
$max = 9;
while($i<$max){
    $imglink = $profile_data->edge_owner_to_timeline_media->edges[$i]->node->shortcode;
    $img = $profile_data->edge_owner_to_timeline_media->edges[$i]->node->thumbnail_resources[0]->src;
    file_put_contents('ig'.$i.'.jpg',file_get_contents($img));
    $html .= '<a href="https://www.instagram.com/p/'.$imglink.'/" target="_blank"><img src="ig'.$i.'.jpg" /></a>';
    $i++;
}
$html .= '</div>';
$instagram = fopen('instagram.html','w');
fwrite($instagram,$html);
fclose($instagram);
?>

Checking to see if a DateTime variable has had a value assigned

DateTime is value type, so it can not never be null. If you think DateTime? ( Nullable ) you can use:

DateTime? something = GetDateTime();
bool isNull = (something == null);
bool isNull2 = !something.HasValue;

Does the 'mutable' keyword have any purpose other than allowing the variable to be modified by a const function?

In some cases (like poorly designed iterators), the class needs to keep a count or some other incidental value, that doesn't really affect the major "state" of the class. This is most often where I see mutable used. Without mutable, you'd be forced to sacrifice the entire const-ness of your design.

It feels like a hack most of the time to me as well. Useful in a very very few situations.

Checking for directory and file write permissions in .NET

The answers by Richard and Jason are sort of in the right direction. However what you should be doing is computing the effective permissions for the user identity running your code. None of the examples above correctly account for group membership for example.

I'm pretty sure Keith Brown had some code to do this in his wiki version (offline at this time) of The .NET Developers Guide to Windows Security. This is also discussed in reasonable detail in his Programming Windows Security book.

Computing effective permissions is not for the faint hearted and your code to attempt creating a file and catching the security exception thrown is probably the path of least resistance.

Using Linq to get the last N elements of a collection?

Little different implementation with usage of circular buffer. The benchmarks show that the method is circa two times faster than ones using Queue (implementation of TakeLast in System.Linq), however not without a cost - it needs a buffer which grows along with the requested number of elements, even if you have a small collection you can get huge memory allocation.

public IEnumerable<T> TakeLast<T>(IEnumerable<T> source, int count)
{
    int i = 0;

    if (count < 1)
        yield break;

    if (source is IList<T> listSource)
    {
        if (listSource.Count < 1)
            yield break;

        for (i = listSource.Count < count ? 0 : listSource.Count - count; i < listSource.Count; i++)
            yield return listSource[i];

    }
    else
    {
        bool move = true;
        bool filled = false;
        T[] result = new T[count];

        using (var enumerator = source.GetEnumerator())
            while (move)
            {
                for (i = 0; (move = enumerator.MoveNext()) && i < count; i++)
                    result[i] = enumerator.Current;

                filled |= move;
            }

        if (filled)
            for (int j = i; j < count; j++)
                yield return result[j];

        for (int j = 0; j < i; j++)
            yield return result[j];

    }
}

Find Active Tab using jQuery and Twitter Bootstrap

First of all you need to remove the data-toggle attribute. We will use some JQuery, so make sure you include it.

  <ul class='nav nav-tabs'>
    <li class='active'><a href='#home'>Home</a></li>
    <li><a href='#menu1'>Menu 1</a></li>
    <li><a href='#menu2'>Menu 2</a></li>
    <li><a href='#menu3'>Menu 3</a></li>
  </ul>

  <div class='tab-content'>
    <div id='home' class='tab-pane fade in active'>
      <h3>HOME</h3>
    <div id='menu1' class='tab-pane fade'>
      <h3>Menu 1</h3>
    </div>
    <div id='menu2' class='tab-pane fade'>
      <h3>Menu 2</h3>
    </div>
    <div id='menu3' class='tab-pane fade'>
      <h3>Menu 3</h3>
    </div>
  </div>
</div>

<script>
$(document).ready(function(){
// Handling data-toggle manually
    $('.nav-tabs a').click(function(){
        $(this).tab('show');
    });
// The on tab shown event
    $('.nav-tabs a').on('shown.bs.tab', function (e) {
        alert('Hello from the other siiiiiide!');
        var current_tab = e.target;
        var previous_tab = e.relatedTarget;
    });
});
</script>

Switch statement with returns -- code correctness

Interesting. The consensus from most of these answers seems to be that the redundant break statement is unnecessary clutter. On the other hand, I read the break statement in a switch as the 'closing' of a case. case blocks that don't end in a break tend to jump out at me as potential fall though bugs.

I know that that's not how it is when there's a return instead of a break, but that's how my eyes 'read' the case blocks in a switch, so I personally would prefer that each case be paired with a break. But many compilers do complain about the break after a return being superfluous/unreachable, and apparently I seem to be in the minority anyway.

So get rid of the break following a return.

NB: all of this is ignoring whether violating the single entry/exit rule is a good idea or not. As far as that goes, I have an opinion that unfortunately changes depending on the circumstances...

Could not connect to SMTP host: smtp.gmail.com, port: 465, response: -1

In my case it was Avast Antivirus interfering with the connection. Actions to disable this feature: Avast -> Settings-> Components -> Mail Shield (Customize) -> SSL scanning -> uncheck "Scan SSL connections".

Count character occurrences in a string in C++

#include <boost/range/algorithm/count.hpp>

std::string str = "a_b_c";
int cnt = boost::count(str, '_');

How to add text to an existing div with jquery

You need to define the button text and have valid HTML for the button. I would also suggest using .on for the click handler of the button

_x000D_
_x000D_
$(function () {_x000D_
  $('#Add').on('click', function () {_x000D_
    $('<p>Text</p>').appendTo('#Content');_x000D_
  });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<div id="Content">_x000D_
    <button id="Add">Add Text</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Also I would make sure the jquery is at the bottom of the page just before the closing </body> tag. Doing so will make it so you do not have to have the whole thing wrapped in $(function but I would still do that. Having your javascript load at the end of the page makes it so the rest of the page loads incase there is a slow down in your javascript somewhere.

Adding an onclick function to go to url in JavaScript?

Not completely sure I understand the question, but do you mean something like this?

$('#something').click(function() { 
    document.location = 'http://somewhere.com/';
} );

How do I get and set Environment variables in C#?

Environment.SetEnvironmentVariable("Variable name", value, EnvironmentVariableTarget.User);

How to use a BackgroundWorker?

You can update progress bar only from ProgressChanged or RunWorkerCompleted event handlers as these are synchronized with the UI thread.

The basic idea is. Thread.Sleep just simulates some work here. Replace it with your real routing call.

public Form1()
{
    InitializeComponent();

    backgroundWorker1.DoWork += backgroundWorker1_DoWork;
    backgroundWorker1.ProgressChanged += backgroundWorker1_ProgressChanged;
    backgroundWorker1.WorkerReportsProgress = true;
}

private void button1_Click(object sender, EventArgs e)
{
    backgroundWorker1.RunWorkerAsync();
}

private void backgroundWorker1_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
    for (int i = 0; i < 100; i++)
    {
        Thread.Sleep(1000);
        backgroundWorker1.ReportProgress(i);
    }
}

private void backgroundWorker1_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
{
    progressBar1.Value = e.ProgressPercentage;
}

unable to remove file that really exists - fatal: pathspec ... did not match any files

I know this is not the OP's problem, but I ran into the same error with an entirely different basis, so I just wanted to drop it here in case anyone else has the same. This is Windows-specific, and I assume does not affect Linux users.

I had a LibreOffice doc file, call it final report.odt. I later changed its case to Final Report.odt. In Windows, this doesn't even count as a rename. final report.odt, Final Report.odt, FiNaL RePoRt.oDt are all the same. In Linux, these are all distinct.

When I eventually went to git rm "Final Report.odt" and got the "pathspec did not match any files" error. Only when I use the original casing at the time the file was added -- git rm "final report.odt" -- did it work.

Lesson learned: to change the case I should have instead done:

git mv "final report.odt" temp.odt
git mv temp.odt "Final Report.odt"

Again, that wasn't the problem for the OP here; and wouldn't affect a Linux user, as his posts shows he clearly is. I'm just including it for others who may have this problem in Windows git and stumble onto this question.

How to create a box when mouse over text in pure CSS?

This is a small tweak on the other answers. If you have nested divs you can include more exciting content such as H1s in your popup.

CSS

div.appear {
    width: 250px; 
    border: #000 2px solid;
    background:#F8F8F8;
    position: relative;
    top: 5px;
    left:15px;
    display:none;
    padding: 0 20px 20px 20px;
    z-index: 1000000;
}
div.hover  {
    cursor:pointer;
    width: 5px;
}
div.hover:hover div.appear {
    display:block;
}

HTML

<div class="hover">
<img src="questionmark.png"/>
    <div class="appear">
       <h1>My popup</h1>Hitherto and whenceforth.
    </div>
</div>

The problem with these solutions is that everything after this in the page gets shifted when the popup is displayed, ie, the rest of the page jumps downwards to 'make space'. The only way I could fix this was by making position:absolute and removing the top and left CSS tags.

c# dictionary one key many values

Microsoft just added an official prelease version of exactly what you're looking for (called a MultiDictionary) available through NuGet here: https://www.nuget.org/packages/Microsoft.Experimental.Collections/

Info on usage and more details can be found through the official MSDN blog post here: http://blogs.msdn.com/b/dotnet/archive/2014/06/20/would-you-like-a-multidictionary.aspx

I'm the developer for this package, so let me know either here or on MSDN if you have any questions about performance or anything.

Hope that helps.

Update

The MultiValueDictionary is now on the corefxlab repo, and you can get the NuGet package from this MyGet feed.

Query EC2 tags from within instance

Once you've got ec2-metadata and ec2-describe-tags installed (as mentioned in Ranieri's answer above), here's an example shell command to get the "name" of the current instance, assuming you have a "Name=Foo" tag on it.

Assumes EC2_PRIVATE_KEY and EC2_CERT environment variables are set.

ec2-describe-tags \
  --filter "resource-type=instance" \
  --filter "resource-id=$(ec2-metadata -i | cut -d ' ' -f2)" \
  --filter "key=Name" | cut -f5

This returns Foo.

Error 500: Premature end of script headers

I tried all of the above but found out it was a missing windows compiler.

Downloading and installing this fixed the issue. To see if this is your problem, try to run PHP from command line.

msvcr110.dll is missing from computer error while installing PHP

java.time.format.DateTimeParseException: Text could not be parsed at index 21

Your original problem was wrong pattern symbol "h" which stands for the clock hour (range 1-12). In this case, the am-pm-information is missing. Better, use the pattern symbol "H" instead (hour of day in range 0-23). So the pattern should rather have been like:

uuuu-MM-dd'T'HH:mm:ss.SSSX (best pattern also suitable for strict mode)

Error: Argument is not a function, got undefined

Because this pops-up in Google when trying to find an answer to: "Error: Argument '' is not a function, got undefined".

It's possible that you are trying to create the same module twice.

The angular.module is a global place for creating, registering and retrieving AngularJS modules.

Passing one argument retrieves an existing angular.Module, whereas passing more than one argument creates a new angular.Module

Source: https://docs.angularjs.org/api/ng/function/angular.module#overview

Example:

angular.module('myApp', []) Is used to create a module without injecting any dependencies.

angular.module('myApp') (Without argument) is used to get an existing module.

Best way to create unique token in Rails?

If you want something that will be unique you can use something like this:

string = (Digest::MD5.hexdigest "#{ActiveSupport::SecureRandom.hex(10)}-#{DateTime.now.to_s}")

however this will generate string of 32 characters.

There is however other way:

require 'base64'

def after_create
update_attributes!(:token => Base64::encode64(id.to_s))
end

for example for id like 10000, generated token would be like "MTAwMDA=" (and you can easily decode it for id, just make

Base64::decode64(string)

Adding placeholder text to textbox

Here I come with this solution inspired by @Kemal Karadag.

I noticed that every solution posted here is relying on the focus,

While I wanted my placeholder to be the exact clone of a standard HTML placeholder in Google Chrome.

Instead of hiding/showing the placeholder when the box is focused,

I hide/show the placeholder depending on the text length of the box:

If the box is empty, the placeholder is shown, and if you type in the box, the placeholder disappears.

As it is inherited from a standard TextBox, you can find it in your Toolbox!

using System;
using System.Drawing;
using System.Windows.Forms;

public class PlaceHolderTextBox : TextBox
{
    private bool isPlaceHolder = true;
    private string placeHolderText;

    public string PlaceHolderText
    {
        get { return placeHolderText; }
        set
        {
            placeHolderText = value;
            SetPlaceholder();
        }
    }

    public PlaceHolderTextBox()
    {
        TextChanged += OnTextChanged;
    }

    private void SetPlaceholder()
    {
        if (!isPlaceHolder)
        {
            this.Text = placeHolderText;
            this.ForeColor = Color.Gray;
            isPlaceHolder = true;
        }
    }

    private void RemovePlaceHolder()
    {
        if (isPlaceHolder)
        {
            this.Text = this.Text[0].ToString(); // Remove placeHolder text, but keep the character we just entered
            this.Select(1, 0); // Place the caret after the character we just entered
            this.ForeColor = System.Drawing.SystemColors.WindowText;
            isPlaceHolder = false;
        }
    }

    private void OnTextChanged(object sender, EventArgs e)
    {
        if (this.Text.Length == 0)
        {
            SetPlaceholder();
        }
        else
        {
            RemovePlaceHolder();
        }
    }
}

What is a good regular expression to match a URL?

I was trying to put together some JavaScript to validate a domain name (ex. google.com) and if it validates enable a submit button. I thought that I would share my code for those who are looking to accomplish something similar. It expects a domain without any http:// or www. value. The script uses a stripped down regular expression from above for domain matching, which isn't strict about fake TLD.

http://jsfiddle.net/nMVDS/1/

$(function () {
  $('#whitelist_add').keyup(function () {
    if ($(this).val() == '') { //Check to see if there is any text entered
        //If there is no text within the input, disable the button
        $('.whitelistCheck').attr('disabled', 'disabled');
    } else {
        // Domain name regular expression
        var regex = new RegExp("^([0-9A-Za-z-\\.@:%_\+~#=]+)+((\\.[a-zA-Z]{2,3})+)(/(.)*)?(\\?(.)*)?");
        if (regex.test($(this).val())) {
            // Domain looks OK
            //alert("Successful match");
            $('.whitelistCheck').removeAttr('disabled');
        } else {
            // Domain is NOT OK
            //alert("No match");
            $('.whitelistCheck').attr('disabled', 'disabled');
        }
    }
  });
});

HTML FORM:

<form action="domain_management.php" method="get">
    <input type="text" name="whitelist_add" id="whitelist_add" placeholder="domain.com">
    <button type="submit" class="btn btn-success whitelistCheck" disabled='disabled'>Add to Whitelist</button>
</form>

How to get database structure in MySQL via query

A variation of the first answer that I found useful

Open your command prompt and enter (you dont have to be logged into your mysql server)

mysqldump -hlocalhost -u<root> -p<password>  <dbname>  --compact --no-data > </path_to_mydump/>mysql.dmp

react-router - pass props to handler component

Use the solution like a below and this works in v3.2.5.

<Route
  path="/foo"
  component={() => (
    <Content
      lang="foo"
      meta={{
        description: lang_foo.description
      }}
    />
  )}
/>

or

<Route path="/foo">
  <Content
    lang="foo"
    meta={{
      description: lang_foo.description
    }}
  />
</Route>

What is the difference between HTTP and REST?

REST is a specific way of approaching the design of big systems (like the web).

It's a set of 'rules' (or 'constraints').

HTTP is a protocol that tries to obey those rules.

How to make sure that a certain Port is not occupied by any other process

It's netstat -ano|findstr port no

Result would show process id in last column

How to delete an object by id with entity framework

The same as @Nix with a small change to be strongly typed:

If you don't want to query for it just create an entity, and then delete it.

                Customer customer = new Customer () { Id = id };
                context.Customers.Attach(customer);
                context.Customers.DeleteObject(customer);
                context.SaveChanges();

How to make an element width: 100% minus padding?

box-sizing: border-box is a quick, easy way to fix it:

This will work in all modern browsers, and IE8+.

Here's a demo: http://jsfiddle.net/thirtydot/QkmSk/301/

.content {
    width: 100%;
    box-sizing: border-box;
}

The browser prefixed versions (-webkit-box-sizing, etc.) are not needed in modern browsers.

Check if string doesn't contain another string

The answers you got assumed static text to compare against. If you want to compare against another column (say, you're joining two tables, and want to find ones where a column from one table is part of a column from another table), you can do this

WHERE NOT (someColumn LIKE '%' || someOtherColumn || '%')

How to get a div to resize its height to fit container?

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<style type="text/css">
#top, #bottom {
    height: 100px;
    width: 100%;
    position: relative;
}
#container {
    overflow: hidden;
    position: relative;
    width: 100%;
}
#container .left {
    height: 550px;
    width: 55%;
    position: relative;
    float: left;
    background-color: #3399FF;
}
#container .right {
    height: 100%;
    position: absolute;
    right: 0;
    left: 55%;
    bottom: 0px;
    top: 0px;
    background-color: #3366CC;
}
</style>
</head>

<body>
<div id="top"></div>
<div id="container">
  <div class="left"></div>
  <div class="right"></div>
</div>
<div id="bottom"></div>
</body>
</html>

How to run the sftp command with a password from Bash script?

You can use sshpass for it. Below are the steps

  1. Install sshpass For Ubuntu - sudo apt-get install sshpass
  2. Add the Remote IP to your known-host file if it is first time For Ubuntu -> ssh user@IP -> enter 'yes'
  3. give a combined command of scp and sshpass for it. Below is a sample code for war coping to remote tomcat sshpass -p '#Password_For_remote_machine' scp /home/ubuntu/latest_build/abc.war #user@#RemoteIP:/var/lib/tomcat7/webapps

mappedBy reference an unknown target entity property

public class User implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id
    @Column(name = "USER_ID")
    Long userId;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "sender", cascade = CascadeType.ALL)
    List<Notification> sender;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "receiver", cascade = CascadeType.ALL)
    List<Notification> receiver;
}

public class Notification implements Serializable {

    private static final long serialVersionUID = 1L;

    @Id

    @Column(name = "NOTIFICATION_ID")
    Long notificationId;

    @Column(name = "TEXT")
    String text;

    @Column(name = "ALERT_STATUS")
    @Enumerated(EnumType.STRING)
    AlertStatus alertStatus = AlertStatus.NEW;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "SENDER_ID")
    @JsonIgnore
    User sender;

    @ManyToOne(fetch = FetchType.LAZY)
    @JoinColumn(name = "RECEIVER_ID")
    @JsonIgnore
    User receiver;
}

What I understood from the answer. mappedy="sender" value should be the same in the notification model. I will give you an example..

User model:

@OneToMany(fetch = FetchType.LAZY, mappedBy = "**sender**", cascade = CascadeType.ALL)
    List<Notification> sender;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "**receiver**", cascade = CascadeType.ALL)
    List<Notification> receiver;

Notification model:

@OneToMany(fetch = FetchType.LAZY, mappedBy = "sender", cascade = CascadeType.ALL)
    List<Notification> **sender**;

    @OneToMany(fetch = FetchType.LAZY, mappedBy = "receiver", cascade = CascadeType.ALL)
    List<Notification> **receiver**;

I gave bold font to user model and notification field. User model mappedBy="sender " should be equal to notification List sender; and mappedBy="receiver" should be equal to notification List receiver; If not, you will get error.

How do I increase the RAM and set up host-only networking in Vagrant?

To increase the memory or CPU count when using Vagrant 2, add this to your Vagrantfile

Vagrant.configure("2") do |config|
    # usual vagrant config here

    config.vm.provider "virtualbox" do |v|
        v.memory = 1024
        v.cpus = 2
    end
end

Delete everything in a MongoDB database

Here are some useful delete operations for mongodb using mongo shell

To delete particular document in collections: db.mycollection.remove( {name:"stack"} )

To delete all documents in collections: db.mycollection.remove()

To delete any particular collection : db.mycollection.drop()

to delete database : first go to that database by use mydb command and then

db.dropDatabase()

React-Native: Module AppRegistry is not a registered callable module

For me just restarting the computer fixed it. (My error was "module appRegistry is not a registered callable module (calling runapplication) js engine: hermes")

Another top answer that is missing here and might have worked was just to kill node processes:

killall -9 node

[ Module AppRegistry is not registered callable module (calling runApplication) ]

How to Add Date Picker To VBA UserForm

You could try the "Microsoft Date and Time Picker Control". To use it, in the Toolbox, you right-click and choose "Additional Controls...". Then you check "Microsoft Date and Time Picker Control 6.0" and OK. You will have a new control in the Toolbox to do what you need.

I just found some printscreen of this on : http://www.logicwurks.com/CodeExamplePages/EDatePickerControl.html Forget the procedures, just check the printscreens.

How to add a classname/id to React-Bootstrap Component?

1st way is to use props

<Row id = "someRandomID">

Wherein, in the Definition, you may just go

const Row = props  => {
 div id = {props.id}
}

The same could be done with class, replacing id with className in the above example.


You might as well use react-html-id, that is an npm package. This is an npm package that allows you to use unique html IDs for components without any dependencies on other libraries.

Ref: react-html-id


Peace.

React prevent event bubbling in nested components on click

React uses event delegation with a single event listener on document for events that bubble, like 'click' in this example, which means stopping propagation is not possible; the real event has already propagated by the time you interact with it in React. stopPropagation on React's synthetic event is possible because React handles propagation of synthetic events internally.

stopPropagation: function(e){
    e.stopPropagation();
    e.nativeEvent.stopImmediatePropagation();
}

Printing Java Collections Nicely (toString Doesn't Return Pretty Output)

With java 8 streams and collectors it can be done easily:

String format(Collection<?> c) {
  String s = c.stream().map(Object::toString).collect(Collectors.joining(","));
  return String.format("[%s]", s);
}

first we use map with Object::toString to create Collection<String> and then use joining collector to join every item in collection with , as delimiter.

disable all form elements inside div

$('#mydiv').find('input, textarea, button, select').attr('disabled','disabled');

Ruby class instance variable vs. class variable

While it may immediately seem useful to utilize class instance variables, since class instance variable are shared among subclasses and they can be referred to within both singleton and instance methods, there is a singificant drawback. They are shared and so subclasses can change the value of the class instance variable, and the base class will also be affected by the change, which is usually undesirable behavior:

class C
  @@c = 'c'
  def self.c_val
    @@c
  end
end

C.c_val
 => "c" 

class D < C
end

D.instance_eval do 
  def change_c_val
    @@c = 'd'
  end
end
 => :change_c_val 

D.change_c_val
(irb):12: warning: class variable access from toplevel
 => "d" 

C.c_val
 => "d" 

Rails introduces a handy method called class_attribute. As the name implies, it declares a class-level attribute whose value is inheritable by subclasses. The class_attribute value can be accessed in both singleton and instance methods, as is the case with the class instance variable. However, the huge benefit with class_attribute in Rails is subclasses can change their own value and it will not impact parent class.

class C
  class_attribute :c
  self.c = 'c'
end

 C.c
 => "c" 

class D < C
end

D.c = 'd'
 => "d" 

 C.c
 => "c" 

How to create a Calendar table for 100 years in Sql

This SQL Server User Defined Function resolves the problem efficiently.No recursion, no complex loops. It takes a very short time to generate.

ALTER FUNCTION [GA].[udf_GenerateCalendar]
(
     @StartDate  DATE        -- StartDate
   , @EndDate    DATE        -- EndDate
)
RETURNS @Results TABLE 
       (
           Date       DATE 
       )
AS

/**********************************************************
Purpose:   Generate a sequence of dates based on StartDate and EndDate 
***********************************************************/

BEGIN

    DECLARE @counter INTEGER = 1 

    DECLARE @days table(
        day INTEGER NOT NULL 
    )

    DECLARE @months table(
        month INTEGER NOT NULL 
    )

    DECLARE @years table(
        year INTEGER NOT NULL 
    )

    DECLARE @calendar table(
        Date DATE NOT NULL 
    )


    -- Populate generic days 
    SET @counter = 1 
    WHILE @counter <= 31 
    BEGIN 
        INSERT INTO @days 
        SELECT @counter dia 

        SELECT @counter = @counter + 1 
    END 

    -- Populate generic months 
    SET @counter = 1 
    WHILE @counter <= 12 
    BEGIN 
        INSERT INTO @months 
        SELECT @counter month 

        SELECT @counter = @counter + 1 
    END 

    -- Populate generic years 
    SET @counter = YEAR(@StartDate) 
    WHILE @counter <= YEAR(@EndDate) 
    BEGIN 
        INSERT INTO @years 
        SELECT @counter year 

        SELECT @counter = @counter + 1 
    END 

    INSERT @calendar (Date) 
    SELECT Date 
    FROM ( 
        SELECT 
            CONVERT(Date, [Date], 102) AS Date 
        FROM ( 
            SELECT 
                CAST(
                    y.year * 10000 
                    + m.month * 100 
                    + d.day 
                    AS VARCHAR(8)) AS Date 
            FROM @days d, @months m, @years y 
            WHERE 
                ISDATE(CAST(
                    y.year * 10000 
                    + m.month * 100 
                    + d.day 
                    AS VARCHAR(8)) 
                    ) = 1 
        ) A 
    ) A 

    INSERT @Results (Date) 
    SELECT Date 
    FROM @calendar 
    WHERE Date BETWEEN @StartDate AND @EndDate

   RETURN 
/*
DECLARE @StartDate DATE = '2015-08-01'
DECLARE @EndDate   DATE = '2015-08-31'
select * from [GA].[udf_GenerateCalendar](@StartDate, @EndDate)
*/
END

How to check whether a string contains a substring in JavaScript?

Another alternative is KMP (Knuth–Morris–Pratt).

The KMP algorithm searches for a length-m substring in a length-n string in worst-case O(n+m) time, compared to a worst-case of O(n·m) for the naive algorithm, so using KMP may be reasonable if you care about worst-case time complexity.

Here's a JavaScript implementation by Project Nayuki, taken from https://www.nayuki.io/res/knuth-morris-pratt-string-matching/kmp-string-matcher.js:

// Searches for the given pattern string in the given text string using the Knuth-Morris-Pratt string matching algorithm.
// If the pattern is found, this returns the index of the start of the earliest match in 'text'. Otherwise -1 is returned.

_x000D_
_x000D_
function kmpSearch(pattern, text) {_x000D_
  if (pattern.length == 0)_x000D_
    return 0; // Immediate match_x000D_
_x000D_
  // Compute longest suffix-prefix table_x000D_
  var lsp = [0]; // Base case_x000D_
  for (var i = 1; i < pattern.length; i++) {_x000D_
    var j = lsp[i - 1]; // Start by assuming we're extending the previous LSP_x000D_
    while (j > 0 && pattern.charAt(i) != pattern.charAt(j))_x000D_
      j = lsp[j - 1];_x000D_
    if (pattern.charAt(i) == pattern.charAt(j))_x000D_
      j++;_x000D_
    lsp.push(j);_x000D_
  }_x000D_
_x000D_
  // Walk through text string_x000D_
  var j = 0; // Number of chars matched in pattern_x000D_
  for (var i = 0; i < text.length; i++) {_x000D_
    while (j > 0 && text.charAt(i) != pattern.charAt(j))_x000D_
      j = lsp[j - 1]; // Fall back in the pattern_x000D_
    if (text.charAt(i) == pattern.charAt(j)) {_x000D_
      j++; // Next char matched, increment position_x000D_
      if (j == pattern.length)_x000D_
        return i - (j - 1);_x000D_
    }_x000D_
  }_x000D_
  return -1; // Not found_x000D_
}_x000D_
_x000D_
console.log(kmpSearch('ays', 'haystack') != -1) // true_x000D_
console.log(kmpSearch('asdf', 'haystack') != -1) // false
_x000D_
_x000D_
_x000D_

Better way to sort array in descending order

class Program
{
    private static int[] table;

    static void Main(string[] args)
    {
        int[] ints = new int[] { 6, 2, 5, 99, 55 };

       table = ints.OrderByDescending(x => x).ToArray();

        foreach (var item in table)
        {
            Console.WriteLine(item);
        }

    }

Python IndentationError unindent does not match any outer indentation level

You are mixing tabs and spaces. Don't do that. Specifically, the __init__ function body is indented with tabs while your on_data method is not.

Here is a screenshot of your code in my text editor; I set the tab stop to 8 spaces (which is what Python uses) and selected the text, which causes the editor to display tabs with continuous horizontal lines:

highlighted code with tabs shown as lines

You have your editor set to expanding tabs to every fourth column instead, so the methods appear to line up.

Run your code with:

python -tt scriptname.py

and fix all errors that finds. Then configure your editor to use spaces only for indentation; a good editor will insert 4 spaces every time you use the TAB key.

db.collection is not a function when using MongoClient v3.0

For those that want to continue using version ^3.0.1 be aware of the changes to how you use the MongoClient.connect() method. The callback doesn't return db instead it returns client, against which there is a function called db(dbname) that you must invoke to get the db instance you are looking for.

const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

// Connection URL
const url = 'mongodb://localhost:27017';

// Database Name
const dbName = 'myproject';

// Use connect method to connect to the server
MongoClient.connect(url, function(err, client) {
  assert.equal(null, err);
  console.log("Connected successfully to server");

  const db = client.db(dbName);

  client.close();
});

NumPy array is not JSON serializable

May do simple for loop with checking types:

with open("jsondontdoit.json", 'w') as fp:
    for key in bests.keys():
        if type(bests[key]) == np.ndarray:
            bests[key] = bests[key].tolist()
            continue
        for idx in bests[key]:
            if type(bests[key][idx]) == np.ndarray:
                bests[key][idx] = bests[key][idx].tolist()
    json.dump(bests, fp)
    fp.close()

sqlite3.OperationalError: unable to open database file

In my case the sqlite db file db.sqlite3 was stored in the DocumentRoot of apache. So, even after setting the following permissions it didn't work:

sudo chown www-data:www-data /path/to/db-folder
sudo chown www-data:www-data /path/to/db-folder/sqlite-db.db

Finally when i moved db.sqlite3 to a newly created folder dbfolder under DocumentRoot and gave the above permissions, and it worked.

Can't perform a React state update on an unmounted component

I know that you're not using history, but in my case I was using the useHistory hook from React Router DOM, which unmounts the component before the state is persisted in my React Context Provider.

To fix this problem I have used the hook withRouter nesting the component, in my case export default withRouter(Login), and inside the component const Login = props => { ...; props.history.push("/dashboard"); .... I have also removed the other props.history.push from the component, e.g, if(authorization.token) return props.history.push('/dashboard') because this causes a loop, because the authorization state.

An alternative to push a new item to history.

Why is Ant giving me a Unsupported major.minor version error

The runtime jre was set to jre 6 instead of jre 7 in the build configuration window.

Android Studio Google JAR file causing GC overhead limit exceeded error

I think there's a separate way to raise the heap limit of the dexing operation. Add this to your android closure in your build.gradle file:

dexOptions {
    javaMaxHeapSize "4g"
}

and see if that helps.

(idea courtesy of this answer from Scott Barta)

How to get scrollbar position with Javascript?

I think the following function can help to have scroll coordinate values:

const getScrollCoordinate = (el = window) => ({
  x: el.pageXOffset || el.scrollLeft,
  y: el.pageYOffset || el.scrollTop,
});

I got this idea from this answer with a little change.

Plotting multiple time series on the same plot using ggplot()

I prefer using the ggfortify library. It is a ggplot2 wrapper that recognizes the type of object inside the autoplot function and chooses the best ggplot methods to plot. At least I don't have to remember the syntax of ggplot2.

library(ggfortify)
ts1 <- 1:100
ts2 <- 1:100*0.8
autoplot(ts( cbind(ts1, ts2)  , start = c(2010,5), frequency = 12 ),
         facets = FALSE)

Plot

CSS overflow-x: visible; and overflow-y: hidden; causing scrollbar issue

After some serious searching it seems i've found the answer to my question:

from: http://www.brunildo.org/test/Overflowxy2.html

In Gecko, Safari, Opera, ‘visible’ becomes ‘auto’ also when combined with ‘hidden’ (in other words: ‘visible’ becomes ‘auto’ when combined with anything else different from ‘visible’). Gecko 1.8, Safari 3, Opera 9.5 are pretty consistent among them.

also the W3C spec says:

The computed values of ‘overflow-x’ and ‘overflow-y’ are the same as their specified values, except that some combinations with ‘visible’ are not possible: if one is specified as ‘visible’ and the other is ‘scroll’ or ‘auto’, then ‘visible’ is set to ‘auto’. The computed value of ‘overflow’ is equal to the computed value of ‘overflow-x’ if ‘overflow-y’ is the same; otherwise it is the pair of computed values of ‘overflow-x’ and ‘overflow-y’.

Short Version:

If you are using visible for either overflow-x or overflow-y and something other than visible for the other, the visible value is interpreted as auto.

How do I measure request and response times at once using cURL?

Option 1. To measure total time:

curl -o /dev/null -s -w 'Total: %{time_total}s\n'  https://www.google.com

Sample output:

enter image description here

Option 2. To get time to establish connection, TTFB: time to first byte and total time:

curl -o /dev/null -s -w 'Establish Connection: %{time_connect}s\nTTFB: %{time_starttransfer}s\nTotal: %{time_total}s\n'  https://www.google.com

Sample output:

enter image description here

Ref: Get response time with curl

Adding header for HttpURLConnection

If you are using Java 8, use the code below.

URLConnection connection = url.openConnection();
HttpURLConnection httpConn = (HttpURLConnection) connection;

String basicAuth = Base64.getEncoder().encodeToString((username+":"+password).getBytes(StandardCharsets.UTF_8));
httpConn.setRequestProperty ("Authorization", "Basic "+basicAuth);

Uncaught SyntaxError: Unexpected token with JSON.parse

It seems you want to stringify the object. So do this:

JSON.stringify(products);

The reason for the error is that JSON.parse() expects a String value and products is an Array.

Note: I think it attempts json.parse('[object Array]') which complains it didn't expect token o after [.

JAVA_HOME does not point to the JDK

I just copied tools.jar file from JDK\lib folder to JRE\lib folder. Since then it worked like a champ.

How can I add a line to a file in a shell script?

Use perl -i, with a command that replaces the beginning of line 1 with what you want to insert (the .bk will have the effect that your original file is backed up):

perl -i.bk -pe 's/^/column1, column2, column3\n/ if($.==1)' testfile.csv  

Submit form with Enter key without submit button?

$("input").keypress(function(event) {
    if (event.which == 13) {
        event.preventDefault();
        $("form").submit();
    }
});

Resizing image in Java

            int newHeight = 150;
            int newWidth = 150; 
            holder.iv_arrow.requestLayout();
            holder.iv_arrow.getLayoutParams().height = newHeight;
            holder.iv_arrow.getLayoutParams().width = newWidth;
            holder.iv_arrow.setScaleType(ImageView.ScaleType.FIT_XY);
            holder.iv_arrow.setImageResource(R.drawable.video_menu);

Could not read JSON: Can not deserialize instance of hello.Country[] out of START_OBJECT token

If you want to avoid using an extra Class and List<Object> genomes you could simply use a Map.

The data structure translates into Map<String, List<Country>>

String resourceEndpoint = "http://api.geonames.org/countryInfoJSON?username=volodiaL";

Map<String, List<Country>> geonames = restTemplate.getForObject(resourceEndpoint, Map.class);

List<Country> countries = geonames.get("geonames");

Counting the number of option tags in a select tag in jQuery

Your question is a little confusing, but assuming you want to display the number of options in a panel:

<div id="preview"></div>

and

$(function() {
  $("#preview").text($("#input1 option").length + " items");
});

Not sure I understand the rest of your question.

Has an event handler already been added?

i agree with alf's answer,but little modification to it is,, to use,

           try
            {
                control_name.Click -= event_Click;
                main_browser.Document.Click += Document_Click;
            }
            catch(Exception exce)
            {
                main_browser.Document.Click += Document_Click;
            }

localhost refused to connect Error in visual studio

Project properties> Web > Create Virtual Directory worked for me

What is a mixin, and why are they useful?

I think previous responses defined very well what MixIns are. However, in order to better understand them, it might be useful to compare MixIns with Abstract Classes and Interfaces from the code/implementation perspective:

1. Abstract Class

  • Class that needs to contain one or more abstract methods

  • Abstract Class can contain state (instance variables) and non-abstract methods

2. Interface

  • Interface contains abstract methods only (no non-abstract methods and no internal state)

3. MixIns

  • MixIns (like Interfaces) do not contain internal state (instance variables)
  • MixIns contain one or more non-abstract methods (they can contain non-abstract methods unlike interfaces)

In e.g. Python these are just conventions, because all of the above are defined as classes. However, the common feature of both Abstract Classes, Interfaces and MixIns is that they should not exist on their own, i.e. should not be instantiated.

Nth word in a string variable

No expensive forks, no pipes, no bashisms:

$ set -- $STRING
$ eval echo \${$N}
three

But beware of globbing.

How can I copy a file from a remote server to using Putty in Windows?

One of the putty tools is pscp.exe; it will allow you to copy files from your remote host.

How to copy a directory structure but only include certain files (using windows batch files)

You don't mention if it has to be batch only, but if you can use ROBOCOPY, try this:

ROBOCOPY C:\Source C:\Destination data.zip info.txt /E

EDIT: Changed the /S parameter to /E to include empty folders.

How to test code dependent on environment variables using JUnit?

For JUnit 4 users, System Lambda as suggested by Stefan Birkner is a great fit.

In case you are using JUnit 5, there is the JUnit Pioneer extension pack. It comes with @ClearEnvironmentVariable and @SetEnvironmentVariable. From the docs:

The @ClearEnvironmentVariable and @SetEnvironmentVariable annotations can be used to clear, respectively, set the values of environment variables for a test execution. Both annotations work on the test method and class level, are repeatable as well as combinable. After the annotated method has been executed, the variables mentioned in the annotation will be restored to their original value or will be cleared if they didn't have one before. Other environment variables that are changed during the test, are not restored.

Example:

@Test
@ClearEnvironmentVariable(key = "SOME_VARIABLE")
@SetEnvironmentVariable(key = "ANOTHER_VARIABLE", value = "new value")
void test() {
    assertNull(System.getenv("SOME_VARIABLE"));
    assertEquals("new value", System.getenv("ANOTHER_VARIABLE"));
}

Replace words in a string - Ruby

sentence.sub! 'Robert', 'Joe'

Won't cause an exception if the replaced word isn't in the sentence (the []= variant will).

How to replace all instances?

The above replaces only the first instance of "Robert".

To replace all instances use gsub/gsub! (ie. "global substitution"):

sentence.gsub! 'Robert', 'Joe'

The above will replace all instances of Robert with Joe.

Write output to a text file in PowerShell

The simplest way is to just redirect the output, like so:

Compare-Object $(Get-Content c:\user\documents\List1.txt) $(Get-Content c:\user\documents\List2.txt) > c:\user\documents\diff_output.txt

> will cause the output file to be overwritten if it already exists.
>> will append new text to the end of the output file if it already exists.

How to use gitignore command in git

git ignore is a convention in git. Setting a file by the name of .gitignore will ignore the files in that directory and deeper directories that match the patterns that the file contains. The most common use is just to have one file like this at the top level. But you can add others deeper in your directory structure to ignore even more patterns or stop ignoring them for that directory and subsequently deeper ones.

Likewise, you can "unignore" certain files in a deeper structure or a specific subset (ie, you ignore *.log but want to still track important.log) by specifying patterns beginning with !. eg:

*.log !important.log

will ignore all log files but will track files named important.log

If you are tracking files you meant to ignore, delete them, add the pattern to you .gitignore file and add all the changes

# delete files that should be ignored, or untrack them with 
# git rm --cached <file list or pattern>

# stage all the changes git commit
git add -A 

from now on your repository will not have them tracked.

If you would like to clean up your history, you can

# if you want to correct the last 10 commits
git rebase -i --preserve-merges HEAD~10 

then mark each commit with e or edit. Save the plan. Now git will replay your history stopping at each commit you marked with e. Here you delete the files you don't want, git add -A and then git rebase --continue until you are done. Your history will be clean. Make sure you tell you coworkers as you will have to force push and they will have to rebase what they didn't push yet.

Linq Query Group By and Selecting First Items

var result = list.GroupBy(x => x.Category).Select(x => x.First())

How to show a confirm message before delete?

Using jQuery:

$(".delete-link").on("click", null, function(){
        return confirm("Are you sure?");
    });

DataTables fixed headers misaligned with columns in wide tables

Faced the same issue recently and was still searching for the solution when I tried something on my css, check if adding to your cells (th and td)

-webkit-box-sizing: content-box; 
-moz-box-sizing: content-box;  
-sizing: content-box;

will resolve this issue; for me, I was using some html/css framework that was adding a the value border-box in every element.

How to recover a dropped stash in Git?

If you didn't close the terminal, just look at the output from git stash pop and you'll have the object ID of the dropped stash. It normally looks like this:

$ git stash pop
[...]
Dropped refs/stash@{0} (2ca03e22256be97f9e40f08e6d6773c7d41dbfd1)

(Note that git stash drop also produces the same line.)

To get that stash back, just run git branch tmp 2cae03e, and you'll get it as a branch. To convert this to a stash, run:

git stash apply tmp
git stash

Having it as a branch also allows you to manipulate it freely; for example, to cherry-pick it or merge it.

Can not find module “@angular-devkit/build-angular”

Install @angular-devkit/build-angular as dev dependency. This package is newly introduced in Angular 6.0

npm install --save-dev @angular-devkit/build-angular

or,

yarn add @angular-devkit/build-angular --dev

row-level trigger vs statement-level trigger

if you want to execute the statement when number of rows are modified then it can be possible by statement level triggers.. viseversa... when you want to execute your statement each modification on your number of rows then you need to go for row level triggers..

for example: statement level triggers works for when table is modified..then more number of records are effected. and row level triggers works for when each row updation or modification..

PostgreSQL: insert from another table

Just supply literal values in the SELECT:

INSERT INTO TABLE1 (id, col_1, col_2, col_3)
SELECT id, 'data1', 'data2', 'data3'
FROM TABLE2
WHERE col_a = 'something';

A select list can contain any value expression:

But the expressions in the select list do not have to reference any columns in the table expression of the FROM clause; they can be constant arithmetic expressions, for instance.

And a string literal is certainly a value expression.

package javax.mail and javax.mail.internet do not exist

I just resolved this for myself, so hope this helps. My project runs on GlassFish 4, Eclipse MARS, with JDK 1.8 and JavaEE 7.

Firstly, you can find javax.mail.jar in the extracted glassfish folder: glassfish4->glassfish->modules

Next, in Eclipse, Right Click on your project in the explorer and navigate the following: Properties->Java Build Path->Libraries->Add External JARs-> Go to the aforementioned folder to add javax.mail.jar

Select from where field not equal to Mysql Php

You can use also

select * from tablename where column1 ='a' and column2!='b';

            

HTTP 400 (bad request) for logical error, not malformed request syntax

On Java EE servers a 400 is returned if your URL refers to a non-existent "web -application". Is that a "syntax error"? Depends on what you mean by syntax error. I would say yes.

In English syntax rules prescribe certain relationships between parts of speech. For instance "Bob marries Mary" is syntactically correct, because it follows the pattern {Noun + Verb + Noun}. Whereas "Bob marriage Mary" would be syntactically incorrect, {Noun + Noun + Noun}.

The syntax of a simple URLis { protocol + : + // + server + : + port }. According to this "http://www.google.com:80" is syntactically correct.

But what about "abc://www.google.com:80"? It seems to follow the exact same pattern. But really it is a syntax error. Why? Because 'abc' is not a DEFINED protocol.

The point is that determining whether or not we have a 400 situation requires more than parsing the characters and spaces and delimiters. It must also recognize what are the valid "parts of speech".

Turn a number into star rating display using jQuery and CSS

using jquery without prototype, update the js code to

$( ".stars" ).each(function() { 
    // Get the value
    var val = $(this).data("rating");
    // Make sure that the value is in 0 - 5 range, multiply to get width
    var size = Math.max(0, (Math.min(5, val))) * 16;
    // Create stars holder
    var $span = $('<span />').width(size);
    // Replace the numerical value with stars
    $(this).html($span);
});

I also added a data attribute by the name of data-rating in the span.

<span class="stars" data-rating="4" ></span>

Synchronizing a local Git repository with a remote one

(This info is from The Git User's Manual)

I'm also learning, so this might not be exactly an answer to the question but it might help somebody:

  1. When a remote repository is initially cloned copies of all branches are stored in your local repository (view them with git branch -r)
  2. To update these copies and make them current (i.e. sync them with the remote branch) use git fetch. This will not effect any of you existing, custom created branches.
  3. To override your local branch checkout a fresh version of whatever branch you are working on (Assuming that you have already executed git add origin /path/to/repository) use git checkout origin/branch_name, this will override your locals changes on branch branch_name

How to convert URL parameters to a JavaScript object?

One of the simplest way to do this using URLSearchParam interface.

Below is the working code snippet:

let paramObj={},
    querystring=window.location.search,
    searchParams = new URLSearchParams(querystring);    

  //*** :loop to add key and values to the param object.
 searchParams.forEach(function(value, key) {
      paramObj[key] = value;
   });

How can I group by date time column without taking time into consideration

Here is the example works fine in oracle

select to_char(columnname, 'DD/MON/yyyy'), count(*) from table_name group by to_char(createddate, 'DD/MON/yyyy');

How to put an image in div with CSS?

This answer by Jaap :

<div class="image"></div>?

and in CSS :

div.image {
   content:url(http://placehold.it/350x150);
}?

you can try it on this link : http://jsfiddle.net/XAh2d/

this is a link about css content http://css-tricks.com/css-content/

This has been tested on Chrome, firefox and Safari. (I'm on a mac, so if someone has the result on IE, tell me to add it)

Recreate the default website in IIS

Check out this answer on SuperUser:

In short: Reinstall both IIS and WAS.

In details -

Step 1

Go to "Add remove programs" "Turn windows features on or off" Remove both IIS and WAS (Windows Process Activation Service) Restart the PC Step 2

Go to "Add remove programs" "Turn windows features on or off" Turn on both IIS and WAS (Windows Process Activation Service) Note: Reinstalling IIS alone won't help. You have to reinstall both IIS and WAS

This approach fixed the problem for me.

TSQL DATETIME ISO 8601

When dealing with dates in SQL Server, the ISO-8601 format is probably the best way to go, since it just works regardless of your language and culture settings.

In order to INSERT data into a SQL Server table, you don't need any conversion codes or anything at all - just specify your dates as literal strings

INSERT INTO MyTable(DateColumn) VALUES('20090430 12:34:56.790')

and you're done.

If you need to convert a date column to ISO-8601 format on SELECT, you can use conversion code 126 or 127 (with timezone information) to achieve the ISO format.

SELECT CONVERT(VARCHAR(33), DateColumn, 126) FROM MyTable

should give you:

2009-04-30T12:34:56.790

Application_Start not firing?

Had the same problem in a Project we had taken over after another vendor built it. The problem was that while there were a number of commands written by the previous vendor in Global.asax.cs, which might lead you to believe it was in use, it was actually being ignored entirely. Global.asax wasn't inheriting from it, and it's easy to never see this file if the .cs file is present - you have to right-click Global.asax and click View Markup to actually see it.

Global.asax:

<%@ Application Language="C#" %>

Needed to be changed to:

<%@ Application Codebehind="Global.asax.cs" Inherits="ProjectNamespace.MvcApplication" Language="C#" %>

Where ProjectNamespace is whatever the namespace is of your Global.asax.cs class (usually the name of your Project).

In our case the file contained a bunch of inline code, some of which was copy-pasted from the .cs file, some not. We just dumped the inline code over to the .cs file and gradually merged our changes back in.

How to find out when an Oracle table was updated the last time

Could you run a checksum of some sort on the result and store that locally? Then when your application queries the database, you can compare its checksum and determine if you should import it?

It looks like you may be able to use the ORA_HASH function to accomplish this.

Update: Another good resource: 10g’s ORA_HASH function to determine if two Oracle tables’ data are equal

How to run a class from Jar which is not the Main-Class in its Manifest file

First of all jar creates a jar, and does not run it. Try java -jar instead.

Second, why do you pass the class twice, as FQCN (com.mycomp.myproj.dir2.MainClass2) and as file (com/mycomp/myproj/dir2/MainClass2.class)?

Edit:

It seems as if java -jar requires a main class to be specified. You could try java -cp your.jar com.mycomp.myproj.dir2.MainClass2 ... instead. -cp sets the jar on the classpath and enables java to look up the main class there.

make html text input field grow as I type?

I know this is a seriously old post - but my answer might be useful to others anyway, so here goes. I found that if my CSS style definition for the contenteditable div has a min-height of 200 instead of a height of 200 , then the div scales automatically.

Using BufferedReader to read Text File

Maybe you mean this:

public class Reader {

public static void main(String[]args) throws IOException{

    FileReader in = new FileReader("C:/test.txt");
    BufferedReader br = new BufferedReader(in);
    String line = br.readLine();
    while (line!=null) {
        System.out.println(line);
        line = br.readLine();
    }
    in.close();

}

Table with fixed header and fixed column on pure css

After two days fighting with Internet Explorer 9 + Chrome + Firefox (Windows) and Safari (Mac), I have found a system that is

  • Compatible with all these browsers
  • Without using javascript
  • Using only une div and one table
  • Fixed header and footer (Except for IE), with scrollable body. Header and body with same column widths

Result: enter image description here

HTML:

  <thead>
    <tr>
      <th class="nombre"><%= f.label :cost_center %></th>
      <th class="cabecera cc">Personal</th>
      <th class="cabecera cc">Dpto</th>
    </tr>
  </thead>
  <tbody>
    <% @cost_centers.each do |cc| %>
    <tr>
      <td class="nombre"><%= cc.nombre_corto %></td>
      <td class="cc"><%= cc.cacentrocoste %></td>
      <td class="cc"><%= cc.cacentrocoste_dpto %></td>
    </tr>
    <% end %>
  </tbody>
  <tfoot>
    <tr>
      <td colspan="3"><a href="#">Mostrar mas usuarios</a></td>
    </tr>
  </tfoot>
</table>

CSS:

div.cost_center{
  width:320px;
  font-size:75%;
  margin-left:5px;
  margin-top:5px;
  margin-bottom: 2px;
  float: right;
  display: inline-block;
  overflow-y: auto;
  overflow-x: hidden;
  max-height:300px;  
}

div.cost_center label { 
  float:none;
  font-size:14px;
}

div.cost_center table{
  width:300px;
  border-collapse: collapse; 
  float:right;
  table-layout:fixed;
}

div.cost_center table tr{
  height:16px;
}
div.cost_center th{
  font-weight:normal;
}

div.cost_center table tbody{
  display: block;
  overflow: auto;
  max-height:240px;
}

div.cost_center table thead{
  display:block;
}

div.cost_center table tfoot{
  display:block;
}
div.cost_center table tfoot td{
  width:280px;
}
div.cost_center .cc{
  width:60px;
  text-align: center; 
  border: 1px solid #999;
}

div.cost_center .nombre{
  width:150px;
}
div.cost_center tbody .nombre{
  border: 1px solid #999;
}

div.cost_center table tfoot td{
 text-align:center;  
 border: 1px solid #999; 
} 

div.cost_center table th, 
div.cost_center table td { 
  padding: 2px;
  vertical-align: middle; 
}

div.cost_center table tbody td {
  white-space: normal;
  font:  .8em/1.4em Verdana, sans-serif;
  color: #000;
  background-color: white;
}
div.cost_center table th.cabecera { 
  font:  0.8em/1.4em Verdana, sans-serif;
  color: #000;
  background-color: #FFEAB5;
}

using href links inside <option> tag

<select name="forma" onchange="location = this.value;">
 <option value="Home.php">Home</option>
 <option value="Contact.php">Contact</option>
 <option value="Sitemap.php">Sitemap</option>
</select>

UPDATE (Nov 2015): In this day and age if you want to have a drop menu there are plenty of arguably better ways to implement one. This answer is a direct answer to a direct question, but I don't advocate this method for public facing web sites.

UPDATE (May 2020): Someone asked in the comments why I wouldn't advocate this solution. I guess it's a question of semantics. I'd rather my users navigate using <a> and kept <select> for making form selections because HTML elements have semantic meeting and they have a purpose, anchors take you places, <select> are for picking things from lists.

Consider, if you are viewing a page with a non-traditional browser (a non graphical browser or screen reader or the page is accessed programmatically, or JavaScript is disabled) what then is the "meaning" or the "intent" of this <select> you have used for navigation? It is saying "please pick a page name" and not a lot else, certainly nothing about navigating. The easy response to this is well i know that my users will be using IE or whatever so shrug but this kinda misses the point of semantic importance.

Whereas a funky drop-down UI element made of suitable layout elements (and some js) containing some regular anchors still retains it intent even if the layout element is lost, "these are a bunch of links, select one and we will navigate there".

Here is an article on the misuse and abuse of <select>.

How to make an input type=button act like a hyperlink and redirect using a get request?

    <script type="text/javascript">
<!-- 
function newPage(num) {
var url=new Array();
url[0]="http://www.htmlforums.com";
url[1]="http://www.codingforums.com.";
url[2]="http://www.w3schools.com";
url[3]="http://www.webmasterworld.com";
window.location=url[num];``
}
// -->
</script>
</head>
<body>
<form action="#">
<div id="container">
<input class="butts" type="button" value="htmlforums" onclick="newPage(0)"/>
<input class="butts" type="button" value="codingforums" onclick="newPage(1)"/>
<input class="butts" type="button" value="w3schools" onclick="newPage(2)"/>
<input class="butts" type="button" value="webmasterworld" onclick="newPage(3)"/>
</div>
</form>
</body>

Here's the other way, it's simpler than the other one.

<input id="inp" type="button" value="Home Page" onclick="location.href='AdminPage.jsp';" />

It's simpler.

How can I find all *.js file in directory recursively in Linux?

find /abs/path/ -name '*.js'

Edit: As Brian points out, add -type f if you want only plain files, and not directories, links, etc.

PHP foreach change original array values

Use &:

foreach($arr as &$value) {
    $value = $newVal;
}

& passes a value of the array as a reference and does not create a new instance of the variable. Thus if you change the reference the original value will change.

PHP documentation for Passing by Reference

Edit 2018

This answer seems to be favored by a lot of people on the internet, which is why I decided to add more information and words of caution.
While pass by reference in foreach (or functions) is a clean and short solution, for many beginners this might be a dangerous pitfall.

  1. Loops in PHP don't have their own scope. - @Mark Amery

    This could be a serious problem when the variables are being reused in the same scope. Another SO question nicely illustrates why that might be a problem.

  2. As foreach relies on the internal array pointer in PHP 5, changing it within the loop may lead to unexpected behavior. - PHP docs for foreach.

    Unsetting a record or changing the hash value (the key) during the iteration on the same loop could lead to potentially unexpected behaviors in PHP < 7. The issue gets even more complicated when the array itself is a reference.

  3. Foreach performance.
    In general, PHP prefers pass by value due to the copy-on-write feature. It means that internally PHP will not create duplicate data unless the copy of it needs to be changed. It is debatable whether pass by reference in foreach would offer a performance improvement. As it is always the case, you need to test your specific scenario and determine which option uses less memory and CPU time. For more information see the SO post linked below by NikiC.

  4. Code readability.
    Creating references in PHP is something that quickly gets out of hand. If you are a novice and don't have full control of what you are doing, it is best to stay away from references. For more information about & operator take a look at this guide: Reference — What does this symbol mean in PHP?
    For those who want to learn more about this part of PHP language: PHP References Explained

A very nice technical explanation by @NikiC of the internal logic of PHP foreach loops:
How does PHP 'foreach' actually work?

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

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

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

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

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

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

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

How to use EditText onTextChanged event when I press the number?

To change the text;

multipleLine.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            MainActivity.myArray.set(pickId,String.valueOf(s));
            MainActivity.myAdapt.notifyDataSetChanged();
        }

        @Override
        public void afterTextChanged(Editable s) {

        }

Add carriage return to a string

string s2 = s1.Replace(",", "," + Environment.NewLine);

Also, just from a performance perspective, here's how the three current solutions I've seen stack up over 100k iterations:

ReplaceWithConstant           - Ms: 328, Ticks: 810908
ReplaceWithEnvironmentNewLine - Ms: 310, Ticks: 766955 
SplitJoin                     - Ms: 483, Ticks: 1192545

ReplaceWithConstant:

string s2 = s1.Replace(",", ",\n");

ReplaceWithEnvironmentNewLine:

string s2 = s1.Replace(",", "," + Environment.NewLine);

SplitJoin:

string s2 = String.Join("," + Environment.NewLine, s1.Split(','));

ReplaceWithEnvironmentNewLine and ReplaceWithConstant are within the margin of error of each other, so there's functionally no difference.

Using Environment.NewLine should be preferred over "\n" for the sake readability and consistency similar to using String.Empty instead of "".

Add column in dataframe from list

Old question; but I always try to use fastest code!

I had a huge list with 69 millions of uint64. np.array() was fastest for me.

df['hashes'] = hashes
Time spent: 17.034842014312744

df['hashes'] = pd.Series(hashes).values
Time spent: 17.141014337539673

df['key'] = np.array(hashes)
Time spent: 10.724546194076538

How to add a Hint in spinner in XML

make your hint at final position in your string array like this City is the hint here

array_city = new String[]{"Irbed", "Amman", "City"};

and then in your array adapter

ArrayAdapter<String> adapter_city = new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_item, array_city) {
            @Override
            public int getCount() {
                // to show hint "Select Gender" and don't able to select
                return array_city.length-1;
            }
        };

so the adapter return just first two item and finally in onCreate() method or what ,,, make Spinner select the hint

yourSpinner.setSelection(array_city.length - 1);

VMWare Player vs VMWare Workstation

re: VMware Workstation support for physical disks vs virtual disks.

I run Player with the VM Disk files on their own dedicated fast hard drive, independent from the OS hard drive. This allows both the OS and Player to simultaneously independently read/write to their own drives, the performance difference is noticeable, and a second WD Black or Raptor or SSD is cheap. Placing the VM disk file on a second drive also works with Microsoft Virtual PC.

What's a concise way to check that environment variables are set in a Unix shell script?

Parameter Expansion

The obvious answer is to use one of the special forms of parameter expansion:

: ${STATE?"Need to set STATE"}
: ${DEST:?"Need to set DEST non-empty"}

Or, better (see section on 'Position of double quotes' below):

: "${STATE?Need to set STATE}"
: "${DEST:?Need to set DEST non-empty}"

The first variant (using just ?) requires STATE to be set, but STATE="" (an empty string) is OK — not exactly what you want, but the alternative and older notation.

The second variant (using :?) requires DEST to be set and non-empty.

If you supply no message, the shell provides a default message.

The ${var?} construct is portable back to Version 7 UNIX and the Bourne Shell (1978 or thereabouts). The ${var:?} construct is slightly more recent: I think it was in System III UNIX circa 1981, but it may have been in PWB UNIX before that. It is therefore in the Korn Shell, and in the POSIX shells, including specifically Bash.

It is usually documented in the shell's man page in a section called Parameter Expansion. For example, the bash manual says:

${parameter:?word}

Display Error if Null or Unset. If parameter is null or unset, the expansion of word (or a message to that effect if word is not present) is written to the standard error and the shell, if it is not interactive, exits. Otherwise, the value of parameter is substituted.

The Colon Command

I should probably add that the colon command simply has its arguments evaluated and then succeeds. It is the original shell comment notation (before '#' to end of line). For a long time, Bourne shell scripts had a colon as the first character. The C Shell would read a script and use the first character to determine whether it was for the C Shell (a '#' hash) or the Bourne shell (a ':' colon). Then the kernel got in on the act and added support for '#!/path/to/program' and the Bourne shell got '#' comments, and the colon convention went by the wayside. But if you come across a script that starts with a colon, now you will know why.


Position of double quotes

blong asked in a comment:

Any thoughts on this discussion? https://github.com/koalaman/shellcheck/issues/380#issuecomment-145872749

The gist of the discussion is:

… However, when I shellcheck it (with version 0.4.1), I get this message:

In script.sh line 13:
: ${FOO:?"The environment variable 'FOO' must be set and non-empty"}
  ^-- SC2086: Double quote to prevent globbing and word splitting.

Any advice on what I should do in this case?

The short answer is "do as shellcheck suggests":

: "${STATE?Need to set STATE}"
: "${DEST:?Need to set DEST non-empty}"

To illustrate why, study the following. Note that the : command doesn't echo its arguments (but the shell does evaluate the arguments). We want to see the arguments, so the code below uses printf "%s\n" in place of :.

$ mkdir junk
$ cd junk
$ > abc
$ > def
$ > ghi
$ 
$ x="*"
$ printf "%s\n" ${x:?You must set x}    # Careless; not recommended
abc
def
ghi
$ unset x
$ printf "%s\n" ${x:?You must set x}    # Careless; not recommended
bash: x: You must set x
$ printf "%s\n" "${x:?You must set x}"  # Careful: should be used
bash: x: You must set x
$ x="*"
$ printf "%s\n" "${x:?You must set x}"  # Careful: should be used
*
$ printf "%s\n" ${x:?"You must set x"}  # Not quite careful enough
abc
def
ghi
$ x=
$ printf "%s\n" ${x:?"You must set x"}  # Not quite careful enough
bash: x: You must set x
$ unset x
$ printf "%s\n" ${x:?"You must set x"}  # Not quite careful enough
bash: x: You must set x
$ 

Note how the value in $x is expanded to first * and then a list of file names when the overall expression is not in double quotes. This is what shellcheck is recommending should be fixed. I have not verified that it doesn't object to the form where the expression is enclosed in double quotes, but it is a reasonable assumption that it would be OK.

How do I center this form in css?

  1. Wrap your form in a div.
  2. Set the div's display to block and text-align to center (this will center the contained form).
  3. Set the form's display to inline-block (auto-sizes to content), left and right margins to auto (centers it horizontally), and text-align to left (or else its children will be center-aligned too).

HTML:

<div class="form">
    <form name="Form1" action="mypage.asp" method="get">
        ...
    </form>
</div>

CSS:

div.form
{
    display: block;
    text-align: center;
}
form
{
    display: inline-block;
    margin-left: auto;
    margin-right: auto;
    text-align: left;
}

Hiding table data using <div style="display:none">

Yes, you can hide only the rows that you want to hide. This can be helpful if you want to show rows only when some condition is satisfied in the rows that are currently being shown. The following worked for me.

<table>
  <tr><th>Sample Table</th></tr>  
  <tr id="row1">
    <td><input id="data1" type="text" name="data1" /></td>
  </tr>
 <tr id="row2" style="display: none;">
    <td><input id="data2" type="text" name="data2" /></td>
 </tr>
 <tr id="row3" style="display: none;">
    <td><input id="data3" type="text" name="data3" /></td>
 </tr>
</table>

In CSS, do the following:

#row2{
    display: none;
}

#row3{
    display: none;
}

In JQuery, you might have something like the following to show the desired rows.

$(document).ready(function(){
    if($("#row1").val() === "sometext"){  //your desired condition
        $("#row2").show();
    }

    if($("#row2").val() !== ""){   //your desired condition
        $("#row3").show();
    }
});

Python coding standards/best practices

I follow it extremely rigorously. The only god before PEP-8 is existing code bases.

How to display a "busy" indicator with jQuery?

I did it in my project:

Global Events in application.js:

$(document).bind("ajaxSend", function(){
   $("#loading").show();
 }).bind("ajaxComplete", function(){
   $("#loading").hide();
 });

"loading" is the element to show and hide!

References: http://api.jquery.com/Ajax_Events/

XmlDocument - load from string?

XmlDocument doc = new XmlDocument();
doc.LoadXml(str);

Where str is your XML string. See the MSDN article for more info.

Can't operator == be applied to generic types in C#?


bool Compare(T x, T y) where T : class { return x == y; }

The above will work because == is taken care of in case of user-defined reference types.
In case of value types, == can be overridden. In which case, "!=" should also be defined.

I think that could be the reason, it disallows generic comparison using "==".

How to define an optional field in protobuf 3

One way is to optional like described in the accepted answer: https://stackoverflow.com/a/62566052/1803821

Another one is to use wrapper objects. You don't need to write them yourself as google already provides them:

At the top of your .proto file add this import:

import "google/protobuf/wrappers.proto";

Now you can use special wrappers for every simple type:

DoubleValue
FloatValue
Int64Value
UInt64Value
Int32Value
UInt32Value
BoolValue
StringValue
BytesValue

So to answer the original question a usage of such a wrapper could be like this:

message Foo {
    int32 bar = 1;
    google.protobuf.Int32Value baz = 2;
}

Now for example in Java I can do stuff like:

if(foo.hasBaz()) { ... }

How to POST form data with Spring RestTemplate?

here is the full program to make a POST rest call using spring's RestTemplate.

import java.util.HashMap;
import java.util.Map;

import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;

import com.ituple.common.dto.ServiceResponse;

   public class PostRequestMain {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        MultiValueMap<String, String> headers = new LinkedMultiValueMap<String, String>();
        Map map = new HashMap<String, String>();
        map.put("Content-Type", "application/json");

        headers.setAll(map);

        Map req_payload = new HashMap();
        req_payload.put("name", "piyush");

        HttpEntity<?> request = new HttpEntity<>(req_payload, headers);
        String url = "http://localhost:8080/xxx/xxx/";

        ResponseEntity<?> response = new RestTemplate().postForEntity(url, request, String.class);
        ServiceResponse entityResponse = (ServiceResponse) response.getBody();
        System.out.println(entityResponse.getData());
    }

}

Check if passed argument is file or directory in Bash

Using -f and -d switches on /bin/test:

F_NAME="${1}"

if test -f "${F_NAME}"
then                                   
   echo "${F_NAME} is a file"
elif test -d "${F_NAME}"
then
   echo "${F_NAME} is a directory"
else                                   
   echo "${F_NAME} is not valid"
fi

Checking if a folder exists using a .bat file

I think the answer is here (possibly duplicate):

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

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

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

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

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

should be enough for modern windows.

Should you use rgba(0, 0, 0, 0) or rgba(255, 255, 255, 0) for transparency in CSS?

I would recommend using rgba(255,255,255,0) because broken (newest) safari thinks that if you are using transparent or rgba(0,0,0,0) in linear-gradent you really mean gray, For more info please head to - What happens in Safari with the transparent color?

Set the absolute position of a view

My code for Xamarin, I am using FrameLayout for this purpose and following is my code:

               List<object> content = new List<object>();

        object aWebView = new {ContentType="web",Width="300", Height = "300",X="10",Y="30",ContentUrl="http://www.google.com" };
        content.Add(aWebView);
        object aWebView2 = new { ContentType = "image", Width = "300", Height = "300", X = "20", Y = "40", ContentUrl = "https://www.nasa.gov/sites/default/files/styles/image_card_4x3_ratio/public/thumbnails/image/leisa_christmas_false_color.png?itok=Jxf0IlS4" };
        content.Add(aWebView2);
        FrameLayout myLayout = (FrameLayout)FindViewById(Resource.Id.frameLayout1);
        foreach (object item in content)
        {

            string contentType = item.GetType().GetProperty("ContentType").GetValue(item, null).ToString();
            FrameLayout.LayoutParams param = new FrameLayout.LayoutParams(Convert.ToInt32(item.GetType().GetProperty("Width").GetValue(item, null).ToString()), Convert.ToInt32(item.GetType().GetProperty("Height").GetValue(item, null).ToString()));
            param.LeftMargin = Convert.ToInt32(item.GetType().GetProperty("X").GetValue(item, null).ToString());
            param.TopMargin = Convert.ToInt32(item.GetType().GetProperty("Y").GetValue(item, null).ToString());

            switch (contentType) {
                case "web":{
                        WebView webview = new WebView(this);

                        //webview.hei;
                        myLayout.AddView(webview, param);
                        webview.SetWebViewClient(new WebViewClient());
                        webview.LoadUrl(item.GetType().GetProperty("ContentUrl").GetValue(item, null).ToString());

                        break;
                    }
                case "image":
                    {
                        ImageView imageview = new ImageView(this);

                        //webview.hei;
                        myLayout.AddView(imageview, param);
                        var imageBitmap =  GetImageBitmapFromUrl("https://www.nasa.gov/sites/default/files/styles/image_card_4x3_ratio/public/thumbnails/image/leisa_christmas_false_color.png?itok=Jxf0IlS4");
                        imageview.SetImageBitmap(imageBitmap);


                        break;
                    }

            }

        }

It was useful for me because I needed the property of view to overlap each other on basis of their appearance, e.g the views get stacked one above other.

What do >> and << mean in Python?

These are bitwise shift operators.

Quoting from the docs:

x << y

Returns x with the bits shifted to the left by y places (and new bits on the right-hand-side are zeros). This is the same as multiplying x by 2**y.

x >> y

Returns x with the bits shifted to the right by y places. This is the same as dividing x by 2**y.

Enabling/installing GD extension? --without-gd

Check if in your php.ini file has the following line:

;extension=php_gd2.dll

if exists, change it to

extension=php_gd2.dll

and restart apache

(it works on MAC)

Xampp-mysql - "Table doesn't exist in engine" #1932

I had the same issue. I had a backup of my C:\xampp\mysql\data folder. But integrating it with the newly installed xampp had issues. So I located the C:\xampp\mysql\bin\my.ini file and directed innodb_data_home_dir = "C:/xampp/mysql/data" to my backed-up data folder and it worked flawlessly.

Default values for Vue component props & how to check if a user did not set the prop?

Vue allows for you to specify a default prop value and type directly, by making props an object (see: https://vuejs.org/guide/components.html#Prop-Validation):

props: {
  year: {
    default: 2016,
    type: Number
  }
}

If the wrong type is passed then it throws an error and logs it in the console, here's the fiddle:

https://jsfiddle.net/cexbqe2q/

Bootstrap 3 modal responsive

You should be able to adjust the width using the .modal-dialog class selector (in conjunction with media queries or whatever strategy you're using for responsive design):

.modal-dialog {
    width: 400px;
}

Getting the "real" Facebook profile picture URL from graph API

If you want the JSON of a good quality profile picture with the URL you can use that:

http://graph.facebook.com/517267866/picture?height=1024&redirect=false

if you just need the picture use it without the parameter redirect:

http://graph.facebook.com/517267866/picture?height=1024

517267866 is the profile ID of one of the above examples. Put the facebook id that you need

I hope that helps

SUM of grouped COUNT in SQL Query

For Sql server you can try this one.

SELECT ISNULL([NAME],'SUM'),Count([NAME]) AS COUNT
FROM TABLENAME
GROUP BY [NAME] WITH CUBE

how to get the last part of a string before a certain character?

You are looking for str.rsplit(), with a limit:

print x.rsplit('-', 1)[0]

.rsplit() searches for the splitting string from the end of input string, and the second argument limits how many times it'll split to just once.

Another option is to use str.rpartition(), which will only ever split just once:

print x.rpartition('-')[0]

For splitting just once, str.rpartition() is the faster method as well; if you need to split more than once you can only use str.rsplit().

Demo:

>>> x = 'http://test.com/lalala-134'
>>> print x.rsplit('-', 1)[0]
http://test.com/lalala
>>> 'something-with-a-lot-of-dashes'.rsplit('-', 1)[0]
'something-with-a-lot-of'

and the same with str.rpartition()

>>> print x.rpartition('-')[0]
http://test.com/lalala
>>> 'something-with-a-lot-of-dashes'.rpartition('-')[0]
'something-with-a-lot-of'

How do we change the URL of a working GitLab install?

GitLab Omnibus

For an Omnibus install, it is a little different.

The correct place in an Omnibus install is:

/etc/gitlab/gitlab.rb
    external_url 'http://gitlab.example.com'

Finally, you'll need to execute sudo gitlab-ctl reconfigure and sudo gitlab-ctl restart so the changes apply.


I was making changes in the wrong places and they were getting blown away.

The incorrect paths are:

/opt/gitlab/embedded/service/gitlab-rails/config/gitlab.yml
/var/opt/gitlab/.gitconfig
/var/opt/gitlab/nginx/conf/gitlab-http.conf

Pay attention to those warnings that read:

# This file is managed by gitlab-ctl. Manual changes will be
# erased! To change the contents below, edit /etc/gitlab/gitlab.rb
# and run `sudo gitlab-ctl reconfigure`.

Where can I find the Tomcat 7 installation folder on Linux AMI in Elastic Beanstalk?

In my case on Ubuntu 16.04 server, and default tomcat installation it's under:

/var/lib/tomcat8

How to limit google autocomplete results to City and Country only

The answer given by Francois results in listing all the cities from a country. But if the requirement is to list all the regions (cities + states + other regions etc) in a country or the establishments in the country, you can filter results accordingly by changing types.

List only cities in the country

 var options = {
  types: ['(cities)'],
  componentRestrictions: {country: "us"}
 };

List all cities, states and regions in the country

 var options = {
  types: ['(regions)'],
  componentRestrictions: {country: "us"}
 };

List all establishments — such as restaurants, stores, and offices in the country

  var options = {
      types: ['establishment'],
      componentRestrictions: {country: "us"}
     };

More information and options available at

https://developers.google.com/maps/documentation/javascript/places-autocomplete

Hope this might be useful to someone

Ansible - Save registered variable to file

Thanks to tmoschou for adding this comment to an outdated accepted answer:

As of Ansible 2.10, The documentation for ansible.builtin.copy says: 

If you need variable interpolation in copied files, use the
ansible.builtin.template module. Using a variable in the content field will
result in unpredictable output.

For more details see this and an explanation


Original answer:

You can use the copy module, with the parameter content=.

I gave the exact same answer here: Write variable to a file in Ansible

In your case, it looks like you want this variable written to a local logfile, so you could combine it with the local_action notation:

- local_action: copy content={{ foo_result }} dest=/path/to/destination/file

Linq filter List<string> where it contains a string value from another List<string>

you can do that

var filteredFileList = fileList.Where(fl => filterList.Contains(fl.ToString()));

"Cannot open include file: 'config-win.h': No such file or directory" while installing mysql-python

If pip fails to install "MySQLdb", a workaround is to download and install it on your machine first from this link

http://www.lfd.uci.edu/~gohlke/pythonlibs/#mysql-python

then copy all MySQL* and _mysql* files and directories from your system Python to your Virtualenv dir:

c:\Python27\Lib\site-packages (or similar path to your system Python) to c:\my_virtenv\Lib\site-packages (path to your virtualenv)

TypeError: ufunc 'add' did not contain a loop with signature matching types

You have a numpy array of strings, not floats. This is what is meant by dtype('<U9') -- a little endian encoded unicode string with up to 9 characters.

try:

return sum(np.asarray(listOfEmb, dtype=float)) / float(len(listOfEmb))

However, you don't need numpy here at all. You can really just do:

return sum(float(embedding) for embedding in listOfEmb) / len(listOfEmb)

Or if you're really set on using numpy.

return np.asarray(listOfEmb, dtype=float).mean()

Need to combine lots of files in a directory

Use the Windows 'copy' command.

C:\Users\dan>help copy
    Copies one or more files to another location.

    COPY [/D] [/V] [/N] [/Y | /-Y] [/Z] [/L] [/A | /B ] source [/A | /B]
         [+ source [/A | /B] [+ ...]] [destination [/A | /B]]

      source       Specifies the file or files to be copied.
      /A           Indicates an ASCII text file.
      /B           Indicates a binary file.
      /D           Allow the destination file to be created decrypted
      destination  Specifies the directory and/or filename for the new file(s).
      /V           Verifies that new files are written correctly.
      /N           Uses short filename, if available, when copying a file with 
                   a non-8dot3 name.
      /Y           Suppresses prompting to confirm you want to overwrite an
                   existing destination file.
      /-Y          Causes prompting to confirm you want to overwrite an
                   existing destination file.
      /Z           Copies networked files in restartable mode.
      /L           If the source is a symbolic link, copy the link to the 
                   target
                   instead of the actual file the source link points to.

    The switch /Y may be preset in the COPYCMD environment variable.
    This may be overridden with /-Y on the command line.  Default is
    to prompt on overwrites unless COPY command is being executed from
    within a batch script.

    **To append files, specify a single file for destination, but 
    multiple files for source (using wildcards or file1+file2+file3 
    format).**

So in your case:

copy *.txt destination.txt

Will concatenate all .txt files in alphabetical order into destination.txt

Thanks for asking, I learned something new!

Huge performance difference when using group by vs distinct

The two queries express the same question. Apparently the query optimizer chooses two different execution plans. My guess would be that the distinct approach is executed like:

  • Copy all business_key values to a temporary table
  • Sort the temporary table
  • Scan the temporary table, returning each item that is different from the one before it

The group by could be executed like:

  • Scan the full table, storing each value of business key in a hashtable
  • Return the keys of the hashtable

The first method optimizes for memory usage: it would still perform reasonably well when part of the temporary table has to be swapped out. The second method optimizes for speed, but potentially requires a large amount of memory if there are a lot of different keys.

Since you either have enough memory or few different keys, the second method outperforms the first. It's not unusual to see performance differences of 10x or even 100x between two execution plans.

The HTTP request is unauthorized with client authentication scheme 'Ntlm'

My problem was; None admin users were getting "the http request is unauthorized with client authentication scheme 'negotiate' asmx" on my asmx services.

I gived read/execute folder permissions for the none admin users and my problem was solved.

Hibernate SessionFactory vs. JPA EntityManagerFactory

SessionFactory vs. EntityManagerFactory

As I explained in the Hibernate User Guide, the Hibernate SessionFactory extends the JPA EntityManagerFactory, as illustrated by the following diagram:

JPA and Hibernate relationship

So, the SessionFactory is also a JPA EntityManagerFactory.

Both the SessionFactory and the EntityManagerFactory contain the entity mapping metadata and allow you to create a Hibernate Session or a EntityManager.

Session vs. EntityManager

Just like the SessionFactory and EntityManagerFactory, the Hibernate Session extends the JPA EntityManager. So, all methods defined by the EntityManager are available in the Hibernate Session.

The Session and the `EntityManager translate entity state transitions into SQL statements, like SELECT, INSERT, UPDATE, and DELETE.

Hibernate vs. JPA bootstrap

When bootstrapping a JPA or Hibernate application, you have two choices:

  1. You can bootstrap via the Hibernate native mechanism, and create a SessionFactory via the BootstrapServiceRegistryBuilder. If you're using Spring, the Hibernate bootstrap is done via the LocalSessionFactoryBean, as illustrated by this GitHub example.
  2. Or, you can create a JPA EntityManagerFactory via the Persistence class or the EntityManagerFactoryBuilder. If you're using Spring, the JPA bootstrap is done via the LocalContainerEntityManagerFactoryBean, as illustrated by this GitHub example.

Bootstrapping via JPA is to be preferred. That's because the JPA FlushModeType.AUTO is a much better choice than the legacy FlushMode.AUTO, which breaks read-your-writes consistency for native SQL queries.

Unwrapping JPA to Hibernate

Also, if you bootstrap via JPA, and you have injected the EntityManagerFactory via the @PersistenceUnit annotation:

@PersistenceUnit
private EntityManagerFactory entityManagerFactory;

You can easily get access to the underlying Sessionfactory using the unwrap method:

SessionFactory sessionFactory = entityManagerFactory.unwrap(SessionFactory.class);

The same can be done with the JPA EntityManager. If you inject the EntityManager via the @PersistenceContext annotation:

@PersistenceContext
private EntityManager entityManager;

You can easily get access to the underlying Session using the unwrap method:

Session session = entityManager.unwrap(Session.class);

Conclusion

So, you should bootstrap via JPA, use the EntityManagerFactory and EntityManager, and only unwrap those to their associated Hibernate interfaces when you want to get access to some Hibernate-specific methods that are not available in JPA, like fetching the entity via its natural identifier.

'python3' is not recognized as an internal or external command, operable program or batch file

There is no python3.exe file, that is why it fails.

Try:

py

instead.

py is just a launcher for python.exe. If you have more than one python versions installed on your machine (2.x, 3.x) you can specify what version of python to launch by

py -2 or py -3

Terminating a script in PowerShell

Throwing an exception will be good especially if you want to clarify the error reason:

throw "Error Message"

This will generate a terminating error.

Add legend to ggplot2 line plot

I really like the solution proposed by @Brian Diggs. However, in my case, I create the line plots in a loop rather than giving them explicitly because I do not know apriori how many plots I will have. When I tried to adapt the @Brian's code I faced some problems with handling the colors correctly. Turned out I needed to modify the aesthetic functions. In case someone has the same problem, here is the code that worked for me.

I used the same data frame as @Brian:

data <- structure(list(month = structure(c(1317452400, 1317538800, 1317625200, 1317711600, 
                                       1317798000, 1317884400, 1317970800, 1318057200, 
                                       1318143600, 1318230000, 1318316400, 1318402800, 
                                       1318489200, 1318575600, 1318662000, 1318748400, 
                                       1318834800, 1318921200, 1319007600, 1319094000), 
                                     class = c("POSIXct", "POSIXt"), tzone = ""),
                   TempMax = c(26.58, 27.78, 27.9, 27.44, 30.9, 30.44, 27.57, 25.71, 
                               25.98, 26.84, 33.58, 30.7, 31.3, 27.18, 26.58, 26.18, 
                               25.19, 24.19, 27.65, 23.92), 
                   TempMed = c(22.88, 22.87, 22.41, 21.63, 22.43, 22.29, 21.89, 20.52,
                                 19.71, 20.73, 23.51, 23.13, 22.95, 21.95, 21.91, 20.72, 
                                 20.45, 19.42, 19.97, 19.61), 
                   TempMin = c(19.34, 19.14, 18.34, 17.49, 16.75, 16.75, 16.88, 16.82, 
                               14.82, 16.01, 16.88, 17.55, 16.75, 17.22, 19.01, 16.95, 
                               17.55, 15.21, 14.22, 16.42)), 
              .Names = c("month", "TempMax", "TempMed", "TempMin"), 
              row.names = c(NA, 20L), class = "data.frame")  

In my case, I generate my.cols and my.names dynamically, but I don't want to make things unnecessarily complicated so I give them explicitly here. These three lines make the ordering of the legend and assigning colors easier.

my.cols <- heat.colors(3, alpha=1)
my.names <- c("TempMin", "TempMed", "TempMax")
names(my.cols) <- my.names

And here is the plot:

p <-  ggplot(data, aes(x = month))

for (i in 1:3){
  p <- p + geom_line(aes_(y = as.name(names(data[i+1])), colour = 
colnames(data[i+1])))#as.character(my.names[i])))
}
p + scale_colour_manual("", 
                        breaks = as.character(my.names),
                        values = my.cols)
p

enter image description here

How to return temporary table from stored procedure

The return type of a procedure is int.

You can also return result sets (as your code currently does) (okay, you can also send messages, which are strings)

Those are the only "returns" you can make. Whilst you can add table-valued parameters to a procedure (see BOL), they're input only.

Edit:

(Or as another poster mentioned, you could also use a Table Valued Function, rather than a procedure)

Working Copy Locked

svn cleanup test-lalala/
svn update

repeat twice

Reset push notification settings for app

The plist: /private/var/mobile/Library/RemoteNotification/Clients.plist

... contains the registered clients for push notifications. Removing your app's entry will cause the prompt to re-appear

What do 'real', 'user' and 'sys' mean in the output of time(1)?

Real, User and Sys process time statistics

One of these things is not like the other. Real refers to actual elapsed time; User and Sys refer to CPU time used only by the process.

  • Real is wall clock time - time from start to finish of the call. This is all elapsed time including time slices used by other processes and time the process spends blocked (for example if it is waiting for I/O to complete).

  • User is the amount of CPU time spent in user-mode code (outside the kernel) within the process. This is only actual CPU time used in executing the process. Other processes and time the process spends blocked do not count towards this figure.

  • Sys is the amount of CPU time spent in the kernel within the process. This means executing CPU time spent in system calls within the kernel, as opposed to library code, which is still running in user-space. Like 'user', this is only CPU time used by the process. See below for a brief description of kernel mode (also known as 'supervisor' mode) and the system call mechanism.

User+Sys will tell you how much actual CPU time your process used. Note that this is across all CPUs, so if the process has multiple threads (and this process is running on a computer with more than one processor) it could potentially exceed the wall clock time reported by Real (which usually occurs). Note that in the output these figures include the User and Sys time of all child processes (and their descendants) as well when they could have been collected, e.g. by wait(2) or waitpid(2), although the underlying system calls return the statistics for the process and its children separately.

Origins of the statistics reported by time (1)

The statistics reported by time are gathered from various system calls. 'User' and 'Sys' come from wait (2) (POSIX) or times (2) (POSIX), depending on the particular system. 'Real' is calculated from a start and end time gathered from the gettimeofday (2) call. Depending on the version of the system, various other statistics such as the number of context switches may also be gathered by time.

On a multi-processor machine, a multi-threaded process or a process forking children could have an elapsed time smaller than the total CPU time - as different threads or processes may run in parallel. Also, the time statistics reported come from different origins, so times recorded for very short running tasks may be subject to rounding errors, as the example given by the original poster shows.

A brief primer on Kernel vs. User mode

On Unix, or any protected-memory operating system, 'Kernel' or 'Supervisor' mode refers to a privileged mode that the CPU can operate in. Certain privileged actions that could affect security or stability can only be done when the CPU is operating in this mode; these actions are not available to application code. An example of such an action might be manipulation of the MMU to gain access to the address space of another process. Normally, user-mode code cannot do this (with good reason), although it can request shared memory from the kernel, which could be read or written by more than one process. In this case, the shared memory is explicitly requested from the kernel through a secure mechanism and both processes have to explicitly attach to it in order to use it.

The privileged mode is usually referred to as 'kernel' mode because the kernel is executed by the CPU running in this mode. In order to switch to kernel mode you have to issue a specific instruction (often called a trap) that switches the CPU to running in kernel mode and runs code from a specific location held in a jump table. For security reasons, you cannot switch to kernel mode and execute arbitrary code - the traps are managed through a table of addresses that cannot be written to unless the CPU is running in supervisor mode. You trap with an explicit trap number and the address is looked up in the jump table; the kernel has a finite number of controlled entry points.

The 'system' calls in the C library (particularly those described in Section 2 of the man pages) have a user-mode component, which is what you actually call from your C program. Behind the scenes, they may issue one or more system calls to the kernel to do specific services such as I/O, but they still also have code running in user-mode. It is also quite possible to directly issue a trap to kernel mode from any user space code if desired, although you may need to write a snippet of assembly language to set up the registers correctly for the call.

More about 'sys'

There are things that your code cannot do from user mode - things like allocating memory or accessing hardware (HDD, network, etc.). These are under the supervision of the kernel, and it alone can do them. Some operations like malloc orfread/fwrite will invoke these kernel functions and that then will count as 'sys' time. Unfortunately it's not as simple as "every call to malloc will be counted in 'sys' time". The call to malloc will do some processing of its own (still counted in 'user' time) and then somewhere along the way it may call the function in kernel (counted in 'sys' time). After returning from the kernel call, there will be some more time in 'user' and then malloc will return to your code. As for when the switch happens, and how much of it is spent in kernel mode... you cannot say. It depends on the implementation of the library. Also, other seemingly innocent functions might also use malloc and the like in the background, which will again have some time in 'sys' then.

CertificateException: No name matching ssl.someUrl.de found

I've found a good resolution here: http://www.mkyong.com/webservices/jax-ws/java-security-cert-certificateexception-no-name-matching-localhost-found/

But my problem was a little bit different and solved it differently.

The web service was on remote host. For example: https://some.remote.host/MyWebService?wsdl

But it was available only by IP for any clients, but certificate was created for domain: some.remote.host (CN=some.remote.host). And this domain can't be resolved by IP because it is not presented in DNS).

So the same problem appeared: if I use IP to connect to web service by ssl, it can't be reached becase certificate CN=some.remote.host and it is not equal to host name I've specified (i.e. host IP).

I've resolved it by matching this hostname with IP in /etc/hosts file. The problem was fixed.

But in case when the Web Service is hosted on localhost app server, it think, it should be solved like mkyong described in his article.

How do I create a simple 'Hello World' module in Magento?

I was trying to make my module from magaplaza hello world tutorial, but something went wrong. I imported code of this module https://github.com/astorm/magento2-hello-world from github and it worked. from that module, i created it a categories subcategories ajax select drop downs Module. After installing it in aap/code directory of your magento2 installation follow this URL.. http://www.example.com/hello_mvvm/hello/world You can download its code from here https://github.com/sanaullahAhmad/Magento2_cat_subcat_ajax_select_dropdowns and place it in your aap/code folder. than run these commands...

php bin/magento setup:update
php bin/magento setup:static-content:deploy -f
php bin/magento c:c

Now you can check module functionality with following URL http://{{www.example.com}}/hello_mvvm/hello/world

Questions every good PHP Developer should be able to answer

Admittedly, I stole this question from somewhere else (can't remember where I read it any more) but thought it was funny:

Q: What is T_PAAMAYIM_NEKUDOTAYIM?
A: Its the scope resolution operator (double colon)

An experienced PHP'er immediately knows what it means. Less experienced (and not Hebrew) developers may want to read this.

But more serious questions now:


Q: What is the cause of this warning: 'Warning: Cannot modify header information - headers already sent', and what is a good practice to prevent it?
A: Cause: body data was sent, causing headers to be sent too.
Prevention: Be sure to execute header specific code first before you output any body data. Be sure you haven't accidentally sent out whitespace or any other characters.


Q: What is wrong with this query: "SELECT * FROM table WHERE id = $_POST[ 'id' ]"?
A: 1. It is vulnarable to SQL injection. Never use user input directly in queries. Sanitize it first. Preferebly use prepared statements (PDO) 2. Don't select all columns (*), but specify every single column. This is predominantly ment to prevent queries hogging up memory when for instance a BLOB column is added at some point in the future.


Q: What is wrong with this if statement: if( !strpos( $haystack, $needle ) ...?
A: strpos returns the index position of where it first found the $needle, which could be 0. Since 0 also resolves to false the solution is to use strict comparison: if( false !== strpos( $haystack, $needle )...


Q: What is the preferred way to write this if statement, and why?
if( 5 == $someVar ) or if( $someVar == 5 )
A: The former, as it prevents accidental assignment of 5 to $someVar when you forget to use 2 equalsigns ($someVar = 5), and will cause an error, the latter won't.


Q: Given this code:

function doSomething( &$arg )
{
    $return = $arg;
    $arg += 1;
    return $return;
}

$a = 3;
$b = doSomething( $a );

...what is the value of $a and $b after the function call and why?
A: $a is 4 and $b is 3. The former because $arg is passed by reference, the latter because the return value of the function is a copy of (not a reference to) the initial value of the argument.


OOP specific

Q: What is the difference between public, protected and private in a class definition?
A: public makes a class member available to "everyone", protected makes the class member available to only itself and derived classes, private makes the class member only available to the class itself.


Q: What is wrong with this code:

class SomeClass
{
    protected $_someMember;

    public function __construct()
    {
        $this->_someMember = 1;
    }

    public static function getSomethingStatic()
    {
        return $this->_someMember * 5; // here's the catch
    }
}

A: Static methods don't have access to $this, because static methods can be executed without instantiating a class.


Q: What is the difference between an interface and an abstract class?
A: An interface defines a contract between an implementing class is and an object that calls the interface. An abstract class pre-defines certain behaviour for classes that will extend it. To a certain degree this can also be considered a contract, since it garantuees certain methods to exist.


Q: What is wrong with classes that predominantly define getters and setters, that map straight to it's internal members, without actually having methods that execute behaviour?
A: This might be a code smell since the object acts as an ennobled array, without much other use.


Q: Why is PHP's implementation of the use of interfaces sub-optimal?
A: PHP doesn't allow you to define the expected return type of the method's, which essentially renders interfaces pretty useless. :-P

FontAwesome icons not showing. Why?

the CDN link that you had posted i suppose is why it wasnt showing correctly, you can use this one below, it works perfectly for me.

_x000D_
_x000D_
<link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet">
_x000D_
_x000D_
_x000D_

Send request to curl with post data sourced from a file

I need to make a POST request via Curl from the command line. Data for this request is located in a file...

All you need to do is have the --data argument start with a @:

curl -H "Content-Type: text/xml" --data "@path_of_file" host:port/post-file-path

For example, if you have the data in a file called stuff.xml then you would do something like:

curl -H "Content-Type: text/xml" --data "@stuff.xml" host:port/post-file-path

The stuff.xml filename can be replaced with a relative or full path to the file: @../xml/stuff.xml, @/var/tmp/stuff.xml, ...

Unstaged changes left after git reset --hard

Similar issue, although I'm sure only on surface. Anyway, it may help someone: what I did (FWIW, in SourceTree): stashed the uncommitted file, then did a hard reset.

Adding a month to a date in T SQL

select * from Reference where reference_dt = DateAdd(month,1,another_date_reference)

LaTeX: remove blank page after a \part or \chapter

I believe that in the book class all \part and \chapter are set to start on a recto page.

from book.cls:

\newcommand\part{%
  \if@openright
    \cleardoublepage
  \else
    \clearpage
  \fi
  \thispagestyle{plain}%
  \if@twocolumn
    \onecolumn
    \@tempswatrue
  \else
    \@tempswafalse
  \fi
  \null\vfil
  \secdef\@part\@spart}

you should be able to renew that command, and something similar for the \chapter.

How to getText on an input in protractor

You can use jQuery to get text in textbox (work well for me), check in image detail

Code:

$(document.evaluate( "xpath" ,document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null ).singleNodeValue).val()

Example: 
$(document.evaluate( "//*[@id='mail']" ,document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null ).singleNodeValue).val()

Inject this above query to your code. Image detail:

enter image description here

Best practices for styling HTML emails

I've fought the HTML email battle before. Here are some of my tips about styling for maximum compatibility between email clients.

  • Inline styles are you best friend. Absolutely don't link style sheets and do not use a <style> tag (GMail, for example, strips that tag and all it's contents).

  • Against your better judgement, use and abuse tables. <div>s just won't cut it (especially in Outlook).

  • Don't use background images, they're spotty and will annoy you.

  • Remember that some email clients will automatically transform typed out hyperlinks into links (if you don't anchor <a> them yourself). This can sometimes achieve negative effects (say if you're putting a style on each of the hyperlinks to appear a different color).

  • Be careful hyperlinking an actual link with something different. For example, don't type out http://www.google.com and then link it to https://gmail.com/. Some clients will flag the message as Spam or Junk.

  • Save your images in as few colors as possible to save on size.

  • If possible, embed your images in your email. The email won't have to reach out to an external web server to download them and they won't appear as attachments to the email.

And lastly, test, test, test! Each email client does things way differently than a browser would do.

How to set TextView textStyle such as bold, italic

Best way is to define it in styles.xml

<style name="common_txt_style_heading" parent="android:style/Widget.TextView">
        <item name="android:textSize">@dimen/common_txtsize_heading</item>
        <item name="android:textColor">@color/color_black</item>
        <item name="android:textStyle">bold|italic</item>
</style>

And update it in TextView

  <TextView
     android:id="@+id/txt_userprofile"
     style="@style/common_txt_style_heading"
     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
     android:layout_centerHorizontal="true"
     android:layout_marginTop="@dimen/margin_small"
     android:text="@string/some_heading" />

What does "ulimit -s unlimited" do?

stack size can indeed be unlimited. _STK_LIM is the default, _STK_LIM_MAX is something that differs per architecture, as can be seen from include/asm-generic/resource.h:

/*
 * RLIMIT_STACK default maximum - some architectures override it:
 */
#ifndef _STK_LIM_MAX
# define _STK_LIM_MAX           RLIM_INFINITY
#endif

As can be seen from this example generic value is infinite, where RLIM_INFINITY is, again, in generic case defined as:

/*
 * SuS says limits have to be unsigned.
 * Which makes a ton more sense anyway.
 *
 * Some architectures override this (for compatibility reasons):
 */
#ifndef RLIM_INFINITY
# define RLIM_INFINITY          (~0UL)
#endif

So I guess the real answer is - stack size CAN be limited by some architecture, then unlimited stack trace will mean whatever _STK_LIM_MAX is defined to, and in case it's infinity - it is infinite. For details on what it means to set it to infinite and what implications it might have, refer to the other answer, it's way better than mine.

Useful example of a shutdown hook in Java?

Shutdown Hooks are unstarted threads that are registered with Runtime.addShutdownHook().JVM does not give any guarantee on the order in which shutdown hooks are started.For more info refer http://techno-terminal.blogspot.in/2015/08/shutdown-hooks.html

CSS to make table 100% of max-width

I had to use:

table, tbody {
    width: 100%;
}

The table alone wasn't enough, the tbody was also needed for it to work for me.

In Javascript, how do I check if an array has duplicate values?

Another approach (also for object/array elements within the array1) could be2:

function chkDuplicates(arr,justCheck){
  var len = arr.length, tmp = {}, arrtmp = arr.slice(), dupes = [];
  arrtmp.sort();
  while(len--){
   var val = arrtmp[len];
   if (/nul|nan|infini/i.test(String(val))){
     val = String(val);
    }
    if (tmp[JSON.stringify(val)]){
       if (justCheck) {return true;}
       dupes.push(val);
    }
    tmp[JSON.stringify(val)] = true;
  }
  return justCheck ? false : dupes.length ? dupes : null;
}
//usages
chkDuplicates([1,2,3,4,5],true);                           //=> false
chkDuplicates([1,2,3,4,5,9,10,5,1,2],true);                //=> true
chkDuplicates([{a:1,b:2},1,2,3,4,{a:1,b:2},[1,2,3]],true); //=> true
chkDuplicates([null,1,2,3,4,{a:1,b:2},NaN],true);          //=> false
chkDuplicates([1,2,3,4,5,1,2]);                            //=> [1,2]
chkDuplicates([1,2,3,4,5]);                                //=> null

See also...

1 needs a browser that supports JSON, or a JSON library if not.
2 edit: function can now be used for simple check or to return an array of duplicate values

how to replace characters in hive?

You can also use translate(). If the third argument is too short, the corresponding characters from the second argument are deleted. Unlike regexp_replace() you don't need to worry about special characters. Source code.

https://cwiki.apache.org/confluence/display/Hive/LanguageManual+UDF#LanguageManualUDF-StringFunctions

Why isn't ProjectName-Prefix.pch created automatically in Xcode 6?

To add .pch file-

1) Add new .pch file to your project->New file->other->PCH file

2) Goto your project's build setting.

3) Search "prefix header". You can find that under Apple LLVM.

4) Paste this in the field $(SRCROOT)/yourPrefixHeaderFileName.pch

5) Clean and build the project. That's it!!!

enter image description here

Package Manager Console Enable-Migrations CommandNotFoundException only in a specific VS project

Check the version of the Entity Framework.

if it is 6.3, downgrade it to 6.2 and it should work just fine

How to uncheck checkbox using jQuery Uniform library

A simpler solution is to do this rather than using uniform:

$('#check1').prop('checked', true); // will check the checkbox with id check1
$('#check1').prop('checked', false); // will uncheck the checkbox with id check1

This will not trigger any click action defined.

You can also use:

$('#check1').click(); // 

This will toggle the check/uncheck for the checkbox but this will also trigger any click action you have defined. So be careful.

EDIT: jQuery 1.6+ uses prop() not attr() for checkboxes checked value

how to make div click-able?

I suggest to use a CSS class called clickbox and activate it with jQuery:

$(".clickbox").click(function(){
     window.location=$(this).find("a").attr("href"); 
     return false;
 });

Now the only thing you have to do is mark your div as clickable and provide a link:

<div id="logo" class="clickbox"><a href="index.php"></a></div>

Plus a CSS style to change the mouse cursor:

.clickbox {
    cursor: pointer;
}

Easy, isn't it?

Conversion failed when converting the varchar value to data type int in sql

Try this one -

CREATE PROC [dbo].[getVoucherNo]
AS BEGIN

     DECLARE 
            @Prefix VARCHAR(10) = 'J'
          , @startFrom INT = 1
          , @maxCode VARCHAR(100)
          , @sCode INT

     IF EXISTS(
          SELECT 1 
          FROM dbo.Journal_Entry
     ) BEGIN

          SELECT @maxCode = CAST(MAX(CAST(SUBSTRING(Voucher_No,LEN(@startFrom)+1,ABS(LEN(Voucher_No)- LEN(@Prefix))) AS INT)) AS varchar(100)) 
          FROM dbo.Journal_Entry;

          SELECT @Prefix + 
               CAST(LEN(LEFT(@maxCode, 10) + 1) AS VARCHAR(10)) + -- !!! possible problem here
               CAST(@maxCode AS VARCHAR(100))

     END
     ELSE BEGIN

          SELECT (@Prefix + CAST(@startFrom AS VARCHAR)) 

     END

END

How should I pass multiple parameters to an ASP.Net Web API GET?

I know this is really old, but I wanted the same thing recently and here's what I found...

    public HttpResponseMessage Get([FromUri] string var, [FromUri] string test) {
        var retStr = new HttpResponseMessage(HttpStatusCode.OK);
        if (var.ToLower() == "getnew" && test.ToLower() == "test") {
            retStr.Content = new StringContent("Found Test", System.Text.Encoding.UTF8, "text/plain");
        } else {
            retStr.Content = new StringContent("Couldn't Find that test", System.Text.Encoding.UTF8, "text/plain");
        }

        return retStr;
    }

So now in your address/URI/...

http(s)://myURL/api/myController/?var=getnew&test=test

Result: "Found Test"


http(s)://myURL/api/myController/?var=getnew&test=anything

Result: "Couldn't Find that test"

How do I print bold text in Python?

class color:
   PURPLE = '\033[95m'
   CYAN = '\033[96m'
   DARKCYAN = '\033[36m'
   BLUE = '\033[94m'
   GREEN = '\033[92m'
   YELLOW = '\033[93m'
   RED = '\033[91m'
   BOLD = '\033[1m'
   UNDERLINE = '\033[4m'
   END = '\033[0m'

print(color.BOLD + 'Hello World !' + color.END)

header location not working in my php code

for me just add ob_start(); at the start of the file.

Where does VBA Debug.Print log to?

Debug.Print outputs to the "Immediate" window.

Debug.Print outputs to the Immediate window

Also, you can simply type ? and then a statement directly into the immediate window (and then press Enter) and have the output appear right below, like this:

simply type ? and then a statement directly into the immediate window

This can be very handy to quickly output the property of an object...

? myWidget.name

...to set the property of an object...

myWidget.name = "thingy"

...or to even execute a function or line of code, while in debugging mode:

Sheet1.MyFunction()

What's a quick way to comment/uncomment lines in Vim?

I mark the first and last lines (ma and mb), and then do :'a,'bs/^# //

Create a Maven project in Eclipse complains "Could not resolve archetype"

You can resolve it by configuring settings.xml in Eclipse.

Go to Window --> Preferences --> Maven --> User Settings --> select the actual path of settings.xml

Can I set an opacity only to the background image of a div?

I implemented Marcus Ekwall's solution but was able to remove a few things to make it simpler and it still works. Maybe 2017 version of html/css?

html:

<div id="content">
  <div id='bg'></div>
  <h2>What is Lorem Ipsum?</h2>
  <p><strong>Lorem Ipsum</strong> 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 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 software like Aldus PageMaker including versions of Lorem Ipsum.</p>
</div>

css:

#content {
  text-align: left;
  width: 75%;
  margin: auto;
  position: relative;
}

#bg {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: url('https://static.pexels.com/photos/6644/sea-water-ocean-waves.jpg') center center;
  opacity: .4;
  width: 100%;
  height: 100%;
}

https://jsfiddle.net/abalter/3te9fjL5/

Execute method on startup in Spring

Posted another solution that implements WebApplicationInitializer and is called much before any spring bean is instantiated, in case someone has that use case

Initialize default Locale and Timezone with Spring configuration

Python name 'os' is not defined

The problem is that you forgot to import os. Add this line of code:

import os

And everything should be fine. Hope this helps!