Programs & Examples On #Getpwnam

Should import statements always be at the top of a module?

It's interesting that not a single answer mentioned parallel processing so far, where it might be REQUIRED that the imports are in the function, when the serialized function code is what is being pushed around to other cores, e.g. like in the case of ipyparallel.

Gradients on UIView and UILabels On iPhone

This is what I got working- set UIButton in xCode's IB to transparent/clear, and no bg image.

UIColor *pinkDarkOp = [UIColor colorWithRed:0.9f green:0.53f blue:0.69f alpha:1.0];
UIColor *pinkLightOp = [UIColor colorWithRed:0.79f green:0.45f blue:0.57f alpha:1.0];

CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = [[shareWordButton layer] bounds];
gradient.cornerRadius = 7;
gradient.colors = [NSArray arrayWithObjects:
                   (id)pinkDarkOp.CGColor,
                   (id)pinkLightOp.CGColor,
                   nil];
gradient.locations = [NSArray arrayWithObjects:
                      [NSNumber numberWithFloat:0.0f],
                      [NSNumber numberWithFloat:0.7],
                      nil];

[[recordButton layer] insertSublayer:gradient atIndex:0];

Interfaces — What's the point?

Here are your examples reexplained:

public interface IFood // not Pizza
{
    public void Prepare();

}

public class Pizza : IFood
{
    public void Prepare() // Not order for explanations sake
    {
        //Prepare Pizza
    }
}

public class Burger : IFood
{
    public void Prepare()
    {
        //Prepare Burger
    }
}

AngularJS - Animate ng-view transitions

Try checking his post. It shows how to implement transitions between web pages using AngularJS's ngRoute and ngAnimate: How to Make iPhone-Style Web Page Transitions Using AngularJS & CSS

What does the @Valid annotation indicate in Spring?

Just adding to the above answer, In a web application @valid is used where the bean to be validated is also annotated with validation annotations e.g. @NotNull, @Email(hibernate annotation) so when while getting input from user the values can be validated and binding result will have the validation results. bindingResult.hasErrors() will tell if any validation failed.

What is the technology behind wechat, whatsapp and other messenger apps?

The WhatsApp Architecture Facebook Bought For $19 Billion explains the architecture involved in design of whatsapp.

Here is the general explanation from the link

  • WhatsApp server is almost completely implemented in Erlang.

  • Server systems that do the backend message routing are done in Erlang.

  • Great achievement is that the number of active users is managed with a really small server footprint. Team consensus is that it is largely because of Erlang.

  • Interesting to note Facebook Chat was written in Erlang in 2009, but they went away from it because it was hard to find qualified programmers.

  • WhatsApp server has started from ejabberd

  • Ejabberd is a famous open source Jabber server written in Erlang.

  • Originally chosen because its open, had great reviews by developers, ease of start and the promise of Erlang’s long term suitability for large communication system.

  • The next few years were spent re-writing and modifying quite a few parts of ejabberd, including switching from XMPP to internally developed protocol, restructuring the code base and redesigning some core components, and making lots of important modifications to Erlang VM to optimize server performance.

  • To handle 50 billion messages a day the focus is on making a reliable system that works. Monetization is something to look at later, it’s far far down the road.

  • A primary gauge of system health is message queue length. The message queue length of all the processes on a node is constantly monitored and an alert is sent out if they accumulate backlog beyond a preset threshold. If one or more processes falls behind that is alerted on, which gives a pointer to the next bottleneck to attack.

  • Multimedia messages are sent by uploading the image, audio or video to be sent to an HTTP server and then sending a link to the content along with its Base64 encoded thumbnail (if applicable).

  • Some code is usually pushed every day. Often, it’s multiple times a day, though in general peak traffic times are avoided. Erlang helps being aggressive in getting fixes and features into production. Hot-loading means updates can be pushed without restarts or traffic shifting. Mistakes can usually be undone very quickly, again by hot-loading. Systems tend to be much more loosely-coupled which makes it very easy to roll changes out incrementally.

  • What protocol is used in Whatsapp app? SSL socket to the WhatsApp server pools. All messages are queued on the server until the client reconnects to retrieve the messages. The successful retrieval of a message is sent back to the whatsapp server which forwards this status back to the original sender (which will see that as a "checkmark" icon next to the message). Messages are wiped from the server memory as soon as the client has accepted the message

  • How does the registration process work internally in Whatsapp? WhatsApp used to create a username/password based on the phone IMEI number. This was changed recently. WhatsApp now uses a general request from the app to send a unique 5 digit PIN. WhatsApp will then send a SMS to the indicated phone number (this means the WhatsApp client no longer needs to run on the same phone). Based on the pin number the app then request a unique key from WhatsApp. This key is used as "password" for all future calls. (this "permanent" key is stored on the device). This also means that registering a new device will invalidate the key on the old device.

Apache VirtualHost and localhost

This worked for me!

To run projects like http://localhost/projectName

<VirtualHost localhost:80>
   ServerAdmin localhost
    DocumentRoot path/to/htdocs/
    ServerName localhost
</VirtualHost>

To run projects like http://somewebsite.com locally

<VirtualHost somewebsite.com:80>
     ServerAdmin [email protected]
     DocumentRoot /path/to/htdocs/somewebsiteFolder
     ServerName www.somewebsite.com
     ServerAlias somewebsite.com
</VirtualHost>

Same for other websites

<VirtualHost anothersite.local:80>
     ServerAdmin [email protected]
     DocumentRoot /path/to/htdocs/anotherSiteFolder
     ServerName www.anothersite.local
     ServerAlias anothersite.com
</VirtualHost>

How to insert selected columns from a CSV file to a MySQL database using LOAD DATA INFILE

Specify the name of columns in the CSV in the load data infile statement.

The code is like this:

LOAD DATA INFILE '/path/filename.csv'
INTO TABLE table_name
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\r\n'
(column_name3, column_name5);

Here you go with adding data to only two columns(you can choose them with the name of the column) to the table.

The only thing you have to take care is that you have a CSV file(filename.csv) with two values per line(row). Otherwise please mention. I have a different solution.

Thank you.

Viewing full version tree in git

There is a very good answer to the same question.
Adding following lines to "~/.gitconfig":

[alias]
lg1 = log --graph --abbrev-commit --decorate --date=relative --format=format:'%C(bold blue)%h%C(reset) - %C(bold green)(%ar)%C(reset) %C(white)%s%C(reset) %C(dim white)- %an%C(reset)%C(bold yellow)%d%C(reset)' --all
lg2 = log --graph --abbrev-commit --decorate --format=format:'%C(bold blue)%h%C(reset) - %C(bold cyan)%aD%C(reset) %C(bold green)(%ar)%C(reset)%C(bold yellow)%d%C(reset)%n''          %C(white)%s%C(reset) %C(dim white)- %an%C(reset)' --all
lg = !"git lg1"

How do I center text vertically and horizontally in Flutter?

Put the Text in a Center:

Container(
      height: 45,
      color: Colors.black,
      child: Center(
        child: Text(
            'test',
            style: TextStyle(color: Colors.white),
        ),
      ),
    );

Correct MIME Type for favicon.ico?

I have noticed that when using type="image/vnd.microsoft.icon", the favicon fails to appear when the browser is not connected to the internet. But type="image/x-icon" works whether the browser can connect to the internet, or not. When developing, at times I am not connected to the internet.

Handling InterruptedException in Java

I would say in some cases it's ok to do nothing. Probably not something you should be doing by default, but in case there should be no way for the interrupt to happen, I'm not sure what else to do (probably logging error, but that does not affect program flow).

One case would be in case you have a task (blocking) queue. In case you have a daemon Thread handling these tasks and you do not interrupt the Thread by yourself (to my knowledge the jvm does not interrupt daemon threads on jvm shutdown), I see no way for the interrupt to happen, and therefore it could be just ignored. (I do know that a daemon thread may be killed by the jvm at any time and therefore are unsuitable in some cases).

EDIT: Another case might be guarded blocks, at least based on Oracle's tutorial at: http://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html

How to import keras from tf.keras in Tensorflow?

I have a similar problem importing those libs. I am using Anaconda Navigator 1.8.2 with Spyder 3.2.8.

My code is the following:

import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
import math

#from tf.keras.models import Sequential  # This does not work!
from tensorflow.python.keras.models import Sequential
from tensorflow.python.keras.layers import InputLayer, Input
from tensorflow.python.keras.layers import Reshape, MaxPooling2D
from tensorflow.python.keras.layers import Conv2D, Dense, Flatten

I get the following error:

from tensorflow.python.keras.models import Sequential

ModuleNotFoundError: No module named 'tensorflow.python.keras'

I solve this erasing tensorflow.python

With this code I solve the error:

import matplotlib.pyplot as plt
import tensorflow as tf
import numpy as np
import math

#from tf.keras.models import Sequential  # This does not work!
from keras.models import Sequential
from keras.layers import InputLayer, Input
from keras.layers import Reshape, MaxPooling2D
from keras.layers import Conv2D, Dense, Flatten

How do I copy an object in Java?

public class MyClass implements Cloneable {

private boolean myField= false;
// and other fields or objects

public MyClass (){}

@Override
public MyClass clone() throws CloneNotSupportedException {
   try
   {
       MyClass clonedMyClass = (MyClass)super.clone();
       // if you have custom object, then you need create a new one in here
       return clonedMyClass ;
   } catch (CloneNotSupportedException e) {
       e.printStackTrace();
       return new MyClass();
   }

  }
}

and in your code:

MyClass myClass = new MyClass();
// do some work with this object
MyClass clonedMyClass = myClass.clone();

How to remove package using Angular CLI?

Sometimes a dependency added with ng add will add more than one package, typing npm uninstall lib1 lib2 could be error prone and slow, so just remove the not needed libraries from package.json and run npm i

Can I pass a JavaScript variable to another browser window?

In your parent window:

var yourValue = 'something';
window.open('/childwindow.html?yourKey=' + yourValue);

Then in childwindow.html:

var query = location.search.substring(1);
var parameters = {};
var keyValues = query.split(/&/);
for (var keyValue in keyValues) {
    var keyValuePairs = keyValue.split(/=/);
    var key = keyValuePairs[0];
    var value = keyValuePairs[1];
    parameters[key] = value;
}

alert(parameters['yourKey']);

There is potentially a lot of error checking you should be doing in the parsing of your key/value pairs but I'm not including it here. Maybe someone can provide a more inclusive Javascript query string parsing routine in a later answer.

List of IP addresses/hostnames from local network in Python

If you know the names of your computers you can use:

import socket
IP1 = socket.gethostbyname(socket.gethostname()) # local IP adress of your computer
IP2 = socket.gethostbyname('name_of_your_computer') # IP adress of remote computer

Otherwise you will have to scan for all the IP addresses that follow the same mask as your local computer (IP1), as stated in another answer.

Python conversion between coordinates

There is a better way to write polar(), here it is:

def polar(x,y):
  `returns r, theta(degrees)`
  return math.hypot(x,y),math.degrees(math.atan2(y,x))

Radio Buttons ng-checked with ng-model

[Personal Option] Avoiding using $scope, based on John Papa Angular Style Guide

so my idea is take advantage of the current model:

_x000D_
_x000D_
(function(){_x000D_
  'use strict';_x000D_
  _x000D_
   var app = angular.module('way', [])_x000D_
   app.controller('Decision', Decision);_x000D_
_x000D_
   Decision.$inject = [];     _x000D_
_x000D_
   function Decision(){_x000D_
     var vm = this;_x000D_
     vm.checkItOut = _register;_x000D_
_x000D_
     function _register(newOption){_x000D_
       console.log('should I stay or should I go');_x000D_
       console.log(newOption);  _x000D_
     }_x000D_
   }_x000D_
_x000D_
     _x000D_
     _x000D_
})();
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<div ng-app="way">_x000D_
  <div ng-controller="Decision as vm">_x000D_
    <form name="myCheckboxTest" ng-submit="vm.checkItOut(decision)">_x000D_
 <label class="radio-inline">_x000D_
  <input type="radio" name="option" ng-model="decision.myWay"_x000D_
                           ng-value="false" ng-checked="!decision.myWay"> Should I stay?_x000D_
                </label>_x000D_
                <label class="radio-inline">_x000D_
                    <input type="radio" name="option" ng-value="true"_x000D_
                           ng-model="decision.myWay" > Should I go?_x000D_
                </label>_x000D_
  _x000D_
</form>_x000D_
  </div>_x000D_
  _x000D_
</div>
_x000D_
_x000D_
_x000D_

I hope I could help ;)

CSS to make table 100% of max-width

max-width is definitely not well supported. If you're going to use it, use it in a media query in your style tag. ios, android, and windows phone default mail all support them. (gmail and outlook mobile don't)

http://www.campaignmonitor.com/guides/mobile/targeting/

Look at the starbucks example at the bottom

The best way to calculate the height in a binary search tree? (balancing an AVL-tree)

Here's an alternate way of finding height. Add an additional attribute to your node called height:

class Node
{
data value; //data is a custom data type
node right;
node left;
int height;
}

Now, we'll do a simple breadth-first traversal of the tree, and keep updating the height value for each node:

int height (Node root)
{
Queue<Node> q = Queue<Node>();
Node lastnode;
//reset height
root.height = 0;

q.Enqueue(root);
while(q.Count > 0)
{
   lastnode = q.Dequeue();
   if (lastnode.left != null){
      lastnode.left.height = lastnode.height + 1; 
      q.Enqueue(lastnode.left);
   }

   if (lastnode.right != null){
      lastnode.right.height = lastnode.height + 1;
      q.Enqueue(lastnode.right);
   }
}
return lastnode.height; //this will return a 0-based height, so just a root has a height of 0
}

Cheers,

How do I make a delay in Java?

Use Thread.sleep(1000);

1000 is the number of milliseconds that the program will pause.

try
{
    Thread.sleep(1000);
}
catch(InterruptedException ex)
{
    Thread.currentThread().interrupt();
}

how to configuring a xampp web server for different root directory

# Possible values for the Options directive are "None", "All",
# or any combination of:
#   Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
#
# Note that "MultiViews" must be named *explicitly* --- "Options All"
# doesn't give it to you.
#
# The Options directive is both complicated and important.  Please see
# http://httpd.apache.org/docs/2.2/mod/core.html#options
# for more information.
#
Options Indexes FollowSymLinks Includes ExecCGI

#
# AllowOverride controls what directives may be placed in .htaccess files.
# It can be "All", "None", or any combination of the keywords:
#   Options FileInfo AuthConfig Limit
#
AllowOverride All

#
# Controls who can get stuff from this server.
#
Require all granted

Write above code inside following tags < Directory "c:\projects" > < / Directory > c:(you can add any directory d: e:) is drive where you have created your project folder.

Alias /projects "c:\projects"

Now you can access the pr0jects directory on your browser :

localhost/projects/

How to split a list by comma not space

kent$  echo "Hello,World,Questions,Answers,bash shell,script"|awk -F, '{for (i=1;i<=NF;i++)print $i}'
Hello
World
Questions
Answers
bash shell
script

Get the current date and time

use DateTime.Now

try this:

DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss")

What's the best way to iterate an Android Cursor?

Below could be the better way:

if (cursor.moveToFirst()) {
   while (!cursor.isAfterLast()) {
         //your code to implement
         cursor.moveToNext();
    }
}
cursor.close();

The above code would insure that it would go through entire iteration and won't escape first and last iteration.

Java default constructor

Java provides a default constructor which takes no arguments and performs no special actions or initializations, when no explicit constructors are provided.

