Programs & Examples On #Process management

GIT vs. Perforce- Two VCS will enter... one will leave

The command that sold me on git personally was bisect. I don't think that this feature is available in any other version control system as of now.

That being said, if people are used to a GUI client for source control they are not going to be impressed with git. Right now the only full-featured client is command-line.

How to find the process id of a running Java process on Windows? And how to kill the process alone?

In windows XP and later, there's a command: tasklist that lists all process id's.

For killing a process in Windows, see:

Really killing a process in Windows | Stack Overflow

You can execute OS-commands in Java by:

Runtime.getRuntime().exec("your command here");

If you need to handle the output of a command, see example: using Runtime.exec() in Java

Tracking CPU and Memory usage per process

Perfmon.exe is built into windows.

How to display an activity indicator with text on iOS 8 with Swift?

Xcode 9.0 • Swift 4.0


import UIKit
class ViewController: UIViewController, UINavigationControllerDelegate, UIImagePickerControllerDelegate {
    @IBOutlet weak var imageView: UIImageView!
    @IBOutlet weak var filterButton: UIButton!
    @IBOutlet weak var saveButton: UIButton!
    let destinationUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
        .appendingPathComponent("filteredImage.png")
    let imagePicker = UIImagePickerController()
    let messageFrame = UIView()
    var activityIndicator = UIActivityIndicatorView()
    var strLabel = UILabel()
    let effectView = UIVisualEffectView(effect: UIBlurEffect(style: .dark))
    func activityIndicator(_ title: String) {
        strLabel.removeFromSuperview()
        activityIndicator.removeFromSuperview()
        effectView.removeFromSuperview()
        strLabel = UILabel(frame: CGRect(x: 50, y: 0, width: 160, height: 46))
        strLabel.text = title
        strLabel.font = .systemFont(ofSize: 14, weight: .medium)
        strLabel.textColor = UIColor(white: 0.9, alpha: 0.7)
        effectView.frame = CGRect(x: view.frame.midX - strLabel.frame.width/2, y: view.frame.midY - strLabel.frame.height/2 , width: 160, height: 46)
        effectView.layer.cornerRadius = 15
        effectView.layer.masksToBounds = true
        activityIndicator = UIActivityIndicatorView(activityIndicatorStyle: .white)
        activityIndicator.frame = CGRect(x: 0, y: 0, width: 46, height: 46)
        activityIndicator.startAnimating()
        effectView.contentView.addSubview(activityIndicator)
        effectView.contentView.addSubview(strLabel)
        view.addSubview(effectView)
    }
    func saveImage() {
        do {
            try imageView.image?.data?.write(to: destinationUrl, options: .atomic)
            print("file saved")
        } catch {
            print(error)
        }
    }        
    func applyFilterToImage() {
        imageView.image = imageView.image?.applying(contrast: 1.5)
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        guard let url = URL(string: "https://upload.wikimedia.org/wikipedia/commons/a/a8/VST_images_the_Lagoon_Nebula.jpg"), let data = try? Data(contentsOf: url), let image = UIImage(data: data) else { return }
        view.backgroundColor = UIColor(white: 0, alpha: 1)
        imageView.image = image
    }
    @IBAction func startSavingImage(_ sender: AnyObject) {
        saveButton.isEnabled = false
        filterButton.isEnabled = false
        activityIndicator("Saving Image")
        DispatchQueue.main.async {
            self.saveImage()
            DispatchQueue.main.async {
                self.effectView.removeFromSuperview()
                self.saveButton.isEnabled = true
                self.filterButton.isEnabled = true
            }
        }
    }
    @IBAction func filterAction(_ sender: AnyObject) {
        filterButton.isEnabled = false
        saveButton.isEnabled = false
        activityIndicator("Applying Filter")
        DispatchQueue.main.async {
            self.applyFilterToImage()
            DispatchQueue.main.async {
                self.effectView.removeFromSuperview()
                self.filterButton.isEnabled = true
                self.saveButton.isEnabled = true
            }
        }
    }
    @IBAction func cameraAction(_ sender: AnyObject) {
        if UIImagePickerController.isSourceTypeAvailable(.camera) {
            imagePicker.delegate = self
            imagePicker.sourceType = .camera
            present(imagePicker, animated: true)
        }
    }
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingImage image: UIImage!, editingInfo: [AnyHashable: Any]!) {
        dismiss(animated: true, completion: nil)
        imageView.image = image
    }
}

extension Data {
    var image: UIImage? { return UIImage(data: self) }
}

extension UIImage {
    var data: Data? { return UIImagePNGRepresentation(self) }
    func applying(contrast value: NSNumber) -> UIImage? {
        guard let ciImage = CIImage(image: self)?.applyingFilter("CIColorControls", withInputParameters: [kCIInputContrastKey: value]) else { return nil }
        UIGraphicsBeginImageContextWithOptions(size, false, scale)
        defer { UIGraphicsEndImageContext() }
        UIImage(ciImage: ciImage).draw(in: CGRect(origin: .zero, size: size))
        return UIGraphicsGetImageFromCurrentImageContext()
    }
}

Getting All Variables In Scope

If you just want to inspect the variables manually to help debug, just fire up the debugger:

debugger;

Straight into the browser console.

is there something like isset of php in javascript/jQuery?

The problem is that passing an undefined variable to a function causes an error.

This means you have to run typeof before passing it as an argument.

The cleanest way I found to do this is like so:

function isset(v){
    if(v === 'undefined'){
        return false;
    }
    return true;
}

Usage:

if(isset(typeof(varname))){
  alert('is set');
} else {
  alert('not set');
}

Now the code is much more compact and readable.

This will still give an error if you try to call a variable from a non instantiated variable like:

isset(typeof(undefVar.subkey))

thus before trying to run this you need to make sure the object is defined:

undefVar = isset(typeof(undefVar))?undefVar:{};

How to refresh app upon shaking the device?

 package com.example.shakingapp;

import android.app.Activity;
import android.graphics.Color;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;


public class MainActivity extends Activity implements SensorEventListener {
  private SensorManager sensorManager;
  private boolean color = false;
  private View view;
  private long lastUpdate;


/** Called when the activity is first created. */

  @Override
  public void onCreate(Bundle savedInstanceState) {
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
        WindowManager.LayoutParams.FLAG_FULLSCREEN);

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    view = findViewById(R.id.textView);
    view.setBackgroundColor(Color.GREEN);

    sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
    lastUpdate = System.currentTimeMillis();
  }

  @Override
  public void onSensorChanged(SensorEvent event) {
    if (event.sensor.getType() == Sensor.TYPE_ACCELEROMETER) {
      getAccelerometer(event);
    }

  }

  private void getAccelerometer(SensorEvent event) {
    float[] values = event.values;
    // Movement
    float x = values[0];
    float y = values[1];
    float z = values[2];

    System.out.println(x);
    System.out.println(y);
    System.out.println(z);
    System.out.println(SensorManager.GRAVITY_EARTH );

    float accelationSquareRoot = (x * x + y * y + z * z)
        / (SensorManager.GRAVITY_EARTH * SensorManager.GRAVITY_EARTH);

    long actualTime = System.currentTimeMillis();
    if (accelationSquareRoot >= 2) //
    {
      if (actualTime - lastUpdate < 200) {
        return;
      }
      lastUpdate = actualTime;
      Toast.makeText(this, "Device was shuffed "+accelationSquareRoot, Toast.LENGTH_SHORT)
          .show();
      if (color) {
        view.setBackgroundColor(Color.GREEN);

      } else {
        view.setBackgroundColor(Color.RED);
      }
      color = !color;
    }
  }

  @Override
  public void onAccuracyChanged(Sensor sensor, int accuracy) {

  }

  @Override
  protected void onResume() {
    super.onResume();
    // register this class as a listener for the orientation and
    // accelerometer sensors
    sensorManager.registerListener(this,
        sensorManager.getDefaultSensor(Sensor.TYPE_ACCELEROMETER),
        SensorManager.SENSOR_DELAY_NORMAL);
  }

  @Override
  protected void onPause() {
    // unregister listener
    super.onPause();
    sensorManager.unregisterListener(this);
  }
} 

Find and replace strings in vim on multiple lines

In vim if you are confused which all lines will be affected, Use below

 :%s/foo/bar/gc  

Change each 'foo' to 'bar', but ask for confirmation first. Press 'y' for yes and 'n' for no. Dont forget to save after that

:wq

How to use System.Net.HttpClient to post a complex type?

The generic HttpRequestMessage<T> has been removed. This :

new HttpRequestMessage<Widget>(widget)

will no longer work.

Instead, from this post, the ASP.NET team has included some new calls to support this functionality:

HttpClient.PostAsJsonAsync<T>(T value) sends “application/json”
HttpClient.PostAsXmlAsync<T>(T value) sends “application/xml”

So, the new code (from dunston) becomes:

Widget widget = new Widget()
widget.Name = "test"
widget.Price = 1;

HttpClient client = new HttpClient();
client.BaseAddress = new Uri("http://localhost:44268");
client.PostAsJsonAsync("api/test", widget)
    .ContinueWith((postTask) => postTask.Result.EnsureSuccessStatusCode() );

Group by multiple field names in java 8

Hi You can simply concatenate your groupingByKey such as

Map<String, List<Person>> peopleBySomeKey = people
                .collect(Collectors.groupingBy(p -> getGroupingByKey(p), Collectors.mapping((Person p) -> p, toList())));



//write getGroupingByKey() function
private String getGroupingByKey(Person p){
return p.getAge()+"-"+p.getName();
}

how to draw a rectangle in HTML or CSS?

Fiddle

HTML

<div id="rectangle"></div>

CSS

#rectangle{
    width:200px;
    height:100px;
    background:blue;
}

I strongly suggest you read about CSS selectors and the basics of HTML.

How to define and use function inside Jenkins Pipeline config?

Solved! The call build job: project, parameters: params fails with an error java.lang.UnsupportedOperationException: must specify $class with an implementation of interface java.util.List when params = [:]. Replacing it with params = null solved the issue. Here the working code below.

def doCopyMibArtefactsHere(projectName) {
    step ([
        $class: 'CopyArtifact',
        projectName: projectName,
        filter: '**/**.mib',
        fingerprintArtifacts: true, 
        flatten: true
    ]);
}

def BuildAndCopyMibsHere(projectName, params = null) {
    build job: project, parameters: params
    doCopyMibArtefactsHere(projectName)
}
node { 
    stage('Prepare Mib'){
        BuildAndCopyMibsHere('project1')
    }
}

downcast and upcast

Upcasting and Downcasting:

Upcasting: Casting from Derived-Class to Base Class Downcasting: Casting from Base Class to Derived Class

Let's understand the same as an example:

Consider two classes Shape as My parent class and Circle as a Derived class, defined as follows:

class Shape
{
    public int Width { get; set; }
    public int Height { get; set; }
}

class Circle : Shape
{
    public int Radius { get; set; }
    public bool FillColor { get; set; }
}

Upcasting:

Shape s = new Shape();

Circle c= s;

Both c and s are referencing to the same memory location, but both of them have different views i.e using "c" reference you can access all the properties of the base class and derived class as well but using "s" reference you can access properties of the only parent class.

A practical example of upcasting is Stream class which is baseclass of all types of stream reader of .net framework:

StreamReader reader = new StreamReader(new FileStreamReader());

here, FileStreamReader() is upcasted to streadm reder.

Downcasting:

Shape s = new Circle(); here as explained above, view of s is the only parent, in order to make it for both parent and a child we need to downcast it

var c = (Circle) s;

The practical example of Downcasting is button class of WPF.

Rock, Paper, Scissors Game Java

I would recommend making Rock, Paper and Scissors objects. The objects would have the logic of both translating to/from Strings and also "knowing" what beats what. The Java enum is perfect for this.

public enum Type{

  ROCK, PAPER, SCISSOR;

  public static Type parseType(String value){
     //if /else logic here to return either ROCK, PAPER or SCISSOR

     //if value is not either, you can return null
  }
}

The parseType method can return null if the String is not a valid type. And you code can check if the value is null and if so, print "invalid try again" and loop back to re-read the Scanner.

Type person=null;

 while(person==null){
      System.out.println("Enter your play: "); 
      person= Type.parseType(scan.next());
      if(person ==null){
         System.out.println("invalid try again");
      }
 }

Furthermore, your type enum can determine what beats what by having each Type object know:

public enum Type{

    //...

    //each type will implement this method differently
    public abstract boolean beats(Type other);


}

each type will implement this method differently to see what beats what:

ROCK{

   @Override
   public boolean beats(Type other){            
        return other ==  SCISSOR;

   }
}

 ...

Then in your code

 Type person, computer;
   if (person.equals(computer)) 
   System.out.println("It's a tie!");
  }else if(person.beats(computer)){
     System.out.println(person+ " beats " + computer + "You win!!"); 
  }else{
     System.out.println(computer + " beats " + person+ "You lose!!");
  }

Getting Serial Port Information

I'm not quite sure what you mean by "sorting the items after index 0", but if you just want to sort the array of strings returned by SerialPort.GetPortNames(), you can use Array.Sort.

Descending order by date filter in AngularJs

see w3schools samples: https://www.w3schools.com/angular/angular_filters.asp https://www.w3schools.com/angular/tryit.asp?filename=try_ng_filters_orderby_click

then add the "reverse" flag:

<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.4/angular.min.js"></script>
<body>

<p>Click the table headers to change the sorting order:</p>

<div ng-app="myApp" ng-controller="namesCtrl">

<table border="1" width="100%">
<tr>
<th ng-click="orderByMe('name')">Name</th>
<th ng-click="orderByMe('country')">Country</th>
</tr>
<tr ng-repeat="x in names | orderBy:myOrderBy:reverse">
<td>{{x.name}}</td>
<td>{{x.country}}</td>
</tr>
</table>

</div>

<script>
angular.module('myApp', []).controller('namesCtrl', function($scope) {
    $scope.names = [
        {name:'Jani',country:'Norway'},
        {name:'Carl',country:'Sweden'},
        {name:'Margareth',country:'England'},
        {name:'Hege',country:'Norway'},
        {name:'Joe',country:'Denmark'},
        {name:'Gustav',country:'Sweden'},
        {name:'Birgit',country:'Denmark'},
        {name:'Mary',country:'England'},
        {name:'Kai',country:'Norway'}
        ];

    $scope.reverse=false;
    $scope.orderByMe = function(x) {

        if($scope.myOrderBy == x) {
            $scope.reverse=!$scope.reverse;
        }
        $scope.myOrderBy = x;
    }
});
</script>

</body>
</html>

get the selected index value of <select> tag in php

As you said..

$Gender  = isset($_POST["gender"]); ' it returns a empty string 

because, you haven't mention method type either use POST or GET, by default it will use GET method. On the other side, you are trying to retrieve your value by using POST method, but in the form you haven't mentioned POST method. Which means miss-match method will result for empty.

Try this code..

<form name="signup_form"  action="./signup.php" onsubmit="return validateForm()"   method="post">
<table> 
  <tr> <td> First Name    </td><td> <input type="text" name="fname" size=10/></td></tr>
  <tr> <td> Last Name     </td><td> <input type="text" name="lname" size=10/></td></tr>
  <tr> <td> Your Email    </td><td> <input type="text" name="email" size=10/></td></tr>
  <tr> <td> Re-type Email </td><td> <input type="text" name="remail"size=10/></td></tr>
  <tr> <td> Password      </td><td> <input type="password" name="paswod" size=10/> </td></tr>
  <tr> <td> Gender        </td><td> <select name="gender">
  <option value="select">                Select </option>    
  <option value="male">   Male   </option>
  <option value="female"> Female </option></select></td></tr> 
  <tr> <td> <input type="submit" value="Sign up" id="signup"/> </td> </tr>
 </table>
 </form>

and on signup page

$Gender  = $_POST["gender"];

i'm sure.. now, you will get the value..

Reverse Y-Axis in PyPlot

You could also use function exposed by the axes object of the scatter plot

scatter = plt.scatter(x, y)
ax = scatter.axes
ax.invert_xaxis()
ax.invert_yaxis()

configuring project ':app' failed to find Build Tools revision

It happens because Build Tools revision 24.4.1 doesn't exist.

The latest version is 23.0.2.
These tools is included in the SDK package and installed in the <sdk>/build-tools/ directory.

Don't confuse the Android SDK Tools with SDK Build Tools.

Change in your build.gradle

android {
   buildToolsVersion "23.0.2"
   // ...

}

Adding maven nexus repo to my pom.xml

It seems the answers here do not support an enterprise use case where a Nexus server has multiple users and has project-based isolation (protection) based on user id ALONG with using an automated build (CI) system like Jenkins. You would not be able to create a settings.xml file to satisfy the different user ids needed for different projects. I am not sure how to solve this, except by opening Nexus up to anonymous access for reading repositories, unless the projects could store a project-specific generic user id in their pom.xml.

Create code first, many to many, with additional fields in association table

It's not possible to create a many-to-many relationship with a customized join table. In a many-to-many relationship EF manages the join table internally and hidden. It's a table without an Entity class in your model. To work with such a join table with additional properties you will have to create actually two one-to-many relationships. It could look like this:

public class Member
{
    public int MemberID { get; set; }

    public string FirstName { get; set; }
    public string LastName { get; set; }

    public virtual ICollection<MemberComment> MemberComments { get; set; }
}

public class Comment
{
    public int CommentID { get; set; }
    public string Message { get; set; }

    public virtual ICollection<MemberComment> MemberComments { get; set; }
}

public class MemberComment
{
    [Key, Column(Order = 0)]
    public int MemberID { get; set; }
    [Key, Column(Order = 1)]
    public int CommentID { get; set; }

    public virtual Member Member { get; set; }
    public virtual Comment Comment { get; set; }

    public int Something { get; set; }
    public string SomethingElse { get; set; }
}

If you now want to find all comments of members with LastName = "Smith" for example you can write a query like this:

var commentsOfMembers = context.Members
    .Where(m => m.LastName == "Smith")
    .SelectMany(m => m.MemberComments.Select(mc => mc.Comment))
    .ToList();

... or ...

var commentsOfMembers = context.MemberComments
    .Where(mc => mc.Member.LastName == "Smith")
    .Select(mc => mc.Comment)
    .ToList();

Or to create a list of members with name "Smith" (we assume there is more than one) along with their comments you can use a projection:

var membersWithComments = context.Members
    .Where(m => m.LastName == "Smith")
    .Select(m => new
    {
        Member = m,
        Comments = m.MemberComments.Select(mc => mc.Comment)
    })
    .ToList();

If you want to find all comments of a member with MemberId = 1:

var commentsOfMember = context.MemberComments
    .Where(mc => mc.MemberId == 1)
    .Select(mc => mc.Comment)
    .ToList();

Now you can also filter by the properties in your join table (which would not be possible in a many-to-many relationship), for example: Filter all comments of member 1 which have a 99 in property Something:

var filteredCommentsOfMember = context.MemberComments
    .Where(mc => mc.MemberId == 1 && mc.Something == 99)
    .Select(mc => mc.Comment)
    .ToList();

Because of lazy loading things might become easier. If you have a loaded Member you should be able to get the comments without an explicit query:

var commentsOfMember = member.MemberComments.Select(mc => mc.Comment);

I guess that lazy loading will fetch the comments automatically behind the scenes.

Edit

Just for fun a few examples more how to add entities and relationships and how to delete them in this model:

1) Create one member and two comments of this member:

var member1 = new Member { FirstName = "Pete" };
var comment1 = new Comment { Message = "Good morning!" };
var comment2 = new Comment { Message = "Good evening!" };
var memberComment1 = new MemberComment { Member = member1, Comment = comment1,
                                         Something = 101 };
var memberComment2 = new MemberComment { Member = member1, Comment = comment2,
                                         Something = 102 };

context.MemberComments.Add(memberComment1); // will also add member1 and comment1
context.MemberComments.Add(memberComment2); // will also add comment2

context.SaveChanges();

2) Add a third comment of member1:

var member1 = context.Members.Where(m => m.FirstName == "Pete")
    .SingleOrDefault();
if (member1 != null)
{
    var comment3 = new Comment { Message = "Good night!" };
    var memberComment3 = new MemberComment { Member = member1,
                                             Comment = comment3,
                                             Something = 103 };

    context.MemberComments.Add(memberComment3); // will also add comment3
    context.SaveChanges();
}

3) Create new member and relate it to the existing comment2:

var comment2 = context.Comments.Where(c => c.Message == "Good evening!")
    .SingleOrDefault();
if (comment2 != null)
{
    var member2 = new Member { FirstName = "Paul" };
    var memberComment4 = new MemberComment { Member = member2,
                                             Comment = comment2,
                                             Something = 201 };

    context.MemberComments.Add(memberComment4);
    context.SaveChanges();
}

4) Create relationship between existing member2 and comment3:

var member2 = context.Members.Where(m => m.FirstName == "Paul")
    .SingleOrDefault();
var comment3 = context.Comments.Where(c => c.Message == "Good night!")
    .SingleOrDefault();
if (member2 != null && comment3 != null)
{
    var memberComment5 = new MemberComment { Member = member2,
                                             Comment = comment3,
                                             Something = 202 };

    context.MemberComments.Add(memberComment5);
    context.SaveChanges();
}

5) Delete this relationship again:

var memberComment5 = context.MemberComments
    .Where(mc => mc.Member.FirstName == "Paul"
        && mc.Comment.Message == "Good night!")
    .SingleOrDefault();
if (memberComment5 != null)
{
    context.MemberComments.Remove(memberComment5);
    context.SaveChanges();
}

6) Delete member1 and all its relationships to the comments:

var member1 = context.Members.Where(m => m.FirstName == "Pete")
    .SingleOrDefault();
if (member1 != null)
{
    context.Members.Remove(member1);
    context.SaveChanges();
}

This deletes the relationships in MemberComments too because the one-to-many relationships between Member and MemberComments and between Comment and MemberComments are setup with cascading delete by convention. And this is the case because MemberId and CommentId in MemberComment are detected as foreign key properties for the Member and Comment navigation properties and since the FK properties are of type non-nullable int the relationship is required which finally causes the cascading-delete-setup. Makes sense in this model, I think.

Styling a disabled input with css only

Use this CSS (jsFiddle example):

input:disabled.btn:hover,
input:disabled.btn:active,
input:disabled.btn:focus {
  color: green
}

You have to write the most outer element on the left and the most inner element on the right.

.btn:hover input:disabled would select any disabled input elements contained in an element with a class btn which is currently hovered by the user.

I would prefer :disabled over [disabled], see this question for a discussion: Should I use CSS :disabled pseudo-class or [disabled] attribute selector or is it a matter of opinion?


By the way, Laravel (PHP) generates the HTML - not the browser.

Xcode source automatic formatting

Swift - https://github.com/nicklockwood/SwiftFormat

It provides Xcode Extension as well as CLI option.

What does "Git push non-fast-forward updates were rejected" mean?

You need to merge and resolve the conflicts locally before you push your changes to remote repo/fork.

1) pull (fetch and merge)

$ git pull remote branch 

2) Push the changes

$ git push remote branch 

Still you have a quick choice to push forcibly by using --force option but should be avoided as it may result in changes loss or affect badly on other contributors.

How to get duration, as int milli's and float seconds from <chrono>?

In AAA style using the explicitly typed initializer idiom:

#include <chrono>
#include <iostream>

int main(){
  auto start = std::chrono::high_resolution_clock::now();
  // Code to time here...
  auto end = std::chrono::high_resolution_clock::now();

  auto dur = end - start;
  auto i_millis = std::chrono::duration_cast<std::chrono::milliseconds>(dur);
  auto f_secs = std::chrono::duration_cast<std::chrono::duration<float>>(dur);
  std::cout << i_millis.count() << '\n';
  std::cout << f_secs.count() << '\n';
}

TypeScript or JavaScript type casting

This is called type assertion in TypeScript, and since TypeScript 1.6, there are two ways to express this:

// Original syntax
var markerSymbolInfo = <MarkerSymbolInfo> symbolInfo;

// Newer additional syntax
var markerSymbolInfo = symbolInfo as MarkerSymbolInfo;

Both alternatives are functionally identical. The reason for introducing the as-syntax is that the original syntax conflicted with JSX, see the design discussion here.

If you are in a position to choose, just use the syntax that you feel more comfortable with. I personally prefer the as-syntax as it feels more fluent to read and write.

Disable Tensorflow debugging information

To add some flexibility here, you can achieve more fine-grained control over the level of logging by writing a function that filters out messages however you like:

logging.getLogger('tensorflow').addFilter(my_filter_func)

where my_filter_func accepts a LogRecord object as input [LogRecord docs] and returns zero if you want the message thrown out; nonzero otherwise.

Here's an example filter that only keeps every nth info message (Python 3 due to the use of nonlocal here):

def keep_every_nth_info(n):
    i = -1
    def filter_record(record):
        nonlocal i
        i += 1
        return int(record.levelname != 'INFO' or i % n == 0)
    return filter_record

# Example usage for TensorFlow:
logging.getLogger('tensorflow').addFilter(keep_every_nth_info(5))

All of the above has assumed that TensorFlow has set up its logging state already. You can ensure this without side effects by calling tf.logging.get_verbosity() before adding a filter.

Difference between abstract class and interface in Python

What you'll see sometimes is the following:

class Abstract1( object ):
    """Some description that tells you it's abstract,
    often listing the methods you're expected to supply."""
    def aMethod( self ):
        raise NotImplementedError( "Should have implemented this" )

Because Python doesn't have (and doesn't need) a formal Interface contract, the Java-style distinction between abstraction and interface doesn't exist. If someone goes through the effort to define a formal interface, it will also be an abstract class. The only differences would be in the stated intent in the docstring.

And the difference between abstract and interface is a hairsplitting thing when you have duck typing.

Java uses interfaces because it doesn't have multiple inheritance.

Because Python has multiple inheritance, you may also see something like this

class SomeAbstraction( object ):
    pass # lots of stuff - but missing something

class Mixin1( object ):
    def something( self ):
        pass # one implementation

class Mixin2( object ):
    def something( self ):
        pass # another

class Concrete1( SomeAbstraction, Mixin1 ):
    pass

class Concrete2( SomeAbstraction, Mixin2 ):
    pass

This uses a kind of abstract superclass with mixins to create concrete subclasses that are disjoint.

Checking if type == list in python

This seems to work for me:

>>>a = ['x', 'y', 'z']
>>>type(a)
<class 'list'>
>>>isinstance(a, list)
True

How Can I Bypass the X-Frame-Options: SAMEORIGIN HTTP Header?

Yes Fiddler is an option for me:

  1. Open Fiddler menu > Rules > Customize Rules (this effectively edits CustomRules.js).
  2. Find the function OnBeforeResponse
  3. Add the following lines:

    oSession.oResponse.headers.Remove("X-Frame-Options");
    oSession.oResponse.headers.Add("Access-Control-Allow-Origin", "*");
    
  4. Remember to save the script!

How to find if directory exists in Python

Just to provide the os.stat version (python 2):

import os, stat, errno
def CheckIsDir(directory):
  try:
    return stat.S_ISDIR(os.stat(directory).st_mode)
  except OSError, e:
    if e.errno == errno.ENOENT:
      return False
    raise

How to convert an ASCII character into an int in C

It is not possible with the C99 standard library, unless you manually write a map from character constants to the corresponding ASCII int value.

Character constants in C like 'a' are not guaranteed to be ASCII.

C99 only makes some guarantees about those constants, e.g. that digits be contiguous.

The word ASCII only appears on the C99 N1256 standard draft in footer notes, and footer note 173) says:

In an implementation that uses the seven-bit US ASCII character set, the printing characters are those whose values lie from 0x20 (space) through 0x7E (tilde); the control characters are those whose values lie from 0 (NUL) through 0x1F (US), and the character 0x7F (DEL).

implying that ASCII is not the only possibility

AttributeError: 'module' object has no attribute 'urlopen'

To get 'dataX = urllib.urlopen(url).read()' working in python3 (this would have been correct for python2) you must just change 2 little things.

1: The urllib statement itself (add the .request in the middle):

dataX = urllib.request.urlopen(url).read()

2: The import statement preceding it (change from 'import urlib' to:

import urllib.request

And it should work in python3 :)

How do I move a redis database from one server to another?

To check where the dump.rdb has to be placed when importing redis data,

start client

$redis-cli

and

then

redis 127.0.0.1:6379> CONFIG GET *
 1) "dir"
 2) "/Users/Admin"

Here /Users/Admin is the location of dump.rdb that is read from server and therefore this is the file that has to be replaced.

Best practice for instantiating a new Android Fragment

Since the questions about best practice, I would add, that very often good idea to use hybrid approach for creating fragment when working with some REST web services

We can't pass complex objects, for example some User model, for case of displaying user fragment

But what we can do, is to check in onCreate that user!=null and if not - then bring him from data layer, otherwise - use existing.

This way we gain both ability to recreate by userId in case of fragment recreation by Android and snappiness for user actions, as well as ability to create fragments by holding to object itself or only it's id

Something likes this:

public class UserFragment extends Fragment {
    public final static String USER_ID="user_id";
    private User user;
    private long userId;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        userId = getArguments().getLong(USER_ID);
        if(user==null){
            //
            // Recreating here user from user id(i.e requesting from your data model,
            // which could be services, direct request to rest, or data layer sitting
            // on application model
            //
             user = bringUser();
        }
    }

    public static UserFragment newInstance(User user, long user_id){
        UserFragment userFragment = new UserFragment();
        Bundle args = new Bundle();
        args.putLong(USER_ID,user_id);
        if(user!=null){
            userFragment.user=user;
        }
        userFragment.setArguments(args);
        return userFragment;

    }

    public static UserFragment newInstance(long user_id){
        return newInstance(null,user_id);
    }

    public static UserFragment newInstance(User user){
        return newInstance(user,user.id);
    }
}

How to compare two dates?

Other answers using datetime and comparisons also work for time only, without a date.

For example, to check if right now it is more or less than 8:00 a.m., we can use:

import datetime

eight_am = datetime.time( 8,0,0 ) # Time, without a date

And later compare with:

datetime.datetime.now().time() > eight_am  

which will return True

How do I iterate through table rows and cells in JavaScript?

Try

for (let row of mytab1.rows) 
{
    for(let cell of row.cells) 
    {
       let val = cell.innerText; // your code below
    }
}

_x000D_
_x000D_
for (let row of mytab1.rows) _x000D_
{_x000D_
    for(let cell of row.cells) _x000D_
    {_x000D_
       console.log(cell.innerText)_x000D_
    }_x000D_
}
_x000D_
<div id="myTabDiv">_x000D_
<table name="mytab" id="mytab1">_x000D_
  <tr> _x000D_
    <td>col1 Val1</td>_x000D_
    <td>col2 Val2</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>col1 Val3</td>_x000D_
    <td>col2 Val4</td>_x000D_
  </tr>_x000D_
</table>_x000D_
</div>
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
for ( let [i,row] of [...mytab1.rows].entries() ) _x000D_
{_x000D_
    for( let [j,cell] of [...row.cells].entries() ) _x000D_
    {_x000D_
       console.log(`[${i},${j}] = ${cell.innerText}`)_x000D_
    }_x000D_
}
_x000D_
<div id="myTabDiv">_x000D_
<table name="mytab" id="mytab1">_x000D_
  <tr> _x000D_
    <td>col1 Val1</td>_x000D_
    <td>col2 Val2</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>col1 Val3</td>_x000D_
    <td>col2 Val4</td>_x000D_
  </tr>_x000D_
</table>_x000D_
</div>
_x000D_
_x000D_
_x000D_

What does T&& (double ampersand) mean in C++11?

It declares an rvalue reference (standards proposal doc).

Here's an introduction to rvalue references.

Here's a fantastic in-depth look at rvalue references by one of Microsoft's standard library developers.

CAUTION: the linked article on MSDN ("Rvalue References: C++0x Features in VC10, Part 2") is a very clear introduction to Rvalue references, but makes statements about Rvalue references that were once true in the draft C++11 standard, but are not true for the final one! Specifically, it says at various points that rvalue references can bind to lvalues, which was once true, but was changed.(e.g. int x; int &&rrx = x; no longer compiles in GCC) – drewbarbs Jul 13 '14 at 16:12

The biggest difference between a C++03 reference (now called an lvalue reference in C++11) is that it can bind to an rvalue like a temporary without having to be const. Thus, this syntax is now legal:

T&& r = T();

rvalue references primarily provide for the following:

Move semantics. A move constructor and move assignment operator can now be defined that takes an rvalue reference instead of the usual const-lvalue reference. A move functions like a copy, except it is not obliged to keep the source unchanged; in fact, it usually modifies the source such that it no longer owns the moved resources. This is great for eliminating extraneous copies, especially in standard library implementations.

For example, a copy constructor might look like this:

foo(foo const& other)
{
    this->length = other.length;
    this->ptr = new int[other.length];
    copy(other.ptr, other.ptr + other.length, this->ptr);
}

If this constructor was passed a temporary, the copy would be unnecessary because we know the temporary will just be destroyed; why not make use of the resources the temporary already allocated? In C++03, there's no way to prevent the copy as we cannot determine we were passed a temporary. In C++11, we can overload a move constructor:

foo(foo&& other)
{
   this->length = other.length;
   this->ptr = other.ptr;
   other.length = 0;
   other.ptr = nullptr;
}

Notice the big difference here: the move constructor actually modifies its argument. This would effectively "move" the temporary into the object being constructed, thereby eliminating the unnecessary copy.

The move constructor would be used for temporaries and for non-const lvalue references that are explicitly converted to rvalue references using the std::move function (it just performs the conversion). The following code both invoke the move constructor for f1 and f2:

foo f1((foo())); // Move a temporary into f1; temporary becomes "empty"
foo f2 = std::move(f1); // Move f1 into f2; f1 is now "empty"

Perfect forwarding. rvalue references allow us to properly forward arguments for templated functions. Take for example this factory function:

template <typename T, typename A1>
std::unique_ptr<T> factory(A1& a1)
{
    return std::unique_ptr<T>(new T(a1));
}

If we called factory<foo>(5), the argument will be deduced to be int&, which will not bind to a literal 5, even if foo's constructor takes an int. Well, we could instead use A1 const&, but what if foo takes the constructor argument by non-const reference? To make a truly generic factory function, we would have to overload factory on A1& and on A1 const&. That might be fine if factory takes 1 parameter type, but each additional parameter type would multiply the necessary overload set by 2. That's very quickly unmaintainable.

rvalue references fix this problem by allowing the standard library to define a std::forward function that can properly forward lvalue/rvalue references. For more information about how std::forward works, see this excellent answer.

This enables us to define the factory function like this:

template <typename T, typename A1>
std::unique_ptr<T> factory(A1&& a1)
{
    return std::unique_ptr<T>(new T(std::forward<A1>(a1)));
}

Now the argument's rvalue/lvalue-ness is preserved when passed to T's constructor. That means that if factory is called with an rvalue, T's constructor is called with an rvalue. If factory is called with an lvalue, T's constructor is called with an lvalue. The improved factory function works because of one special rule:

When the function parameter type is of the form T&& where T is a template parameter, and the function argument is an lvalue of type A, the type A& is used for template argument deduction.

Thus, we can use factory like so:

auto p1 = factory<foo>(foo()); // calls foo(foo&&)
auto p2 = factory<foo>(*p1);   // calls foo(foo const&)