The only action taken by the implicit default constructor is to call the superclass constructor using the super() call. Constructor arguments provide you with a way to provide parameters for the initialization of an object.

Below is an example of a cube class containing 2 constructors. (one default and one parameterized constructor).

public class Cube1 {
    int length;
    int breadth;
    int height;
    public int getVolume() {
        return (length * breadth * height);
    }

    Cube1() {
        length = 10;
        breadth = 10;
        height = 10;
    }

    Cube1(int l, int b, int h) {
        length = l;
        breadth = b;
        height = h;
    }

    public static void main(String[] args) {
        Cube1 cubeObj1, cubeObj2;
        cubeObj1 = new Cube1();
        cubeObj2 = new Cube1(10, 20, 30);
        System.out.println("Volume of Cube1 is : " + cubeObj1.getVolume());
        System.out.println("Volume of Cube1 is : " + cubeObj2.getVolume());
    }
}

Select a dummy column with a dummy value in SQL?

If you meant just ABC as simple value, answer above is the one that works fine.

If you meant concatenation of values of rows that are not selected by your main query, you will need to use a subquery.

Something like this may work:

SELECT t1.col1, 
t1.col2, 
(SELECT GROUP_CONCAT(col2 SEPARATOR '') FROM  Table1 t2 WHERE t2.col1 != 0) as col3 
FROM Table1 t1
WHERE t1.col1 = 0;

Actual syntax maybe a bit off though

How to convert an Object {} to an Array [] of key-value pairs in JavaScript

You can use Object.values([]), you might need this polyfill if you don't already:

const objectToValuesPolyfill = (object) => {
  return Object.keys(object).map(key => object[key]);
};
Object.values = Object.values || objectToValuesPolyfill;

https://stackoverflow.com/a/54822153/846348

Then you can just do:

var object = {1: 'hello', 2: 'world'};
var array = Object.values(object);