Important rvalue reference properties:

  • For overload resolution, lvalues prefer binding to lvalue references and rvalues prefer binding to rvalue references. Hence why temporaries prefer invoking a move constructor / move assignment operator over a copy constructor / assignment operator.
  • rvalue references will implicitly bind to rvalues and to temporaries that are the result of an implicit conversion. i.e. float f = 0f; int&& i = f; is well formed because float is implicitly convertible to int; the reference would be to a temporary that is the result of the conversion.
  • Named rvalue references are lvalues. Unnamed rvalue references are rvalues. This is important to understand why the std::move call is necessary in: foo&& r = foo(); foo f = std::move(r);

Using Ajax.BeginForm with ASP.NET MVC 3 Razor

Example

//In Model

public class MyModel
{  
   [Required]
    public string Name{ get; set; }
}

//In PartailView //PartailView.cshtml

@model MyModel

<div>
    <div>
      @Html.LabelFor(model=>model.Name)
    </div>
    <div>
        @Html.EditorFor(model=>model.Name)
        @Html.ValidationMessageFor(model => model.Name)
    </div>
</div>

In Index.cshtml view

@model MyModel
<div id="targetId">
    @{Html.RenderPartial("PartialView",Model)}
</div>

@using(Ajax.BeginForm("AddName", new AjaxOptions { UpdateTargetId = "targetId", HttpMethod = "Post" }))
{
     <div>
        <input type="submit" value="Add Unit" />
    </div>
}

In Controller

public ActionResult Index()
{
  return View(new MyModel());
}


public string AddName(MyModel model)
{
   string HtmlString = RenderPartialViewToString("PartailView",model);
   return HtmlString;
}


protected string RenderPartialViewToString(string viewName, object model)
        {
            if (string.IsNullOrEmpty(viewName))
                viewName = ControllerContext.RouteData.GetRequiredString("action");

            ViewData.Model = model;

            using (StringWriter sw = new StringWriter())
            {
                ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
                ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
                viewResult.View.Render(viewContext, sw);
                return sw.GetStringBuilder().ToString();
            }
        }

you must be pass ViewName and Model to RenderPartialViewToString method. it will return you view with validation which are you applied in model and append the content in "targetId" div in Index.cshtml. I this way by catching RenderHtml of partial view you can apply validation.

How to save and load cookies using Python + Selenium WebDriver