Just remember that arrays in js can only use numerical keys so if you used something else in the object then those will become `0,1,2...x``

It can be useful to remove duplicates for example if you have a unique key.

var obj = {};
object[uniqueKey] = '...';

Is it possible to move/rename files in Git and maintain their history?

While the core of Git, the Git plumbing doesn't keep track of renames, the history you display with the Git log "porcelain" can detect them if you like.

For a given git log use the -M option:

git log -p -M

With a current version of Git.

This works for other commands like git diff as well.

There are options to make the comparisons more or less rigorous. If you rename a file without making significant changes to the file at the same time it makes it easier for Git log and friends to detect the rename. For this reason some people rename files in one commit and change them in another.

There's a cost in CPU use whenever you ask Git to find where files have been renamed, so whether you use it or not, and when, is up to you.

If you would like to always have your history reported with rename detection in a particular repository you can use:

git config diff.renames 1

Files moving from one directory to another is detected. Here's an example:

commit c3ee8dfb01e357eba1ab18003be1490a46325992
Author: John S. Gruber <[email protected]>
Date:   Wed Feb 22 22:20:19 2017 -0500

    test rename again

diff --git a/yyy/power.py b/zzz/power.py
similarity index 100%
rename from yyy/power.py
rename to zzz/power.py

commit ae181377154eca800832087500c258a20c95d1c3
Author: John S. Gruber <[email protected]>
Date:   Wed Feb 22 22:19:17 2017 -0500

    rename test

diff --git a/power.py b/yyy/power.py
similarity index 100%
rename from power.py
rename to yyy/power.py

Please note that this works whenever you are using diff, not just with git log. For example:

$ git diff HEAD c3ee8df
diff --git a/power.py b/zzz/power.py
similarity index 100%
rename from power.py
rename to zzz/power.py

As a trial I made a small change in one file in a feature branch and committed it and then in the master branch I renamed the file, committed, and then made a small change in another part of the file and committed that. When I went to feature branch and merged from master the merge renamed the file and merged the changes. Here's the output from the merge:

 $ git merge -v master
 Auto-merging single
 Merge made by the 'recursive' strategy.
  one => single | 4 ++++
  1 file changed, 4 insertions(+)
  rename one => single (67%)

The result was a working directory with the file renamed and both text changes made. So it's possible for Git to do the right thing despite the fact that it doesn't explicitly track renames.

This is an late answer to an old question so the other answers may have been correct for the Git version at the time.

How to convert enum names to string in c

I usually do this:

#define COLOR_STR(color)                            \
    (RED       == color ? "red"    :                \
     (BLUE     == color ? "blue"   :                \
      (GREEN   == color ? "green"  :                \
       (YELLOW == color ? "yellow" : "unknown"))))   

Pycharm/Python OpenCV and CV2 install error

First step:

pip uninstall numpy
pip uninstall opencv-python

Second step:

pip install numpy
pip install opencv-python

Download File Using jQuery

I might suggest this, as a more gracefully degrading solution, using preventDefault:

$('a').click(function(e) {
    e.preventDefault();  //stop the browser from following
    window.location.href = 'uploads/file.doc';
});

<a href="no-script.html">Download now!</a>

Even if there's no Javascript, at least this way the user will get some feedback.

How to list running screen sessions?

The command screen -list may be what you want.

See the man

How can I view the source code for a function?

There is a very handy function in R edit

new_optim <- edit(optim)

It will open the source code of optim using the editor specified in R's options, and then you can edit it and assign the modified function to new_optim. I like this function very much to view code or to debug the code, e.g, print some messages or variables or even assign them to a global variables for further investigation (of course you can use debug).

If you just want to view the source code and don't want the annoying long source code printed on your console, you can use

invisible(edit(optim))

Clearly, this cannot be used to view C/C++ or Fortran source code.

BTW, edit can open other objects like list, matrix, etc, which then shows the data structure with attributes as well. Function de can be used to open an excel like editor (if GUI supports it) to modify matrix or data frame and return the new one. This is handy sometimes, but should be avoided in usual case, especially when you matrix is big.

Prevent redirect after form is submitted

The simple answer is to shoot your call off to an external scrip via AJAX request. Then handle the response how you like.

How to use ArrayList.addAll()?

Collections.addAll is what you want.

Collections.addAll(myArrayList, '+', '-', '*', '^');

Another option is to pass the list into the constructor using Arrays.asList like this:

List<Character> myArrayList = new ArrayList<Character>(Arrays.asList('+', '-', '*', '^'));

If, however, you are good with the arrayList being fixed-length, you can go with the creation as simple as list = Arrays.asList(...). Arrays.asList specification states that it returns a fixed-length list which acts as a bridge to the passed array, which could be not what you need.

how to change text box value with jQuery?

Use like this on dropdown change
$("#assetgroupSelect").change(function(){
    $("#idValue").val($this.val());
})

How to execute a shell script in PHP?

If you are having a small script that you need to run (I simply needed to copy a file), I found it much easier to call the commands on the PHP script by calling

exec("sudo cp /tmp/testfile1 /var/www/html/testfile2");

and enabling such transaction by editing (or rather adding) a permitting line to the sudoers by first calling sudo visudo and adding the following line to the very end of it

www-data ALL=(ALL) NOPASSWD:/bin/cp /tmp/testfile1 /var/www/html/testfile2

All I wanted to do was to copy a file and I have been having problems with doing so because of the root password problem, and as you mentioned I did NOT want to expose the system to have no password for all root transactions.

Xcode 6.1 - How to uninstall command line tools?

You can simply delete this folder

/Library/Developer/CommandLineTools

Please note: This is the root /Library, not user's ~/Library).

SQL multiple columns in IN clause

In general you can easily write the Where-Condition like this:

select * from tab1
where (col1, col2) in (select col1, col2 from tab2)

Note
Oracle ignores rows where one or more of the selected columns is NULL. In these cases you probably want to make use of the NVL-Funktion to map NULL to a special value (that should not be in the values):

select * from tab1
where (col1, NVL(col2, '---') in (select col1, NVL(col2, '---') from tab2)

How do I find which program is using port 80 in Windows?

Start menu → Accessories → right click on "Command prompt". In the menu, click "Run as Administrator" (on Windows XP you can just run it as usual), run netstat -anb, and then look through output for your program.

BTW, Skype by default tries to use ports 80 and 443 for incoming connections.

You can also run netstat -anb >%USERPROFILE%\ports.txt followed by start %USERPROFILE%\ports.txt to open the port and process list in a text editor, where you can search for the information you want.

You can also use PowerShell to parse netstat output and present it in a better way (or process it any way you want):

$proc = @{};
Get-Process | ForEach-Object { $proc.Add($_.Id, $_) };
netstat -aon | Select-String "\s*([^\s]+)\s+([^\s]+):([^\s]+)\s+([^\s]+):([^\s]+)\s+([^\s]+)?\s+([^\s]+)" | ForEach-Object {
    $g = $_.Matches[0].Groups;
    New-Object PSObject |
        Add-Member @{ Protocol =           $g[1].Value  } -PassThru |
        Add-Member @{ LocalAddress =       $g[2].Value  } -PassThru |
        Add-Member @{ LocalPort =     [int]$g[3].Value  } -PassThru |
        Add-Member @{ RemoteAddress =      $g[4].Value  } -PassThru |
        Add-Member @{ RemotePort =         $g[5].Value  } -PassThru |
        Add-Member @{ State =              $g[6].Value  } -PassThru |
        Add-Member @{ PID =           [int]$g[7].Value  } -PassThru |
        Add-Member @{ Process = $proc[[int]$g[7].Value] } -PassThru;
#} | Format-Table Protocol,LocalAddress,LocalPort,RemoteAddress,RemotePort,State -GroupBy @{Name='Process';Expression={$p=$_.Process;@{$True=$p.ProcessName; $False=$p.MainModule.FileName}[$p.MainModule -eq $Null] + ' PID: ' + $p.Id}} -AutoSize
} | Sort-Object PID | Out-GridView

Also it does not require elevation to run.

ListView with Add and Delete Buttons in each Row in android

You will first need to create a custom layout xml which will represent a single item in your list. You will add your two buttons to this layout along with any other items you want to display from your list.

<?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" > 

<TextView
    android:id="@+id/list_item_string"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerVertical="true"
    android:layout_alignParentLeft="true"
    android:paddingLeft="8dp"
    android:textSize="18sp"
    android:textStyle="bold" /> 

<Button
    android:id="@+id/delete_btn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentRight="true"
    android:layout_centerVertical="true"
    android:layout_marginRight="5dp"
    android:text="Delete" /> 

<Button
    android:id="@+id/add_btn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_toLeftOf="@id/delete_btn"
    android:layout_centerVertical="true"
    android:layout_marginRight="10dp"
    android:text="Add" />

</RelativeLayout>

Next you will need to create a Custom ArrayAdapter Class which you will use to inflate your xml layout, as well as handle your buttons and on click events.

public class MyCustomAdapter extends BaseAdapter implements ListAdapter { 
private ArrayList<String> list = new ArrayList<String>(); 
private Context context; 



public MyCustomAdapter(ArrayList<String> list, Context context) { 
    this.list = list; 
    this.context = context; 
} 

@Override
public int getCount() { 
    return list.size(); 
} 

@Override
public Object getItem(int pos) { 
    return list.get(pos); 
} 

@Override
public long getItemId(int pos) { 
    return list.get(pos).getId();
    //just return 0 if your list items do not have an Id variable.
} 

@Override
public View getView(final int position, View convertView, ViewGroup parent) {
    View view = convertView;
    if (view == null) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
        view = inflater.inflate(R.layout.my_custom_list_layout, null);
    } 

    //Handle TextView and display string from your list
    TextView listItemText = (TextView)view.findViewById(R.id.list_item_string); 
    listItemText.setText(list.get(position)); 

    //Handle buttons and add onClickListeners
    Button deleteBtn = (Button)view.findViewById(R.id.delete_btn);
    Button addBtn = (Button)view.findViewById(R.id.add_btn);

    deleteBtn.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v) { 
            //do something
            list.remove(position); //or some other task
            notifyDataSetChanged();
        }
    });
    addBtn.setOnClickListener(new View.OnClickListener(){
        @Override
        public void onClick(View v) { 
            //do something
            notifyDataSetChanged();
        }
    });

    return view; 
} 
}

Finally, in your activity you can instantiate your custom ArrayAdapter class and set it to your listview.

public class MyActivity extends Activity { 

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

    //generate list
    ArrayList<String> list = new ArrayList<String>();
    list.add("item1");
    list.add("item2");

    //instantiate custom adapter
    MyCustomAdapter adapter = new MyCustomAdapter(list, this);

    //handle listview and assign adapter
    ListView lView = (ListView)findViewById(R.id.my_listview);
    lView.setAdapter(adapter);
}

Hope this helps!

NULL value for int in Update statement

If this is nullable int field then yes.

update TableName
set FiledName = null
where Id = SomeId

Return value in a Bash function

Another way to achive this is name references (requires Bash 4.3+).

function example {
  local -n VAR=$1
  VAR=foo
}

example RESULT
echo $RESULT

Delete all lines starting with # or ; in Notepad++

In Notepad++, you can use the Mark tab in the Find dialogue to Bookmark all lines matching your query which can be regex or normal (wildcard).

Then use Search > Bookmark > Remove Bookmarked Lines.

Spring MVC UTF-8 Encoding

In addition to Benjamin's answer - in case if you are using Spring Security, placing the CharacterEncodingFilter in web.xml might not always work. In this case you need to create a custom filter and add it to the filter chain as the first filter. To make sure it's the first filter in the chain, you need to add it before ChannelProcessingFilter, using addFilterBefore in your WebSecurityConfigurerAdapter:

@Configuration
@EnableWebSecurity 
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    @Override
    protected void configure(HttpSecurity http) throws Exception {

        //add your custom encoding filter as the first filter in the chain
        http.addFilterBefore(new EncodingFilter(), ChannelProcessingFilter.class);

        http.authorizeRequests()
            .and()
            // your code here ...
    }
}

The ordering of all filters in Spring Security is available here: HttpSecurityBuilder - addFilter()

Your custom UTF-8 encoding filter can look like following:

public class EncodingFilter extends GenericFilterBean {

    @Override
    public void doFilter(
            ServletRequest request, 
            ServletResponse response,
            FilterChain chain) throws IOException, ServletException {

        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");

        chain.doFilter(request, response);
    }
}

Don't forget to add in your jsp files:

<%@ page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8" %>

And remove the CharacterEncodingFilter from web.xml if it's there.

Is there an addHeaderView equivalent for RecyclerView?

here some itemdecoration for recyclerview

public class HeaderItemDecoration extends RecyclerView.ItemDecoration {

private View customView;

public HeaderItemDecoration(View view) {
    this.customView = view;
}

@Override
public void onDraw(Canvas c, RecyclerView parent, RecyclerView.State state) {
    super.onDraw(c, parent, state);
    customView.layout(parent.getLeft(), 0, parent.getRight(), customView.getMeasuredHeight());
    for (int i = 0; i < parent.getChildCount(); i++) {
        View view = parent.getChildAt(i);
        if (parent.getChildAdapterPosition(view) == 0) {
            c.save();
            final int height = customView.getMeasuredHeight();
            final int top = view.getTop() - height;
            c.translate(0, top);
            customView.draw(c);
            c.restore();
            break;
        }
    }
}

@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
    if (parent.getChildAdapterPosition(view) == 0) {
        customView.measure(View.MeasureSpec.makeMeasureSpec(parent.getMeasuredWidth(), View.MeasureSpec.AT_MOST),
                View.MeasureSpec.makeMeasureSpec(parent.getMeasuredHeight(), View.MeasureSpec.AT_MOST));
        outRect.set(0, customView.getMeasuredHeight(), 0, 0);
    } else {
        outRect.setEmpty();
    }
}
}      

What is the difference between Forking and Cloning on GitHub?

Another weird subtle difference on GitHub is that changes to forks are not counted in your activity log until your changes are pulled into the original repo. What's more, to change a fork into a proper clone, you have to contact Github support, apparently.

From Why are my contributions not showing up:

Commit was made in a fork

Commits made in a fork will not count toward your contributions. To make them count, you must do one of the following:

Open a pull request to have your changes merged into the parent repository. To detach the fork and turn it into a standalone repository on GitHub, contact GitHub Support. If the fork has forks of its own, let support know if the forks should move with your repository into a new network or remain in the current network. For more information, see "About forks."

How do I use cx_freeze?

I'm really not sure what you're doing to get that error, it looks like you're trying to run cx_Freeze on its own, without arguments. So here is a short step-by-step guide on how to do it in windows (Your screenshot looks rather like the windows command line, so I'm assuming that's your platform)

  1. Write your setup.py file. Your script above looks correct so it should work, assuming that your script exists.

  2. Open the command line (Start -> Run -> "cmd")

  3. Go to the location of your setup.py file and run python setup.py build

Notes:

  1. There may be a problem with the name of your script. "Main.py" contains upper case letters, which might cause confusion since windows' file names are not case sensitive, but python is. My approach is to always use lower case for scripts to avoid any conflicts.

  2. Make sure that python is on your PATH (read http://docs.python.org/using/windows.html)1

  3. Make sure are are looking at the new cx_Freeze documentation. Google often seems to bring up the old docs.

Difference between xcopy and robocopy

Robocopy replaces XCopy in the newer versions of windows

  1. Uses Mirroring, XCopy does not
  2. Has a /RH option to allow a set time for the copy to run
  3. Has a /MON:n option to check differences in files
  4. Copies over more file attributes than XCopy

Yes i agree with Mark Setchell, They are both crap. (brought to you by Microsoft)


UPDATE:

XCopy return codes:

0 - Files were copied without error.
1 - No files were found to copy.
2 - The user pressed CTRL+C to terminate xcopy. enough memory or disk space, or you entered an invalid drive name or invalid syntax on the command line.
5 - Disk write error occurred.

Robocopy returns codes:

0 - No errors occurred, and no copying was done. The source and destination directory trees are completely synchronized.
1 - One or more files were copied successfully (that is, new files have arrived).
2 - Some Extra files or directories were detected. No files were copied Examine the output log for details. 
3 - (2+1) Some files were copied. Additional files were present. No failure was encountered.
4 - Some Mismatched files or directories were detected. Examine the output log. Some housekeeping may be needed.
5 - (4+1) Some files were copied. Some files were mismatched. No failure was encountered.
6 - (4+2) Additional files and mismatched files exist. No files were copied and no failures were encountered. This means that the files already exist in the destination directory
7 - (4+1+2) Files were copied, a file mismatch was present, and additional files were present.
8 - Some files or directories could not be copied (copy errors occurred and the retry limit was exceeded). Check these errors further.
16 - Serious error. Robocopy did not copy any files. Either a usage error or an error due to insufficient access privileges on the source or destination directories.

There is more details on Robocopy return values here: http://ss64.com/nt/robocopy-exit.html

Cannot add or update a child row: a foreign key constraint fails

Maybe whilst you added the userID column, there is a data for that certain table that it is established so it will have a default value of 0, try adding the column without the NOT NULL

Selenium 2.53 not working on Firefox 47

You can try using this code,

private WebDriver driver;
System.setProperty("webdriver.firefox.marionette","Your path to driver/geckodriver.exe");        
driver = new FirefoxDriver();

I upgraded to selenium 3.0.0 and Firefox version is 49.0.1

You can download geckodriver.exe from https://github.com/mozilla/geckodriver/releases

Make sure you download zip file only, geckodriver-v0.11.1-win64.zip file or win32 one as per your system and extract it in a folder.

Put the path for that folder in the "Your path to driver" quotes.Don't forget to put geckodriver.exe in the path.

Quickly create a large file on a Linux system

You can use "yes" command also. The syntax is fairly simple:

#yes >> myfile

Press "Ctrl + C" to stop this, else it will eat up all your space available.

To clean this file run:

#>myfile

will clean this file.

How can I compare two dates in PHP?

This works because of PHP's string comparison logic. Simply you can check...

if ($startdate < $date) {// do something} 
if ($startdate > $date) {// do something}

Both dates must be in the same format. Digits need to be zero-padded to the left and ordered from most significant to least significant. Y-m-d and Y-m-d H:i:s satisfy these conditions.

Get the latest date from grouped MySQL data

Using max(date) didn't solve my problem as there is no assurance that other columns will be from the same row as the max(date) is. Instead of that this one solved my problem and sorted group by in a correct order and values of other columns are from the same row as the max date is:

SELECT model, date 
FROM (SELECT * FROM doc ORDER BY date DESC) as sortedTable
GROUP BY model

SharePoint : How can I programmatically add items to a custom list instance

I think these both blog post should help you solving your problem.

http://blog.the-dargans.co.uk/2007/04/programmatically-adding-items-to.html http://asadewa.wordpress.com/2007/11/19/adding-a-custom-content-type-specific-item-on-a-sharepoint-list/

Short walk through:

  1. Get a instance of the list you want to add the item to.
  2. Add a new item to the list:

    SPListItem newItem = list.AddItem();
    
  3. To bind you new item to a content type you have to set the content type id for the new item:

    newItem["ContentTypeId"] = <Id of the content type>;
    
  4. Set the fields specified within your content type.

  5. Commit your changes:

    newItem.Update();
    

What's is the difference between train, validation and test set, in neural networks?

Say you train a model on a training set and then measure its performance on a test set. You think that there is still room for improvement and you try tweaking the hyper-parameters ( If the model is a Neural Network - hyper-parameters are the number of layers, or nodes in the layers ). Now you get a slightly better performance. However, when the model is subjected to another data ( not in the testing and training set ) you may not get the same level of accuracy. This is because you introduced some bias while tweaking the hyper-parameters to get better accuracy on the testing set. You basically have adapted the model and hyper-parameters to produce the best model for that particular training set.

A common solution is to split the training set further to create a validation set. Now you have

  • training set
  • testing set
  • validation set

You proceed as before but this time you use the validation set to test the performance and tweak the hyper-parameters. More specifically, you train multiple models with various hyper-parameters on the reduced training set (i.e., the full training set minus the validation set), and you select the model that performs best on the validation set.

Once you've selected the best performing model on the validation set, you train the best model on the full training set (including the valida- tion set), and this gives you the final model.

Lastly, you evaluate this final model on the test set to get an estimate of the generalization error.

Difference between text and varchar (character varying)

In my opinion, varchar(n) has it's own advantages. Yes, they all use the same underlying type and all that. But, it should be pointed out that indexes in PostgreSQL has its size limit of 2712 bytes per row.

TL;DR: If you use text type without a constraint and have indexes on these columns, it is very possible that you hit this limit for some of your columns and get error when you try to insert data but with using varchar(n), you can prevent it.

Some more details: The problem here is that PostgreSQL doesn't give any exceptions when creating indexes for text type or varchar(n) where n is greater than 2712. However, it will give error when a record with compressed size of greater than 2712 is tried to be inserted. It means that you can insert 100.000 character of string which is composed by repetitive characters easily because it will be compressed far below 2712 but you may not be able to insert some string with 4000 characters because the compressed size is greater than 2712 bytes. Using varchar(n) where n is not too much greater than 2712, you're safe from these errors.

What is TypeScript and why would I use it in place of JavaScript?

Ecma script 5 (ES5) which all browser support and precompiled. ES6/ES2015 and ES/2016 came this year with lots of changes so to pop up these changes there is something in between which should take cares about so TypeScript.

• TypeScript is Types -> Means we have to define datatype of each property and methods. If you know C# then Typescript is easy to understand.

• Big advantage of TypeScript is we identify Type related issues early before going to production. This allows unit tests to fail if there is any type mismatch.

How do I split a string with multiple separators in JavaScript?

Another simple but effective method is to use split + join repeatedly.

"a=b,c:d".split('=').join(',').split(':').join(',').split(',')

Essentially doing a split followed by a join is like a global replace so this replaces each separator with a comma then once all are replaced it does a final split on comma

The result of the above expression is:

['a', 'b', 'c', 'd']

Expanding on this you could also place it in a function:

function splitMulti(str, tokens){
        var tempChar = tokens[0]; // We can use the first token as a temporary join character
        for(var i = 1; i < tokens.length; i++){
            str = str.split(tokens[i]).join(tempChar);
        }
        str = str.split(tempChar);
        return str;
}

Usage:

splitMulti('a=b,c:d', ['=', ',', ':']) // ["a", "b", "c", "d"]

If you use this functionality a lot it might even be worth considering wrapping String.prototype.split for convenience (I think my function is fairly safe - the only consideration is the additional overhead of the conditionals (minor) and the fact that it lacks an implementation of the limit argument if an array is passed).

Be sure to include the splitMulti function if using this approach to the below simply wraps it :). Also worth noting that some people frown on extending built-ins (as many people do it wrong and conflicts can occur) so if in doubt speak to someone more senior before using this or ask on SO :)

    var splitOrig = String.prototype.split; // Maintain a reference to inbuilt fn
    String.prototype.split = function (){
        if(arguments[0].length > 0){
            if(Object.prototype.toString.call(arguments[0]) == "[object Array]" ) { // Check if our separator is an array
                return splitMulti(this, arguments[0]);  // Call splitMulti
            }
        }
        return splitOrig.apply(this, arguments); // Call original split maintaining context
    };

Usage:

var a = "a=b,c:d";
    a.split(['=', ',', ':']); // ["a", "b", "c", "d"]

// Test to check that the built-in split still works (although our wrapper wouldn't work if it didn't as it depends on it :P)
        a.split('='); // ["a", "b,c:d"] 

Enjoy!

How can I check if a directory exists in a Bash shell script?

This answer wrapped up as a shell script

Examples

$ is_dir ~                           
YES

$ is_dir /tmp                        
YES

$ is_dir ~/bin                       
YES

$ mkdir '/tmp/test me'

$ is_dir '/tmp/test me'
YES

$ is_dir /asdf/asdf                  
NO

# Example of calling it in another script
DIR=~/mydata
if [ $(is_dir $DIR) == "NO" ]
then
  echo "Folder doesnt exist: $DIR";
  exit;
fi

is_dir

function show_help()
{
  IT=$(CAT <<EOF

  usage: DIR
  output: YES or NO, depending on whether or not the directory exists.

  )
  echo "$IT"
  exit
}

if [ "$1" == "help" ]
then
  show_help
fi
if [ -z "$1" ]
then
  show_help
fi

DIR=$1
if [ -d $DIR ]; then 
   echo "YES";
   exit;
fi
echo "NO";

Run R script from command line

Just for documentation, sometimes you need to run the script as sudo:

sudo Rscript path/to/your/file.R

java.lang.IllegalStateException: Cannot (forward | sendRedirect | create session) after response has been committed

A common misunderstanding among starters is that they think that the call of a forward(), sendRedirect(), or sendError() would magically exit and "jump" out of the method block, hereby ignoring the remnant of the code. For example:

protected void doXxx() {
    if (someCondition) {
        sendRedirect();
    }
    forward(); // This is STILL invoked when someCondition is true!
}

This is thus actually not true. They do certainly not behave differently than any other Java methods (expect of System#exit() of course). When the someCondition in above example is true and you're thus calling forward() after sendRedirect() or sendError() on the same request/response, then the chance is big that you will get the exception:

java.lang.IllegalStateException: Cannot forward after response has been committed

If the if statement calls a forward() and you're afterwards calling sendRedirect() or sendError(), then below exception will be thrown:

java.lang.IllegalStateException: Cannot call sendRedirect() after the response has been committed

To fix this, you need either to add a return; statement afterwards

protected void doXxx() {
    if (someCondition) {
        sendRedirect();
        return;
    }
    forward();
}

... or to introduce an else block.

protected void doXxx() {
    if (someCondition) {
        sendRedirect();
    } else {
        forward();
    }
}

To naildown the root cause in your code, just search for any line which calls a forward(), sendRedirect() or sendError() without exiting the method block or skipping the remnant of the code. This can be inside the same servlet before the particular code line, but also in any servlet or filter which was been called before the particular servlet.

In case of sendError(), if your sole purpose is to set the response status, use setStatus() instead.


Another probable cause is that the servlet writes to the response while a forward() will be called, or has been called in the very same method.

protected void doXxx() {
    out.write("some string");
    // ... 
    forward(); // Fail!
}

The response buffer size defaults in most server to 2KB, so if you write more than 2KB to it, then it will be committed and forward() will fail the same way:

java.lang.IllegalStateException: Cannot forward after response has been committed

Solution is obvious, just don't write to the response in the servlet. That's the responsibility of the JSP. You just set a request attribute like so request.setAttribute("data", "some string") and then print it in JSP like so ${data}. See also our Servlets wiki page to learn how to use Servlets the right way.


Another probable cause is that the servlet writes a file download to the response after which e.g. a forward() is called.

protected void doXxx() {
    out.write(bytes);
    // ... 
    forward(); // Fail!
}

This is technically not possible. You need to remove the forward() call. The enduser will stay on the currently opened page. If you actually intend to change the page after a file download, then you need to move the file download logic to page load of the target page.


Yet another probable cause is that the forward(), sendRedirect() or sendError() methods are invoked via Java code embedded in a JSP file in form of old fashioned way <% scriptlets %>, a practice which was officially discouraged since 2001. For example:

<!DOCTYPE html>
<html lang="en">
    <head>
        ... 
    </head>
    <body>
        ...

        <% sendRedirect(); %>
        
        ...
    </body>
</html>

The problem here is that JSP internally immediately writes template text (i.e. HTML code) via out.write("<!DOCTYPE html> ... etc ...") as soon as it's encountered. This is thus essentially the same problem as explained in previous section.

Solution is obvious, just don't write Java code in a JSP file. That's the responsibility of a normal Java class such as a Servlet or a Filter. See also our Servlets wiki page to learn how to use Servlets the right way.


See also:


Unrelated to your concrete problem, your JDBC code is leaking resources. Fix that as well. For hints, see also How often should Connection, Statement and ResultSet be closed in JDBC?

How to find if an array contains a specific string in JavaScript/jQuery?

You can use a for loop:

var found = false;
for (var i = 0; i < categories.length && !found; i++) {
  if (categories[i] === "specialword") {
    found = true;
    break;
  }
}

Adding an img element to a div with javascript

function image()
{
    //dynamically add an image and set its attribute
    var img=document.createElement("img");
    img.src="p1.jpg"
    img.id="picture"
    var foo = document.getElementById("fooBar");
    foo.appendChild(img);
}

<span id="fooBar">&nbsp;</span>

What is the difference between Google App Engine and Google Compute Engine?

The cloud services provides a range of options from fully managed to less managed services. Less managed services gives more control to the developers. The same is the difference in Compute and App engine also. The below image elaborate more on this point enter image description here

What is the purpose of Node.js module.exports and how do you use it?

The intent is:

Modular programming is a software design technique that emphasizes separating the functionality of a program into independent, interchangeable modules, such that each contains everything necessary to execute only one aspect of the desired functionality.

Wikipedia

I imagine it becomes difficult to write a large programs without modular / reusable code. In nodejs we can create modular programs utilising module.exports defining what we expose and compose our program with require.

Try this example:

fileLog.js

function log(string) { require('fs').appendFileSync('log.txt',string); }

module.exports = log;

stdoutLog.js

function log(string) { console.log(string); }

module.exports = log;

program.js

const log = require('./stdoutLog.js')

log('hello world!');

execute

$ node program.js

hello world!

Now try swapping ./stdoutLog.js for ./fileLog.js.

Equivalent of SQL ISNULL in LINQ?

Looks like the type is boolean and therefore can never be null and should be false by default.

Url decode UTF-8 in Python

You can achieve an expected result with requests library as well:

import requests

url = "http://www.mywebsite.org/Data%20Set.zip"

print(f"Before: {url}")
print(f"After:  {requests.utils.unquote(url)}")

Output:

$ python3 test_url_unquote.py

Before: http://www.mywebsite.org/Data%20Set.zip
After:  http://www.mywebsite.org/Data Set.zip

Might be handy if you are already using requests, without using another library for this job.

How can I parse / create a date time stamp formatted with fractional seconds UTC timezone (ISO 8601, RFC 3339) in Swift?

There is a new ISO8601DateFormatter class that let's you create a string with just one line. For backwards compatibility I used an old C-library. I hope this is useful for someone.

Swift 3.0

extension Date {
    var iso8601: String {
        if #available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *) {
            return ISO8601DateFormatter.string(from: self, timeZone: TimeZone.current, formatOptions: .withInternetDateTime)
        } else {
            var buffer = [CChar](repeating: 0, count: 25)
            var time = time_t(self.timeIntervalSince1970)
            strftime_l(&buffer, buffer.count, "%FT%T%z", localtime(&time), nil)
            return String(cString: buffer)
        }
    }
}

how to split the ng-repeat data with three columns using bootstrap

this answers the original question which is how to get 1,2,3 in a column. – asked by kuppu Feb 8 '14 at 13:47

angularjs code:

function GetStaffForFloor(floor) {
    var promiseGet = Directory_Service.getAllStaff(floor);
    promiseGet.then(function (pl) {
        $scope.staffList = chunk(pl.data, 3); //pl.data; //
    },
    function (errorOD) {
        $log.error('Errored while getting staff list.', errorOD);
    });
}
function chunk(array, columns) {
    var numberOfRows = Math.ceil(array.length / columns);

    //puts 1, 2, 3 into column
    var newRow = []; //array is row-based.
    for (var i = 0; i < array.length; i++) {
        var columnData = new Array(columns);
        if (i == numberOfRows) break;
        for (j = 0; j < columns; j++)
        {
            columnData[j] = array[i + numberOfRows * j];
        }
        newRow.push(columnData); 
    }
    return newRow;

    ////this works but 1, 2, 3 is in row
    //var newRow = [];
    //for (var i = 0; i < array.length; i += columns) {
    //    newRow.push(array.slice(i, i + columns)); //push effectively does the pivot. array is row-based.
    //}
    //return newRow;
};

View Code (note: using bootstrap 3):

<div class="staffContainer">
    <div class="row" ng-repeat="staff in staffList">
        <div class="col-md-4" ng-repeat="item in staff">{{item.FullName.length > 0 ? item.FullName + ": Rm " + item.RoomNumber : ""}}</div>
    </div>
</div>

Copy array items into another array

Try this:

var arrayA = [1, 2];
var arrayB = [3, 4];
var newArray = arrayB.reduce((pre, cur) => [...pre, ...cur], arrayA);
console.log(newArray)

Create whole path automatically when writing to a new file

Since Java 1.7 you can use Files.createFile:

Path pathToFile = Paths.get("/home/joe/foo/bar/myFile.txt");
Files.createDirectories(pathToFile.getParent());
Files.createFile(pathToFile);

ThreeJS: Remove object from scene

clearScene: function() {
    var objsToRemove = _.rest(scene.children, 1);
    _.each(objsToRemove, function( object ) {
          scene.remove(object);
    });
},

this uses undescore.js to iterrate over all children (except the first) in a scene (it's part of code I use to clear a scene). just make sure you render the scene at least once after deleting, because otherwise the canvas does not change! There is no need for a "special" obj flag or anything like this.

Also you don't delete the object by name, just by the object itself, so calling

scene.remove(object); 

instead of scene.remove(object.name); can be enough

PS: _.each is a function of underscore.js

Set a default parameter value for a JavaScript function

If for some reason you are not on ES6 and are using lodash here is a concise way to default function parameters via _.defaultTo method:

_x000D_
_x000D_
var fn = function(a, b) {_x000D_
  a = _.defaultTo(a, 'Hi')_x000D_
  b = _.defaultTo(b, 'Mom!')_x000D_
_x000D_
  console.log(a, b)_x000D_
}_x000D_
_x000D_
fn()                 // Hi Mom!_x000D_
fn(undefined, null)  // Hi Mom!_x000D_
fn(NaN, NaN)         // Hi Mom!_x000D_
fn(1)                // 1 "Mom!"_x000D_
fn(null, 2)          // Hi 2_x000D_
fn(false, false)     // false false_x000D_
fn(0, 2)             // 0 2
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

Which will set the default if the current value is NaN, null, or undefined

disable horizontal scroll on mobile web

try like this

css

*{
    box-sizing: border-box;
    -webkit-box-sizing: border-box;
    -msbox-sizing: border-box;
}
body{
   overflow-x: hidden;
}
img{
   max-width:100%;
}

CreateProcess error=2, The system cannot find the file specified

Assuming that winrar.exe is in the PATH, then Runtime.exec is capable of finding it, if it is not, you will need to supply the fully qualified path to it, for example, assuming winrar.exe is installed in C:/Program Files/WinRAR you would need to use something like...

p=r.exec("C:/Program Files/WinRAR/winrar x h:\\myjar.jar *.* h:\\new");

Personally, I would recommend that you use ProcessBuilder as it has some additional configuration abilities amongst other things. Where possible, you should also separate your command and parameters into separate String elements, it deals with things like spaces much better then a single String variable, for example...

ProcessBuilder pb = new ProcessBuilder(
    "C:/Program Files/WinRAR/winrar",
    "x",
    "myjar.jar",
    "*.*",
    "new");
pb.directory(new File("H:/"));
pb. redirectErrorStream(true);

Process p = pb.start();

Don't forget to read the contents of the InputStream from the process, as failing to do so may stall the process

Do a "git export" (like "svn export")?

As simple as clone then delete the .git folder:

git clone url_of_your_repo path_to_export && rm -rf path_to_export/.git

Why doesn't java.io.File have a close method?

A BufferedReader can be opened and closed but a File is never opened, it just represents a path in the filesystem.

Excel VBA, error 438 "object doesn't support this property or method

The Error is here

lastrow = wsPOR.Range("A" & Rows.Count).End(xlUp).Row + 1

wsPOR is a workbook and not a worksheet. If you are working with "Sheet1" of that workbook then try this

lastrow = wsPOR.Sheets("Sheet1").Range("A" & _
          wsPOR.Sheets("Sheet1").Rows.Count).End(xlUp).Row + 1

Similarly

wsPOR.Range("A2:G" & lastrow).Select

should be

wsPOR.Sheets("Sheet1").Range("A2:G" & lastrow).Select

jquery (or pure js) simulate enter key pressed for testing

Demo Here

var e = jQuery.Event("keypress");
e.which = 13; //choose the one you want
e.keyCode = 13;
$("#theInputToTest").trigger(e);

ios app maximum memory budget

Starting with iOS13, there is an Apple-supported way of querying this by using

#include <os/proc.h>

size_t os_proc_available_memory(void)

Introduced here: https://developer.apple.com/videos/play/wwdc2019/606/

Around min 29-ish.

Edit: Adding link to documentation https://developer.apple.com/documentation/os/3191911-os_proc_available_memory?language=objc

How to reverse an std::string?

I'm not sure what you mean by a string that contains binary numbers. But for reversing a string (or any STL-compatible container), you can use std::reverse(). std::reverse() operates in place, so you may want to make a copy of the string first:

#include <algorithm>
#include <iostream>
#include <string>

int main()
{
    std::string foo("foo");
    std::string copy(foo);
    std::cout << foo << '\n' << copy << '\n';

    std::reverse(copy.begin(), copy.end());
    std::cout << foo << '\n' << copy << '\n';
}

Does JavaScript guarantee object property order?

As of ES2015, property order is guaranteed for certain methods that iterate over properties. but not others. Unfortunately, the methods which are not guaranteed to have an order are generally the most often used:

  • Object.keys, Object.values, Object.entries
  • for..in loops
  • JSON.stringify

But, as of ES2020, property order for these previously untrustworthy methods will be guaranteed by the specification to be iterated over in the same deterministic manner as the others, due to to the finished proposal: for-in mechanics.

Just like with the methods which have a guaranteed iteration order (like Reflect.ownKeys and Object.getOwnPropertyNames), the previously-unspecified methods will also iterate in the following order:

  • Numeric array keys, in ascending numeric order
  • All other non-Symbol keys, in insertion order
  • Symbol keys, in insertion order

This is what pretty much every implementation does already (and has done for many years), but the new proposal has made it official.

Although the current specification leaves for..in iteration order "almost totally unspecified, real engines tend to be more consistent:"

The lack of specificity in ECMA-262 does not reflect reality. In discussion going back years, implementors have observed that there are some constraints on the behavior of for-in which anyone who wants to run code on the web needs to follow.

Because every implementation already iterates over properties predictably, it can be put into the specification without breaking backwards compatibility.


There are a few weird cases which implementations currently do not agree on, and in such cases, the resulting order will continue be unspecified. For property order to be guaranteed:

Neither the object being iterated nor anything in its prototype chain is a proxy, typed array, module namespace object, or host exotic object.

Neither the object nor anything in its prototype chain has its prototype change during iteration.

Neither the object nor anything in its prototype chain has a property deleted during iteration.

Nothing in the object's prototype chain has a property added during iteration.

No property of the object or anything in its prototype chain has its enumerability change during iteration.

No non-enumerable property shadows an enumerable one.

Is ASCII code 7-bit or 8-bit?

The original ASCII code provided 128 different characters numbered 0 to 127. ASCII a 7-bit are synonymous, since the 8-bit byte is the common storage element, ASCII leaves room for 128 additional characters which are used for foreign languages and other symbols. But 7-bit code was original made before 8-bit code. ASCII stand for American Standard Code for Information Interchange In early internet mail systems, it only supported only 7-bit ASCII codes, this was because it then could execute programs and multimedia files over suck systems. These systems use 8 bits of the byte but then it must then be turned into a 7-bit format using coding methods such as MIME, UUcoding and BinHex. This mean that the 8-bit has been converted to a 7-bit characters, which adds extra bytes to encode them.

Java ArrayList copy

Yes, assignment will just copy the value of l1 (which is a reference) to l2. They will both refer to the same object.

Creating a shallow copy is pretty easy though:

List<Integer> newList = new ArrayList<>(oldList);

(Just as one example.)

How to compare dates in c#

Firstly, understand that DateTime objects aren't formatted. They just store the Year, Month, Day, Hour, Minute, Second, etc as a numeric value and the formatting occurs when you want to represent it as a string somehow. You can compare DateTime objects without formatting them.

To compare an input date with DateTime.Now, you need to first parse the input into a date and then compare just the Year/Month/Day portions:

DateTime inputDate;
if(!DateTime.TryParse(inputString, out inputDate))
    throw new ArgumentException("Input string not in the correct format.");

if(inputDate.Date == DateTime.Now.Date) {
    // Same date!
}

How to parse JSON using Node.js?

Just want to complete the answer (as I struggled with it for a while), want to show how to access the json information, this example shows accessing Json Array:

_x000D_
_x000D_
var request = require('request');_x000D_
request('https://server/run?oper=get_groups_joined_by_user_id&user_id=5111298845048832', function (error, response, body) {_x000D_
  if (!error && response.statusCode == 200) {_x000D_
    var jsonArr = JSON.parse(body);_x000D_
    console.log(jsonArr);_x000D_
    console.log("group id:" + jsonArr[0].id);_x000D_
  }_x000D_
})
_x000D_
_x000D_
_x000D_

How do I disable the security certificate check in Python requests

To add to Blender's answer, you can disable SSL certificate validation for all requests using Session.verify = False

import requests

session = requests.Session()
session.verify = False
session.post(url='https://example.com', data={'bar':'baz'})

Note that urllib3, (which Requests uses), strongly discourages making unverified HTTPS requests and will raise an InsecureRequestWarning.

how to configure lombok in eclipse luna

if you're on windows, make sure you 'unblock' the lombok.jar before you install it. if you don't do this, it will install but it wont work.

How can I get current location from user in iOS

For Swift 5, here's a quick short class to get the location:

class MyLocationManager: NSObject, CLLocationManagerDelegate {
    let manager: CLLocationManager

    override init() {
        manager = CLLocationManager()
        super.init()
        manager.delegate = self
        manager.distanceFilter = kCLDistanceFilterNone
        manager.desiredAccuracy = kCLLocationAccuracyBest
        manager.requestWhenInUseAuthorization()
        manager.startUpdatingLocation()
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        // do something with locations
    }
}

What are the rules about using an underscore in a C++ identifier?

As for the other part of the question, it's common to put the underscore at the end of the variable name to not clash with anything internal.

I do this even inside classes and namespaces because I then only have to remember one rule (compared to "at the end of the name in global scope, and the beginning of the name everywhere else").

How do I copy an entire directory of files into an existing directory using Python?

This is inspired from the original best answer provided by atzz, I just added replace file / folder logic. So it doesn't actually merge, but deletes the existing file/ folder and copies the new one:

import shutil
import os
def copytree(src, dst, symlinks=False, ignore=None):
    for item in os.listdir(src):
        s = os.path.join(src, item)
        d = os.path.join(dst, item)
        if os.path.exists(d):
            try:
                shutil.rmtree(d)
            except Exception as e:
                print e
                os.unlink(d)
        if os.path.isdir(s):
            shutil.copytree(s, d, symlinks, ignore)
        else:
            shutil.copy2(s, d)
    #shutil.rmtree(src)

Uncomment the rmtree to make it a move function.

How do I get the path of the Python script I am running in?

7.2 of Dive Into Python: Finding the Path.

import sys, os

print('sys.argv[0] =', sys.argv[0])             
pathname = os.path.dirname(sys.argv[0])        
print('path =', pathname)
print('full path =', os.path.abspath(pathname)) 

Constructor in an Interface?

A problem that you get when you allow constructors in interfaces comes from the possibility to implement several interfaces at the same time. When a class implements several interfaces that define different constructors, the class would have to implement several constructors, each one satisfying only one interface, but not the others. It will be impossible to construct an object that calls each of these constructors.

Or in code:

interface Named { Named(String name); }
interface HasList { HasList(List list); }

class A implements Named, HasList {

  /** implements Named constructor.
   * This constructor should not be used from outside, 
   * because List parameter is missing
   */
  public A(String name)  { 
    ...
  }

  /** implements HasList constructor.
   * This constructor should not be used from outside, 
   * because String parameter is missing
   */
  public A(List list) {
    ...
  }

  /** This is the constructor that we would actually 
   * need to satisfy both interfaces at the same time
   */ 
  public A(String name, List list) {
    this(name);
    // the next line is illegal; you can only call one other super constructor
    this(list); 
  }
}

pandas get rows which are NOT in other dataframe

One method would be to store the result of an inner merge form both dfs, then we can simply select the rows when one column's values are not in this common:

In [119]:

common = df1.merge(df2,on=['col1','col2'])
print(common)
df1[(~df1.col1.isin(common.col1))&(~df1.col2.isin(common.col2))]
   col1  col2
0     1    10
1     2    11
2     3    12
Out[119]:
   col1  col2
3     4    13
4     5    14

EDIT

Another method as you've found is to use isin which will produce NaN rows which you can drop:

In [138]:

df1[~df1.isin(df2)].dropna()
Out[138]:
   col1  col2
3     4    13
4     5    14

However if df2 does not start rows in the same manner then this won't work:

df2 = pd.DataFrame(data = {'col1' : [2, 3,4], 'col2' : [11, 12,13]})

will produce the entire df:

In [140]:

df1[~df1.isin(df2)].dropna()
Out[140]:
   col1  col2
0     1    10
1     2    11
2     3    12
3     4    13
4     5    14

What does Python's socket.recv() return for non-blocking sockets if no data is received until a timeout occurs?

When you use recv in connection with select if the socket is ready to be read from but there is no data to read that means the client has closed the connection.

Here is some code that handles this, also note the exception that is thrown when recv is called a second time in the while loop. If there is nothing left to read this exception will be thrown it doesn't mean the client has closed the connection :

def listenToSockets(self):

    while True:

        changed_sockets = self.currentSockets

        ready_to_read, ready_to_write, in_error = select.select(changed_sockets, [], [], 0.1)

        for s in ready_to_read:

            if s == self.serverSocket:
                self.acceptNewConnection(s)
            else:
                self.readDataFromSocket(s)

And the function that receives the data :

def readDataFromSocket(self, socket):

    data = ''
    buffer = ''
    try:

        while True:
            data = socket.recv(4096)

            if not data: 
                break

            buffer += data

    except error, (errorCode,message): 
        # error 10035 is no data available, it is non-fatal
        if errorCode != 10035:
            print 'socket.error - ('+str(errorCode)+') ' + message


    if data:
        print 'received '+ buffer
    else:
        print 'disconnected'

Horizontal line using HTML/CSS

Or change it to height: 0.1em; orso, minimal size of anything displayable is 1px.

The 0.05 em you are using means, get the current font size in pixels of this elements and give me 5% of it. Which for 12 pixels returns 0.6 pixels which is too little to display. if you would turn up the font size of the div to atleast 20pixels it would display fine. I suppose Chrome doesnt round up sizes to be atleast 1pixel where other browsers do.

JavaScript data grid for millions of rows

Take a look at dGrid:

https://dgrid.io/

I agree that users will NEVER, EVER need to view millions of rows of data all at once, but dGrid can display them quickly (a screenful at a time).

Don't boil the ocean to make a cup of tea.

Android emulator not able to access the internet

I experienced this same issue after upgrade. Upon opening the Chrome browser in the emulator, google.com could no longer be reached.

I found a post on SO that suggested the problem was with the emulator trying to use a disconnected network adapter. For me the problem was occurring when I was connected to a LAN. Disabling the wireless LAN adapter fixed the issue.

To disable the adapter:

  1. Navigate to Network connections
  2. Find the adapter
  3. Right click and choose disable

How to get HTML 5 input type="date" working in Firefox and/or IE 10

Thank Alexander, I found a way how to modify format for en lang. (Didn't know which lang uses such format)

 $.webshims.formcfg = {
        en: {
            dFormat: '/',
            dateSigns: '/',
            patterns: {
                d: "yy/mm/dd"
            }
        }
     };

 $.webshims.activeLang('en');

How to pass an array into a function, and return the results with an array

You seem to be looking for pass-by-reference, to do that make your function look this way (note the ampersand):

function foo(&$array)
{
    $array[3]=$array[0]+$array[1]+$array[2];
}

Alternately, you can assign the return value of the function to a variable:

function foo($array)
{
    $array[3]=$array[0]+$array[1]+$array[2];
    return $array;
}

$waffles = foo($waffles)

jQuery - Click event on <tr> elements with in a table and getting <td> element values

Unless otherwise definied (<tfoot>, <thead>), browsers put <tr> implicitly in a <tbody>.

You need to put a > tbody in between > table and > tr:

$("div.custList > table > tbody > tr")

Alternatively, you can also be less strict in selecting the rows (the > denotes the immediate child):

$("div.custList table tr")

That said, you can get the immediate <td> children there by $(this).children('td').

Printing Even and Odd using two Threads in Java

I have done it this way, while printing using two threads we cannot predict the sequence which thread
would get executed first so to overcome this situation we have to synchronize the shared resource,in
my case the print function which two threads are trying to access.

class Printoddeven{

    public synchronized void print(String msg) {
        try {
            if(msg.equals("Even")) {
                for(int i=0;i<=10;i+=2) {
                    System.out.println(msg+" "+i);
                    Thread.sleep(2000);
                    notify();
                    wait();
                }
            } else {
                for(int i=1;i<=10;i+=2) {
                    System.out.println(msg+" "+i);
                    Thread.sleep(2000);
                    notify();
                    wait();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}

class PrintOdd extends Thread{
    Printoddeven oddeven;
    public PrintOdd(Printoddeven oddeven){
        this.oddeven=oddeven;
    }

    public void run(){
        oddeven.print("ODD");
    }
}

class PrintEven extends Thread{
    Printoddeven oddeven;
    public PrintEven(Printoddeven oddeven){
        this.oddeven=oddeven;
    }

    public void run(){
        oddeven.print("Even");
    }
}



public class mainclass 
{
    public static void main(String[] args) {
        Printoddeven obj = new Printoddeven();//only one object  
        PrintEven t1=new PrintEven(obj);  
        PrintOdd t2=new PrintOdd(obj);  
        t1.start();  
        t2.start();  
    }
}

The breakpoint will not currently be hit. No symbols have been loaded for this document in a Silverlight application

For me the issue was that I had "Optimize code" enabled in the Build tab of my project's settings.

PostgreSQL: How to change PostgreSQL user password?

This was the first result on google, when I was looking how to rename a user, so:

ALTER USER <username> WITH PASSWORD '<new_password>';  -- change password
ALTER USER <old_username> RENAME TO <new_username>;    -- rename user

A couple of other commands helpful for user management:

CREATE USER <username> PASSWORD '<password>' IN GROUP <group>;
DROP USER <username>;

Move user to another group

ALTER GROUP <old_group> DROP USER <username>;
ALTER GROUP <new_group> ADD USER <username>;

Parse JSON response using jQuery

jQuery.ajax({
            type: 'GET',
            url: "../struktur2/load.php",
            async: false,
            contentType: "application/json",
            dataType: 'json',
            success: function(json) {
              items = json;
            },
            error: function(e) {
              console.log("jQuery error message = "+e.message);
            }
        });

Java - Opposite of .contains (does not contain)

It seems that Luiggi Mendoza and joey rohan both already answered this, but I think it can be clarified a little.

You can write it as a single if statement:

if (inventory.contains("bread") && !inventory.contains("water")) {
    // do something
}

how to get right offset of an element? - jQuery

Alex, Gary:

As requested, here is my comment posted as an answer:

var rt = ($(window).width() - ($whatever.offset().left + $whatever.outerWidth()));

Thanks for letting me know.

In pseudo code that can be expressed as:

The right offset is:

The window's width MINUS
( The element's left offset PLUS the element's outer width )

How to set maximum height for table-cell?

Try something like this:-

 table {
    width: 50%;
    height: 50%;
    border-spacing: 0;
    position:absolute;
}
td {
    border: 1px solid black;
}
#content {
    position:absolute;
    width:100%;
    left:0px;
    top:20px;
    bottom:20px;
    overflow: hidden;
}

How to compile c# in Microsoft's new Visual Studio Code?

Intellisense does work for C# 6, and it's great.

For running console apps you should set up some additional tools:

  • ASP.NET 5; in Powershell: &{$Branch='dev';iex ((new-object net.webclient).DownloadString('https://raw.githubusercontent.com/aspnet/Home/dev/dnvminstall.ps1'))}
  • Node.js including package manager npm.
  • The rest of required tools including Yeoman yo: npm install -g yo grunt-cli generator-aspnet bower
  • You should also invoke .NET Version Manager: c:\Users\Username\.dnx\bin\dnvm.cmd upgrade -u

Then you can use yo as wizard for Console Application: yo aspnet Choose name and project type. After that go to created folder cd ./MyNewConsoleApp/ and run dnu restore

To execute your program just type >run in Command Palette (Ctrl+Shift+P), or execute dnx . run in shell from the directory of your project.

Border Height on CSS

Yes, you can set the line height after defining the border like this:

border-right: 1px solid;
line-height: 10px;

Why both no-cache and no-store should be used in HTTP response?

I must clarify that no-cache does not mean do not cache. In fact, it means "revalidate with server" before using any cached response you may have, on every request.

must-revalidate, on the other hand, only needs to revalidate when the resource is considered stale.

If the server says that the resource is still valid then the cache can respond with its representation, thus alleviating the need for the server to resend the entire resource.

no-store is effectively the full do not cache directive and is intended to prevent storage of the representation in any form of cache whatsoever.

I say whatsoever, but note this in the RFC 2616 HTTP spec:

History buffers MAY store such responses as part of their normal operation

But this is omitted from the newer RFC 7234 HTTP spec in potentially an attempt to make no-store stronger, see:

http://tools.ietf.org/html/rfc7234#section-5.2.1.5

How to activate a specific worksheet in Excel?

An alternative way to (not dynamically) link a text to activate a worksheet without macros is to make the selected string an actual link. You can do this by selecting the cell that contains the text and press CTRL+K then select the option/tab 'Place in this document' and select the tab you want to activate. If you would click the text (that is now a link) the configured sheet will become active/selected.

Append text using StreamWriter

Also look at log4net, which makes logging to 1 or more event stores — whether it's the console, the Windows event log, a text file, a network pipe, a SQL database, etc. — pretty trivial. You can even filter stuff in its configuration, for instance, so that only log records of a particular severity (say ERROR or FATAL) from a single component or assembly are directed to a particular event store.

http://logging.apache.org/log4net/

I get conflicting provisioning settings error when I try to archive to submit an iOS app

  1. General -> Signing -> check automatically manage signing and select team

  2. Build settings -> Signing -> Code Signing Identity -> SET ALL TO "IOS developer"

Deleting multiple columns based on column names in Pandas

This is probably a good way to do what you want. It will delete all columns that contain 'Unnamed' in their header.

for col in df.columns:
    if 'Unnamed' in col:
        del df[col]

How to format a QString?

Use QString::arg() for the same effect.

IF EXISTS condition not working with PLSQL

IF EXISTS() is semantically incorrect. EXISTS condition can be used only inside a SQL statement. So you might rewrite your pl/sql block as follows:

declare
  l_exst number(1);
begin
  select case 
           when exists(select ce.s_regno 
                         from courseoffering co
                         join co_enrolment ce
                           on ce.co_id = co.co_id
                        where ce.s_regno=403 
                          and ce.coe_completionstatus = 'C' 
                          and ce.c_id = 803
                          and rownum = 1
                        )
           then 1
           else 0
         end  into l_exst
  from dual;

  if l_exst = 1 
  then
    DBMS_OUTPUT.put_line('YES YOU CAN');
  else
    DBMS_OUTPUT.put_line('YOU CANNOT'); 
  end if;
end;

Or you can simply use count function do determine the number of rows returned by the query, and rownum=1 predicate - you only need to know if a record exists:

declare
  l_exst number;
begin
   select count(*) 
     into l_exst
     from courseoffering co
          join co_enrolment ce
            on ce.co_id = co.co_id
    where ce.s_regno=403 
      and ce.coe_completionstatus = 'C' 
      and ce.c_id = 803
      and rownum = 1;

  if l_exst = 0
  then
    DBMS_OUTPUT.put_line('YOU CANNOT');
  else
    DBMS_OUTPUT.put_line('YES YOU CAN');
  end if;
end;

Cannot find the '@angular/common/http' module

Is this issue resolved.

I am getting this error: ERROR in node_modules/ngx-restangular/lib/ngx-restangular-http.d.ts(3,27): error TS2307: Cannot find module '@angular/common/http/src/response'.

After updating my angular to version=8

Disable HttpClient logging

We use XML, rather than a properties file, to configure our logging output. The following code worked to silence this chatter.

<logger name="org.apache.commons.httpclient">
    <level value="fatal"/>
</logger>

<logger name="httpclient.wire.header">
    <level value="fatal"/>
</logger>

<logger name="httpclient.wire.content">
    <level value="fatal"/>
</logger>

Convert Datetime column from UTC to local time in select statement

If enabling CLR on your database is an option as well as using the sql server's timezone, it can be written in .Net quite easily.

public partial class UserDefinedFunctions
{
    [Microsoft.SqlServer.Server.SqlFunction]
    public static SqlDateTime fn_GetLocalFromUTC(SqlDateTime UTC)
    {
        if (UTC.IsNull)
            return UTC;

        return new SqlDateTime(UTC.Value.ToLocalTime());
    }
}

A UTC datetime value goes in and the local datetime value relative to the server comes out. Null values return null.

How do you perform address validation?

You could also try SAP's Data Quality solutions which are available in both a server platform is processing a large number of requests or as an embeddable SDK if you wanted to run it in process with your application. We use it in our application and it's very robust and scalable.

'tsc command not found' in compiling typescript

The only solution that work for me was put npx tsc -v or for the compiling npx tsc salida.ts

"salida.ts" is the name of the file

POST: sending a post request in a url itself

In Java you can use GET which shows requested data on URL.But POST method cannot , because POST has body but GET donot have body.

How do I compare a value to a backslash?

Use following code to perform if-else conditioning in python: Here, I am checking the length of the string. If the length is less than 3 then do nothing, if more then 3 then I check the last 3 characters. If last 3 characters are "ing" then I add "ly" at the end otherwise I add "ing" at the end.

Code-

if (len(s)<=3):
    return s
elif s[-3:]=="ing":
    return s+"ly"
else: return s + "ing"

Could not obtain information about Windows NT group user

I was having the same issue, which turned out to be caused by the Domain login that runs the SQL service being locked out in AD. The lockout was caused by an unrelated usage of the service account for another purpose with the wrong password.

The errors received from SQL Agent logs did not mention the service account's name, just the name of the user (job owner) that couldn't be authenticated (since it uses the service account to check with AD).

How do I get Fiddler to stop ignoring traffic to localhost?

Windows XP:

Be sure to set to click the settings button for each of the items in the "Dial-up and Virtual Private Network settings" listbox in the "Connections" tab of the "Internet Options" control panel applet.

I noticed that Fiddler would stop using the "LAN settings" configuration once I connected to my VPN. Even if the traffic wasn't going through the VPN.

C++ STL Vectors: Get iterator from index?

Try this:

vector<Type>::iterator nth = v.begin() + index;

AppFabric installation failed because installer MSI returned with error code : 1603

My problem was that there was task already for Customer Experience Improvement Program in Task Scheduler "\Microsoft\Windows\AppFabric\Customer Experience Improvement Program\Consolidator". I removed that task and after that installation succeeded.

How do you find the first key in a dictionary?

Update: as of Python 3.7, insertion order is maintained, so you don't need an OrderedDict here. You can use the below approaches with a normal dict

Changed in version 3.7: Dictionary order is guaranteed to be insertion order. This behavior was an implementation detail of CPython from 3.6.

source


Python 3.6 and earlier*

If you are talking about a regular dict, then the "first key" doesn't mean anything. The keys are not ordered in any way you can depend on. If you iterate over your dict you will likely not get "banana" as the first thing you see.

If you need to keep things in order, then you have to use an OrderedDict and not just a plain dictionary.

import collections
prices  = collections.OrderedDict([
        ("banana", 4),
        ("apple", 2),
        ("orange", 1.5),
        ("pear", 3),
])

If you then wanted to see all the keys in order you could do so by iterating through it

for k in prices:
    print(k)

You could, alternatively put all of the keys into a list and then work with that

ks = list(prices)
print(ks[0]) # will print "banana"

A faster way to get the first element without creating a list would be to call next on the iterator. This doesn't generalize nicely when trying to get the nth element though

>>> next(iter(prices))
'banana'

* CPython had guaranteed insertion order as an implementation detail in 3.6.

Force LF eol in git repo and working copy

To force LF line endings for all text files, you can create .gitattributes file in top-level of your repository with the following lines (change as desired):

# Ensure all C and PHP files use LF.
*.c         eol=lf
*.php       eol=lf

which ensures that all files that Git considers to be text files have normalized (LF) line endings in the repository (normally core.eol configuration controls which one do you have by default).

Based on the new attribute settings, any text files containing CRLFs should be normalized by Git. If this won't happen automatically, you can refresh a repository manually after changing line endings, so you can re-scan and commit the working directory by the following steps (given clean working directory):

$ echo "* text=auto" >> .gitattributes
$ rm .git/index     # Remove the index to force Git to
$ git reset         # re-scan the working directory
$ git status        # Show files that will be normalized
$ git add -u
$ git add .gitattributes
$ git commit -m "Introduce end-of-line normalization"

or as per GitHub docs:

git add . -u
git commit -m "Saving files before refreshing line endings"
git rm --cached -r . # Remove every file from Git's index.
git reset --hard # Rewrite the Git index to pick up all the new line endings.
git add . # Add all your changed files back, and prepare them for a commit.
git commit -m "Normalize all the line endings" # Commit the changes to your repository.

See also: @Charles Bailey post.

In addition, if you would like to exclude any files to not being treated as a text, unset their text attribute, e.g.

manual.pdf      -text

Or mark it explicitly as binary:

# Denote all files that are truly binary and should not be modified.
*.png binary
*.jpg binary

To see some more advanced git normalization file, check .gitattributes at Drupal core:

# Drupal git normalization
# @see https://www.kernel.org/pub/software/scm/git/docs/gitattributes.html
# @see https://www.drupal.org/node/1542048

# Normally these settings would be done with macro attributes for improved
# readability and easier maintenance. However macros can only be defined at the
# repository root directory. Drupal avoids making any assumptions about where it
# is installed.

# Define text file attributes.
# - Treat them as text.
# - Ensure no CRLF line-endings, neither on checkout nor on checkin.
# - Detect whitespace errors.
#   - Exposed by default in `git diff --color` on the CLI.
#   - Validate with `git diff --check`.
#   - Deny applying with `git apply --whitespace=error-all`.
#   - Fix automatically with `git apply --whitespace=fix`.

*.config  text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.css     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.dist    text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.engine  text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.html    text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=html
*.inc     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.install text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.js      text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.json    text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.lock    text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.map     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.md      text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.module  text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.php     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.po      text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.profile text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.script  text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.sh      text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.sql     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.svg     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.theme   text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2 diff=php
*.twig    text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.txt     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.xml     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2
*.yml     text eol=lf whitespace=blank-at-eol,-blank-at-eof,-space-before-tab,tab-in-indent,tabwidth=2

# Define binary file attributes.
# - Do not treat them as text.
# - Include binary diff in patches instead of "binary files differ."
*.eot     -text diff
*.exe     -text diff
*.gif     -text diff
*.gz      -text diff
*.ico     -text diff
*.jpeg    -text diff
*.jpg     -text diff
*.otf     -text diff
*.phar    -text diff
*.png     -text diff
*.svgz    -text diff
*.ttf     -text diff
*.woff    -text diff
*.woff2   -text diff

See also:

Completely uninstall PostgreSQL 9.0.4 from Mac OSX Lion?

This blog post explains very well:

(just replace 9.X by your version. e.g: 9.6)

A. If installed PostgreSQL with homebrew, enter brew uninstall postgresql

B. If you used the EnterpriseDB installer, follow the following step.

Run the uninstaller on terminal window: sudo /Library/PostgreSQL/9.X/uninstall-postgresql.app/Contents/MacOS/installbuilder.sh

C. If installed with Postgres Installer, do:

open /Library/PostgreSQL/9.X/uninstall-postgresql.app

Remove the PostgreSQL and data folders. The Wizard will notify you that these were not removed.

sudo rm -rf /Library/PostgreSQL

Remove the ini file:

sudo rm /etc/postgres-reg.ini

Remove the PostgreSQL user using System Preferences -> Users & Groups.

Unlock the settings panel by clicking on the padlock and entering your password. Select the PostgreSQL user and click on the minus button. Restore your shared memory settings: sudo rm /etc/sysctl.conf

Do I really need to encode '&' as '&amp;'?

Yes. Just as the error said, in HTML, attributes are #PCDATA meaning they're parsed. This means you can use character entities in the attributes. Using & by itself is wrong and if not for lenient browsers and the fact that this is HTML not XHTML, would break the parsing. Just escape it as &amp; and everything would be fine.

HTML5 allows you to leave it unescaped, but only when the data that follows does not look like a valid character reference. However, it's better just to escape all instances of this symbol than worry about which ones should be and which ones don't need to be.

Keep this point in mind; if you're not escaping & to &amp;, it's bad enough for data that you create (where the code could very well be invalid), you might also not be escaping tag delimiters, which is a huge problem for user-submitted data, which could very well lead to HTML and script injection, cookie stealing and other exploits.

Please just escape your code. It will save you a lot of trouble in the future.

How to set a fixed width column with CSS flexbox

You should use the flex or flex-basis property rather than width. Read more on MDN.

.flexbox .red {
  flex: 0 0 25em;
}

The flex CSS property is a shorthand property specifying the ability of a flex item to alter its dimensions to fill available space. It contains:

flex-grow: 0;     /* do not grow   - initial value: 0 */
flex-shrink: 0;   /* do not shrink - initial value: 1 */
flex-basis: 25em; /* width/height  - initial value: auto */

A simple demo shows how to set the first column to 50px fixed width.

_x000D_
_x000D_
.flexbox {_x000D_
  display: flex;_x000D_
}_x000D_
.red {_x000D_
  background: red;_x000D_
  flex: 0 0 50px;_x000D_
}_x000D_
.green {_x000D_
  background: green;_x000D_
  flex: 1;_x000D_
}_x000D_
.blue {_x000D_
  background: blue;_x000D_
  flex: 1;_x000D_
}
_x000D_
<div class="flexbox">_x000D_
  <div class="red">1</div>_x000D_
  <div class="green">2</div>_x000D_
  <div class="blue">3</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_


See the updated codepen based on your code.

Try-catch-finally-return clarification

If the return in the try block is reached, it transfers control to the finally block, and the function eventually returns normally (not a throw).

If an exception occurs, but then the code reaches a return from the catch block, control is transferred to the finally block and the function eventually returns normally (not a throw).

In your example, you have a return in the finally, and so regardless of what happens, the function will return 34, because finally has the final (if you will) word.

Although not covered in your example, this would be true even if you didn't have the catch and if an exception were thrown in the try block and not caught. By doing a return from the finally block, you suppress the exception entirely. Consider:

public class FinallyReturn {
  public static final void main(String[] args) {
    System.out.println(foo(args));
  }

  private static int foo(String[] args) {
    try {
      int n = Integer.parseInt(args[0]);
      return n;
    }
    finally {
      return 42;
    }
  }
}

If you run that without supplying any arguments:

$ java FinallyReturn

...the code in foo throws an ArrayIndexOutOfBoundsException. But because the finally block does a return, that exception gets suppressed.

This is one reason why it's best to avoid using return in finally.

Scrolling a flexbox with overflowing content

You can simply put overflow property to "auto"

_x000D_
_x000D_
     .contain{
          background-color: #999999;
          margin: 5px; 
          padding: 10px 5px;
          width: 20%;
          height: 20%;
          overflow: auto;
      }              
       
_x000D_
_x000D_
_x000D_

contain is one of my flex-item class name

result :

scroll bar seen properly

Get environment value in controller

It Doesn't work in Laravel 5.3+ if you want to try to access the value from the controller like below. It always returns null

<?php

    $value = env('MY_VALUE', 'default_value');

SOLUTION: Rather, you need to create a file in the configuration folder, say values.php and then write the code like below

File values.php

<?php

    return [

        'myvalue' => env('MY_VALUE',null),

        // Add other values as you wish

Then access the value in your controller with the following code

<?php

    $value = \Config::get('values.myvalue')

Where "values" is the filename followed by the key "myvalue".

Difference between checkout and export in SVN

As you stated, a checkout includes the .svn directories. Thus it is a working copy and will have the proper information to make commits back (if you have permission). If you do an export you are just taking a copy of the current state of the repository and will not have any way to commit back any changes.

How do I convert a String object into a Hash object?

Quick and dirty method would be

eval("{ :key_a => { :key_1a => 'value_1a', :key_2a => 'value_2a' }, :key_b => { :key_1b => 'value_1b' } }") 

But it has severe security implications.
It executes whatever it is passed, you must be 110% sure (as in, at least no user input anywhere along the way) it would contain only properly formed hashes or unexpected bugs/horrible creatures from outer space might start popping up.

Check/Uncheck a checkbox on datagridview

The code you are trying here will flip the states (if true then became false vice versa) of the checkboxes irrespective of the user selected checkbox because here the foreach is selecting each checkbox and performing the operations.

To make it clear, store the index of the user selected checkbox before performing the foreach operation and after the foreach operation call the checkbox by mentioning the stored index and check it (In your case, make it True -- I think).

This is just logic and I am damn sure it is correct. I will try to implement some sample code if possible.

Modify your foreach something like this:

    //Store the index of the selected checkbox here as Integer (you can use e.RowIndex or e.ColumnIndex for it).
    private void chkItems_CheckedChanged(object sender, EventArgs e)
    {
        foreach (DataGridViewRow row in datagridview1.Rows)
        {
            DataGridViewCheckBoxCell chk = (DataGridViewCheckBoxCell)row.Cells[1];
            if (chk.Selected == true)
            {
                chk.Selected = false;
            }
            else
            {
                chk.Selected = true;
            }
        }
    }
    //write the function for checking(making true) the user selected checkbox by calling the stored Index

The above function makes all the checkboxes true including the user selected CheckBox. I think this is what you want..

How to use jQuery Plugin with Angular 4?

You should not use jQuery in Angular. While it is possible (see other answers for this question), it is discouraged. Why?

Angular holds an own representation of the DOM in its memory and doesn't use query-selectors (functions like document.getElementById(id)) like jQuery. Instead all the DOM-manipulation is done by Renderer2 (and Angular-directives like *ngFor and *ngIf accessing that Renderer2 in the background/framework-code). If you manipulate DOM with jQuery yourself you will sooner or later...

  1. Run into synchronization problems and have things wrongly appearing or not disappearing at the right time from your screen
  2. Have performance issues in more complex components, as Angular's internal DOM-representation is bound to zone.js and its change detection-mechanism - so updating the DOM manually will always block the thread your app is running on.
  3. Have other confusing errors you don't know the origin of.
  4. Not being able to test the application correctly (Jasmine requires you to know when elements have been rendered)
  5. Not being able to use Angular Universal or WebWorkers

If you really want to include jQuery (for duck-taping some prototype that you will 100% definitively throw away), I recommend to at least include it in your package.json with npm install --save jquery instead of getting it from google's CDN.

TLDR: For learning how to manipulate the DOM in the Angular way please go through the official tour-of heroes tutorial first: https://angular.io/tutorial/toh-pt2 If you need to access elements higher up in the DOM hierarchy (parent or document body) or for some other reason directives like *ngIf, *ngFor, custom directives, pipes and other angular utilities like [style.background], [class.myOwnCustomClass] don't satisfy your needs, use Renderer2: https://www.concretepage.com/angular-2/angular-4-renderer2-example

Java Strings: "String s = new String("silly");"

The best way to answer your question would be to make you familiar with the "String constant pool". In java string objects are immutable (i.e their values cannot be changed once they are initialized), so when editing a string object you end up creating a new edited string object wherease the old object just floats around in a special memory ares called the "string constant pool". creating a new string object by

String s = "Hello";

will only create a string object in the pool and the reference s will refer to it, but by using

String s = new String("Hello");

you create two string objects: one in the pool and the other in the heap. the reference will refer to the object in the heap.

Unicode character as bullet for list-item in CSS

You can construct it:

#modal-select-your-position li {
/* handle multiline */
    overflow: visible;
    padding-left: 17px;
    position: relative;
}

#modal-select-your-position li:before {
/* your own marker in content */
   content: "—";
   left: 0;
   position: absolute;
}

How can I render inline JavaScript with Jade / Pug?

The :javascript filter was removed in version 7.0

The docs says you should use a script tag now, followed by a . char and no preceding space.

Example:

script.
  if (usingJade)
    console.log('you are awesome')
  else
    console.log('use jade')

will be compiled to

<script>
  if (usingJade)
    console.log('you are awesome')
  else
    console.log('use jade')
</script>

Maintain image aspect ratio when changing height

To keep images from stretching in either axis inside a flex parent I have found a couple of solutions.

You can try using object-fit on the image which, e.g.

object-fit: contain;

http://jsfiddle.net/ykw3sfjd/

Or you can add flex-specfic rules which may work better in some cases.

align-self: center;
flex: 0 0 auto;

Configuring diff tool with .gitconfig

Git offers a range of difftools pre-configured "out-of-the-box" (kdiff3, kompare, tkdiff, meld, xxdiff, emerge, vimdiff, gvimdiff, ecmerge, diffuse, opendiff, p4merge and araxis), and also allows you to specify your own. To use one of the pre-configured difftools (for example, "vimdiff"), you add the following lines to your ~/.gitconfig:

[diff]
    tool = vimdiff

Now, you will be able to run "git difftool" and use your tool of choice.

Specifying your own difftool, on the other hand, takes a little bit more work, see How do I view 'git diff' output with my preferred diff tool/ viewer?

SQL, How to Concatenate results?

Small update on Marc we will have additional " , " at the end. i used stuff function to remove extra semicolon .

       SELECT STUFF((  SELECT ',' + ModuleValue AS ModuleValue
                           FROM ModuleValue WHERE ModuleID=@ModuleID
                      FOR XML PATH('') 
                     ), 1, 1, '' )

Better way to remove specific characters from a Perl string

You could use the tr instead:

       $p =~ tr/fo//d;

will delete every f and every o from $p. In your case it should be:

       $p =~ tr/\$#@~!&*()[];.,:?^ `\\\///d

See Perl's tr documentation.

tr/SEARCHLIST/REPLACEMENTLIST/cdsr

Transliterates all occurrences of the characters found (or not found if the /c modifier is specified) in the search list with the positionally corresponding character in the replacement list, possibly deleting some, depending on the modifiers specified.

[…]

If the /d modifier is specified, any characters specified by SEARCHLIST not found in REPLACEMENTLIST are deleted.

Numpy: Get random set of rows from 2D array

>>> A = np.random.randint(5, size=(10,3))
>>> A
array([[1, 3, 0],
       [3, 2, 0],
       [0, 2, 1],
       [1, 1, 4],
       [3, 2, 2],
       [0, 1, 0],
       [1, 3, 1],
       [0, 4, 1],
       [2, 4, 2],
       [3, 3, 1]])
>>> idx = np.random.randint(10, size=2)
>>> idx
array([7, 6])
>>> A[idx,:]
array([[0, 4, 1],
       [1, 3, 1]])

Putting it together for a general case:

A[np.random.randint(A.shape[0], size=2), :]

For non replacement (numpy 1.7.0+):

A[np.random.choice(A.shape[0], 2, replace=False), :]

I do not believe there is a good way to generate random list without replacement before 1.7. Perhaps you can setup a small definition that ensures the two values are not the same.