This is a solution that saves the profile directory for Firefox (similar to the user-data-dir (user data directory) in Chrome) (it involves manually copying the directory around. I haven't been able to find another way):

It was tested on Linux.


Short version:

  • To save the profile
driver.execute_script("window.close()")
time.sleep(0.5)
currentProfilePath = driver.capabilities["moz:profile"]
profileStoragePath = "/tmp/abc"
shutil.copytree(currentProfilePath, profileStoragePath,
                ignore_dangling_symlinks=True
                )
  • To load the profile
driver = Firefox(executable_path="geckodriver-v0.28.0-linux64",
                 firefox_profile=FirefoxProfile(profileStoragePath)
                )

Long version (with demonstration that it works and a lot of explanation -- see comments in the code)

The code uses localStorage for demonstration, but it works with cookies as well.

#initial imports

from selenium.webdriver import Firefox, FirefoxProfile

import shutil
import os.path
import time

# Create a new profile

driver = Firefox(executable_path="geckodriver-v0.28.0-linux64",
                  # * I'm using this particular version. If yours is
                  # named "geckodriver" and placed in system PATH
                  # then this is not necessary
                )

# Navigate to an arbitrary page and set some local storage
driver.get("https://DuckDuckGo.com")
assert driver.execute_script(r"""{
        const tmp = localStorage.a; localStorage.a="1";
        return [tmp, localStorage.a]
    }""") == [None, "1"]

# Make sure that the browser writes the data to profile directory.
# Choose one of the below methods
if 0:
    # Wait for some time for Firefox to flush the local storage to disk.
    # It's a long time. I tried 3 seconds and it doesn't work.
    time.sleep(10)

elif 1:
    # Alternatively:
    driver.execute_script("window.close()")
    # NOTE: It might not work if there are multiple windows!

    # Wait for a bit for the browser to clean up
    # (shutil.copytree might throw some weird error if the source directory changes while copying)
    time.sleep(0.5)

else:
    pass
    # I haven't been able to find any other, more elegant way.
    #`close()` and `quit()` both delete the profile directory


# Copy the profile directory (must be done BEFORE driver.quit()!)
currentProfilePath = driver.capabilities["moz:profile"]
assert os.path.isdir(currentProfilePath)
profileStoragePath = "/tmp/abc"
try:
    shutil.rmtree(profileStoragePath)
except FileNotFoundError:
    pass

shutil.copytree(currentProfilePath, profileStoragePath,
                ignore_dangling_symlinks=True # There's a lock file in the
                                              # profile directory that symlinks
                                              # to some IP address + port
               )

driver.quit()
assert not os.path.isdir(currentProfilePath)
# Selenium cleans up properly if driver.quit() is called,
# but not necessarily if the object is destructed


# Now reopen it with the old profile

driver=Firefox(executable_path="geckodriver-v0.28.0-linux64",
               firefox_profile=FirefoxProfile(profileStoragePath)
              )

# Note that the profile directory is **copied** -- see FirefoxProfile documentation
assert driver.profile.path!=profileStoragePath
assert driver.capabilities["moz:profile"]!=profileStoragePath

# Confusingly...
assert driver.profile.path!=driver.capabilities["moz:profile"]
# And only the latter is updated.
# To save it again, use the same method as previously mentioned

# Check the data is still there

driver.get("https://DuckDuckGo.com")

data = driver.execute_script(r"""return localStorage.a""")
assert data=="1", data

driver.quit()

assert not os.path.isdir(driver.capabilities["moz:profile"])
assert not os.path.isdir(driver.profile.path)

What doesn't work:

  • Initialize Firefox(capabilities={"moz:profile": "/path/to/directory"}) -- the driver will not be able to connect.
  • options=Options(); options.add_argument("profile"); options.add_argument("/path/to/directory"); Firefox(options=options) -- same as above.

Clearing Magento Log Data

Cleaning Logs via Magento Admin Panel

This method is easier for non technical store owners who don’t want’ to mess directly with the Magento store’s database. To activate log cleaning option in Magento just do the following:

Log on to your Magento Admin Panel. Go to System => Configuration. On the left under Advanced click on System (Advanced = > System). Under system you will see “Log Cleaning” option. Fill the desired “Log Cleaning” option values and click Save.

Cleaning Logs via phpMyAdmin

If you are comfortable with mysql and queries then this method is more efficient and quicker than default Magento Log Cleaning tool. This method also allows your to clean whatever you like, you can even clean tables which aren’t included in default Magento’s Log Cleaning tool.

Open the database in phpMyAdmin In the right frame, click on the boxes for the following tables: dataflow_batch_export

dataflow_batch_import

log_customer

log_quote

log_summary

log_summary_type

log_url

log_url_info

log_visitor

log_visitor_info

log_visitor_online

report_viewed_product_index

report_compared_product_index

report_event

Look to the bottom of the page, then click the drop down box that says “with selected” and click empty. Click Yes on confirmation screen, and this will truncate all the selected tables.

or you can use script to run

TRUNCATE dataflow_batch_export;
TRUNCATE dataflow_batch_import;
TRUNCATE log_customer;
TRUNCATE log_quote;
TRUNCATE log_summary;
TRUNCATE log_summary_type;
TRUNCATE log_url;
TRUNCATE log_url_info;
TRUNCATE log_visitor;
TRUNCATE log_visitor_info;
TRUNCATE log_visitor_online;
TRUNCATE report_viewed_product_index;
TRUNCATE report_compared_product_index;
TRUNCATE report_event;
TRUNCATE index_event;

Keep in mind that we are here to empty (Truncate) selected tables are not drop them. Be very careful when you do this.

Performing this regularly will definitely improve your Magento store’s performance and efficiency. You can setup up scripts to do this automatically at regular intervals too using “CRON”.

How to delete a stash created with git stash create?

git stash drop takes no parameter - which drops the top stash - or a stash reference which looks like: stash@{n} which n nominates which stash to drop. You can't pass a commit id to git stash drop.

git stash drop            # drop top hash, stash@{0}
git stash drop stash@{n}  # drop specific stash - see git stash list

Dropping a stash will change the stash@{n} designations of all stashes further down the stack.

I'm not sure why you think need to drop a stash because if you are using stash create a stash entry isn't created for your "stash" so there isn't anything to drop.

SCRIPT438: Object doesn't support property or method IE

Implement "use strict" in all script tags to find inconsistencies and fix potential unscoped variables!

Official way to ask jQuery wait for all images to load before executing something

For those who want to be notified of download completion of a single image that gets requested after $(window).load fires, you can use the image element's load event.

e.g.:

// create a dialog box with an embedded image
var $dialog = $("<div><img src='" + img_url + "' /></div>");

// get the image element (as a jQuery object)
var $imgElement = $dialog.find("img");

// wait for the image to load 
$imgElement.load(function() {
    alert("The image has loaded; width: " + $imgElement.width() + "px");
});

Cloning git repo causes error - Host key verification failed. fatal: The remote end hung up unexpectedly

The issue could be that Github isn't present in your ~/.ssh/known_hosts file.

Append GitHub to the list of authorized hosts:

ssh-keyscan -H github.com >> ~/.ssh/known_hosts

In a bootstrap responsive page how to center a div

without display table and without bootstrap , i would rather do that

<div class="container container-table">
    <div class="row vertical-center-row">
        <div class="text-center col-md-4 col-md-offset-4" style="background:red">TEXT</div>
    </div>
</div>


 html, body, .container-table {
    height: 100%;
}
.container-table {
    width:100vw;
  height:150px;
  border:1px solid black;
}
.vertical-center-row {
   margin:auto;
  width:30%;
  padding:63px;
  text-align:center;

}

http://codepen.io/matoeil/pen/PbbWgQ

Javascript format date / time

Please do not reinvent the wheel. There are many open-source & COTS solutions that already exist to solve this problem.

Please take a look at the following JavaScript libraries:


Demo

I wrote a one-liner using Moment.js below. You can check out the demo here: JSFiddle.

moment('2014-08-20 15:30:00').format('MM/DD/YYYY h:mm a'); // 08/20/2014 3:30 pm

Dots in URL causes 404 with ASP.NET mvc and IIS

I believe you have to set the property relaxedUrlToFileSystemMapping in your web.config. Haack wrote an article about this a little while ago (and there are some other SO posts asking the same types of question)

<system.web>
<httpRuntime relaxedUrlToFileSystemMapping="true" />

Edit From the comments below, later versions of .NET / IIS may require this to be in the system.WebServer element.

<system.webServer>
<httpRuntime relaxedUrlToFileSystemMapping="true" />

System.IO.IOException: file used by another process

 System.Drawing.Image FileUploadPhoto = System.Drawing.Image.FromFile(location1);
                                 FileUploadPhoto.Save(location2);
                                 FileUploadPhoto.Dispose();

How to split a large text file into smaller files with equal number of lines?

you can also use awk

awk -vc=1 'NR%200000==0{++c}{print $0 > c".txt"}' largefile

Web API Put Request generates an Http 405 Method Not Allowed error

So, I checked Windows Features to make sure I didn't have this thing called WebDAV installed, and it said I didn't. Anyways, I went ahead and placed the following in my web.config (both front end and WebAPI, just to be sure), and it works now. I placed this inside <system.webServer>.

<modules runAllManagedModulesForAllRequests="true">
    <remove name="WebDAVModule"/> <!-- add this -->
</modules>

Additionally, it is often required to add the following to web.config in the handlers. Thanks to Babak

<handlers>
    <remove name="WebDAV" />
    ...
</handlers>

Set left margin for a paragraph in html

<p style="margin-left:5em;">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet. Phasellus tempor nisi eget tellus venenatis tempus. Aliquam dapibus porttitor convallis. Praesent pretium luctus orci, quis ullamcorper lacus lacinia a. Integer eget molestie purus. Vestibulum porta mollis tempus. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. </p>

That'll do it, there's a few improvements obviously, but that's the basics. And I use 'em' as the measurement, you may want to use other units, like 'px'.

EDIT: What they're describing above is a way of associating groups of styles, or classes, with elements on a web page. You can implement that in a few ways, here's one which may suit you:

In your HTML page, containing the <p> tagged content from your DB add in a new 'style' node and wrap the styles you want to declare in a class like so:

<head>
  <style type="text/css">
    p { margin-left:5em; /* Or another measurement unit, like px */ }
  </style>
</head>
<body>
  <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet.</p>
</body>

So above, all <p> elements in your document will have that style rule applied. Perhaps you are pumping your paragraph content into a container of some sort? Try this:

<head>
  <style type="text/css">
    .container p { margin-left:5em; /* Or another measurement unit, like px */ }
  </style>
</head>
<body>
  <div class="container">
    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut lacinia vestibulum quam sit amet aliquet.</p>
  </div>
  <p>Vestibulum porta mollis tempus. Class aptent taciti sociosqu ad litora torquent per conubia nostra.</p>
</body>

In the example above, only the <p> element inside the div, whose class name is 'container', will have the styles applied - and not the <p> element outside the container.

In addition to the above, you can collect your styles together and remove the style element from the <head> tag, replacing it with a <link> tag, which points to an external CSS file. This external file is where you'd now put your <p> tag styles. This concept is known as 'seperating content from style' and is considered good practice, and is also an extendible way to create styles, and can help with low maintenance.

How to load/edit/run/save text files (.py) into an IPython notebook cell?

EDIT: Starting from IPython 3 (now Jupyter project), the notebook has a text editor that can be used as a more convenient alternative to load/edit/save text files.

A text file can be loaded in a notebook cell with the magic command %load.

If you execute a cell containing:

%load filename.py

the content of filename.py will be loaded in the next cell. You can edit and execute it as usual.

To save the cell content back into a file add the cell-magic %%writefile filename.py at the beginning of the cell and run it. Beware that if a file with the same name already exists it will be silently overwritten.

To see the help for any magic command add a ?: like %load? or %%writefile?.

For general help on magic functions type "%magic" For a list of the available magic functions, use %lsmagic. For a description of any of them, type %magic_name?, e.g. '%cd?'.

See also: Magic functions from the official IPython docs.

Automapper missing type map configuration or unsupported mapping - Error

I did this to remove the error:

Mapper.CreateMap<FacebookUser, ProspectModel>();
prospect = Mapper.Map(prospectFromDb, prospect);

Execute a batch file on a remote PC using a batch file on local PC

If you are in same WORKGROUP shutdown.exe /s /m \\<target-computer-name> should be enough shutdown /? for more, otherwise you need software to connect and control the target server.

UPDATE:

Seems shutdown.bat here is for shutting down apache-tomcat.

So, you might be interested to psexec or PuTTY: A Free Telnet/SSH Client

As native solution could be wmic

Example:

wmic /node:<target-computer-name> process call create "cmd.exe c:\\somefolder\\batch.bat"

In your example should be:

wmic /node:inidsoasrv01 process call create ^
    "cmd.exe D:\\apache-tomcat-6.0.20\\apache-tomcat-7.0.30\\bin\\shutdown.bat"

wmic /? and wmic /node /? for more

What is the difference between baud rate and bit rate?

Serial Data Speed:

Data rate (bps) = 1/Tb Tb is the time duration of 1 bit If the bit duration is 2ms then data rate is 1/2x10-3 , which is about 500 bps.

Baud rate:

Baud rate is defined as no. of signalling elements(symbols) in a given unit of time (say 1 sec) or it means number of time signal changes its state.When the signal is binary then baud rate and bit rate are same.

Bit rate:- Bit rate is nothing but number of bits transmitted per second.For example if Bit rate is 1000 bps then 1000 bits are i.e. 0s or 1s transmitted per second.

There are few other terms similar to this (i.e serial speed, bit rate, baud rate, USB transfer rate),and i guess(?) the values that are printed on serial monitor relates to serial speed, baud rate and USB transfer rate. Bit rate isn't an another term, please correct me if i am wrong, because serial monitor prints some values at an interval of time and value is definitely a set of bits. so if one value is printed i can say no of bits present in the respective value which gets printed on serial monitor per unit time will be the bit rate.

Using ResourceManager

The quick and dirty way to check what string you need it to look at the generated .resources files.

Your .resources are generated in the resources projects obj/Debug directory. (if not right click on .resx file in solution explorer and hit 'Run Custom Tool' to generate the .resources files)

Navigate to this directory and have a look at the filenames. You should see a file ending in XYZ.resources. Copy that filename and remove the trailing .resources and that is the file you should be loading.

For example in my obj/Bin directory I have the file:

MyLocalisation.Properties.Resources.resources

If the resource files are in the same Class library/Application I would use the following C#

ResourceManager RM = new ResourceManager("MyLocalisation.Properties.Resources", Assembly.GetExecutingAssembly());

However, as it sounds like you are using the resources file from a separate Class library/Application you probably want

Assembly localisationAssembly = Assembly.Load("MyLocalisation");
ResourceManager RM =  new ResourceManager("MyLocalisation.Properties.Resources", localisationAssembly);

How to Generate Unique Public and Private Key via RSA

When you use a code like this:

using (var rsa = new RSACryptoServiceProvider(1024))
{
   // Do something with the key...
   // Encrypt, export, etc.
}

.NET (actually Windows) stores your key in a persistent key container forever. The container is randomly generated by .NET

This means:

  1. Any random RSA/DSA key you have EVER generated for the purpose of protecting data, creating custom X.509 certificate, etc. may have been exposed without your awareness in the Windows file system. Accessible by anyone who has access to your account.

  2. Your disk is being slowly filled with data. Normally not a big concern but it depends on your application (e.g. it might generates hundreds of keys every minute).

To resolve these issues:

using (var rsa = new RSACryptoServiceProvider(1024))
{
   try
   {
      // Do something with the key...
      // Encrypt, export, etc.
   }
   finally
   {
      rsa.PersistKeyInCsp = false;
   }
}

ALWAYS

How can I make a JUnit test wait?

There is a general problem: it's hard to mock time. Also, it's really bad practice to place long running/waiting code in a unit test.

So, for making a scheduling API testable, I used an interface with a real and a mock implementation like this:

public interface Clock {
    
    public long getCurrentMillis();
    
    public void sleep(long millis) throws InterruptedException;
    
}

public static class SystemClock implements Clock {

    @Override
    public long getCurrentMillis() {
        return System.currentTimeMillis();
    }

    @Override
    public void sleep(long millis) throws InterruptedException {
        Thread.sleep(millis);
    }
    
}

public static class MockClock implements Clock {

    private final AtomicLong currentTime = new AtomicLong(0);
    

    public MockClock() {
        this(System.currentTimeMillis());
    }
    
    public MockClock(long currentTime) {
        this.currentTime.set(currentTime);
    }
    

    @Override
    public long getCurrentMillis() {
        return currentTime.addAndGet(5);
    }

    @Override
    public void sleep(long millis) {
        currentTime.addAndGet(millis);
    }
    
}

With this, you could imitate time in your test:

@Test
public void testExpiration() {
    MockClock clock = new MockClock();
    SomeCacheObject sco = new SomeCacheObject();
    sco.putWithExpiration("foo", 1000);
    clock.sleep(2000) // wait for 2 seconds
    assertNull(sco.getIfNotExpired("foo"));
}

An advanced multi-threading mock for Clock is much more complex, of course, but you can make it with ThreadLocal references and a good time synchronization strategy, for example.

How to get user name using Windows authentication in asp.net?

Username you get like this:

var userName = HttpContext.Current.Request.LogonUserIdentity?.Name;

Uncaught TypeError: Cannot read property 'appendChild' of null

There isn't an element on your page with the id "mainContent" when your callback is being executed.

In the line:

document.getElementById("mainContent").appendChild(p);

the section document.getElementById("mainContent") is returning null

How to remove all white spaces from a given text file

$ man tr
NAME
    tr - translate or delete characters

SYNOPSIS
    tr [OPTION]... SET1 [SET2]

DESCRIPTION
   Translate, squeeze, and/or delete characters from standard 
   input, writing to standard output.

In order to wipe all whitespace including newlines you can try:

cat file.txt | tr -d " \t\n\r" 

You can also use the character classes defined by tr (credits to htompkins comment):

cat file.txt | tr -d "[:space:]"

For example, in order to wipe just horizontal white space:

cat file.txt | tr -d "[:blank:]"

Detect click inside/outside of element with single event handler

What about this?

<style type="text/css">
div {border: 1px solid red; color: black; background-color: #9999DD;
width: 20em; height: 40em;}
</style>

<script type="text/javascript">
function sayLoc(e) {
e = e || window.event;
var tgt = e.target || e.srcElement;

// Get top lef co-ords of div
var divX = findPosX(tgt);
var divY = findPosY(tgt);

// Workout if page has been scrolled
var pXo = getPXoffset();
var pYo = getPYoffset();

// Subtract div co-ords from event co-ords
var clickX = e.clientX - divX + pXo;
var clickY = e.clientY - divY + pYo;

alert('Co-ords within div (x, y): '
+ clickX + ', ' + clickY);
}

function findPosX(obj) {
var curleft = 0;
if (obj.offsetParent) {
while (obj.offsetParent) {
curleft += obj.offsetLeft
obj = obj.offsetParent;
}
} else if (obj.x) {
curleft += obj.x;
}
return curleft;
}

function findPosY(obj) {
var curtop = 0;
if (obj.offsetParent) {
while (obj.offsetParent) {
curtop += obj.offsetTop
obj = obj.offsetParent;
}
} else if (obj.y) {
curtop += obj.y;
}
return curtop;
}

function getPXoffset(){
if (self.pageXOffset) { // all except Explorer
return self.pageXOffset;
} else if (document.documentElement
&& document.documentElement.scrollTop) {// Explorer 6 Strict
return document.documentElement.scrollLeft;
} else if (document.body) { // all other Explorers
return document.body.scrollLeft;
}
}

function getPYoffset(){
if (self.pageYOffset) { // all except Explorer
return self.pageYOffset;
} else if (document.documentElement
&& document.documentElement.scrollTop) {// Explorer 6 Strict
return document.documentElement.scrollTop;
} else if (document.body) { // all other Explorers
return document.body.scrollTop;
}
}
</script>

<div onclick="sayLoc(event);"></div>

(from http://bytes.com/topic/javascript/answers/151689-detect-click-inside-div-mozilla, using the Google.)

How can I access and process nested objects, arrays or JSON?

You could use lodash _get function:

var object = { 'a': [{ 'b': { 'c': 3 } }] };

_.get(object, 'a[0].b.c');
// => 3

How to copy Java Collections list

Every other Object not --> you need to iterate and do a copy by yourself.

To avoid this implement Cloneable.

public class User implements Serializable, Cloneable {

    private static final long serialVersionUID = 1L;

    private String user;
    private String password;
    ...

    @Override
    public Object clone() {
        Object o = null;
        try {
          o = super.clone();
        } catch(CloneNotSupportedException e) {
        }
        return o;
     }
 }

....

  public static void main(String[] args) {

      List<User> userList1 = new ArrayList<User>();

      User user1 = new User();
      user1.setUser("User1");
      user1.setPassword("pass1");
      ...

      User user2 = new User();
      user2.setUser("User2");
      user2.setPassword("pass2");
      ...

      userList1 .add(user1);
      userList1 .add(user2);

      List<User> userList2 = new ArrayList<User>();


      for(User u: userList1){
          u.add((User)u.clone());
      }

      //With this you can avoid 
      /*
        for(User u: userList1){
            User tmp = new User();
            tmp.setUser(u.getUser);
            tmp.setPassword(u.getPassword);
            ...
            u.add(tmp);               
        }
       */

  }

Update div with jQuery ajax response html

It's also possible to use jQuery's .load()

$('#submitform').click(function() {
  $('#showresults').load('getinfo.asp #showresults', {
    txtsearch: $('#appendedInputButton').val()
  }, function() {
    // alert('Load was performed.')
    // $('#showresults').slideDown('slow')
  });
});

unlike $.get(), allows us to specify a portion of the remote document to be inserted. This is achieved with a special syntax for the url parameter. If one or more space characters are included in the string, the portion of the string following the first space is assumed to be a jQuery selector that determines the content to be loaded.

We could modify the example above to use only part of the document that is fetched:

$( "#result" ).load( "ajax/test.html #container" );

When this method executes, it retrieves the content of ajax/test.html, but then jQuery parses the returned document to find the element with an ID of container. This element, along with its contents, is inserted into the element with an ID of result, and the rest of the retrieved document is discarded.

When does a process get SIGABRT (signal 6)?

The GNU libc will print out information to /dev/tty regarding some fatal conditions before it calls abort() (which then triggers SIGABRT), but if you are running your program as a service or otherwise not in a real terminal window, these message can get lost, because there is no tty to display the messages.

See my post on redirecting libc to write to stderr instead of /dev/tty:

Catching libc error messages, redirecting from /dev/tty

Convert generic list to dataset in C#

I have slightly modified the accepted answer by handling value types. I came across this when trying to do the following and because GetProperties() is zero length for value types I was getting an empty dataset. I know this is not the use case for the OP but thought I'd post this change in case anyone else came across the same thing.

Enumerable.Range(1, 10).ToList().ToDataSet();

public static DataSet ToDataSet<T>(this IList<T> list)
{
    var elementType = typeof(T);
    var ds = new DataSet();
    var t = new DataTable();
    ds.Tables.Add(t);

    if (elementType.IsValueType)
    {
        var colType = Nullable.GetUnderlyingType(elementType) ?? elementType;
        t.Columns.Add(elementType.Name, colType);

    } else
    {
        //add a column to table for each public property on T
        foreach (var propInfo in elementType.GetProperties())
        {
            var colType = Nullable.GetUnderlyingType(propInfo.PropertyType) ?? propInfo.PropertyType;
            t.Columns.Add(propInfo.Name, colType);
        }
    }

    //go through each property on T and add each value to the table
    foreach (var item in list)
    {
        var row = t.NewRow();

        if (elementType.IsValueType)
        {
            row[elementType.Name] = item;
        }
        else
        {
            foreach (var propInfo in elementType.GetProperties())
            {
                row[propInfo.Name] = propInfo.GetValue(item, null) ?? DBNull.Value;
            }
        }
        t.Rows.Add(row);
    }

    return ds;
}

laravel Unable to prepare route ... for serialization. Uses Closure

This is definitely a bug.Laravel offers predefined code in routes/api.php

Route::middleware('auth:api')->get('/user', function (Request $request) { 
     return $request->user(); 
});

which is unabled to be processed by:

php artisan route:cache

This definitely should be fixed by Laravel team.(check the link),

simply if you want to fix it you should replace routes\api.php code with some thing like :

Route::middleware('auth:api')->get('/user', 'UserController@AuthRouteAPI');

and in UserController put this method:

 public function AuthRouteAPI(Request $request){
    return $request->user();
 }

.crx file install in chrome

I had a similar issue where I was not able to either install a CRX file into Chrome.

It turns out that since I had my Downloads folder set to a network mapped drive, it would not allow Chrome to install any extensions and would either do nothing (drag and drop on Chrome) or ask me to download the extension (if I clicked a link from the Web Store).

Setting the Downloads folder to a local disk directory instead of a network directory allowed extensions to be installed.

Running: 20.0.1132.57 m

What are the best PHP input sanitizing functions?

Database Input - How to prevent SQL Injection

  1. Check to make sure data of type integer, for example, is valid by ensuring it actually is an integer
    • In the case of non-strings you need to ensure that the data actually is the correct type
    • In the case of strings you need to make sure the string is surrounded by quotes in the query (obviously, otherwise it wouldn't even work)
  2. Enter the value into the database while avoiding SQL injection (mysql_real_escape_string or parameterized queries)
  3. When Retrieving the value from the database be sure to avoid Cross Site Scripting attacks by making sure HTML can't be injected into the page (htmlspecialchars)

You need to escape user input before inserting or updating it into the database. Here is an older way to do it. You would want to use parameterized queries now (probably from the PDO class).

$mysql['username'] = mysql_real_escape_string($clean['username']);
$sql = "SELECT * FROM userlist WHERE username = '{$mysql['username']}'";
$result = mysql_query($sql);

Output from database - How to prevent XSS (Cross Site Scripting)

Use htmlspecialchars() only when outputting data from the database. The same applies for HTML Purifier. Example:

$html['username'] = htmlspecialchars($clean['username'])

And Finally... what you requested

I must point out that if you use PDO objects with parameterized queries (the proper way to do it) then there really is no easy way to achieve this easily. But if you use the old 'mysql' way then this is what you would need.

function filterThis($string) {
    return mysql_real_escape_string($string);
}

Display all items in array using jquery

Original from Sept. 13, 2015:
Quick and easy.

$.each(yourArray, function(index, value){
    $('.element').html( $('.element').html() + '<span>' + value +'</span>')
});

Update Sept 9, 2019: No jQuery is needed to iterate the array.

yourArray.forEach((value) => {
    $(".element").html(`${$(".element").html()}<span>${value}</span>`);
});

/* --- Or without jQuery at all --- */

yourArray.forEach((value) => {
    document.querySelector(".element").innerHTML += `<span>${value}</span>`;
});

How to write data to a JSON file using Javascript

JSON can be written into local storage using the JSON.stringify to serialize a JS object. You cannot write to a JSON file using only JS. Only cookies or local storage

    var obj = {"nissan": "sentra", "color": "green"};

localStorage.setItem('myStorage', JSON.stringify(obj));

And to retrieve the object later

var obj = JSON.parse(localStorage.getItem('myStorage'));

How to activate JMX on my JVM for access with jconsole?

I'm using WAS ND 7.0

My JVM need all the following arguments to be monitored in JConsole

    -Djavax.management.builder.initial= 
    -Dcom.sun.management.jmxremote 
    -Dcom.sun.management.jmxremote.port=8855 
    -Dcom.sun.management.jmxremote.authenticate=false 
    -Dcom.sun.management.jmxremote.ssl=false

How to change Toolbar Navigation and Overflow Menu icons (appcompat v7)?

To change the navigation icon you can use:

Toolbar toolbar = (Toolbar) findViewById(R.id.my_awesome_toolbar);
setSupportActionBar(toolbar);
toolbar.setNavigationIcon(R.drawable.my_icon);

To change the overflow icon you can use the method:

toolbar.setOverflowIcon(ContextCompat.getDrawable(this, R.drawable.ic_my_menu);

If you would like to change the color of the icons you can use:

with a Material Components Theme (with a MaterialToolbar for example):

<com.google.android.material.appbar.MaterialToolbar
    android:theme="@style/MyThemeOverlay_Toolbar"
    ...>

  <style name="MyThemeOverlay_Toolbar" parent="ThemeOverlay.MaterialComponents.Toolbar.Primary">
    <!-- color used by navigation icon and overflow icon -->
    <item name="colorOnPrimary">@color/myColor</item>
  </style>

With an AppCompat Theme:

<android.support.v7.widget.Toolbar
  app:theme="@style/ThemeToolbar" />


<style name="ThemeToolbar" parent="Theme.AppCompat.Light">

   <!-- navigation icon color -->
   <item name="colorControlNormal">@color/my_color</item>

    <!-- color of the menu overflow icon -->
    <item name="android:textColorSecondary">@color/my_color</item>
</style>

You can also change the overflow icon overriding in the app theme the actionOverflowButtonStyle attribute:

With a Material Components Theme:

<style name="AppTheme.Base" parent="Theme.MaterialComponents.DayNight">
    <item name="actionOverflowButtonStyle">@style/OverFlow</item>
</style>

<style name="OverFlow" parent="Widget.AppCompat.ActionButton.Overflow">
    <item name="srcCompat">@drawable/my_overflow_menu</item>
</style>

With an AppCompat theme:

<style name="AppTheme.Base" parent="Theme.AppCompat.Light">
    <item name="actionOverflowButtonStyle">@style/OverFlow</item>
</style>

<style name="OverFlow" parent="Widget.AppCompat.ActionButton.Overflow">
    <item name="srcCompat">@drawable/my_overflow_menu</item>
</style>

how to convert String into Date time format in JAVA?

With SimpleDateFormat. And steps are -

  1. Create your date pattern string
  2. Create SimpleDateFormat Object
  3. And parse with it.
  4. It will return Date Object.

Is there a “not in” operator in JavaScript for checking object properties?

Two quick possibilities:

if(!('foo' in myObj)) { ... }

or

if(myObj['foo'] === undefined) { ... }

How to lose margin/padding in UITextView?

This workaround was written in 2009 when IOS 3.0 was released. It no longer applies.

I ran into the exact same problem, in the end I had to wind up using

nameField.contentInset = UIEdgeInsetsMake(-4,-8,0,0);

where nameField is a UITextView. The font I happened to be using was Helvetica 16 point. Its only a custom solution for the particular field size I was drawing. This makes the left offset flush with the left side, and the top offset where I want it for the box its draw in.

In addition, this only seems to apply to UITextViews where you are using the default aligment, ie.

nameField.textAlignment = NSTextAlignmentLeft;

Align to the right for example and the UIEdgeInsetsMake seems to have no impact on the right edge at all.

At very least, using the .contentInset property allows you to place your fields with the "correct" positions, and accommodate the deviations without offsetting your UITextViews.

What is the difference between "mvn deploy" to a local repo and "mvn install"?

Ken, good question. I should be more explicit in the The Definitive Guide about the difference. "install" and "deploy" serve two different purposes in a build. "install" refers to the process of installing an artifact in your local repository. "deploy" refers to the process of deploying an artifact to a remote repository.

Example:

  1. When I run a large multi-module project on a my machine, I'm going to usually run "mvn install". This is going to install all of the generated binary software artifacts (usually JARs) in my local repository. Then when I build individual modules in the build, Maven is going to retrieve the dependencies from the local repository.

  2. When it comes time to deploy snapshots or releases, I'm going to run "mvn deploy". Running this is going to attempt to deploy the files to a remote repository or server. Usually I'm going to be deploying to a repository manager such as Nexus

It is true that running "deploy" is going to require some extra configuration, you are going to have to supply a distributionManagement section in your POM.

Why am I getting "IndentationError: expected an indented block"?

As the error message indicates, you have an indentation error. It is probably caused by a mix of tabs and spaces.

How do I decrease the size of my sql server log file?

This is one of the best suggestion in which is done using query. Good for those who has a lot of databases just like me. Can run it using a script.

https://medium.com/@bharatdwarkani/shrinking-sql-server-db-log-file-size-sql-server-db-maintenance-7ddb0c331668

USE DatabaseName;
GO
-- Truncate the log by changing the database recovery model to SIMPLE.
ALTER DATABASE DatabaseName
SET RECOVERY SIMPLE;
GO
-- Shrink the truncated log file to 1 MB.
DBCC SHRINKFILE (DatabaseName_Log, 1);
GO
-- Reset the database recovery model.
ALTER DATABASE DatabaseName
SET RECOVERY FULL;
GO

How to save python screen output to a text file

We can simply pass the output of python inbuilt print function to a file after opening the file with the append option by using just two lines of code:

with open('filename.txt', 'a') as file:
    print('\nThis printed data will store in a file', file=file)

Hope this may resolve the issue...

Note: this code works with python3 however, python2 is not being supported currently.

Creating a folder if it does not exists - "Item already exists"

I was not even concentrating, here is how to do it

$DOCDIR = [Environment]::GetFolderPath("MyDocuments")
$TARGETDIR = '$DOCDIR\MatchedLog'
if(!(Test-Path -Path $TARGETDIR )){
    New-Item -ItemType directory -Path $TARGETDIR
}

The difference between bracket [ ] and double bracket [[ ]] for accessing the elements of a list or dataframe

[] extracts a list, [[]] extracts elements within the list

alist <- list(c("a", "b", "c"), c(1,2,3,4), c(8e6, 5.2e9, -9.3e7))

str(alist[[1]])
 chr [1:3] "a" "b" "c"

str(alist[1])
List of 1
 $ : chr [1:3] "a" "b" "c"

str(alist[[1]][1])
 chr "a"

ImportError: DLL load failed: %1 is not a valid Win32 application. But the DLL's are there

Please check if the python version you are using is also 64 bit. If not then that could be the issue. You would be using a 32 bit python version and would have installed a 64 bit binaries for the OPENCV library.

Custom CSS Scrollbar for Firefox

Here I have tried this CSS for all major browser & tested: Custom color are working fine on scrollbar.

Yes, there are limitations on several versions of different browsers.

_x000D_
_x000D_
/* Only Chrome */
html::-webkit-scrollbar {width: 17px;}
html::-webkit-scrollbar-thumb {background-color: #0064a7; background-clip: padding-box; border: 1px solid #8ea5b5;}
html::-webkit-scrollbar-track {background-color: #8ea5b5; }
::-webkit-scrollbar-button {background-color: #8ea5b5;}
/* Only IE */
html {scrollbar-face-color: #0064a7; scrollbar-shadow-color: #8ea5b5; scrollbar-highlight-color: #8ea5b5;}
/* Only FireFox */
html {scrollbar-color: #0064a7 #8ea5b5;}
/* View Scrollbar */
html {overflow-y: scroll;overflow-x: hidden;}
_x000D_
<!doctype html>
<html lang="en" class="no-js">
<head>
    <meta charset="utf-8">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
    <header>
        <div id="logo"><img src="/logo.png">HTML5&nbsp;Layout</div>
        <nav>  
            <ul>
                <li><a href="/">Home</a>
                <li><a href="https://html-css-js.com/">HTML</a>
                <li><a href="https://html-css-js.com/css/code/">CSS</a>
                <li><a href="https://htmlcheatsheet.com/js/">JS</a>
            </ul>
        </nav>
    </header>
    <section>
        <strong>Demonstration of a simple page layout using HTML5 tags: header, nav, section, main, article, aside, footer, address.</strong>
    </section>
    <section id="pageContent">
        <main role="main">
            <article>
                <h2>Stet facilis ius te</h2>
                <p>Lorem ipsum dolor sit amet, nonumes voluptatum mel ea, cu case ceteros cum. Novum commodo malorum vix ut. Dolores consequuntur in ius, sale electram dissentiunt quo te. Cu duo omnes invidunt, eos eu mucius fabellas. Stet facilis ius te, quando voluptatibus eos in. Ad vix mundi alterum, integre urbanitas intellegam vix in.</p>
            </article>
            <article>
                <h2>Illud mollis moderatius</h2>
                <p>Eum facete intellegat ei, ut mazim melius usu. Has elit simul primis ne, regione minimum id cum. Sea deleniti dissentiet ea. Illud mollis moderatius ut per, at qui ubique populo. Eum ad cibo legimus, vim ei quidam fastidii.</p>
            </article>
            <article>
                <h2>Ex ignota epicurei quo</h2>
                <p>Quo debet vivendo ex. Qui ut admodum senserit partiendo. Id adipiscing disputando eam, sea id magna pertinax concludaturque. Ex ignota epicurei quo, his ex doctus delenit fabellas, erat timeam cotidieque sit in. Vel eu soleat voluptatibus, cum cu exerci mediocritatem. Malis legere at per, has brute putant animal et, in consul utamur usu.</p>
            </article>
            <article>
                <h2>His at autem inani volutpat</h2>
                <p>Te has amet modo perfecto, te eum mucius conclusionemque, mel te erat deterruisset. Duo ceteros phaedrum id, ornatus postulant in sea. His at autem inani volutpat. Tollit possit in pri, platonem persecuti ad vix, vel nisl albucius gloriatur no.</p>
            </article>
        </main>
        <aside>
            <div>Sidebar 1</div>
            <div>Sidebar 2</div>
            <div>Sidebar 3</div>
        </aside>
    </section>
    <footer>
        <p>&copy; You can copy, edit and publish this template but please leave a link to our website | <a href="https://html5-templates.com/" target="_blank" rel="nofollow">HTML5 Templates</a></p>
        <address>
            Contact: <a href="mailto:[email protected]">Mail me</a>
        </address>
    </footer>


</body>

</html>
_x000D_
_x000D_
_x000D_

Expand a random range from 1–5 to 1–7

This algorithm reduces the number of calls of rand5 to the theoretical minimum of 7/5. Calling it 7 times by produce the next 5 rand7 numbers.

There are no rejection of any random bit, and there are NO possibility to keep waiting the result for always.

#!/usr/bin/env ruby

# random integer from 1 to 5
def rand5
    STDERR.putc '.'
    1 + rand( 5 )
end

@bucket = 0
@bucket_size = 0

# random integer from 1 to 7
def rand7
    if @bucket_size == 0
        @bucket = 7.times.collect{ |d| rand5 * 5**d }.reduce( &:+ )
        @bucket_size = 5
    end

    next_rand7 = @bucket%7 + 1

    @bucket      /= 7
    @bucket_size -= 1

    return next_rand7
end

35.times.each{ putc rand7.to_s }

Add ... if string is too long PHP

<?php
function truncate($string, $length, $stopanywhere=false) {
    //truncates a string to a certain char length, stopping on a word if not specified otherwise.
    if (strlen($string) > $length) {
        //limit hit!
        $string = substr($string,0,($length -3));
        if ($stopanywhere) {
            //stop anywhere
            $string .= '...';
        } else{
            //stop on a word.
            $string = substr($string,0,strrpos($string,' ')).'...';
        }
    }
    return $string;
}
?>

I use the above code snippet many-a-times..

Prevent content from expanding grid items

By default, a grid item cannot be smaller than the size of its content.

Grid items have an initial size of min-width: auto and min-height: auto.

You can override this behavior by setting grid items to min-width: 0, min-height: 0 or overflow with any value other than visible.

From the spec:

6.6. Automatic Minimum Size of Grid Items

To provide a more reasonable default minimum size for grid items, this specification defines that the auto value of min-width / min-height also applies an automatic minimum size in the specified axis to grid items whose overflow is visible. (The effect is analogous to the automatic minimum size imposed on flex items.)

Here's a more detailed explanation covering flex items, but it applies to grid items, as well:

This post also covers potential problems with nested containers and known rendering differences among major browsers.


To fix your layout, make these adjustments to your code:

.month-grid {
  display: grid;
  grid-template: repeat(6, 1fr) / repeat(7, 1fr);
  background: #fff;
  grid-gap: 2px;
  min-height: 0;  /* NEW */
  min-width: 0;   /* NEW; needed for Firefox */
}

.day-item {
  padding: 10px;
  background: #DFE7E7;
  overflow: hidden;  /* NEW */
  min-width: 0;      /* NEW; needed for Firefox */
}

jsFiddle demo


1fr vs minmax(0, 1fr)

The solution above operates at the grid item level. For a container level solution, see this post:

Dynamic WHERE clause in LINQ

You can also use the PredicateBuilder from LinqKit to chain multiple typesafe lambda expressions using Or or And.

http://www.albahari.com/nutshell/predicatebuilder.aspx

Postgresql : Connection refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections

The error you quote has nothing to do with pg_hba.conf; it's failing to connect, not failing to authorize the connection.

Do what the error message says:

Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections

You haven't shown the command that produces the error. Assuming you're connecting on localhost port 5432 (the defaults for a standard PostgreSQL install), then either:

  • PostgreSQL isn't running

  • PostgreSQL isn't listening for TCP/IP connections (listen_addresses in postgresql.conf)

  • PostgreSQL is only listening on IPv4 (0.0.0.0 or 127.0.0.1) and you're connecting on IPv6 (::1) or vice versa. This seems to be an issue on some older Mac OS X versions that have weird IPv6 socket behaviour, and on some older Windows versions.

  • PostgreSQL is listening on a different port to the one you're connecting on

  • (unlikely) there's an iptables rule blocking loopback connections

(If you are not connecting on localhost, it may also be a network firewall that's blocking TCP/IP connections, but I'm guessing you're using the defaults since you didn't say).

So ... check those:

  • ps -f -u postgres should list postgres processes

  • sudo lsof -n -u postgres |grep LISTEN or sudo netstat -ltnp | grep postgres should show the TCP/IP addresses and ports PostgreSQL is listening on

BTW, I think you must be on an old version. On my 9.3 install, the error is rather more detailed:

$ psql -h localhost -p 12345
psql: could not connect to server: Connection refused
        Is the server running on host "localhost" (::1) and accepting
        TCP/IP connections on port 12345?

#1055 - Expression of SELECT list is not in GROUP BY clause and contains nonaggregated column this is incompatible with sql_mode=only_full_group_by

You need to specify all of the columns that you're not using for an aggregation function in your GROUP BY clause like this:

select libelle,credit_initial,disponible_v,sum(montant) as montant 
FROM fiche,annee,type where type.id_type=annee.id_type and annee.id_annee=fiche.id_annee 
and annee = year(current_timestamp) GROUP BY libelle,credit_initial,disponible_v order by libelle asc

The full_group_by mode basically makes you write more idiomatic SQL. You can turn off this setting if you'd like. There are different ways to do this that are outlined in the MySQL Documentation. Here's MySQL's definition of what I said above:

MySQL 5.7.5 and up implements detection of functional dependence. If the ONLY_FULL_GROUP_BY SQL mode is enabled (which it is by default), MySQL rejects queries for which the select list, HAVING condition, or ORDER BY list refer to nonaggregated columns that are neither named in the GROUP BY clause nor are functionally dependent on them. (Before 5.7.5, MySQL does not detect functional dependency and ONLY_FULL_GROUP_BY is not enabled by default. For a description of pre-5.7.5 behavior, see the MySQL 5.6 Reference Manual.)

You're getting the error because you're on a version < 5.7.5

Get a Div Value in JQuery

You could use

jQuery('#gregsButton').click(function() { 
    var mb = jQuery('#myDiv').text(); 
    alert("Value of div is: " + mb); 
});

Looks like there may be a conflict with using the $. Remember that the variable 'mb' will not be accessible outside of the event handler. Also, the text() function returns a string, no need to get mb.value.

How do I use an image as a submit button?

Why not:

<button type="submit">
<img src="mybutton.jpg" />
</button>

Stacked Bar Plot in R

The dataset:

dat <- read.table(text = "A   B   C   D   E   F    G
1 480 780 431 295 670 360  190
2 720 350 377 255 340 615  345
3 460 480 179 560  60 735 1260
4 220 240 876 789 820 100   75", header = TRUE)

Now you can convert the data frame into a matrix and use the barplot function.

barplot(as.matrix(dat))

enter image description here

rsync: how can I configure it to create target directory on server?

If you have more than the last leaf directory to be created, you can either run a separate ssh ... mkdir -p first, or use the --rsync-path trick as explained here :

rsync -a --rsync-path="mkdir -p /tmp/x/y/z/ && rsync" $source user@remote:/tmp/x/y/z/

Or use the --relative option as suggested by Tony. In that case, you only specify the root of the destination, which must exist, and not the directory structure of the source, which will be created:

rsync -a --relative /new/x/y/z/ user@remote:/pre_existing/dir/

This way, you will end up with /pre_existing/dir/new/x/y/z/

And if you want to have "y/z/" created, but not inside "new/x/", you can add ./ where you want --relativeto begin:

rsync -a --relative /new/x/./y/z/ user@remote:/pre_existing/dir/

would create /pre_existing/dir/y/z/.

How to set tbody height with overflow scroll

If you want tbody to show a scrollbar, set its display: block;.

Set display: table; for the tr so that it keeps the behavior of a table.

To evenly spread the cells, use table-layout: fixed;.

DEMO tbody scroll


CSS:

table, tr td {
    border: 1px solid red
}
tbody {
    display: block;
    height: 50px;
    overflow: auto;
}
thead, tbody tr {
    display: table;
    width: 100%;
    table-layout: fixed;/* even columns width , fix width of table too*/
}
thead {
    width: calc( 100% - 1em )/* scrollbar is average 1em/16px width, remove it from thead width */
}
table {
    width: 400px;
}

If tbody doesn't show a scroll, because content is less than height or max-height, set the scroll any time with: overflow-y: scroll;. DEMO 2

Important note: this approach to making a table scrollable has drawbacks in some cases. (See comments below.)

How to create a GUID/UUID using iOS

[[UIDevice currentDevice] uniqueIdentifier]

Returns the Unique ID of your iPhone.

EDIT: -[UIDevice uniqueIdentifier] is now deprecated and apps are being rejected from the App Store for using it. The method below is now the preferred approach.

If you need to create several UUID, just use this method (with ARC):

+ (NSString *)GetUUID
{
  CFUUIDRef theUUID = CFUUIDCreate(NULL);
  CFStringRef string = CFUUIDCreateString(NULL, theUUID);
  CFRelease(theUUID);
  return (__bridge NSString *)string;
}

EDIT: Jan, 29 2014: If you're targeting iOS 6 or later, you can now use the much simpler method:

NSString *UUID = [[NSUUID UUID] UUIDString];

Excel add one hour

In cell A1, enter the time.
In cell B2, enter =A1+1/24

json: cannot unmarshal object into Go value of type

You JSON doesn't match your struct fields: E.g. "district" in JSON and "District" as the field.

Also: Your Item is a slice type but your JSON is a dict value. Do not mix this up. Slices decode from arrays.

How do I get the size of a java.sql.ResultSet?

theStatement=theConnection.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);

ResultSet theResult=theStatement.executeQuery(query); 

//Get the size of the data returned
theResult.last();     
int size = theResult.getRow() * theResult.getMetaData().getColumnCount();       
theResult.beforeFirst();

What is a mutex?

Mutex: Mutex stands for Mutual Exclusion. It means only one process/thread can enter into critical section at a given time. In concurrent programming multiple threads/process updating the shared resource (any variable, shared memory etc.) may lead to some unexpected result. ( As the result depends upon the which thread/process gets the first access).

In order to avoid such an unexpected result we need some synchronization mechanism, which ensures that only one thread/process gets access to such a resource at a time.

pthread library provides support for Mutex.

typedef union
{
  struct __pthread_mutex_s
  {
    ***int __lock;***
    unsigned int __count;
    int __owner;
#ifdef __x86_64__
    unsigned int __nusers;
#endif
int __kind;
#ifdef __x86_64__
    short __spins;
    short __elision;
    __pthread_list_t __list;
# define __PTHREAD_MUTEX_HAVE_PREV      1
# define __PTHREAD_SPINS             0, 0
#else
    unsigned int __nusers;
    __extension__ union
    {
      struct
      {
        short __espins;
        short __elision;
# define __spins __elision_data.__espins
# define __elision __elision_data.__elision
# define __PTHREAD_SPINS         { 0, 0 }
      } __elision_data;
      __pthread_slist_t __list;
    };
#endif

This is the structure for mutex data type i.e pthread_mutex_t. When mutex is locked, __lock set to 1. When it is unlocked __lock set to 0.

This ensure that no two processes/threads can access the critical section at same time.

Convert Little Endian to Big Endian

I think you can use function htonl(). Network byte order is big endian.

Boxplot show the value of mean

You can use the output value from stat_summary()

ggplot(data=PlantGrowth, aes(x=group, y=weight, fill=group)) 
+ geom_boxplot() 
+ stat_summary(fun.y=mean, colour="darkred", geom="point", hape=18, size=3,show_guide = FALSE)
+ stat_summary(fun.y=mean, colour="red", geom="text", show_guide = FALSE, 
               vjust=-0.7, aes( label=round(..y.., digits=1)))

How to implement DrawerArrowToggle from Android appcompat v7 21 library

First, you should know now the android.support.v4.app.ActionBarDrawerToggle is deprecated.

You must replace that with android.support.v7.app.ActionBarDrawerToggle.

Here is my example and I use the new Toolbar to replace the ActionBar.

MainActivity.java

public class MainActivity extends ActionBarActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(mToolbar);
    DrawerLayout mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(
        this,  mDrawerLayout, mToolbar,
        R.string.navigation_drawer_open, R.string.navigation_drawer_close
    );
    mDrawerLayout.setDrawerListener(mDrawerToggle);
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    getSupportActionBar().setHomeButtonEnabled(true);
    mDrawerToggle.syncState();
}

styles.xml

<style name="AppTheme" parent="Theme.AppCompat.Light">
    <item name="drawerArrowStyle">@style/DrawerArrowStyle</item>
</style>

<style name="DrawerArrowStyle" parent="Widget.AppCompat.DrawerArrowToggle">
    <item name="spinBars">true</item>
    <item name="color">@android:color/white</item>
</style>

You can read the documents on AndroidDocument#DrawerArrowToggle_spinBars

This attribute is the key to implement the menu-to-arrow animation.

public static int DrawerArrowToggle_spinBars

Whether bars should rotate or not during transition
Must be a boolean value, either "true" or "false".

So, you set this: <item name="spinBars">true</item>.

Then the animation can be presented.

Hope this can help you.

Calculate the date yesterday in JavaScript

var date = new Date();

date ; //# => Fri Apr 01 2011 11:14:50 GMT+0200 (CEST)

date.setDate(date.getDate() - 1);

date ; //# => Thu Mar 31 2011 11:14:50 GMT+0200 (CEST)

Find and Replace string in all files recursive using grep and sed

grep -rl SOSTITUTETHIS . | xargs sed -Ei 's/(.*)SOSTITUTETHIS(.*)/\1WITHTHIS\2/g'

Using multiple property files (via PropertyPlaceholderConfigurer) in multiple projects/modules

You can have multiple <context:property-placeholder /> elements instead of explicitly declaring multiple PropertiesPlaceholderConfigurer beans.

What is the "realm" in basic authentication

From RFC 1945 (HTTP/1.0) and RFC 2617 (HTTP Authentication referenced by HTTP/1.1)

The realm attribute (case-insensitive) is required for all authentication schemes which issue a challenge. The realm value (case-sensitive), in combination with the canonical root URL of the server being accessed, defines the protection space. These realms allow the protected resources on a server to be partitioned into a set of protection spaces, each with its own authentication scheme and/or authorization database. The realm value is a string, generally assigned by the origin server, which may have additional semantics specific to the authentication scheme.

In short, pages in the same realm should share credentials. If your credentials work for a page with the realm "My Realm", it should be assumed that the same username and password combination should work for another page with the same realm.

How do I get a file name from a full path with PHP?

I've done this using the function PATHINFO which creates an array with the parts of the path for you to use! For example, you can do this:

<?php
    $xmlFile = pathinfo('/usr/admin/config/test.xml');

    function filePathParts($arg1) {
        echo $arg1['dirname'], "\n";
        echo $arg1['basename'], "\n";
        echo $arg1['extension'], "\n";
        echo $arg1['filename'], "\n";
    }

    filePathParts($xmlFile);
?>

This will return:

/usr/admin/config
test.xml
xml
test

The use of this function has been available since PHP 5.2.0!

Then you can manipulate all the parts as you need. For example, to use the full path, you can do this:

$fullPath = $xmlFile['dirname'] . '/' . $xmlFile['basename'];

What is the difference between properties and attributes in HTML?

well these are specified by the w3c what is an attribute and what is a property http://www.w3.org/TR/SVGTiny12/attributeTable.html

but currently attr and prop are not so different and there are almost the same

but they prefer prop for some things

Summary of Preferred Usage

The .prop() method should be used for boolean attributes/properties and for properties which do not exist in html (such as window.location). All other attributes (ones you can see in the html) can and should continue to be manipulated with the .attr() method.

well actually you dont have to change something if you use attr or prop or both, both work but i saw in my own application that prop worked where atrr didnt so i took in my 1.6 app prop =)

Execute JavaScript code stored as a string

A bit like what @Hossein Hajizadeh alerady said, though in more detail:

There is an alternative to eval().

The function setTimeout() is designed to execute something after an interval of milliseconds, and the code to be executed just so happens to be formatted as a string.

It would work like this:

_x000D_
_x000D_
ExecuteJavascriptString(); //Just for running it_x000D_
_x000D_
function ExecuteJavascriptString()_x000D_
{_x000D_
    var s = "alert('hello')";_x000D_
    setTimeout(s, 1);_x000D_
}
_x000D_
_x000D_
_x000D_

1 means it will wait 1 millisecond before executing the string.

It might not be the most correct way to do it, but it works.

How to Query Database Name in Oracle SQL Developer?

Edit: Whoops, didn't check your question tags before answering.

Check that you can actually connect to DB (have the driver placed? tested the conn when creating it?).

If so, try runnung those queries with F5

Programmatically close aspx page from code behind

UPDATE: I have taken all of your input and came up with the following solution:

In code behind:

protected void Page_Load(object sender, EventArgs e)    
{
    Page.ClientScript.RegisterOnSubmitStatement(typeof(Page), "closePage", "window.onunload = CloseWindow();");
}

In aspx page:

function CloseWindow() {
    window.close();
}

Auto-refreshing div with jQuery - setTimeout or another method?

Another modification:

function update() {
  $.get("response.php", function(data) {
    $("#some_div").html(data);
    window.setTimeout(update, 10000);
  });
}

The difference with this is that it waits 10 seconds AFTER the ajax call is one. So really the time between refreshes is 10 seconds + length of ajax call. The benefit of this is if your server takes longer than 10 seconds to respond, you don't get two (and eventually, many) simultaneous AJAX calls happening.

Also, if the server fails to respond, it won't keep trying.

I've used a similar method in the past using .ajax to handle even more complex behaviour:

function update() {
  $("#notice_div").html('Loading..'); 
  $.ajax({
    type: 'GET',
    url: 'response.php',
    timeout: 2000,
    success: function(data) {
      $("#some_div").html(data);
      $("#notice_div").html(''); 
      window.setTimeout(update, 10000);
    },
    error: function (XMLHttpRequest, textStatus, errorThrown) {
      $("#notice_div").html('Timeout contacting server..');
      window.setTimeout(update, 60000);
    }
}

This shows a loading message while loading (put an animated gif in there for typical "web 2.0" style). If the server times out (in this case takes longer than 2s) or any other kind of error happens, it shows an error, and it waits for 60 seconds before contacting the server again.

This can be especially beneficial when doing fast updates with a larger number of users, where you don't want everyone to suddenly cripple a lagging server with requests that are all just timing out anyways.

How do I set a value in CKEditor with Javascript?

I have used the below code and it is working fine as describing->

CKEDITOR.instances.mail_msg.insertText(obj["template"]);

Here-> CKEDITOR ->Your editor Name, mail_msg -> Id of your textarea(to which u bind the ckeditor), obj["template"]->is the value that u want to bind

jQuery ui dialog change title after load-callback

Using dialog methods:

$('.selectorUsedToCreateTheDialog').dialog('option', 'title', 'My New title');

Or directly, hacky though:

$("span.ui-dialog-title").text('My New Title'); 

For future reference, you can skip google with jQuery. The jQuery API will answer your questions most of the time. In this case, the Dialog API page. For the main library: http://api.jquery.com

org.hibernate.PersistentObjectException: detached entity passed to persist

This exists in @ManyToOne relation. I solved this issue by just using CascadeType.MERGE instead of CascadeType.PERSIST or CascadeType.ALL. Hope it helps you.

@ManyToOne(cascade = CascadeType.ALL)
@JoinColumn(name="updated_by", referencedColumnName = "id")
private Admin admin;

Solution:

@ManyToOne(cascade = CascadeType.MERGE)
@JoinColumn(name="updated_by", referencedColumnName = "id")
private Admin admin;

NSOperation vs Grand Central Dispatch

Another reason to prefer NSOperation over GCD is the cancelation mechanism of NSOperation. For example, an App like 500px that shows dozens of photos, use NSOperation we can cancel requests of invisible image cells when we scroll table view or collection view, this can greatly improve App performance and reduce memory footprint. GCD can't easily support this.

Also with NSOperation, KVO can be possible.

Here is an article from Eschaton which is worth reading.

Using grep to help subset a data frame in R

It's pretty straightforward using [ to extract:

grep will give you the position in which it matched your search pattern (unless you use value = TRUE).

grep("^G45", My.Data$x)
# [1] 2

Since you're searching within the values of a single column, that actually corresponds to the row index. So, use that with [ (where you would use My.Data[rows, cols] to get specific rows and columns).

My.Data[grep("^G45", My.Data$x), ]
#      x y
# 2 G459 2

The help-page for subset shows how you can use grep and grepl with subset if you prefer using this function over [. Here's an example.

subset(My.Data, grepl("^G45", My.Data$x))
#      x y
# 2 G459 2

As of R 3.3, there's now also the startsWith function, which you can again use with subset (or with any of the other approaches above). According to the help page for the function, it's considerably faster than using substring or grepl.

subset(My.Data, startsWith(as.character(x), "G45"))
#      x y
# 2 G459 2

"insufficient memory for the Java Runtime Environment " message in eclipse

Try to modify your eclipse.ini with below

-startup
plugins/org.eclipse.equinox.launcher_1.3.0.v20120522-1813.jar
--launcher.library
plugins/org.eclipse.equinox.launcher.win32.win32.x86_64_1.1.200.v20120913-144807
-product
org.eclipse.epp.package.jee.product
--launcher.defaultAction
openFile
--launcher.XXMaxPermSize
512M
-showsplash
org.eclipse.platform
--launcher.XXMaxPermSize
512m
--launcher.defaultAction
openFile
-vmargs
-Dosgi.requiredJavaVersion=1.5
-Dhelp.lucene.tokenizer=standard
-Xms2G
-Xmx3G
-XX:MaxPermSize=2G
-XX:+UseCompressedOops
-XX:+UseParallelGC

Once you open your eclipse you can try below

Looks like your application consumes more memory than allocated (Default). I will try two things

  1. As suggested by Harmlezz increase your memory allocation to JVM to -Xms2g -Xmx2g (If needed increase it more and try it out)

  2. Download eclipse memory analyzer and check for what causing memory leak OR even you can use JConsole to see JVM memory utilization in order to figure out application memory leak issue.

Is it possible to iterate through JSONArray?

You can use the opt(int) method and use a classical for loop.

How to read file with async/await properly?

To keep it succint and retain all functionality of fs:

const fs = require('fs');
const fsPromises = fs.promises;

async function loadMonoCounter() {
    const data = await fsPromises.readFile('monolitic.txt', 'binary');
    return new Buffer(data);
}

Importing fs and fs.promises separately will give access to the entire fs API while also keeping it more readable... So that something like the next example is easily accomplished.

// the 'next example'
fsPromises.access('monolitic.txt', fs.constants.R_OK | fs.constants.W_OK)
    .then(() => console.log('can access'))
    .catch(() => console.error('cannot access'));

Differences between dependencyManagement and dependencies in Maven

The difference between the two is best brought in what seems a necessary and sufficient definition of the dependencyManagement element available in Maven website docs:

dependencyManagement

"Default dependency information for projects that inherit from this one. The dependencies in this section are not immediately resolved. Instead, when a POM derived from this one declares a dependency described by a matching groupId and artifactId, the version and other values from this section are used for that dependency if they were not already specified." [ https://maven.apache.org/ref/3.6.1/maven-model/maven.html ]

It should be read along with some more information available on a different page:

“..the minimal set of information for matching a dependency reference against a dependencyManagement section is actually {groupId, artifactId, type, classifier}. In many cases, these dependencies will refer to jar artifacts with no classifier. This allows us to shorthand the identity set to {groupId, artifactId}, since the default for the type field is jar, and the default classifier is null.” [https://maven.apache.org/guides/introduction/introduction-to-dependency-mechanism.html ]

Thus, all the sub-elements (scope, exclusions etc.,) of a dependency element--other than groupId, artifactId, type, classifier, not just version--are available for lockdown/default at the point (and thus inherited from there onward) you specify the dependency within a dependencyElement. If you’d specified a dependency with the type and classifier sub-elements (see the first-cited webpage to check all sub-elements) as not jar and not null respectively, you’d need {groupId, artifactId, classifier, type} to reference (resolve) that dependency at any point in an inheritance originating from the dependencyManagement element. Else, {groupId, artifactId} would suffice if you do not intend to override the defaults for classifier and type (jar and null respectively). So default is a good keyword in that definition; any sub-element(s) (other than groupId, artifactId, classifier and type, of course) explicitly assigned value(s) at the point you reference a dependency override the defaults in the dependencyManagement element.

So, any dependency element outside of dependencyManagement, whether as a reference to some dependencyManagement element or as a standalone is immediately resolved (i.e. installed to the local repository and available for classpaths).

Output array to CSV in Ruby

To a file:

require 'csv'
CSV.open("myfile.csv", "w") do |csv|
  csv << ["row", "of", "CSV", "data"]
  csv << ["another", "row"]
  # ...
end

To a string:

require 'csv'
csv_string = CSV.generate do |csv|
  csv << ["row", "of", "CSV", "data"]
  csv << ["another", "row"]
  # ...
end

Here's the current documentation on CSV: http://ruby-doc.org/stdlib/libdoc/csv/rdoc/index.html

How to print from Flask @app.route to python console

It seems like you have it worked out, but for others looking for this answer, an easy way to do this is by printing to stderr. You can do that like this:

from __future__ import print_function # In python 2.7
import sys

@app.route('/button/')
def button_clicked():
    print('Hello world!', file=sys.stderr)
    return redirect('/')

Flask will display things printed to stderr in the console. For other ways of printing to stderr, see this stackoverflow post

Custom Cell Row Height setting in storyboard is not responding

One other thing you can do is to go to your Document Outline, select the table view that your prototype cell is nested. Then on the Size Inspector, change your table view Row Height to your desired value and uncheck the Automatic box.

Oracle DB: How can I write query ignoring case?

Also don't forget the obvious, does the data in the tables need to have case? You could only insert rows already in lower case (or convert the existing DB rows to lower case) and be done with it right from the start.

Laravel password validation rule

A Custom Laravel Validation Rule will allow developers to provide a custom message with each use case for a better UX experience.

php artisan make:rule IsValidPassword

namespace App\Rules;

use Illuminate\Support\Str;
use Illuminate\Contracts\Validation\Rule;

class isValidPassword implements Rule
{
    /**
     * Determine if the Length Validation Rule passes.
     *
     * @var boolean
     */
    public $lengthPasses = true;

    /**
     * Determine if the Uppercase Validation Rule passes.
     *
     * @var boolean
     */
    public $uppercasePasses = true;

    /**
     * Determine if the Numeric Validation Rule passes.
     *
     * @var boolean
     */
    public $numericPasses = true;

    /**
     * Determine if the Special Character Validation Rule passes.
     *
     * @var boolean
     */
    public $specialCharacterPasses = true;

    /**
     * Determine if the validation rule passes.
     *
     * @param  string  $attribute
     * @param  mixed  $value
     * @return bool
     */
    public function passes($attribute, $value)
    {
        $this->lengthPasses = (Str::length($value) >= 10);
        $this->uppercasePasses = (Str::lower($value) !== $value);
        $this->numericPasses = ((bool) preg_match('/[0-9]/', $value));
        $this->specialCharacterPasses = ((bool) preg_match('/[^A-Za-z0-9]/', $value));

        return ($this->lengthPasses && $this->uppercasePasses && $this->numericPasses && $this->specialCharacterPasses);
    }

    /**
     * Get the validation error message.
     *
     * @return string
     */
    public function message()
    {
        switch (true) {
            case ! $this->uppercasePasses
                && $this->numericPasses
                && $this->specialCharacterPasses:
                return 'The :attribute must be at least 10 characters and contain at least one uppercase character.';

            case ! $this->numericPasses
                && $this->uppercasePasses
                && $this->specialCharacterPasses:
                return 'The :attribute must be at least 10 characters and contain at least one number.';

            case ! $this->specialCharacterPasses
                && $this->uppercasePasses
                && $this->numericPasses:
                return 'The :attribute must be at least 10 characters and contain at least one special character.';

            case ! $this->uppercasePasses
                && ! $this->numericPasses
                && $this->specialCharacterPasses:
                return 'The :attribute must be at least 10 characters and contain at least one uppercase character and one number.';

            case ! $this->uppercasePasses
                && ! $this->specialCharacterPasses
                && $this->numericPasses:
                return 'The :attribute must be at least 10 characters and contain at least one uppercase character and one special character.';

            case ! $this->uppercasePasses
                && ! $this->numericPasses
                && ! $this->specialCharacterPasses:
                return 'The :attribute must be at least 10 characters and contain at least one uppercase character, one number, and one special character.';

            default:
                return 'The :attribute must be at least 10 characters.';
        }
    }
}

Then on your request validation:

$request->validate([
    'email'    => 'required|string|email:filter',
    'password' => [
        'required',
        'confirmed',
        'string',
        new isValidPassword(),
    ],
]);

How to make a <svg> element expand or contract to its parent container?

Suppose I have an SVG which looks like this: pic1

And I want to put it in a div and make it fill the div responsively. My way of doing it is as follows:

First I open the SVG file in an application like inkscape. In File->Document Properties I set the width of the document to 800px and and the height to 600px (you can choose other sizes). Then I fit the SVG into this document.

pic2

Then I save this file as a new SVG file and get the path data from this file. Now in HTML the code that does the magic is as follows:

<div id="containerId">    
    <svg
    id="svgId" 
    xmlns:svg="http://www.w3.org/2000/svg"
    xmlns="http://www.w3.org/2000/svg"
    version="1.1"
    x="0"
    y="0"
    width="100%"
    height="100%"
    viewBox="0 0 800 600"
    preserveAspectRatio="none">
       <path d="m0 0v600h800v-600h-75.07031l-431 597.9707-292.445315-223.99609 269.548825-373.97461h-271.0332z" fill="#f00"/>
    </svg>
</div>

Note that width and height of SVG are both set to 100%, since we want it to fill the container vertically and horizontally ,but width and height of the viewBox are the same as the width and height of the document in inkscape which is 800px X 600px. The next thing you need to do is set the preserveAspectRatio to "none". If you need to have more information on this attribute here's a good link. And that's all there is to it.

One more thing is that this code works on almost all the major browsers even the old ones but on some versions of android and ios you need to use some javascrip/jQuery code to keep it consistent. I use the following in document ready and resize functions:

$('#svgId').css({
    'width': $('#containerId').width() + 'px',
    'height': $('#containerId').height() + 'px'
});

Hope it helps!

How do I log errors and warnings into a file?

In addition, you need the "AllowOverride Options" directive for this to work. (Apache 2.2.15)

jQuery append() vs appendChild()

append is a jQuery method to append some content or HTML to an element.

$('#example').append('Some text or HTML');

appendChild is a pure DOM method for adding a child element.

document.getElementById('example').appendChild(newElement);

<button> background image

Astonishing that no answer addresses or mentions the actual problem here.

The CSS selector button #rock says "give me an element with the id rock inside a <button> element", like this:

<button>
    <span id="rock">This element is going to be affected.</span>
</button>

But what you wanted is a <button> element with the id rock. And the selector for that would be button#rock (note the missing space between button and #rock).

And as @Greg already mentioned: #rock is already specific enough to target the button and could be used on its own.

Determining the version of Java SDK on the Mac

The simplest solution would be open terminal

$ java -version

it shows the following

java version "1.6.0_65"
  1. Stefan's solution also works for me. Here's the exact input:

$ cd /System/Library/Frameworks/JavaVM.framework/Versions

$ ls -l

Below is the last line of output:

lrwxr-xr-x   1 root  wheel   59 Feb 12 14:57 CurrentJDK -> /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents

1.6.0.jdk would be the answer

Ajax using https on an http page

Here's what I do:

Generate a hidden iFrame with the data you would like to post. Since you still control that iFrame, same origin does not apply. Then submit the form in that iFrame to the ssl page. The ssl page then redirects to a non-ssl page with status messages. You have access to the iFrame.

Remove last specific character in a string c#

The TrimEnd method takes an input character array and not a string. The code below from Dot Net Perls, shows a more efficient example of how to perform the same functionality as TrimEnd.

static string TrimTrailingChars(string value)
{
    int removeLength = 0;
    for (int i = value.Length - 1; i >= 0; i--)
    {
        char let = value[i];
        if (let == '?' || let == '!' || let == '.')
        {
            removeLength++;
        }
        else
        {
            break;
        }
    }
    if (removeLength > 0)
    {
        return value.Substring(0, value.Length - removeLength);
    }
    return value;
}

<input type="file"> limit selectable files by extensions

NOTE: This answer is from 2011. It was a really good answer back then, but as of 2015, native HTML properties are supported by most browsers, so there's (usually) no need to implement such custom logic in JS. See Edi's answer and the docs.


Before the file is uploaded, you can check the file's extension using Javascript, and prevent the form being submitted if it doesn't match. The name of the file to be uploaded is stored in the "value" field of the form element.

Here's a simple example that only allows files that end in ".gif" to be uploaded:

<script type="text/javascript">
    function checkFile() {
        var fileElement = document.getElementById("uploadFile");
        var fileExtension = "";
        if (fileElement.value.lastIndexOf(".") > 0) {
            fileExtension = fileElement.value.substring(fileElement.value.lastIndexOf(".") + 1, fileElement.value.length);
        }
        if (fileExtension.toLowerCase() == "gif") {
            return true;
        }
        else {
            alert("You must select a GIF file for upload");
            return false;
        }
    }
</script>

<form action="upload.aspx" enctype="multipart/form-data" onsubmit="return checkFile();">
    <input name="uploadFile" id="uploadFile" type="file" />

    <input type="submit" />
</form>

However, this method is not foolproof. Sean Haddy is correct that you always want to check on the server side, because users can defeat your Javascript checking by turning off javascript, or editing your code after it arrives in their browser. Definitely check server-side in addition to the client-side check. Also I recommend checking for size server-side too, so that users don't crash your server with a 2 GB file (there's no way that I know of to check file size on the client side without using Flash or a Java applet or something).

However, checking client side before hand using the method I've given here is still useful, because it can prevent mistakes and is a minor deterrent to non-serious mischief.

What is a None value?

largest=none
smallest =none 
While True :
          num =raw_input ('enter a number ') 
          if num =="done ": break 
          try :
           inp =int (inp) 
          except:
              Print'Invalid input' 
           if largest is none :
               largest=inp
           elif inp>largest:
                largest =none 
           print 'maximum', largest

          if smallest is none:
               smallest =none
          elif inp<smallest :
               smallest =inp
          print 'minimum', smallest 

print 'maximum, minimum, largest, smallest 

How to handle calendar TimeZones using Java?

You can solve it with Joda Time:

Date utcDate = new Date(timezoneFrom.convertLocalToUTC(date.getTime(), false));
Date localDate = new Date(timezoneTo.convertUTCToLocal(utcDate.getTime()));

Java 8:

LocalDateTime localDateTime = LocalDateTime.parse("2007-12-03T10:15:30");
ZonedDateTime fromDateTime = localDateTime.atZone(
    ZoneId.of("America/Toronto"));
ZonedDateTime toDateTime = fromDateTime.withZoneSameInstant(
    ZoneId.of("Canada/Newfoundland"));

How to cast the size_t to double or int C++

If your code is prepared to deal with overflow errors, you can throw an exception if data is too large.

size_t data = 99999999;
if ( data > INT_MAX )
{
   throw std::overflow_error("data is larger than INT_MAX");
}
int convertData = static_cast<int>(data);

Convert base class to derived class

You can implement the conversion yourself, but I would not recommend that. Take a look at the Decorator Pattern if you want to do this in order to extend the functionality of an existing object.

How to find EOF through fscanf?

If you have integers in your file fscanf returns 1 until integer occurs. For example:

FILE *in = fopen("./task.in", "r");
int length = 0;
int counter;
int sequence;

for ( int i = 0; i < 10; i++ ) {
    counter = fscanf(in, "%d", &sequence);
    if ( counter == 1 ) {
        length += 1;
    }
}

To find out the end of the file with symbols you can use EOF. For example:

char symbol;
FILE *in = fopen("./task.in", "r");

for ( ; fscanf(in, "%c", &symbol) != EOF; ) {
    printf("%c", symbol); 
}

Lock down Microsoft Excel macro

you can set a password to your vba code but this can be quite easily broken up.

you can also create an addin and compile it into a DLL. See here for more information. That's at least the most secure way to protect your code.

Regards,

How can I change the color of a Google Maps marker?

Personally, I think the icons generated by the Google Charts API look great and are easy to customise dynamically.

See my answer on Google Maps API 3 - Custom marker color for default (dot) marker

Getting the count of unique values in a column in bash

To see a frequency count for column two (for example):

awk -F '\t' '{print $2}' * | sort | uniq -c | sort -nr

fileA.txt

z    z    a
a    b    c
w    d    e

fileB.txt

t    r    e
z    d    a
a    g    c

fileC.txt

z    r    a
v    d    c
a    m    c

Result:

  3 d
  2 r
  1 z
  1 m
  1 g
  1 b

TypeError: $(...).autocomplete is not a function

Simple solution: The sequence is really matter while including the auto complete libraries:

<link href="http://code.jquery.com/ui/1.10.2/themes/smoothness/jquery-ui.css" rel="Stylesheet"></link>
<script src='https://cdn.rawgit.com/pguso/jquery-plugin-circliful/master/js/jquery.circliful.min.js'></script>
<script src="http://code.jquery.com/ui/1.10.2/jquery-ui.js" ></script>

What is the difference between 'java', 'javaw', and 'javaws'?

I have checked that the output redirection works with javaw:

javaw -cp ... mypath.MyClass ... arguments 1>log.txt 2>err.txt

It means, if the Java application prints out anything via System.out or System.err, it is written to those files, as also with using java (without w). Especially on starting java, the JRE may write starting errors (class not found) on the error output pipe. In this respect, it is essential to know about errors. I suggest to use the console redirection in any case if javaw is invoked.

In opposite if you use

start java .... 1>log.txt 2>err.txt

With the Windows console start command, the console output redirection does not work with java nor with javaw.

Explanation why it is so: I think that javaw opens an internal process in the OS (adequate using the java.lang.Process class), and transfers a known output redirection to this process. If no redirection is given on the command line, nothing is redirected and the internal started process for javaw doesn't have any console outputs. The behavior for java.lang.Process is similar. The virtual machine may use this internal feature for javaw too.

If you use 'start', the Windows console creates a new process for Windows to execute the command after start, but this mechanism does not use a given redirection for the started sub process, unfortunately.

How do I verify/check/test/validate my SSH passphrase?

If your passphrase is to unlock your SSH key and you don't have ssh-agent, but do have sshd (the SSH daemon) installed on your machine, do:

cat ~/.ssh/id_rsa.pub >> ~/.ssh/authorized_keys;
ssh localhost -i ~/.ssh/id_rsa

Where ~/.ssh/id_rsa.pub is the public key, and ~/.ssh/id_rsa is the private key.

Count number of cells with any value (string or number) in a column in Google Docs Spreadsheet

Shorter and dealing with a column (entire, not just a section of a column):

=COUNTA(A:A)

COUNTA

Beware, a cell containing just a space would be included in the count.

SQLite "INSERT OR REPLACE INTO" vs. "UPDATE ... WHERE"

REPLACE INTO table(column_list) VALUES(value_list);

is a shorter form of

INSERT OR REPLACE INTO table(column_list) VALUES(value_list);

For REPLACE to execute correctly your table structure must have unique rows, whether a simple primary key or a unique index.

REPLACE deletes, then INSERTs the record and will cause an INSERT Trigger to execute if you have them setup. If you have a trigger on INSERT, you may encounter issues.


This is a work around.. not checked the speed..

INSERT OR IGNORE INTO table (column_list) VALUES(value_list);

followed by

UPDATE table SET field=value,field2=value WHERE uniqueid='uniquevalue'

This method allows a replace to occur without causing a trigger.

Finding the number of days between two dates

Using this simple function. Declare function

<?php
function dateDiff($firstDate,$secondDate){
    $firstDate = strtotime($firstDate);
    $secondDate = strtotime($secondDate);

    $datediff = $firstDate - $secondDate;
    $output = round($datediff / (60 * 60 * 24));
    return $output;
}
?>

and call this function like this where you want

<?php
    echo dateDiff("2018-01-01","2018-12-31");    

// OR

    $firstDate = "2018-01-01";
    $secondDate = "2018-01-01";
    echo dateDiff($firstDate,$secondDate);    
?>

How get value from URL

You can access those values with the global $_GET variable

//www.example.com/index.php?id=7
print $_GET['id']; // prints "7"

You should check all "incoming" user data - so here, that "id" is an INT. Don't use it directly in your SQL (vulnerable to SQL injections).

How to stop docker under Linux

In my case, it was neither systemd nor a cron job, but it was snap. So I had to run:

sudo snap stop docker
sudo snap remove docker

... and the last command actually never ended, I don't know why: this snap thing is really a pain. So I also ran:

sudo apt purge snap

:-)

How can I show and hide elements based on selected option with jQuery?

You are missing a :selected on the selector for show() - see the jQuery documentation for an example of how to use this.

In your case it will probably look something like this:

$('#'+$('#colorselector option:selected').val()).show();

How can I retrieve Id of inserted entity using Entity framework?

Repository.addorupdate(entity, entity.id);
Repository.savechanges();
Var id = entity.id;

This will work.

Creating a JSON dynamically with each input value using jquery

Like this:

function createJSON() {
    jsonObj = [];
    $("input[class=email]").each(function() {

        var id = $(this).attr("title");
        var email = $(this).val();

        item = {}
        item ["title"] = id;
        item ["email"] = email;

        jsonObj.push(item);
    });

    console.log(jsonObj);
}

Explanation

You are looking for an array of objects. So, you create a blank array. Create an object for each input by using 'title' and 'email' as keys. Then you add each of the objects to the array.

If you need a string, then do

jsonString = JSON.stringify(jsonObj);

Sample Output

[{"title":"QA","email":"a@b"},{"title":"PROD","email":"b@c"},{"title":"DEV","email":"c@d"}] 

jQuery looping .each() JSON key/value not working

Since you have an object, not a jQuery wrapper, you need to use a different variant of $.each()

$.each(json, function (key, data) {
    console.log(key)
    $.each(data, function (index, data) {
        console.log('index', data)
    })
})

Demo: Fiddle

Can lambda functions be templated?

There is a gcc extension which allows lambda templates:

// create the widgets and set the label
base::for_each(_widgets, [] <typename Key_T, typename Widget_T>
                         (boost::fusion::pair<Key_T, Widget_T*>& pair) -> void {
                             pair.second = new Widget_T();
                             pair.second->set_label_str(Key_T::label);
                          }
              );

where _widgets is a std::tuple< fusion::pair<Key_T, Widget_T>... >

Execution Failed for task :app:compileDebugJavaWithJavac in Android Studio

The problem is just in naming folder, if your folder to save your project contains special characters then remove them. If the error persists try to save the folder with no space.

What does the regex \S mean in JavaScript?

\s matches whitespace (spaces, tabs and new lines). \S is negated \s.

How do I force git to use LF instead of CR+LF under windows?

Context

If you

  1. want to force all users to have LF line endings for text files and
  2. you cannot ensure that all users change their git config,

you can do that starting with git 2.10. 2.10 or later is required, because 2.10 fixed the behavior of text=auto together with eol=lf. Source.

Solution

Put a .gitattributes file in the root of your git repository having following contents:

* text=auto eol=lf

Commit it.

Optional tweaks

You can also add an .editorconfig in the root of your repository to ensure that modern tooling creates new files with the desired line endings.

# EditorConfig is awesome: http://EditorConfig.org

# top-most EditorConfig file
root = true

# Unix-style newlines with a newline ending every file
[*]
end_of_line = lf
insert_final_newline = true

How to set different colors in HTML in one statement?

How about using FONT tag?

Like:

H<font color="red">E</font>LLO.

Can't show example here, because this site doesn't allow font tag use.

Span style is fast and easy too.

How can I change the size of a Bootstrap checkbox?

I have used this library with sucess

http://plugins.krajee.com/checkbox-x

It requires jQuery and bootstrap 3.x

Download the zip here: https://github.com/kartik-v/bootstrap-checkbox-x/zipball/master

Put the contents of the zip in a folder within your project

Pop the needed libs in your header

<link href="http://netdna.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet">
<link href="path/to/css/checkbox-x.min.css" media="all" rel="stylesheet" type="text/css" />
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.12.3/jquery.min.js"></script>
<script src="path/to/js/checkbox-x.min.js" type="text/javascript"></script>

Add the data controls to the element using the data-size="xl" to change the size as shown here http://plugins.krajee.com/cbx-sizes-demo

<label for="element_id">CheckME</label>
<input type="checkbox" name="my_element" id="element_id" value="1" data-toggle="checkbox-x" data-three-state="false" data-size="xl"/>

There are numerous other features as well if you browse the plugin site.

Shell Script Syntax Error: Unexpected End of File

Indentation when using a block can cause this error and is very hard to find.

if [ ! -d /var/lib/mysql/mysql ]; then
   /usr/bin/mysql --protocol=socket --user root << EOSQL
        SET @@SESSION.SQL_LOG_BIN=0;
        CREATE USER 'root'@'%';
   EOSQL
fi

=> Example above will cause an error because EOSQL is indented. Remove indentation as shown below. Posting this because it took me over an hour to figure out the error.

if [ ! -d /var/lib/mysql/mysql ]; then
   /usr/bin/mysql --protocol=socket --user root << EOSQL
        SET @@SESSION.SQL_LOG_BIN=0;
        CREATE USER 'root'@'%';
EOSQL
fi

NHibernate.MappingException: No persister for: XYZ

Something obvious, yet quite useful for someone new to NHibernate.

All XML Mapping files should be treated as Embedded Resources rather than the default Content. This option is set by editing the Build Action attribute in the file's properties.

XML files are then embedded into the assembly, and parsed at project startup during NHibernate's configuration phase.

Spring data JPA query with parameter properties

@Autowired
private EntityManager entityManager;

@RequestMapping("/authors/{fname}/{lname}")
    public List actionAutherMulti(@PathVariable("fname") String fname, @PathVariable("lname") String lname) {
        return entityManager.createQuery("select A from Auther A WHERE A.firstName = ?1 AND A.lastName=?2")
                .setParameter(1, fname)
                .setParameter(2, lname)
                .getResultList();
    }

How can I check if mysql is installed on ubuntu?

Multiple ways of searching for the program.

Type mysql in your terminal, see the result.

Search the /usr/bin, /bin directories for the binary.

Type apt-cache show mysql to see if it is installed

locate mysql

Tomcat base URL redirection

In Tomcat 8 you can also use the rewrite-valve

RewriteCond %{REQUEST_URI} ^/$
RewriteRule ^/(.*)$         /somethingelse/index.jsp

To setup the rewrite-valve look here:

http://tonyjunkes.com/blog/a-brief-look-at-the-rewrite-valve-in-tomcat-8/

How to extract URL parameters from a URL with Ruby or Rails?

In your Controller, you should be able to access a dictionary (hash) called params. So, if you know what the names of each query parameter is, then just do params[:param1] to access it... If you don't know what the names of the parameters are, you could traverse the dictionary and get the keys.

Some simple examples here.

How do I change the color of radio buttons?

As other said, there's no way to achieve this in all browser, so best way of doing so crossbrowser is using javascript unobtrusively. Basically you have to turn your radiobutton into links (fully customizable via CSS). each click on link will be bound to the related radiobox, toggling his state and all the others.

Php artisan make:auth command is not defined

In Laravel 6.0 make:auth no longer exists. Read more here

A- Shorthand:

Update Nov 18th: Taylor just released Laravel Installer 2.3.0 added a new "--auth" flag to create a new project with the authentication scaffolding installed!

To update laravel installer read here

It means we can do:

laravel new project --auth

cd project

php artisan migrate

npm install
npm run dev

Which is a shorthand of commands in the Section B. Also read more here


B - Details:

Follow these three steps

Step 1 - First do this:

laravel new project

cd project

composer require laravel/ui --dev

Note: Laravel UI Composer package is a new first-party package that extracts the UI portion of a Laravel project ( frontend scaffolding typically provided with previous releases of Laravel ) into a separate laravel/ui package. The separate package enables the Laravel team to update, develop and version UI scaffolding package separately from the primary framework and the main Laravel codebase.

Step 2 - Then do this:

php artisan ui bootstrap --auth
php artisan migrate

or

php artisan ui vue --auth
php artisan migrate

instead of

php artisan make:auth  ( which works for Laravel 5.8 and older versions )

More Options here

php artisan ui:auth

The above command will generate only the auth routes, a HomeController, auth views, and a app.blade.php layout file.

You can also generate the views only with:

php artisan ui:auth --views

The console command will prompt you to confirm overwriting auth files if you've already run the command before.

// Generate basic scaffolding...
php artisan ui vue
php artisan ui react

and also:

// Generate login / registration scaffolding...
php artisan ui vue --auth
php artisan ui react --auth

To see differences read this article

Step 3 - Then you need to do:

npm install
npm run dev

Is it possible to use argsort in descending order?

If you negate an array, the lowest elements become the highest elements and vice-versa. Therefore, the indices of the n highest elements are:

(-avgDists).argsort()[:n]

Another way to reason about this, as mentioned in the comments, is to observe that the big elements are coming last in the argsort. So, you can read from the tail of the argsort to find the n highest elements:

avgDists.argsort()[::-1][:n]

Both methods are O(n log n) in time complexity, because the argsort call is the dominant term here. But the second approach has a nice advantage: it replaces an O(n) negation of the array with an O(1) slice. If you're working with small arrays inside loops then you may get some performance gains from avoiding that negation, and if you're working with huge arrays then you can save on memory usage because the negation creates a copy of the entire array.

Note that these methods do not always give equivalent results: if a stable sort implementation is requested to argsort, e.g. by passing the keyword argument kind='mergesort', then the first strategy will preserve the sorting stability, but the second strategy will break stability (i.e. the positions of equal items will get reversed).

Example timings:

Using a small array of 100 floats and a length 30 tail, the view method was about 15% faster

>>> avgDists = np.random.rand(100)
>>> n = 30
>>> timeit (-avgDists).argsort()[:n]
1.93 µs ± 6.68 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
>>> timeit avgDists.argsort()[::-1][:n]
1.64 µs ± 3.39 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
>>> timeit avgDists.argsort()[-n:][::-1]
1.64 µs ± 3.66 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

For larger arrays, the argsort is dominant and there is no significant timing difference

>>> avgDists = np.random.rand(1000)
>>> n = 300
>>> timeit (-avgDists).argsort()[:n]
21.9 µs ± 51.2 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
>>> timeit avgDists.argsort()[::-1][:n]
21.7 µs ± 33.3 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
>>> timeit avgDists.argsort()[-n:][::-1]
21.9 µs ± 37.1 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)

Please note that the comment from nedim below is incorrect. Whether to truncate before or after reversing makes no difference in efficiency, since both of these operations are only striding a view of the array differently and not actually copying data.

How can one use multi threading in PHP applications

pcntl_fork won't work in a web server environment if it has safe mode turned on. In this case, it will only work in the CLI version of PHP.

How to pass an array into a SQL Server stored procedure

There is no support for array in sql server but there are several ways by which you can pass collection to a stored proc .

  1. By using datatable
  2. By using XML.Try converting your collection in an xml format and then pass it as an input to a stored procedure

The below link may help you

passing collection to a stored procedure

How to resolve TypeError: can only concatenate str (not "int") to str

Problem is you are doing the following

str(chr(char + 7429146))

where char is a string. You cannot add a int with a string. this will cause that error

maybe if you want to get the ascii code and add it with a constant number. if so , you can just do ord(char) and add it to a number. but again, chr can take values between 0 and 1114112

How to check if image exists with given url?

From here:

// when the DOM is ready
$(function () {
  var img = new Image();
  // wrap our new image in jQuery, then:
  $(img)
    // once the image has loaded, execute this code
    .load(function () {
      // set the image hidden by default    
      $(this).hide();
      // with the holding div #loader, apply:
      $('#loader')
        // remove the loading class (so no background spinner), 
        .removeClass('loading')
        // then insert our image
        .append(this);
      // fade our image in to create a nice effect
      $(this).fadeIn();
    })
    // if there was an error loading the image, react accordingly
    .error(function () {
      // notify the user that the image could not be loaded
    })
    // *finally*, set the src attribute of the new image to our image
    .attr('src', 'images/headshot.jpg');
});

How can I decrypt a password hash in PHP?

The passwords cannot be decrypted as will makes a vulnerability for users. So, you can simply use password_verify() method to compare the passwords.

if(password_verify($upass, $userRow['user_pass'])){
     //code for redirecting to login screen }

where, $upass is password entered by user and $userRow['user_pass'] is user_pass field in database which is encrypted by password_hash() function.

Retrieve specific commit from a remote Git repository

In a project we had a problem so that we had to revert back to a certain commit. We made it with the following command successfully:

git reset --hard <commitID>

How to select the first row of each group?

A nice way of doing this with the dataframe api is using the argmax logic like so

  val df = Seq(
    (0,"cat26",30.9), (0,"cat13",22.1), (0,"cat95",19.6), (0,"cat105",1.3),
    (1,"cat67",28.5), (1,"cat4",26.8), (1,"cat13",12.6), (1,"cat23",5.3),
    (2,"cat56",39.6), (2,"cat40",29.7), (2,"cat187",27.9), (2,"cat68",9.8),
    (3,"cat8",35.6)).toDF("Hour", "Category", "TotalValue")

  df.groupBy($"Hour")
    .agg(max(struct($"TotalValue", $"Category")).as("argmax"))
    .select($"Hour", $"argmax.*").show

 +----+----------+--------+
 |Hour|TotalValue|Category|
 +----+----------+--------+
 |   1|      28.5|   cat67|
 |   3|      35.6|    cat8|
 |   2|      39.6|   cat56|
 |   0|      30.9|   cat26|
 +----+----------+--------+

function to remove duplicate characters in a string

The function looks fine to me. I've written inline comments. Hope it helps:

// function takes a char array as input.
// modifies it to remove duplicates and adds a 0 to mark the end
// of the unique chars in the array.
public static void removeDuplicates(char[] str) {
  if (str == null) return; // if the array does not exist..nothing to do return.
  int len = str.length; // get the array length.
  if (len < 2) return; // if its less than 2..can't have duplicates..return.
  int tail = 1; // number of unique char in the array.
  // start at 2nd char and go till the end of the array.
  for (int i = 1; i < len; ++i) { 
    int j;
    // for every char in outer loop check if that char is already seen.
    // char in [0,tail) are all unique.
    for (j = 0; j < tail; ++j) {
      if (str[i] == str[j]) break; // break if we find duplicate.
    }
    // if j reachs tail..we did not break, which implies this char at pos i
    // is not a duplicate. So we need to add it our "unique char list"
    // we add it to the end, that is at pos tail.
    if (j == tail) {
      str[tail] = str[i]; // add
      ++tail; // increment tail...[0,tail) is still "unique char list"
    }
  }
  str[tail] = 0; // add a 0 at the end to mark the end of the unique char.
}

Call to a member function on a non-object

It could also mean that when you initialized your object, you may have re-used the object name in another part of your code. Therefore changing it's aspect from an object to a standard variable.

IE

$game = new game;

$game->doGameStuff($gameReturn);

foreach($gameArray as $game)
{
   $game['STUFF']; // No longer an object and is now a standard variable pointer for $game.
}



$game->doGameStuff($gameReturn);  // Wont work because $game is declared as a standard variable.  You need to be careful when using common variable names and were they are declared in your code.

Difference between Grunt, NPM and Bower ( package.json vs bower.json )

Update for mid 2016:

The things are changing so fast that if it's late 2017 this answer might not be up to date anymore!

Beginners can quickly get lost in choice of build tools and workflows, but what's most up to date in 2016 is not using Bower, Grunt or Gulp at all! With help of Webpack you can do everything directly in NPM!

Don't get me wrong people use other workflows and I still use GULP in my legacy project(but slowly moving out of it), but this is how it's done in the best companies and developers working in this workflow make a LOT of money!

Look at this template it's a very up-to-date setup consisting of a mixture of the best and the latest technologies: https://github.com/coryhouse/react-slingshot

  • Webpack
  • NPM as a build tool (no Gulp, Grunt or Bower)
  • React with Redux
  • ESLint
  • the list is long. Go and explore!

Your questions:

When I want to add a package (and check in the dependency into git), where does it belong - into package.json or into bower.json

  • Everything belongs in package.json now

  • Dependencies required for build are in "devDependencies" i.e. npm install require-dir --save-dev (--save-dev updates your package.json by adding an entry to devDependencies)

  • Dependencies required for your application during runtime are in "dependencies" i.e. npm install lodash --save (--save updates your package.json by adding an entry to dependencies)

If that is the case, when should I ever install packages explicitly like that without adding them to the file that manages dependencies (apart from installing command line tools globally)?

Always. Just because of comfort. When you add a flag (--save-dev or --save) the file that manages deps (package.json) gets updated automatically. Don't waste time by editing dependencies in it manually. Shortcut for npm install --save-dev package-name is npm i -D package-name and shortcut for npm install --save package-name is npm i -S package-name

What is the difference between the HashMap and Map objects in Java?

There is no difference between the objects; you have a HashMap<String, Object> in both cases. There is a difference in the interface you have to the object. In the first case, the interface is HashMap<String, Object>, whereas in the second it's Map<String, Object>. But the underlying object is the same.

The advantage to using Map<String, Object> is that you can change the underlying object to be a different kind of map without breaking your contract with any code that's using it. If you declare it as HashMap<String, Object>, you have to change your contract if you want to change the underlying implementation.


Example: Let's say I write this class:

class Foo {
    private HashMap<String, Object> things;
    private HashMap<String, Object> moreThings;

    protected HashMap<String, Object> getThings() {
        return this.things;
    }

    protected HashMap<String, Object> getMoreThings() {
        return this.moreThings;
    }

    public Foo() {
        this.things = new HashMap<String, Object>();
        this.moreThings = new HashMap<String, Object>();
    }

    // ...more...
}

The class has a couple of internal maps of string->object which it shares (via accessor methods) with subclasses. Let's say I write it with HashMaps to start with because I think that's the appropriate structure to use when writing the class.

Later, Mary writes code subclassing it. She has something she needs to do with both things and moreThings, so naturally she puts that in a common method, and she uses the same type I used on getThings/getMoreThings when defining her method:

class SpecialFoo extends Foo {
    private void doSomething(HashMap<String, Object> t) {
        // ...
    }

    public void whatever() {
        this.doSomething(this.getThings());
        this.doSomething(this.getMoreThings());
    }

    // ...more...
}

Later, I decide that actually, it's better if I use TreeMap instead of HashMap in Foo. I update Foo, changing HashMap to TreeMap. Now, SpecialFoo doesn't compile anymore, because I've broken the contract: Foo used to say it provided HashMaps, but now it's providing TreeMaps instead. So we have to fix SpecialFoo now (and this kind of thing can ripple through a codebase).

Unless I had a really good reason for sharing that my implementation was using a HashMap (and that does happen), what I should have done was declare getThings and getMoreThings as just returning Map<String, Object> without being any more specific than that. In fact, barring a good reason to do something else, even within Foo I should probably declare things and moreThings as Map, not HashMap/TreeMap:

class Foo {
    private Map<String, Object> things;             // <== Changed
    private Map<String, Object> moreThings;         // <== Changed

    protected Map<String, Object> getThings() {     // <== Changed
        return this.things;
    }

    protected Map<String, Object> getMoreThings() { // <== Changed
        return this.moreThings;
    }

    public Foo() {
        this.things = new HashMap<String, Object>();
        this.moreThings = new HashMap<String, Object>();
    }

    // ...more...
}

Note how I'm now using Map<String, Object> everywhere I can, only being specific when I create the actual objects.

If I had done that, then Mary would have done this:

class SpecialFoo extends Foo {
    private void doSomething(Map<String, Object> t) { // <== Changed
        // ...
    }

    public void whatever() {
        this.doSomething(this.getThings());
        this.doSomething(this.getMoreThings());
    }
}

...and changing Foo wouldn't have made SpecialFoo stop compiling.

Interfaces (and base classes) let us reveal only as much as is necessary, keeping our flexibility under the covers to make changes as appropriate. In general, we want to have our references be as basic as possible. If we don't need to know it's a HashMap, just call it a Map.

This isn't a blind rule, but in general, coding to the most general interface is going to be less brittle than coding to something more specific. If I'd remembered that, I wouldn't have created a Foo that set Mary up for failure with SpecialFoo. If Mary had remembered that, then even though I messed up Foo, she would have declared her private method with Map instead of HashMap and my changing Foo's contract wouldn't have impacted her code.

Sometimes you can't do that, sometimes you have to be specific. But unless you have a reason to be, err toward the least-specific interface.

How to disable Python warnings?

There's the -W option.

python -W ignore foo.py

How to annotate MYSQL autoincrement field with JPA annotations

As you have define the id in int type at the database creation, you have to use the same data type in the model class too. And as you have defined the id to auto increment in the database, you have to mention it in the model class by passing value 'GenerationType.AUTO' into the attribute 'strategy' within the annotation @GeneratedValue. Then the code becomes as below.

@Entity
public class Operator{

  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  private int id;

  private String username;

  private String password;

  private Integer active;

  //Getters and setters...
}

Split page vertically using CSS

Here is the flex-box approach:

CSS

 .parent {
  display:flex;
  height:100vh;
  }
  .child{
    flex-grow:1;
  }
  .left{
    background:#ddd;
  }
  .center{
    background:#666;
  }

  .right{
    background:#999;
  }

HTML

<div class="parent">
    <div class="child left">Left</div>
    <div class="child center">Center</div>
    <div class="child right">Right</div>
</div>

You can try the same in js fiddle.

How to style readonly attribute with CSS?

capitalize the first letter of Only

_x000D_
_x000D_
input[readOnly] {_x000D_
      background: red !important;_x000D_
    }
_x000D_
<input type="text" name="country" value="China" readonly="readonly" />
_x000D_
_x000D_
_x000D_

How to find index of STRING array in Java from a given value?

Try this Function :

public int indexOfArray(String input){
     for(int i=0;i<TYPES,length();i++)
       {
         if(TYPES[i].equals(input))
         {
          return i ;
         }
        }
      return -1     // if the text not found the function return -1
      }

jQuery trigger event when click outside the element

Just have your menuWraper element call event.stopPropagation() so that its click event doesn't bubble up to the document.

Try it out: http://jsfiddle.net/Py7Mu/

$(document).click(function() {
    alert('clicked outside');
});

$(".menuWraper").click(function(event) {
    alert('clicked inside');
    event.stopPropagation();
});

Alternatively, you could return false; instead of using event.stopPropagation();

How do I make a PHP form that submits to self?

I guess , you means $_SERVER['PHP_SELF']. And if so , you really shouldn't use it without sanitizing it first. This leaves you open to XSS attacks.

The if(isset($_POST['submit'])) condition should be above all the HTML output, and should contain a header() function with a redirect to current page again (only now , with some nice notice that "emails has been sent" .. or something ). For that you will have to use $_SESSION or $_COOKIE.

And please. Stop using $_REQUEST. It too poses a security threat.

Nginx: Job for nginx.service failed because the control process exited

Just write this your work get done

sudo rm /etc/nginx/sites-enabled/default

sudo service nginx restart

systemctl status nginx

Happy Learning

continuous page numbering through section breaks

You can check out this post on SuperUser.

Word starts page numbering over for each new section by default.

I do it slightly differently than the post above that goes through the ribbon menus, but in both methods you have to go through the document to each section's beginning.

My method:

  • open up the footer (or header if that's where your page number is)
  • drag-select the page number
  • right-click on it
  • hit Format Page Numbers
  • click on the Continue from Previous Section radio button under Page numbering

I find this right-click method to be a little faster. Also, usually if I insert the page numbers first before I start making any new sections, this problem doesn't happen in the first place.

How to set full calendar to a specific start date when it's initialized for the 1st time?

I've had better luck with calling the gotoDate in the viewRender callback:

$('#calendar').fullCalendar({
  firstDay: 0,
  defaultView: 'basicWeek',
  header: {
    left: '',
    center: 'basicDay,basicWeek,month',
    right:  'today prev,next'
  },
  viewRender: function(view, element) {
    $('#calendar').fullCalendar( 'gotoDate', 2014, 4, 24 );
  }
});

Calling gotoDate outside of the callback didn't have the expected results due to a race condition.

'Missing recommended icon file - The bundle does not contain an app icon for iPhone / iPod Touch of exactly '120x120' pixels, in .png format'

In my case it was linked with CocoaPods. I've spent a bunch of time to find what was the reason, cause everything seemed correct. I found it over here https://github.com/CocoaPods/CocoaPods/issues/7003. I just moved the "[CP] Copy Pods Resources" and "[CP] Embed Pods Frameworks" above "Copy Bundle Resources" in the Build Phases and the error dissapeared.

Where can I get Google developer key

"Public API access" the key generated there is the key you got to paste into your public static final String DEVELOPER_KEY as part of this writing 26.12.2013 It is not the clientID but you got take the steps mentioned above to obtain one and generate the public api access key.

Automatically scroll down chat div

As I am not master in js but I myself write code which check if user is at bottom. If user is at bottom then chat page will automatically scroll with new message. and if user scroll up then page will not auto scroll to bottom..

JS code -

var checkbottom;
jQuery(function($) {
$('.chat_screen').on('scroll', function() {
    var check = $(this).scrollTop() + $(this).innerHeight() >= $(this) 
[0].scrollHeight;
    if(check) {
       checkbottom = "bottom";
    }
    else {
    checkbottom = "nobottom";
    }
})
});
window.setInterval(function(){
if (checkbottom=="bottom") {
var objDiv = document.getElementById("chat_con");
objDiv.scrollTop = objDiv.scrollHeight;
}
}, 500);

html code -

<div id="chat_con" class="chat_screen">
</div>

PHP php_network_getaddresses: getaddrinfo failed: No such host is known

IMO it's the different way to resolve a name from the OS and PHP.

Try:

echo gethostbyname("host.name.tld");

and

var_export (dns_get_record ( "host.name.tld") );

or

$dns=array("8.8.8.8","8.8.4.4");
var_export (dns_get_record ( "host.name.tld" ,  DNS_ALL , $dns ));

You should found some DNS/resolver error.

Change the image source on rollover using jQuery

Whilst looking for a solution some time back, I found a similar script to the below, which after some tweaking I got working for me.

It handles two images, that almost always default to "off", where the mouse is off the image (image-example_off.jpg), and the occasional "on", where for the times the mouse is hovered, the required alternative image (image-example_on.jpg) is displayed.

<script type="text/javascript">        
    $(document).ready(function() {        
        $("img", this).hover(swapImageIn, swapImageOut);

        function swapImageIn(e) {
            this.src = this.src.replace("_off", "_on");
        }
        function swapImageOut (e) {
            this.src = this.src.replace("_on", "_off");
        }
    });
</script>