Where/How to getIntent().getExtras() in an Android Fragment?

you can still use

String Item = getIntent().getExtras().getString("name");

in the fragment, you just need call getActivity() first:

String Item = getActivity().getIntent().getExtras().getString("name");

This saves you having to write some code.

How to create cron job using PHP?

This is the best explanation with code in PHP I have found so far:

http://code.tutsplus.com/tutorials/managing-cron-jobs-with-php--net-19428

In short:

Although the syntax of scheduling a new job may seem daunting at first glance, it's actually relatively simple to understand once you break it down. A cron job will always have five columns each of which represent a chronological 'operator' followed by the full path and command to execute:

* * * * * home/path/to/command/the_command.sh

Each of the chronological columns has a specific relevance to the schedule of the task. They are as follows:

Minutes represents the minutes of a given hour, 0-59 respectively.
Hours represents the hours of a given day, 0-23 respectively.
Days represents the days of a given month, 1-31 respectively.
Months represents the months of a given year, 1-12 respectively.
Day of the Week represents the day of the week, Sunday through Saturday, numerically, as 0-6 respectively.

enter image description here

So, for example, if one wanted to schedule a task for 12am on the first day of every month it would look something like this:

0 0 1 * * home/path/to/command/the_command.sh

If we wanted to schedule a task to run every Saturday at 8:30am we'd write it as follows:

30 8 * * 6 home/path/to/command/the_command.sh

There are also a number of operators which can be used to customize the schedule even further:

Commas is used to create a comma separated list of values for any of the cron columns.
Dashes is used to specify a range of values.
Asterisksis used to specify 'all' or 'every' value

Visit the link for the full article, it explains:

  1. What is the format of the cronjob if you want to enter/edit it manually.
  2. How to use PHP with SSH2 library to authenticate as the user, which crontab you are going to edit.
  3. Full PHP class with all necessary methods for authentication, editing and deleting crontab entries.

Can I write a CSS selector selecting elements NOT having a certain class or attribute?

The :not negation pseudo class

The negation CSS pseudo-class, :not(X), is a functional notation taking a simple selector X as an argument. It matches an element that is not represented by the argument. X must not contain another negation selector.

You can use :not to exclude any subset of matched elements, ordered as you would normal CSS selectors.


Simple example: excluding by class

div:not(.class)

Would select all div elements without the class .class

_x000D_
_x000D_
div:not(.class) {_x000D_
  color: red;_x000D_
}
_x000D_
<div>Make me red!</div>_x000D_
<div class="class">...but not me...</div>
_x000D_
_x000D_
_x000D_


Complex example: excluding by type / hierarchy

:not(div) > div

Would select all div elements which arent children of another div

_x000D_
_x000D_
div {_x000D_
  color: black_x000D_
}_x000D_
:not(div) > div {_x000D_
  color: red;_x000D_
}
_x000D_
<div>Make me red!</div>_x000D_
<div>_x000D_
  <div>...but not me...</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_


Complex example: chaining pseudo selectors

With the notable exception of not being able to chain/nest :not selectors and pseudo elements, you can use in conjunction with other pseudo selectors.

_x000D_
_x000D_
div {_x000D_
  color: black_x000D_
}_x000D_
:not(:nth-child(2)){_x000D_
  color: red;_x000D_
}
_x000D_
<div>_x000D_
  <div>Make me red!</div>_x000D_
  <div>...but not me...</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_


Browser Support, etc.

:not is a CSS3 level selector, the main exception in terms of support is that it is IE9+

The spec also makes an interesting point:

the :not() pseudo allows useless selectors to be written. For instance :not(*|*), which represents no element at all, or foo:not(bar), which is equivalent to foo but with a higher specificity.

How do I convert Word files to PDF programmatically?

To sum it up for vb.net users, the free option (must have office installed):

Microsoft office assembies download:

VB.NET example:

        Dim word As Application = New Application()
        Dim doc As Document = word.Documents.Open("c:\document.docx")
        doc.Activate()
        doc.SaveAs2("c:\document.pdf", WdSaveFormat.wdFormatPDF)
        doc.Close()

TensorFlow, "'module' object has no attribute 'placeholder'"

If you have this error after an upgrade to TensorFlow 2.0, you can still use 1.X API by replacing:

import tensorflow as tf

by

import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()

How to save RecyclerView's scroll position using RecyclerView.State?

I've had the same requirement, but the solutions here didn't quite get me across the line, due to the source of data for the recyclerView.

I was extracting the RecyclerViews' LinearLayoutManager state in onPause()

private Parcelable state;

Public void onPause() {
    state = mLinearLayoutManager.onSaveInstanceState();
}

Parcelable state is saved in onSaveInstanceState(Bundle outState), and extracted again in onCreate(Bundle savedInstanceState), when savedInstanceState != null.

However, the recyclerView adapter is populated and updated by a ViewModel LiveData object returned by a DAO call to a Room database.

mViewModel.getAllDataToDisplay(mSelectedData).observe(this, new Observer<List<String>>() {
    @Override
    public void onChanged(@Nullable final List<String> displayStrings) {
        mAdapter.swapData(displayStrings);
        mLinearLayoutManager.onRestoreInstanceState(state);
    }
});

I eventually found that restoring the instance state directly after the data is set in the adapter would keep the scroll-state across rotations.

I suspect this either is because the LinearLayoutManager state that I'd restored was being overwritten when the data was returned by the database call, or the restored state was meaningless against an 'empty' LinearLayoutManager.

If the adapter data is available directly (ie not contigent on a database call), then restoring the instance state on the LinearLayoutManager can be done after the adapter is set on the recyclerView.

The distinction between the two scenarios held me up for ages.

Merging two images with PHP

You can do this with the ImageMagick extension. I'm guessing that the combineImages() method will do what you want.

How to convert Excel values into buckets?

I use this trick for equal data bucketing. Instead of text result you get the number. Here is example for four buckets. Suppose you have data in A1:A100 range. Put this formula in B1:

=MAX(ROUNDUP(PERCENTRANK($A$1:$A$100,A1) *4,0),1)

Fill down the formula all across B column and you are done. The formula divides the range into 4 equal buckets and it returns the bucket number which the cell A1 falls into. The first bucket contains the lowest 25% of values.

Adjust the number of buckets according to thy wish:

=MAX(ROUNDUP(PERCENTRANK([Range],[OneCellOfTheRangeToTest]) *[NumberOfBuckets],0),1)

The number of observation in each bucket will be equal or almost equal. For example if you have a 100 observations and you want to split it into 3 buckets (like in your example) then the buckets will contain 33, 33, 34 observations. So almost equal. You do not have to worry about that - the formula works that out for you.

Pass Method as Parameter using C#

You can use the Func delegate in .net 3.5 as the parameter in your RunTheMethod method. The Func delegate allows you to specify a method that takes a number of parameters of a specific type and returns a single argument of a specific type. Here is an example that should work:

public class Class1
{
    public int Method1(string input)
    {
        //... do something
        return 0;
    }

    public int Method2(string input)
    {
        //... do something different
        return 1;
    }

    public bool RunTheMethod(Func<string, int> myMethodName)
    {
        //... do stuff
        int i = myMethodName("My String");
        //... do more stuff
        return true;
    }

    public bool Test()
    {
        return RunTheMethod(Method1);
    }
}

Remove all whitespace from C# string with regex

No need for regex. This will also remove tabs, newlines etc

var newstr = String.Join("",str.Where(c=>!char.IsWhiteSpace(c)));

WhiteSpace chars : 0009 , 000a , 000b , 000c , 000d , 0020 , 0085 , 00a0 , 1680 , 180e , 2000 , 2001 , 2002 , 2003 , 2004 , 2005 , 2006 , 2007 , 2008 , 2009 , 200a , 2028 , 2029 , 202f , 205f , 3000.

Unable to use Intellij with a generated sources folder

You can just change the project structure to add that folder as a "source" directory.

Project Structure ? Modules ? Click the generated-sources folder and make it a sources folder.

Or:

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>build-helper-maven-plugin</artifactId>
    <version>1.4</version>
    <executions>
        <execution>
            <id>test</id>
            <phase>generate-sources</phase>
            <goals>
                <goal>add-source</goal>
            </goals>
            <configuration>
                <sources>
                    <source>${basedir}/target/generated-sources</source>
                </sources>
            </configuration>
        </execution>
    </executions>
</plugin>

Running code after Spring Boot starts

It is as simple as this:

@EventListener(ApplicationReadyEvent.class)
public void doSomethingAfterStartup() {
    System.out.println("hello world, I have just started up");
}

Tested on version 1.5.1.RELEASE

What is the difference between hg forget and hg remove?

From the documentation, you can apparently use either command to keep the file in the project history. Looks like you want remove, since it also deletes the file from the working directory.

From the Mercurial book at http://hgbook.red-bean.com/read/:

Removing a file does not affect its history. It is important to understand that removing a file has only two effects. It removes the current version of the file from the working directory. It stops Mercurial from tracking changes to the file, from the time of the next commit. Removing a file does not in any way alter the history of the file.

The man page hg(1) says this about forget:

Mark the specified files so they will no longer be tracked after the next commit. This only removes files from the current branch, not from the entire project history, and it does not delete them from the working directory.

And this about remove:

Schedule the indicated files for removal from the repository. This only removes files from the current branch, not from the entire project history.

file_put_contents(meta/services.json): failed to open stream: Permission denied

As per Laravel 5.4 which is the latest as I am writing this, if you have any problem like this, you ned to change the permission. DO NOT LISTEN TO ANYONE WHO TELLS YOU TO SET 777 FOR ANY DIRECTORY. It has a security issue. Change the permission of storage folder like this

sudo chmod -R 775 storage

Change bootstrap folder permission like this

sudo chmod -R 775 bootstrap/cache

Now please make sure that you're executing both commands from your application directory. You won't face problems in future regarding permission. 775 doesn't compromise any security of your machine.

Android studio: emulator is running but not showing up in Run App "choose a running device"

in your device you want to run app on Go to settings About device >> Build number triple clicks or more and back to settings you will found "Developer options" appear go to and click on "USB debugging" Done

CSS On hover show another element

It is indeed possible with the following code

 <div href="#" id='a'>
     Hover me
 </div>

<div id='b'>
    Show me
</div>

and css

#a {
  display: block;
}

#a:hover + #b {
  display:block;
}

#b {
  display:none;
  }

Now by hovering on element #a shows element #b.

Git Bash won't run my python files?

When you install python for windows, there is an option to include it in the path. For python 2 this is not the default. It adds the python installation folder and script folder to the Windows path. When starting the GIT Bash command prompt, it have included it in the linux PATH variable.

If you start the python installation again, you should select the option Change python and in the next step you can "Add python.exe to Path". Next time you open GIT Bash, the path is correct.

Multiple aggregations of the same column using pandas GroupBy.agg()

You can simply pass the functions as a list:

In [20]: df.groupby("dummy").agg({"returns": [np.mean, np.sum]})
Out[20]:         
           mean       sum
dummy                    
1      0.036901  0.369012

or as a dictionary:

In [21]: df.groupby('dummy').agg({'returns':
                                  {'Mean': np.mean, 'Sum': np.sum}})
Out[21]: 
        returns          
           Mean       Sum
dummy                    
1      0.036901  0.369012

How can I scroll a web page using selenium webdriver in python?

You can use send_keys to simulate a PAGE_DOWN key press (which normally scroll the page):

from selenium.webdriver.common.keys import Keys
html = driver.find_element_by_tag_name('html')
html.send_keys(Keys.PAGE_DOWN)

using jquery $.ajax to call a PHP function

I would stick with normal approach to call the file directly, but if you really want to call a function, have a look at JSON-RPC (JSON Remote Procedure Call).

You basically send a JSON string in a specific format to the server, e.g.

{ "method": "echo", "params": ["Hello JSON-RPC"], "id": 1}

which includes the function to call and the parameters of that function.

Of course the server has to know how to handle such requests.
Here is jQuery plugin for JSON-RPC and e.g. the Zend JSON Server as server implementation in PHP.


This might be overkill for a small project or less functions. Easiest way would be karim's answer. On the other hand, JSON-RPC is a standard.

Call static method with reflection

As the documentation for MethodInfo.Invoke states, the first argument is ignored for static methods so you can just pass null.

foreach (var tempClass in macroClasses)
{
   // using reflection I will be able to run the method as:
   tempClass.GetMethod("Run").Invoke(null, null);
}

As the comment points out, you may want to ensure the method is static when calling GetMethod:

tempClass.GetMethod("Run", BindingFlags.Public | BindingFlags.Static).Invoke(null, null);

What is Unicode, UTF-8, UTF-16?

Originally, Unicode was intended to have a fixed-width 16-bit encoding (UCS-2). Early adopters of Unicode, like Java and Windows NT, built their libraries around 16-bit strings.

Later, the scope of Unicode was expanded to include historical characters, which would require more than the 65,536 code points a 16-bit encoding would support. To allow the additional characters to be represented on platforms that had used UCS-2, the UTF-16 encoding was introduced. It uses "surrogate pairs" to represent characters in the supplementary planes.

Meanwhile, a lot of older software and network protocols were using 8-bit strings. UTF-8 was made so these systems could support Unicode without having to use wide characters. It's backwards-compatible with 7-bit ASCII.

How to detect if a string contains at least a number?

DECLARE @str AS VARCHAR(50)
SET @str = 'PONIES!!...pon1es!!...p0n1es!!'

IF PATINDEX('%[0-9]%', @str) > 0
   PRINT 'YES, The string has numbers'
ELSE
   PRINT 'NO, The string does not have numbers' 

What represents a double in sql server?

Also, here is a good answer for SQL-CLR Type Mapping with a useful chart.

From that post (by David): enter image description here

Date Conversion from String to sql Date in Java giving different output?

mm is minutes. You want MM for months:

SimpleDateFormat sdf1 = new SimpleDateFormat("dd-MM-yyyy");

Don't feel bad - this exact mistake comes up a lot.

How to use JQuery with ReactJS

Yes, we can use jQuery in ReactJs. Here I will tell how we can use it using npm.

step 1: Go to your project folder where the package.json file is present via using terminal using cd command.

step 2: Write the following command to install jquery using npm : npm install jquery --save

step 3: Now, import $ from jquery into your jsx file where you need to use.

Example:

write the below in index.jsx

import React from 'react';
import ReactDOM from 'react-dom';
import $ from 'jquery';


//   react code here


$("button").click(function(){
    $.get("demo_test.asp", function(data, status){
        alert("Data: " + data + "\nStatus: " + status);
    });
});

// react code here

write the below in index.html

<!DOCTYPE html>
<html>
<head>
    <script src="index.jsx"></script>
    <!-- other scripting files -->
</head>
<body>
    <!-- other useful tags -->
    <div id="div1">
        <h2>Let jQuery AJAX Change This Text</h2>
    </div>
    <button>Get External Content</button>
</body>
</html>

Format price in the current locale and currency

For formatting the price in another currency than the current one:

Mage::app()->getLocale()->currency('EUR')->toCurrency($price);

Datatable vs Dataset

When you are only dealing with a single table anyway, the biggest practical difference I have found is that DataSet has a "HasChanges" method but DataTable does not. Both have a "GetChanges" however, so you can use that and test for null.

How to install Python MySQLdb module using pip?

If you are use Raspberry Pi [Raspbian OS]

There are need to be install pip command at first

apt-get install python-pip

So that just install Sequently

apt-get install python-dev libmysqlclient-dev

apt-get install python-pip

pip install MySQL-python

How do I insert an image in an activity with android studio?

since you followed the tutorial, I presume you have a screen that says Hello World.

that means you have some code in your layout xml that looks like this

<TextView        
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/hello_world" />

you want to display an image, so instead of TextView you want to have ImageView. and instead of a text attribute you want an src attribute, that links to your drawable resource

<ImageView
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/cool_pic"
/>

C# create simple xml file

I'd recommend serialization,

public class Person
{
      public  string FirstName;
      public  string MI;
      public  string LastName;
}

static void Serialize()
{
      clsPerson p = new Person();
      p.FirstName = "Jeff";
      p.MI = "A";
      p.LastName = "Price";
      System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(p.GetType());
      x.Serialize(System.Console.Out, p);
      System.Console.WriteLine();
      System.Console.WriteLine(" --- Press any key to continue --- ");
      System.Console.ReadKey();
}

You can further control serialization with attributes.
But if it is simple, you could use XmlDocument:

using System;
using System.Xml;

public class GenerateXml {
    private static void Main() {
        XmlDocument doc = new XmlDocument();
        XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
        doc.AppendChild(docNode);

        XmlNode productsNode = doc.CreateElement("products");
        doc.AppendChild(productsNode);

        XmlNode productNode = doc.CreateElement("product");
        XmlAttribute productAttribute = doc.CreateAttribute("id");
        productAttribute.Value = "01";
        productNode.Attributes.Append(productAttribute);
        productsNode.AppendChild(productNode);

        XmlNode nameNode = doc.CreateElement("Name");
        nameNode.AppendChild(doc.CreateTextNode("Java"));
        productNode.AppendChild(nameNode);
        XmlNode priceNode = doc.CreateElement("Price");
        priceNode.AppendChild(doc.CreateTextNode("Free"));
        productNode.AppendChild(priceNode);

        // Create and add another product node.
        productNode = doc.CreateElement("product");
        productAttribute = doc.CreateAttribute("id");
        productAttribute.Value = "02";
        productNode.Attributes.Append(productAttribute);
        productsNode.AppendChild(productNode);
        nameNode = doc.CreateElement("Name");
        nameNode.AppendChild(doc.CreateTextNode("C#"));
        productNode.AppendChild(nameNode);
        priceNode = doc.CreateElement("Price");
        priceNode.AppendChild(doc.CreateTextNode("Free"));
        productNode.AppendChild(priceNode);

        doc.Save(Console.Out);
    }
}

And if it needs to be fast, use XmlWriter:

public static void WriteXML()
{
    // Create an XmlWriterSettings object with the correct options.
    System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings();
    settings.Indent = true;
    settings.IndentChars = "    "; //  "\t";
    settings.OmitXmlDeclaration = false;
    settings.Encoding = System.Text.Encoding.UTF8;

    using (System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create("data.xml", settings))
    {

        writer.WriteStartDocument();
        writer.WriteStartElement("books");

        for (int i = 0; i < 100; ++i)
        {
            writer.WriteStartElement("book");
            writer.WriteElementString("item", "Book "+ (i+1).ToString());
            writer.WriteEndElement();
        }

        writer.WriteEndElement();

        writer.Flush();
        writer.Close();
    } // End Using writer 

}

And btw, the fastest way to read XML is XmlReader:

public static void ReadXML()
{
    using (System.Xml.XmlReader xmlReader = System.Xml.XmlReader.Create("http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml"))
    {
        while (xmlReader.Read())
        {
            if ((xmlReader.NodeType == System.Xml.XmlNodeType.Element) && (xmlReader.Name == "Cube"))
            {
                if (xmlReader.HasAttributes)
                    System.Console.WriteLine(xmlReader.GetAttribute("currency") + ": " + xmlReader.GetAttribute("rate"));
            }

        } // Whend 

    } // End Using xmlReader

    System.Console.ReadKey();
}

And the most convenient way to read XML is to just deserialize the XML into a class.
This also works for creating the serialization classes, btw.
You can generate the class from XML with Xml2CSharp:
https://xmltocsharp.azurewebsites.net/

What does DIM stand for in Visual Basic and BASIC?

Dimension a variable, basically you are telling the compiler that you are going to need a variable of this type at some point.

how to enable sqlite3 for php?

Only use:

sudo apt-get install php5-sqlite

and later

sudo service apache2 restart

PL/SQL ORA-01422: exact fetch returns more than requested number of rows

A SELECT INTO statement will throw an error if it returns anything other than 1 row. If it returns 0 rows, you'll get a no_data_found exception. If it returns more than 1 row, you'll get a too_many_rows exception. Unless you know that there will always be exactly 1 employee with a salary greater than 3000, you do not want a SELECT INTO statement here.

Most likely, you want to use a cursor to iterate over (potentially) multiple rows of data (I'm also assuming that you intended to do a proper join between the two tables rather than doing a Cartesian product so I'm assuming that there is a departmentID column in both tables)

BEGIN
  FOR rec IN (SELECT EMPLOYEE.EMPID, 
                     EMPLOYEE.ENAME, 
                     EMPLOYEE.DESIGNATION, 
                     EMPLOYEE.SALARY,  
                     DEPARTMENT.DEPT_NAME 
                FROM EMPLOYEE, 
                     DEPARTMENT 
               WHERE employee.departmentID = department.departmentID
                 AND EMPLOYEE.SALARY > 3000)
  LOOP
    DBMS_OUTPUT.PUT_LINE ('Employee Nnumber: ' || rec.EMPID);
    DBMS_OUTPUT.PUT_LINE ('---------------------------------------------------');
    DBMS_OUTPUT.PUT_LINE ('Employee Name: ' || rec.ENAME);
    DBMS_OUTPUT.PUT_LINE ('---------------------------------------------------');
    DBMS_OUTPUT.PUT_LINE ('Employee Designation: ' || rec.DESIGNATION);
    DBMS_OUTPUT.PUT_LINE ('----------------------------------------------------');
    DBMS_OUTPUT.PUT_LINE ('Employee Salary: ' || rec.SALARY);
    DBMS_OUTPUT.PUT_LINE ('----------------------------------------------------');
    DBMS_OUTPUT.PUT_LINE ('Employee Department: ' || rec.DEPT_NAME);
  END LOOP;
END;

I'm assuming that you are just learning PL/SQL as well. In real code, you'd never use dbms_output like this and would not depend on anyone seeing data that you write to the dbms_output buffer.

LINQ: "contains" and a Lambda query

The Linq extension method Any could work for you...

buildingStatus.Any(item => item.GetCharValue() == v.Status)

How to replace all strings to numbers contained in each string in Notepad++?

In Notepad++ to replace, hit Ctrl+H to open the Replace menu.

Then if you check the "Regular expression" button and you want in your replacement to use a part of your matching pattern, you must use "capture groups" (read more on google). For example, let's say that you want to match each of the following lines

value="4"
value="403"
value="200"
value="201"
value="116"
value="15"

using the .*"\d+" pattern and want to keep only the number. You can then use a capture group in your matching pattern, using parentheses ( and ), like that: .*"(\d+)". So now in your replacement you can simply write $1, where $1 references to the value of the 1st capturing group and will return the number for each successful match. If you had two capture groups, for example (.*)="(\d+)", $1 will return the string value and $2 will return the number.

So by using:

Find: .*"(\d+)"

Replace: $1

It will return you

4
403
200
201
116
15

Please note that there many alternate and better ways of matching the aforementioned pattern. For example the pattern value="([0-9]+)" would be better, since it is more specific and you will be sure that it will match only these lines. It's even possible of making the replacement without the use of capture groups, but this is a slightly more advanced topic, so I'll leave it for now :)

How to add a WiX custom action that happens only on uninstall (via MSI)?

The biggest problem with a batch script is handling rollback when the user clicks cancel (or something goes wrong during your install). The correct way to handle this scenario is to create a CustomAction that adds temporary rows to the RemoveFiles table. That way the Windows Installer handles the rollback cases for you. It is insanely simpler when you see the solution.

Anyway, to have an action only execute during uninstall add a Condition element with:

REMOVE ~= "ALL"

the ~= says compare case insensitive (even though I think ALL is always uppercaesd). See the MSI SDK documentation about Conditions Syntax for more information.

PS: There has never been a case where I sat down and thought, "Oh, batch file would be a good solution in an installation package." Actually, finding an installation package that has a batch file in it would only encourage me to return the product for a refund.

Laravel Checking If a Record Exists

It depends if you want to work with the user afterwards or only check if one exists.

If you want to use the user object if it exists:

$user = User::where('email', '=', Input::get('email'))->first();
if ($user === null) {
   // user doesn't exist
}

And if you only want to check

if (User::where('email', '=', Input::get('email'))->count() > 0) {
   // user found
}

Or even nicer

if (User::where('email', '=', Input::get('email'))->exists()) {
   // user found
}

Force the origin to start at 0

In the latest version of ggplot2, this can be more easy.

p <- ggplot(mtcars, aes(wt, mpg))
p + geom_point()
p+ geom_point() + scale_x_continuous(expand = expansion(mult = c(0, 0))) + scale_y_continuous(expand = expansion(mult = c(0, 0)))

enter image description here

See ?expansion() for more details.

Setting Icon for wpf application (VS 08)

Assuming you use VS Express and C#. The icon is set in the project properties page. To open it right click on the project name in the solution explorer. in the page that opens, there is an Application tab, in this tab you can set the icon.

XML to CSV Using XSLT

Found an XML transform stylesheet here (wayback machine link, site itself is in german)

The stylesheet added here could be helpful:

<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="text" encoding="iso-8859-1"/>

<xsl:strip-space elements="*" />

<xsl:template match="/*/child::*">
<xsl:for-each select="child::*">
<xsl:if test="position() != last()">"<xsl:value-of select="normalize-space(.)"/>",    </xsl:if>
<xsl:if test="position()  = last()">"<xsl:value-of select="normalize-space(.)"/>"<xsl:text>&#xD;</xsl:text>
</xsl:if>
</xsl:for-each>
</xsl:template>

</xsl:stylesheet>

Perhaps you want to remove the quotes inside the xsl:if tags so it doesn't put your values into quotes, depending on where you want to use the CSV file.

How to log as much information as possible for a Java Exception?

What's wrong with the printStacktrace() method provided by Throwable (and thus every exception)? It shows all the info you requested, including the type, message, and stack trace of the root exception and all (nested) causes. In Java 7, it even shows you the information about "supressed" exceptions that might occur in a try-with-resources statement.

Of course you wouldn't want to write to System.err, which the no-argument version of the method does, so instead use one of the available overloads.

In particular, if you just want to get a String:

  Exception e = ...
  StringWriter sw = new StringWriter();
  e.printStackTrace(new PrintWriter(sw));
  String exceptionDetails = sw.toString();

If you happen to use the great Guava library, it provides a utility method doing this: com.google.common.base.Throwables#getStackTraceAsString(Throwable).

Getting the number of filled cells in a column (VBA)

You can also use

Cells.CurrentRegion

to give you a range representing the bounds of your data on the current active sheet

Msdn says on the topic

Returns a Range object that represents the current region. The current region is a range bounded by any combination of blank rows and blank columns. Read-only.

Then you can determine the column count via

Cells.CurrentRegion.Columns.Count

and the row count via

Cells.CurrentRegion.Rows.Count

Swift Modal View Controller with transparent background

You can do it like this:

In your main view controller:

func showModal() {
    let modalViewController = ModalViewController()
    modalViewController.modalPresentationStyle = .overCurrentContext
    presentViewController(modalViewController, animated: true, completion: nil)
}

In your modal view controller:

class ModalViewController: UIViewController {
    override func viewDidLoad() {
        view.backgroundColor = UIColor.clearColor()
        view.opaque = false
    }
}

If you are working with a storyboard:

Just add a Storyboard Segue with Kind set to Present Modally to your modal view controller and on this view controller set the following values:

  • Background = Clear Color
  • Drawing = Uncheck the Opaque checkbox
  • Presentation = Over Current Context

As Crashalot pointed out in his comment: Make sure the segue only uses Default for both Presentation and Transition. Using Current Context for Presentation makes the modal turn black instead of remaining transparent.

How to manage exceptions thrown in filters in Spring?

You can use the following method inside the catch block:

response.sendError(HttpStatus.UNAUTHORIZED.value(), "Invalid token")

Notice that you can use any HttpStatus code and a custom message.

Simple export and import of a SQLite database on Android

Import and Export of a SQLite database on Android

Here is my function for export database into device storage

private void exportDB(){
    String DatabaseName = "Sycrypter.db";
    File sd = Environment.getExternalStorageDirectory();
    File data = Environment.getDataDirectory();
    FileChannel source=null;
    FileChannel destination=null;
    String currentDBPath = "/data/"+ "com.synnlabz.sycryptr" +"/databases/"+DatabaseName ;
    String backupDBPath = SAMPLE_DB_NAME;
    File currentDB = new File(data, currentDBPath);
    File backupDB = new File(sd, backupDBPath);
    try {
        source = new FileInputStream(currentDB).getChannel();
        destination = new FileOutputStream(backupDB).getChannel();
        destination.transferFrom(source, 0, source.size());
        source.close();
        destination.close();
        Toast.makeText(this, "Your Database is Exported !!", Toast.LENGTH_LONG).show();
    } catch(IOException e) {
        e.printStackTrace();
    }
}

Here is my function for import database from device storage into android application

private void importDB(){
    String dir=Environment.getExternalStorageDirectory().getAbsolutePath();
    File sd = new File(dir);
    File data = Environment.getDataDirectory();
    FileChannel source = null;
    FileChannel destination = null;
    String backupDBPath = "/data/com.synnlabz.sycryptr/databases/Sycrypter.db";
    String currentDBPath = "Sycrypter.db";
    File currentDB = new File(sd, currentDBPath);
    File backupDB = new File(data, backupDBPath);

    try {
        source = new FileInputStream(currentDB).getChannel();
        destination = new FileOutputStream(backupDB).getChannel();
        destination.transferFrom(source, 0, source.size());
        source.close();
        destination.close();
        Toast.makeText(this, "Your Database is Imported !!", Toast.LENGTH_SHORT).show();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Android: why setVisibility(View.GONE); or setVisibility(View.INVISIBLE); do not work

First see your code:

dp2.setVisibility(View.GONE);
dp2.setVisibility(View.INVISIBLE);
btn2.setVisibility(View.GONE);
btn2.setVisibility(View.INVISIBLE);

Here you set both visibility to same field so that's the problem. I give one sample for that sample demo

Convert HTML + CSS to PDF

Just to bump the thread, I've tried DOMPDF and it worked perfectly. I've used DIV and other block level elements to position everything, I kept it strictly CSS 2.1 and it played very nicely.