Programs & Examples On #Perl4

Can you get a Windows (AD) username in PHP?

We have multiple domains in our environment so I use preg_replace with regex to get just the username without DOMAIN\ .

preg_replace("/^.+\\\\/", "", $_SERVER["AUTH_USER"]);

Delete duplicate records from a SQL table without a primary key

I'm not an SQL expert so bear with me. I'm sure you'll get a better answer soon enough. Here's how you can find the duplicate records.

select t1.empid, t1.empssn, count(*)
from employee as t1 
inner join employee as t2 on (t1.empid=t2.empid and t1.empssn = t2.empssn)
group by t1.empid, t1.empssn
having count(*) > 1

Deleting them will be more tricky because there is nothing in the data that you could use in a delete statement to differentiate the duplicates. I suspect the answer will involve row_number() or adding an identity column.

if A vs if A is not None:

The statement

if A:

will call A.__nonzero__() (see Special method names documentation) and use the return value of that function. Here's the summary:

object.__nonzero__(self)

Called to implement truth value testing and the built-in operation bool(); should return False or True, or their integer equivalents 0 or 1. When this method is not defined, __len__() is called, if it is defined, and the object is considered true if its result is nonzero. If a class defines neither __len__() nor __nonzero__(), all its instances are considered true.

On the other hand,

if A is not None:

compares only the reference A with None to see whether it is the same or not.

What difference between the DATE, TIME, DATETIME, and TIMESTAMP Types

DATE: It is used for values with a date part but no time part. MySQL retrieves and displays DATE values in YYYY-MM-DD format. The supported range is 1000-01-01 to 9999-12-31.

DATETIME: It is used for values that contain both date and time parts. MySQL retrieves and displays DATETIME values in YYYY-MM-DD HH:MM:SS format. The supported range is 1000-01-01 00:00:00 to 9999-12-31 23:59:59.

TIMESTAMP: It is also used for values that contain both date and time parts, and includes the time zone. TIMESTAMP has a range of 1970-01-01 00:00:01 UTC to 2038-01-19 03:14:07 UTC.

TIME: Its values are in HH:MM:SS format (or HHH:MM:SS format for large hours values). TIME values may range from -838:59:59 to 838:59:59. The hours part may be so large because the TIME type can be used not only to represent a time of day (which must be less than 24 hours), but also elapsed time or a time interval between two events (which may be much greater than 24 hours, or even negative).

typescript: error TS2693: 'Promise' only refers to a type, but is being used as a value here

I solved this by adding below code to tsconfig.json file.

"lib": [
    "ES5",
    "ES2015",
    "DOM",
    "ScriptHost"]

How do change the color of the text of an <option> within a <select>?

Try just this without the span tag:

<option selected="selected" class="grey_color">select one option</option>

For bigger flexibility you can use any JS widget.

Check if string ends with certain pattern

You can test if a string ends with work followed by one character like this:

theString.matches(".*work.$");

If the trailing character is optional you can use this:

theString.matches(".*work.?$");

To make sure the last character is a period . or a slash / you can use this:

theString.matches(".*work[./]$");

To test for work followed by an optional period or slash you can use this:

theString.matches(".*work[./]?$");

To test for work surrounded by periods or slashes, you could do this:

theString.matches(".*[./]work[./]$");

If the tokens before and after work must match each other, you could do this:

theString.matches(".*([./])work\\1$");

Your exact requirement isn't precisely defined, but I think it would be something like this:

theString.matches(".*work[,./]?$");

In other words:

  • zero or more characters
  • followed by work
  • followed by zero or one , . OR /
  • followed by the end of the input

Explanation of various regex items:

.               --  any character
*               --  zero or more of the preceeding expression
$               --  the end of the line/input
?               --  zero or one of the preceeding expression
[./,]           --  either a period or a slash or a comma
[abc]           --  matches a, b, or c
[abc]*          --  zero or more of (a, b, or c)
[abc]?          --  zero or one of (a, b, or c)

enclosing a pattern in parentheses is called "grouping"

([abc])blah\\1  --  a, b, or c followed by blah followed by "the first group"

Here's a test harness to play with:

class TestStuff {

    public static void main (String[] args) {

        String[] testStrings = { 
                "work.",
                "work-",
                "workp",
                "/foo/work.",
                "/bar/work",
                "baz/work.",
                "baz.funk.work.",
                "funk.work",
                "jazz/junk/foo/work.",
                "funk/punk/work/",
                "/funk/foo/bar/work",
                "/funk/foo/bar/work/",
                ".funk.foo.bar.work.",
                ".funk.foo.bar.work",
                "goo/balls/work/",
                "goo/balls/work/funk"
        };

        for (String t : testStrings) {
            print("word: " + t + "  --->  " + matchesIt(t));
        }
    }

    public static boolean matchesIt(String s) {
        return s.matches(".*([./,])work\\1?$");
    }

    public static void print(Object o) {
        String s = (o == null) ? "null" : o.toString();
        System.out.println(o);
    }

}

Invoke a second script with arguments from a script

Invoke-Expression should work perfectly, just make sure you are using it correctly. For your case it should look like this:

Invoke-Expression "$scriptPath $argumentList"

I tested this approach with Get-Service and seems to be working as expected.

create multiple tag docker image

Since 1.10 release, you can now add multiple tags at once on build:

docker build -t name1:tag1 -t name1:tag2 -t name2 .

Source: Add ability to add multiple tags with docker build

.jar error - could not find or load main class

I found this question when I was looking for the answer to the above question. But in my case the issue was the use of an 'en dash' rather than a 'dash'. Check which dash you are using, it might be the wrong one. I hope this answer speeds up someone else's search, a comment like this could have saved me a bit of time.

Creating/writing into a new file in Qt

That is weird, everything looks fine, are you sure it does not work for you? Because this main surely works for me, so I would look somewhere else for the source of your problem.

#include <QFile>
#include <QTextStream>


int main()
{
    QString filename = "Data.txt";
    QFile file(filename);
    if (file.open(QIODevice::ReadWrite)) {
        QTextStream stream(&file);
        stream << "something" << endl;
    }
}

The code you provided is also almost the same as the one provided in detailed description of QTextStream so I am pretty sure, that the problem is elsewhere :)

Also note, that the file is not called Data but Data.txt and should be created/located in the directory from which the program was run (not necessarily the one where the executable is located).

Method List in Visual Studio Code

There is a plugin called show functions which lists all the function definitions in a file. It also allows you to sort the function so can search them easily.

How to cut first n and last n columns?

You can cut using following ,
-d: delimiter ,-f for fields
\t used for tab separated fields

cut -d$'\t' -f 1-3,7-

Unbalanced calls to begin/end appearance transitions for <UITabBarController: 0x197870>

For me this error occurred because i didn't have UIWindow declared in the upper level of my class when setting a root view controller

            rootViewController?.showTimeoutAlert = showTimeOut
            let navigationController = SwipeNavigationController(rootViewController: rootViewController!)
            self.window = UIWindow(frame: UIScreen.main.bounds)
            self.window?.rootViewController = navigationController
            self.window?.makeKeyAndVisible()

Ex if I tried declaring window in that block of code instead of referencing self then I would receive the error

how to break the _.each function in underscore.js

Maybe you want Underscore's any() or find(), which will stop processing when a condition is met.

Change Date Format(DD/MM/YYYY) in SQL SELECT Statement

There's also another way to do this-

select TO_CHAR(SA.[RequestStartDate] , 'DD/MM/YYYY') as RequestStartDate from ... ;

Get POST data in C#/ASP.NET

The following is OK in HTML4, but not in XHTML. Check your editor.

<input type=button value="Submit" />

Compiling LaTex bib source

Just in case it helps someone, since these questions (and answers) helped me really much; I decided to create an alias that runs these 4 commands in a row:

Just add the following line to your ~/.bashrc file (modify the main keyword accordingly to the name of your .tex and .bib files)

alias texbib = 'pdflatex main.tex && bibtex main && pdflatex main.tex && pdflatex main.tex'

And now, by just executing the texbib command (alias), all these commands will be executed sequentially.

Run a Docker image as a container

To view a list of all images on your Docker host, run:

  $ docker images
   REPOSITORY          TAG           IMAGE ID            CREATED             SIZE
   apache_snapshot     latest        13037686eac3        22 seconds ago      249MB
   ubuntu              latest        00fd29ccc6f1        3 weeks ago         111MB

Now you can run the Docker image as a container in interactive mode:

   $ docker run -it apache_snapshot /bin/bash

OR if you don't have any images locally,Search Docker Hub for an image to download:

    $ docker search ubuntu
    NAME                            DESCRIPTION             STARS  OFFICIAL  AUTOMATED
    ubuntu                          Ubuntu is a Debian...   6759   [OK]       
    dorowu/ubuntu-desktop-lxde-vnc  Ubuntu with openss...   141              [OK]
    rastasheep/ubuntu-sshd          Dockerized SSH ser...   114              [OK]
    ansible/ubuntu14.04-ansible     Ubuntu 14.04 LTS w...   88               [OK]
    ubuntu-upstart                  Upstart is an even...   80     [OK]

Pull the Docker image from a repository with the docker pull command:

     $ docker pull ubuntu

Run the Docker image as a container:

     $ docker run -it ubuntu /bin/bash

how to find my angular version in my project?

For Angular 1 or 2 (but not for Angular 4+):

You can also open the console and go to the element tab on the developer tools of whatever browser you use.

Or

Type angular.version to access the Javascript object that holds angular version.

For Angular 4+ There is are the number of ways as listed below :

Write below code in the command prompt/or in the terminal in the VS Code.

  1. ng version or ng --version (See the attachment for the reference.)
  2. ng v
  3. ng -v

In the terminal you can find the angular version as shown in the attached image : enter image description here

  1. You can also open the console and go to the element tab on the developer tools of whatever browser you use. As displayed in the below image :

enter image description here

5.Find the package.json file, You will find all the installed packages and their version.

  1. declare the variable named as 'VERSION', Import the dependencies.
import { VERSION } from '@angular/core';

// To display the version in the console.

console.log(VERSION.full); 

Alternative for PHP_excel

I wrote a very simple class for exporting to "Excel XML" aka SpreadsheetML. It's not quite as convenient for the end user as XSLX (depending on file extension and Excel version, they may get a warning message), but it's a lot easier to work with than XLS or XLSX.

http://github.com/elidickinson/php-export-data

Defining a percentage width for a LinearLayout?

*You can use layout_weight properties. If you want to take 70% of parent width you must set child layout_width property value 0dp, like android:layout_width="0dp"*

What datatype to use when storing latitude and longitude data in SQL databases?

I think it depends on the operations you'll be needing to do most frequently.

If you need the full value as a decimal number, then use decimal with appropriate precision and scale. Float is way beyond your needs, I believe.

If you'll be converting to/from degºmin'sec"fraction notation often, I'd consider storing each value as an integer type (smallint, tinyint, tinyint, smallint?).

Get array elements from index to end

The [:-1] removes the last element. Instead of

a[3:-1]

write

a[3:]

You can read up on Python slicing notation here: Explain Python's slice notation

NumPy slicing is an extension of that. The NumPy tutorial has some coverage: Indexing, Slicing and Iterating.

PHP Fatal error: Cannot access empty property

To access a variable in a class, you must use $this->myVar instead of $this->$myvar.

And, you should use access identifier to declare a variable instead of var.

Please read the doc here.

CSS text-align not working

Change the rule on your <a> element from:

.navigation ul a {
    color: #000;
    display: block;
    padding: 0 65px 0 0;
    text-decoration: none;
}?

to

.navigation ul a {
    color: #000;
    display: block;
    padding: 0 65px 0 0;
    text-decoration: none;
    width:100%;
    text-align:center;
}?

Just add two new rules (width:100%; and text-align:center;). You need to make the anchor expand to take up the full width of the list item and then text-align center it.

jsFiddle example

convert ArrayList<MyCustomClass> to JSONArray

Use Gson library to convert ArrayList to JsonArray.

Gson gson = new GsonBuilder().create();
JsonArray myCustomArray = gson.toJsonTree(myCustomList).getAsJsonArray();

Python: Find in list

If you are going to check if value exist in the collectible once then using 'in' operator is fine. However, if you are going to check for more than once then I recommend using bisect module. Keep in mind that using bisect module data must be sorted. So you sort data once and then you can use bisect. Using bisect module on my machine is about 12 times faster than using 'in' operator.

Here is an example of code using Python 3.8 and above syntax:

import bisect
from timeit import timeit

def bisect_search(container, value):
    return (
      (index := bisect.bisect_left(container, value)) < len(container) 
      and container[index] == value
    )

data = list(range(1000))
# value to search
true_value = 666
false_value = 66666

# times to test
ttt = 1000

print(f"{bisect_search(data, true_value)=} {bisect_search(data, false_value)=}")

t1 = timeit(lambda: true_value in data, number=ttt)
t2 = timeit(lambda: bisect_search(data, true_value), number=ttt)

print("Performance:", f"{t1=:.4f}, {t2=:.4f}, diffs {t1/t2=:.2f}")

Output:

bisect_search(data, true_value)=True bisect_search(data, false_value)=False
Performance: t1=0.0220, t2=0.0019, diffs t1/t2=11.71

How to recover corrupted Eclipse workspace?

I know this sounds obvious, but if I'm writing code for a living I would be sure to do a full backup weekly, with corresponding incremental backups daily.

Simple and easy recovery.

For a simple way to backup your eclipse directory and assuming your using Linux, you could use rsync.

rsync -ar <eclipse-dir> <backup-eclipse-dir>

You can put this in cron and have it backup your files automatically. It will only copy over the changed files to your backup-eclipse-dir on subsequent runs.

Can I get "&&" or "-and" to work in PowerShell?

Use:

if (start-process filename1.exe) {} else {start-process filename2.exe}

It's a little longer than "&&", but it accomplishes the same thing without scripting and is not too hard to remember.

Android: how to create Switch case from this?

You can do this:

@Override
protected Dialog onCreateDialog(int id) {
    String messageDialog;
    String valueOK;
    String valueCancel;
    String titleDialog;
    switch (id) {

    case id:
        titleDialog = itemTitle;
        messageDialog = itemDescription
        valueOK = "OK";            
        return new AlertDialog.Builder(HomeView.this).setTitle(titleDialog).setPositiveButton(valueOK, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) {
                Log.d(this.getClass().getName(), "AlertItem");
            }
        }).setMessage(messageDialog).create(); 

and then call to

showDialog(numbreOfItem);

How to list branches that contain a given commit?

The answer for git branch -r --contains <commit> works well for normal remote branches, but if the commit is only in the hidden head namespace that GitHub creates for PRs, you'll need a few more steps.

Say, if PR #42 was from deleted branch and that PR thread has the only reference to the commit on the repo, git branch -r doesn't know about PR #42 because refs like refs/pull/42/head aren't listed as a remote branch by default.

In .git/config for the [remote "origin"] section add a new line:

fetch = +refs/pull/*/head:refs/remotes/origin/pr/*

(This gist has more context.)

Then when you git fetch you'll get all the PR branches, and when you run git branch -r --contains <commit> you'll see origin/pr/42 contains the commit.

Easy pretty printing of floats in python?

print "[%s]"%", ".join(map(str,yourlist))

This will avoid the rounding errors in the binary representation when printed, without introducing a fixed precision constraint (like formating with "%.2f"):

[9.0, 0.053, 0.0325754, 0.0108928, 0.0557025, 0.0793303]

How do I launch a Git Bash window with particular working directory using a script?

Git Bash uses cmd.exe for its terminal plus extentions from MSYS/MinGW which are provided by sh.exe, a sort of cmd.exe wrapper. In Windows you launch a new terminal using the start command.

Thus a shell script which launches a new Git Bash terminal with a specific working directory is:

(cd C:/path/to/dir1 && start sh --login) &
(cd D:/path/to/dir2 && start sh --login) &

An equivalent Windows batch script is:

C:
cd \path\to\dir1
start "" "%SYSTEMDRIVE%\Program Files (x86)\Git\bin\sh.exe" --login 
D:
cd \path\to\dir2
start "" "%SYSTEMDRIVE%\Program Files (x86)\Git\bin\sh.exe" --login 

To get the same font and window size as the Git Bash launched from the start menu, it is easiest to copy the start menu shortcut settings to the command console defaults (to change defaults, open cmd.exe, left-click the upper left icon, and select Defaults).

Check whether a string is not null and not empty

Almost every library I know defines a utility class called StringUtils, StringUtil or StringHelper, and they usually include the method you are looking for.

My personal favorite is Apache Commons / Lang, where in the StringUtils class, you get both the

  1. StringUtils.isEmpty(String) and the
  2. StringUtils.isBlank(String) method

(The first checks whether a string is null or empty, the second checks whether it is null, empty or whitespace only)

There are similar utility classes in Spring, Wicket and lots of other libs. If you don't use external libraries, you might want to introduce a StringUtils class in your own project.


Update: many years have passed, and these days I'd recommend using Guava's Strings.isNullOrEmpty(string) method.

Can .NET load and parse a properties file equivalent to Java Properties class?

Final class. Thanks @eXXL.

public class Properties
{
    private Dictionary<String, String> list;
    private String filename;

    public Properties(String file)
    {
        reload(file);
    }

    public String get(String field, String defValue)
    {
        return (get(field) == null) ? (defValue) : (get(field));
    }
    public String get(String field)
    {
        return (list.ContainsKey(field))?(list[field]):(null);
    }

    public void set(String field, Object value)
    {
        if (!list.ContainsKey(field))
            list.Add(field, value.ToString());
        else
            list[field] = value.ToString();
    }

    public void Save()
    {
        Save(this.filename);
    }

    public void Save(String filename)
    {
        this.filename = filename;

        if (!System.IO.File.Exists(filename))
            System.IO.File.Create(filename);

        System.IO.StreamWriter file = new System.IO.StreamWriter(filename);

        foreach(String prop in list.Keys.ToArray())
            if (!String.IsNullOrWhiteSpace(list[prop]))
                file.WriteLine(prop + "=" + list[prop]);

        file.Close();
    }

    public void reload()
    {
        reload(this.filename);
    }

    public void reload(String filename)
    {
        this.filename = filename;
        list = new Dictionary<String, String>();

        if (System.IO.File.Exists(filename))
            loadFromFile(filename);
        else
            System.IO.File.Create(filename);
    }

    private void loadFromFile(String file)
    {
        foreach (String line in System.IO.File.ReadAllLines(file))
        {
            if ((!String.IsNullOrEmpty(line)) &&
                (!line.StartsWith(";")) &&
                (!line.StartsWith("#")) &&
                (!line.StartsWith("'")) &&
                (line.Contains('=')))
            {
                int index = line.IndexOf('=');
                String key = line.Substring(0, index).Trim();
                String value = line.Substring(index + 1).Trim();

                if ((value.StartsWith("\"") && value.EndsWith("\"")) ||
                    (value.StartsWith("'") && value.EndsWith("'")))
                {
                    value = value.Substring(1, value.Length - 2);
                }

                try
                {
                    //ignore dublicates
                    list.Add(key, value);
                }
                catch { }
            }
        }
    }


}

Sample use:

//load
Properties config = new Properties(fileConfig);
//get value whith default value
com_port.Text = config.get("com_port", "1");
//set value
config.set("com_port", com_port.Text);
//save
config.Save()

Remove part of a string

Here's the strsplit solution if s is a vector:

> s <- c("TGAS_1121", "MGAS_1432")
> s1 <- sapply(strsplit(s, split='_', fixed=TRUE), function(x) (x[2]))
> s1
[1] "1121" "1432"

Rails: How does the respond_to block work?

From what I know, respond_to is a method attached to the ActionController, so you can use it in every single controller, because all of them inherits from the ActionController. Here is the Rails respond_to method:

def respond_to(&block)
  responder = Responder.new(self)
  block.call(responder)
  responder.respond
end

You are passing it a block, like I show here:

respond_to <<**BEGINNING OF THE BLOCK**>> do |format|
  format.html
  format.xml  { render :xml => @whatever }
end <<**END OF THE BLOCK**>>

The |format| part is the argument that the block is expecting, so inside the respond_to method we can use that. How?

Well, if you notice we pass the block with a prefixed & in the respond_to method, and we do that to treat that block as a Proc. Since the argument has the ".xml", ".html" we can use that as methods to be called.

What we basically do in the respond_to class is call methods ".html, .xml, .json" to an instance of a Responder class.

Find the files existing in one directory but not in the other

Another (maybe faster for large directories) approach:

$ find dir1 | sed 's,^[^/]*/,,' | sort > dir1.txt && find dir2 | sed 's,^[^/]*/,,' | sort > dir2.txt
$ diff dir1.txt dir2.txt

The sed command removes the first directory component thanks to Erik`s post)

How to update only one field using Entity Framework?

i'm using this:

entity:

public class Thing 
{
    [Key]
    public int Id { get; set; }
    public string Info { get; set; }
    public string OtherStuff { get; set; }
}

dbcontext:

public class MyDataContext : DbContext
{
    public DbSet<Thing > Things { get; set; }
}

accessor code:

MyDataContext ctx = new MyDataContext();

// FIRST create a blank object
Thing thing = ctx.Things.Create();

// SECOND set the ID
thing.Id = id;

// THIRD attach the thing (id is not marked as modified)
db.Things.Attach(thing); 

// FOURTH set the fields you want updated.
thing.OtherStuff = "only want this field updated.";

// FIFTH save that thing
db.SaveChanges();

Linux: command to open URL in default browser

In Java (version 6+), you can also do:

Desktop d = Desktop.getDesktop();
d.browse(uri);

Though this won't work on all Linuxes. At the time of writing, Gnome is supported, KDE isn't.

php codeigniter count rows

replace the query inside your model function with this

$query = $this->db->query("SELECT id FROM home");

in view:

echo $query->num_rows();

socket programming multiple client to one server

See O'Reilly "Java Cookbook", Ian Darwin - recipe 17.4 Handling Multiple Clients.

Pay attention that accept() is not thread safe, so the call is wrapped within synchronized.

64: synchronized(servSock) {
65:     clientSocket = servSock.accept();
66: }

How can I remove the extension of a filename in a shell script?

My recommendation is to use basename.
It is by default in Ubuntu, visually simple code and deal with majority of cases.

Here are some sub-cases to deal with spaces and multi-dot/sub-extension:

pathfile="../space fld/space -file.tar.gz"
echo ${pathfile//+(*\/|.*)}

It usually get rid of extension from first ., but fail in our .. path

echo **"$(basename "${pathfile%.*}")"**  
space -file.tar     # I believe we needed exatly that

Here is an important note:

I used double quotes inside double quotes to deal with spaces. Single quote will not pass due to texting the $. Bash is unusual and reads "second "first" quotes" due to expansion.

However, you still need to think of .hidden_files

hidden="~/.bashrc"
echo "$(basename "${hidden%.*}")"  # will produce "~" !!!  

not the expected "" outcome. To make it happen use $HOME or /home/user_path/
because again bash is "unusual" and don't expand "~" (search for bash BashPitfalls)

hidden2="$HOME/.bashrc" ;  echo '$(basename "${pathfile%.*}")'

How to select all rows which have same value in some column

You can do this without a JOIN:

SELECT *
FROM (SELECT *,COUNT(*) OVER(PARTITION BY phone_number) as Phone_CT
      FROM YourTable
      )sub
WHERE Phone_CT > 1
ORDER BY phone_number, employee_ids

Demo: SQL Fiddle

Error during installing HAXM, VT-X not working

I had the same issues on my notebook which runs Windows 8.1

Try this:

  • Check if Hyper-V options in "Windows Features activate or deactivate" are deactivated
  • Download and install the latest Oracle VirtualBox
  • Reboot
  • Install HAXM
  • Reboot-->open BIOS--> Enable 'Execute Disable'

It looks like that the installation of VirtualBox sets a flag that "turns" VT-X on.

Which comment style should I use in batch files?

Comments with REM

A REM can remark a complete line, also a multiline caret at the line end, if it's not the end of the first token.

REM This is a comment, the caret is ignored^
echo This line is printed

REM This_is_a_comment_the_caret_appends_the_next_line^
echo This line is part of the remark

REM followed by some characters .:\/= works a bit different, it doesn't comment an ampersand, so you can use it as inline comment.

echo First & REM. This is a comment & echo second

But to avoid problems with existing files like REM, REM.bat or REM;.bat only a modified variant should be used.

REM^;<space>Comment

And for the character ; is also allowed one of ;,:\/=

REM is about 6 times slower than :: (tested on Win7SP1 with 100000 comment lines).
For a normal usage it's not important (58µs versus 360µs per comment line)

Comments with ::

A :: always executes a line end caret.

:: This is also a comment^
echo This line is also a comment

Labels and also the comment label :: have a special logic in parenthesis blocks.
They span always two lines SO: goto command not working.
So they are not recommended for parenthesis blocks, as they are often the cause for syntax errors.

With ECHO ON a REM line is shown, but not a line commented with ::

Both can't really comment out the rest of the line, so a simple %~ will cause a syntax error.

REM This comment will result in an error %~ ...

But REM is able to stop the batch parser at an early phase, even before the special character phase is done.

@echo ON
REM This caret ^ is visible

You can use &REM or &:: to add a comment to the end of command line. This approach works because '&' introduces a new command on the same line.

Comments with percent signs %= comment =%

There exists a comment style with percent signs.

In reality these are variables but they are expanded to nothing.
But the advantage is that they can be placed in the same line, even without &.
The equal sign ensures, that such a variable can't exists.

echo Mytest
set "var=3"     %= This is a comment in the same line=%

The percent style is recommended for batch macros, as it doesn't change the runtime behaviour, as the comment will be removed when the macro is defined.

set $test=(%\n%
%=Start of code=% ^
echo myMacro%\n%
)

final keyword in method parameters

final keyword in the method input parameter is not needed. Java creates a copy of the reference to the object, so putting final on it doesn't make the object final but just the reference, which doesn't make sense

How do you share code between projects/solutions in Visual Studio?

There is a very good case for using "adding existing file links" when reusing code across projects, and that is when you need to reference and support different versions of dependent libraries.

Making multiple assemblies with references to different external assemblies isn't easy to do otherwise without duplicating your code, or utilizing tricks with source code control.

I believe that it's easiest to maintain one project for development and unit test, then to create 'build' projects using existing file links when you need to create the assemblies which reference different versions of those external assemblies.

How to symbolicate crash log Xcode?

There is an easier way using Xcode (without using command line tools and looking up addresses one at a time)

  1. Take any .xcarchive file. If you have one from before you can use that. If you don't have one, create one by running the Product > Archive from Xcode.

  2. Right click on the .xcarchive file and select 'Show Package Contents'

  3. Copy the dsym file (of the version of the app that crashed) to the dSYMs folder

  4. Copy the .app file (of the version of the app that crashed) to the Products > Applications folder

  5. Edit the Info.plist and edit the CFBundleShortVersionString and CFBundleVersion under the ApplicationProperties dictionary. This will help you identify the archive later

  6. Double click the .xcarchive to import it to Xcode. It should open Organizer.

  7. Go back to the crash log (in Devices window in Xcode)

  8. Drag your .crash file there (if not already present)

  9. The entire crash log should now be symbolicated. If not, then right click and select 'Re-symbolicate crash log'

String comparison: InvariantCultureIgnoreCase vs OrdinalIgnoreCase?

You seem to be doing file name comparisons, so I would just add that OrdinalIgnoreCase is closest to what NTFS does (it's not exactly the same, but it's closer than InvariantCultureIgnoreCase)

what does numpy ndarray shape do?

array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])

enter image description here

Apply Calibri (Body) font to text

There is no such font as “Calibri (Body)”. You probably saw this string in Microsoft Word font selection menu, but it’s not a font name (see e.g. the explanation Font: +body (in W07)).

So use just font-family: Calibri or, better, font-family: Calibri, sans-serif. (There is no adequate backup font for Calibri, but the odds are that when Calibri is not available, the browser’s default sans-serif font suits your design better than the browser’s default font, which is most often a serif font.)

How to apply a CSS filter to a background image

I didn't write this, but I noticed there was a polyfill for the partially supported backdrop-filter using the CSS SASS compiler, so if you have a compilation pipeline it can be achieved nicely (it also uses TypeScript):

https://codepen.io/mixal_bl4/pen/EwPMWo

Converting serial port data to TCP/IP in a Linux environment

You don't need to write a program to do this in Linux. Just pipe the serial port through netcat:

netcat www.example.com port </dev/ttyS0 >/dev/ttyS0

Just replace the address and port information. Also, you may be using a different serial port (i.e. change the /dev/ttyS0 part). You can use the stty or setserial commands to change the parameters of the serial port (baud rate, parity, stop bits, etc.).

How To Pass GET Parameters To Laravel From With GET Method ?

I had same problem. I need show url for a search engine

I use two routes like this

Route::get('buscar/{nom}', 'FrontController@buscarPrd');

Route::post('buscar', function(){

   $bsqd = Input::get('nom');    

   return Redirect::action('FrontController@buscarPrd', array('nom'=>$bsqd));

});

First one used to show url like we want

Second one used by form and redirect to first one

Prompt for user input in PowerShell

Read-Host is a simple option for getting string input from a user.

$name = Read-Host 'What is your username?'

To hide passwords you can use:

$pass = Read-Host 'What is your password?' -AsSecureString

To convert the password to plain text:

[Runtime.InteropServices.Marshal]::PtrToStringAuto(
    [Runtime.InteropServices.Marshal]::SecureStringToBSTR($pass))

As for the type returned by $host.UI.Prompt(), if you run the code at the link posted in @Christian's comment, you can find out the return type by piping it to Get-Member (for example, $results | gm). The result is a Dictionary where the key is the name of a FieldDescription object used in the prompt. To access the result for the first prompt in the linked example you would type: $results['String Field'].

To access information without invoking a method, leave the parentheses off:

PS> $Host.UI.Prompt

MemberType          : Method
OverloadDefinitions : {System.Collections.Generic.Dictionary[string,psobject] Pr
                    ompt(string caption, string message, System.Collections.Ob
                    jectModel.Collection[System.Management.Automation.Host.Fie
                    ldDescription] descriptions)}
TypeNameOfValue     : System.Management.Automation.PSMethod
Value               : System.Collections.Generic.Dictionary[string,psobject] Pro
                    mpt(string caption, string message, System.Collections.Obj
                    ectModel.Collection[System.Management.Automation.Host.Fiel
                    dDescription] descriptions)
Name                : Prompt
IsInstance          : True

$Host.UI.Prompt.OverloadDefinitions will give you the definition(s) of the method. Each definition displays as <Return Type> <Method Name>(<Parameters>).

Declaring static constants in ES6 classes?

class Whatever {
    static get MyConst() { return 10; }
}

let a = Whatever.MyConst;

Seems to work for me.

PostgreSQL: Why psql can't connect to server?

In my case I had this error, /var/run/postgresql/.s.PGSQL.5433 (note, one number up from the file it was looking for, .s.PGSQL.5432) was present. Tried the instructions at the top of this page but nothing worked.

Turns out there was an old directory for PostGreSQL 12 config files in /etc/postgresql/12, which I deleted, which solved the issue.

saving a file (from stream) to disk using c#

Just do it with a simple filestream.

var sr1 = new FileStream(FilePath, FileMode.Create);
                sr1.Write(_UploadFile.File, 0, _UploadFile.File.Length);
                sr1.Close();
                sr1.Dispose();

_UploadFile.File is a byte[], and in the FilePath you get to specify the file extention.

How to detect simple geometric shapes using OpenCV

The answer depends on the presence of other shapes, level of noise if any and invariance you want to provide for (e.g. rotation, scaling, etc). These requirements will define not only the algorithm but also required pre-procesing stages to extract features.

Template matching that was suggested above works well when shapes aren't rotated or scaled and when there are no similar shapes around; in other words, it finds a best translation in the image where template is located:

double minVal, maxVal;
Point minLoc, maxLoc;
Mat image, template, result; // template is your shape
matchTemplate(image, template, result, CV_TM_CCOEFF_NORMED);
minMaxLoc(result, &minVal, &maxVal, &minLoc, &maxLoc); // maxLoc is answer

Geometric hashing is a good method to get invariance in terms of rotation and scaling; this method would require extraction of some contour points.

Generalized Hough transform can take care of invariance, noise and would have minimal pre-processing but it is a bit harder to implement than other methods. OpenCV has such transforms for lines and circles.

In the case when number of shapes is limited calculating moments or counting convex hull vertices may be the easiest solution: openCV structural analysis

how to change color of TextinputLayout's label and edittext underline android

<style name="Widget.Design.TextInputLayout" parent="android:Widget">
    <item name="hintTextAppearance">@style/TextAppearance.Design.Hint</item>
    <item name="errorTextAppearance">@style/TextAppearance.Design.Error</item>
</style>

You can override this style for layout

And also you can change inner EditText-item style too.

Force git stash to overwrite added files

Use git checkout instead of git stash apply:

$ git checkout stash -- .
$ git commit

This will restore all the files in the current directory to their stashed version.


If there are changes to other files in the working directory that should be kept, here is a less heavy-handed alternative:

$ git merge --squash --strategy-option=theirs stash

If there are changes in the index, or the merge will touch files with local changes, git will refuse to merge. Individual files can be checked out from the stash using

$ git checkout stash -- <paths...>

or interactively with

$ git checkout -p stash

How to get the android Path string to a file on Assets folder?

Have a look at the ReadAsset.java from API samples that come with the SDK.

       try {
        InputStream is = getAssets().open("read_asset.txt");

        // We guarantee that the available method returns the total
        // size of the asset...  of course, this does mean that a single
        // asset can't be more than 2 gigs.
        int size = is.available();

        // Read the entire asset into a local byte buffer.
        byte[] buffer = new byte[size];
        is.read(buffer);
        is.close();

        // Convert the buffer into a string.
        String text = new String(buffer);

        // Finally stick the string into the text view.
        TextView tv = (TextView)findViewById(R.id.text);
        tv.setText(text);
    } catch (IOException e) {
        // Should never happen!
        throw new RuntimeException(e);
    }

Select multiple images from android gallery

A lot of these answers have similarities but are all missing the most important part which is in onActivityResult, check if data.getClipData is null before checking data.getData

The code to call the file chooser:

Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*"); //allows any image file type. Change * to specific extension to limit it
//**The following line is the important one!
intent.putExtra(Intent.EXTRA_ALLOW_MULTIPLE, true);
startActivityForResult(Intent.createChooser(intent, "Select Picture"), SELECT_PICTURES); //SELECT_PICTURES is simply a global int used to check the calling intent in onActivityResult

The code to get all of the images selected:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(requestCode == SELECT_PICTURES) {
        if(resultCode == Activity.RESULT_OK) {
            if(data.getClipData() != null) {
                int count = data.getClipData().getItemCount(); //evaluate the count before the for loop --- otherwise, the count is evaluated every loop.
                for(int i = 0; i < count; i++)  
                    Uri imageUri = data.getClipData().getItemAt(i).getUri();
                    //do something with the image (save it to some directory or whatever you need to do with it here) 
                }
            } else if(data.getData() != null) {
                String imagePath = data.getData().getPath();
                //do something with the image (save it to some directory or whatever you need to do with it here)
            }
        }
    }
}

Note that Android's chooser has Photos and Gallery available on some devices. Photos allows multiple images to be selected. Gallery allows just one at a time.

How to iterate over the file in python

Just use for x in f: ..., this gives you line after line, is much shorter and readable (partly because it automatically stops when the file ends) and also saves you the rstrip call because the trailing newline is already stipped.

The error is caused by the exit condition, which can never be true: Even if the file is exhausted, readline will return an empty string, not None. Also note that you could still run into trouble with empty lines, e.g. at the end of the file. Adding if line.strip() == "": continue makes the code ignore blank lines, which is propably a good thing anyway.

What does <? php echo ("<pre>"); ..... echo("</pre>"); ?> mean?

here whatever we write in between the pre tags it will be interpreted same as html pre tag

ex:

<?php
echo '<pre>';
echo '
code here 
will be displayed
as it 
is 


namaste
';
echo "this line get printed in new line";
echo "</pre>";
echo "Now pre ended:";
echo "this line gets joined to above line";
?>

and content b/w 's font also changes.

Is there a way that I can check if a data attribute exists?

You can use jQuery's hasData method.

http://api.jquery.com/jQuery.hasData/

The primary advantage of jQuery.hasData(element) is that it does not create and associate a data object with the element if none currently exists. In contrast, jQuery.data(element) always returns a data object to the caller, creating one if no data object previously existed.

This will only check for the existence of any data objects (or events) on your element, it won't be able to confirm if it specifically has a "timer" object.

Can't push to GitHub because of large file which I already deleted

If the file was added with your most recent commit, and you have not pushed to the remote repository, you can delete the file and amend the commit, Taken from here:

git rm --cached giant_file
    # Stage "giant_file" for removal with "git rm"
    # Leave it on disk with "--cached". if you want to remove it from disk
    # then ignore the "--cached" parameter
git commit --amend -CHEAD
    # Commit the current tree without the giant file using "git commit"
    # Amend the previous commit with your change "--amend" 
    # (simply making a new commit won't work, as you need
    # to remove the file from the unpushed history as well)
    # Use the log/authorship/timestamp of the last commit (the one we are
    # amending) with "-CHEAD", equivalent to --reuse-message=HEAD
git push
    # Push our rewritten, smaller commit with "git push"

You need to install postgresql-server-dev-X.Y for building a server-side extension or libpq-dev for building a client-side application

For me this simple command solved the problem:

sudo apt-get install postgresql postgresql-contrib libpq-dev python-dev

Then I can do:

 pip install psycopg2

Is there a printf converter to print in binary format?

None of the previously posted answers are exactly what I was looking for, so I wrote one. It is super simple to use %B with the printf!

/*
 * File:   main.c
 * Author: Techplex.Engineer
 *
 * Created on February 14, 2012, 9:16 PM
 */

#include <stdio.h>
#include <stdlib.h>
#include <printf.h>
#include <math.h>
#include <string.h>

static int printf_arginfo_M(const struct printf_info *info, size_t n, int *argtypes)
{
    /* "%M" always takes one argument, a pointer to uint8_t[6]. */
    if (n > 0) {
        argtypes[0] = PA_POINTER;
    }
    return 1;
}

static int printf_output_M(FILE *stream, const struct printf_info *info, const void *const *args)
{
    int value = 0;
    int len;

    value = *(int **) (args[0]);

    // Beginning of my code ------------------------------------------------------------
    char buffer [50] = "";  // Is this bad?
    char buffer2 [50] = "";  // Is this bad?
    int bits = info->width;
    if (bits <= 0)
        bits = 8;  // Default to 8 bits

    int mask = pow(2, bits - 1);
    while (mask > 0) {
        sprintf(buffer, "%s", ((value & mask) > 0 ? "1" : "0"));
        strcat(buffer2, buffer);
        mask >>= 1;
    }
    strcat(buffer2, "\n");
    // End of my code --------------------------------------------------------------
    len = fprintf(stream, "%s", buffer2);
    return len;
}

int main(int argc, char** argv)
{
    register_printf_specifier('B', printf_output_M, printf_arginfo_M);

    printf("%4B\n", 65);

    return EXIT_SUCCESS;
}

How to remove "Server name" items from history of SQL Server Management Studio

Here is simpliest way to clear items from this list.

  1. Open the Microsoft SQL Server Management Studio (SSMS) version you want to affect.
  2. Open the Connect to Server dialog (File->Connect Object Explorer, Object Explorer-> Connect-> Database Engine, etc).
  3. Click on the Server Name field drop down list’s down arrow.
  4. Hover over the items you want to remove.
  5. Press the delete (DEL) key on your keyboard.

there we go.

How to completely uninstall Android Studio on Mac?

Execute these commands in the terminal (excluding the lines with hashtags - they're comments):

# Deletes the Android Studio application
# Note that this may be different depending on what you named the application as, or whether you downloaded the preview version
rm -Rf /Applications/Android\ Studio.app
# Delete All Android Studio related preferences
# The asterisk here should target all folders/files beginning with the string before it
rm -Rf ~/Library/Preferences/AndroidStudio*
rm -Rf ~/Library/Preferences/Google/AndroidStudio*
# Deletes the Android Studio's plist file
rm -Rf ~/Library/Preferences/com.google.android.*
# Deletes the Android Emulator's plist file
rm -Rf ~/Library/Preferences/com.android.*
# Deletes mainly plugins (or at least according to what mine (Edric) contains)
rm -Rf ~/Library/Application\ Support/AndroidStudio*
rm -Rf ~/Library/Application\ Support/Google/AndroidStudio*
# Deletes all logs that Android Studio outputs
rm -Rf ~/Library/Logs/AndroidStudio*
rm -Rf ~/Library/Logs/Google/AndroidStudio*
# Deletes Android Studio's caches
rm -Rf ~/Library/Caches/AndroidStudio*
# Deletes older versions of Android Studio
rm -Rf ~/.AndroidStudio*

If you would like to delete all projects:

rm -Rf ~/AndroidStudioProjects

To remove gradle related files (caches & wrapper)

rm -Rf ~/.gradle

Use the below command to delete all Android Virtual Devices(AVDs) and keystores.

Note: This folder is used by other Android IDEs as well, so if you still using other IDE you may not want to delete this folder)

rm -Rf ~/.android

To delete Android SDK tools

rm -Rf ~/Library/Android*

Emulator Console Auth Token

rm -Rf ~/.emulator_console_auth_token

Thanks to those who commented/improved on this answer!


Notes

  1. The flags for rm are case-sensitive1 (as with most other commands), which means that the f flag must be in lower case. However, the r flag can also be capitalised.
  2. The flags for rm can be either combined together or separated. They don't have to be combined.

What the flags indicate

  1. The r flag indicates that the rm command should-

    attempt to remove the file hierarchy rooted in each file argument. - DESCRIPTION section on the manpage for rm (See man rm for more info)

  2. The f flag indicates that the rm command should-

    attempt to remove the files without prompting for confirmation, regardless of the file's permissions. - DESCRIPTION section on the manpage for rm (See man rm for more info)

Android transparent status bar and actionbar

It supports after KITKAT. Just add following code inside onCreate method of your Activity. No need any modifications to Manifest file.

 if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
                Window w = getWindow(); // in Activity's onCreate() for instance
                w.setFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS, WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
            }

Find out the history of SQL queries

You can use this sql statement to get the history for any date:

SELECT * FROM V$SQL V where  to_date(v.FIRST_LOAD_TIME,'YYYY-MM-DD hh24:mi:ss') > sysdate - 60

How does Java import work?

Import in Java does not work at all, as it is evaluated at compile time only. (Treat it as shortcuts so you do not have to write fully qualified class names). At runtime there is no import at all, just FQCNs.

At runtime it is necessary that all classes you have referenced can be found by classloaders. (classloader infrastructure is sometimes dark magic and highly dependent on environment.) In case of an applet you will have to rig up your HTML tag properly and also provide necessary JAR archives on your server.

PS: Matching at runtime is done via qualified class names - class found under this name is not necessarily the same or compatible with class you have compiled against.

How do I return clean JSON from a WCF Service?

When you are using GET Method the contract must be this.

[WebGet(UriTemplate = "/", BodyStyle = WebMessageBodyStyle.Bare, ResponseFormat = WebMessageFormat.Json)]
List<User> Get();

with this we have a json without the boot parameter

Aldo Flores @alduar http://alduar.blogspot.com

Compare two dates with JavaScript

Try using this code

var f =date1.split("/");

var t =date2.split("/");

var x =parseInt(f[2]+f[1]+f[0]);

var y =parseInt(t[2]+t[1]+t[0]);

if(x > y){
    alert("date1 is after date2");
}

else if(x < y){
    alert("date1 is before date2");
}

else{
    alert("both date are same");
}

Get to UIViewController from UIView?

Using the example posted by Brock, I modified it so that it is a category of UIView instead UIViewController and made it recursive so that any subview can (hopefully) find the parent UIViewController.

@interface UIView (FindUIViewController)
- (UIViewController *) firstAvailableUIViewController;
- (id) traverseResponderChainForUIViewController;
@end

@implementation UIView (FindUIViewController)
- (UIViewController *) firstAvailableUIViewController {
    // convenience function for casting and to "mask" the recursive function
    return (UIViewController *)[self traverseResponderChainForUIViewController];
}

- (id) traverseResponderChainForUIViewController {
    id nextResponder = [self nextResponder];
    if ([nextResponder isKindOfClass:[UIViewController class]]) {
        return nextResponder;
    } else if ([nextResponder isKindOfClass:[UIView class]]) {
        return [nextResponder traverseResponderChainForUIViewController];
    } else {
        return nil;
    }
}
@end

To use this code, add it into an new class file (I named mine "UIKitCategories") and remove the class data... copy the @interface into the header, and the @implementation into the .m file. Then in your project, #import "UIKitCategories.h" and use within the UIView code:

// from a UIView subclass... returns nil if UIViewController not available
UIViewController * myController = [self firstAvailableUIViewController];

Why a function checking if a string is empty always returns true?

PHP evaluates an empty string to false, so you can simply use:

if (trim($userinput['phoneNumber'])) {
  // validate the phone number
} else {
  echo "Phone number not entered<br/>";
}

iPhone app could not be installed at this time

I have had the same issue after fiddling around with certificates (argh).

The problem became apparent as I followed the comment of @Duraiamuthan.H, I installed on a device. The device reported 0xe8008016 (Entitlements) see SO here

The initial reason was, that the testflight target used the App store distribution certificate, not the Team certificate. I fixed that and the application was installing on the device over Xcode and then it also worked with testflight.

Notification bar icon turns white in Android 5 Lollipop

This is the code Android uses to display notification icons:

// android_frameworks_base/packages/SystemUI/src/com/android/systemui/
//   statusbar/BaseStatusBar.java

if (entry.targetSdk >= Build.VERSION_CODES.LOLLIPOP) {
    entry.icon.setColorFilter(mContext.getResources().getColor(android.R.color.white));
} else {
    entry.icon.setColorFilter(null);
}

So you need to set the target sdk version to something <21 and the icons will stay colored. This is an ugly workaround but it does what it is expected to do. Anyway, I really suggest following Google's Design Guidelines: "Notification icons must be entirely white."

Here is how you can implement it:

If you are using Gradle/Android Studio to build your apps, use build.gradle:

defaultConfig {
    targetSdkVersion 20
}

Otherwise (Eclipse etc) use AndroidManifest.xml:

<uses-sdk android:minSdkVersion="..." android:targetSdkVersion="20" />

sending mail from Batch file

Blat:

blat -to [email protected] -server smtp.example.com -f [email protected] -subject "subject" -body "body"

Windows equivalent of linux cksum command

To avoid annoying non-checksum lines : CertUtil -v -hashfile "your_file" SHA1 | FIND /V "CertUtil" This will display only line(s) NOT contaning CertUtil

Get querystring from URL using jQuery

To retrieve the entire querystring from the current URL, beginning with the ? character, you can use

location.search

https://developer.mozilla.org/en-US/docs/DOM/window.location

Example:

// URL = https://example.com?a=a%20a&b=b123
console.log(location.search); // Prints "?a=a%20a&b=b123" 

In regards to retrieving specific querystring parameters, while although classes like URLSearchParams and URL exist, they aren't supported by Internet Explorer at this time, and should probably be avoided. Instead, you can try something like this:

/**
 * Accepts either a URL or querystring and returns an object associating 
 * each querystring parameter to its value. 
 *
 * Returns an empty object if no querystring parameters found.
 */
function getUrlParams(urlOrQueryString) {
  if ((i = urlOrQueryString.indexOf('?')) >= 0) {
    const queryString = urlOrQueryString.substring(i+1);
    if (queryString) {
      return _mapUrlParams(queryString);
    } 
  }

  return {};
}

/**
 * Helper function for `getUrlParams()`
 * Builds the querystring parameter to value object map.
 *
 * @param queryString {string} - The full querystring, without the leading '?'.
 */
function _mapUrlParams(queryString) {
  return queryString    
    .split('&') 
    .map(function(keyValueString) { return keyValueString.split('=') })
    .reduce(function(urlParams, [key, value]) {
      if (Number.isInteger(parseInt(value)) && parseInt(value) == value) {
        urlParams[key] = parseInt(value);
      } else {
        urlParams[key] = decodeURI(value);
      }
      return urlParams;
    }, {});
}

You can use the above like so:

// Using location.search
let urlParams = getUrlParams(location.search); // Assume location.search = "?a=1&b=2b2"
console.log(urlParams); // Prints { "a": 1, "b": "2b2" }

// Using a URL string
const url = 'https://example.com?a=A%20A&b=1';
urlParams = getUrlParams(url);
console.log(urlParams); // Prints { "a": "A A", "b": 1 }

// To check if a parameter exists, simply do:
if (urlParams.hasOwnProperty('parameterName') { 
  console.log(urlParams.parameterName);
}

How to move the layout up when the soft keyboard is shown android

Make use of Relative layout it will adjust the view so that you can see that view while typing the text

How to display and hide a div with CSS?

you can use any of the following five ways to hide element, depends upon your requirements.

Opacity

.hide {
  opacity: 0;
}

Visibility

.hide {
   visibility: hidden;
}

Display

.hide {
   display: none;
}

Position

.hide {
   position: absolute;
   top: -9999px;
   left: -9999px;
}

clip-path

.hide {
  clip-path: polygon(0px 0px,0px 0px,0px 0px,0px 0px);
}

To show use any of the following: opacity: 1; visibility: visible; display: block;

Source : https://www.sitepoint.com/five-ways-to-hide-elements-in-css/

how to check the jdk version used to compile a .class file

You can try jclasslib:

https://github.com/ingokegel/jclasslib

It's nice that it can associate itself with *.class extension.

How to get the day name from a selected date?

What about if we use String.Format here

_x000D_
_x000D_
DateTime today = DateTime.Today;_x000D_
String.Format("{0:dd-MM}, {1:dddd}", today, today) //In dd-MM format_x000D_
String.Format("{0:MM-dd}, {1:dddd}", today, today) //In MM-dd format
_x000D_
_x000D_
_x000D_

How do I concatenate strings with variables in PowerShell?

This will get all dll files and filter ones that match a regex of your directory structure.

Get-ChildItem C:\code -Recurse -filter "*.dll" | where { $_.directory -match 'C:\\code\\myproj.\\bin\\debug'}

If you just want the path, not the object you can add | select fullname to the end like this:

Get-ChildItem C:\code -Recurse -filter "*.dll" | where { $_.directory -match 'C:\\code\\myproj.\\bin\\debug'} | select fullname

Could someone explain this for me - for (int i = 0; i < 8; i++)

for (int i = 0; i < 8; i++)

It's a for loop, which will execute the next statement a number of times, depending on the conditions inside the parenthesis.

for (int i = 0; i < 8; i++)

Start by setting i = 0

for (int i = 0; i < 8; i++)

Continue looping while i < 8.

for (int i = 0; i < 8; i++)

Every time you've been around the loop, increase i by 1.

For example;

for (int i = 0; i < 8; i++)
    do(i);

will call do(0), do(1), ... do(7) in order, and stop when i reaches 8 (ie i < 8 is false)

"call to undefined function" error when calling class method

Mates,

I stumbled upon this error today while testing a simple script. I am not using "class" function though so it take it with grain of salt. I was calling function before its definition & declaration ...something like this

      try{
             foo();
         }
       catch (exception $e)
           {
            echo "$e->getMessage()";
           }

       function foo(){
                       echo "blah blah blah";
                     }

so php was throwing me error "call to undefined function ".

This kinda seem classic programming error but may help someone in need of clue.

How do you configure HttpOnly cookies in tomcat / java webapps?

In Tomcat6, You can conditionally enable from your HTTP Listener Class:

public void contextInitialized(ServletContextEvent event) {                 
   if (Boolean.getBoolean("HTTP_ONLY_SESSION")) HttpOnlyConfig.enable(event);
}

Using this class

import java.lang.reflect.Field;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import org.apache.catalina.core.StandardContext;
public class HttpOnlyConfig
{
    public static void enable(ServletContextEvent event)
    {
        ServletContext servletContext = event.getServletContext();
        Field f;
        try
        { // WARNING TOMCAT6 SPECIFIC!!
            f = servletContext.getClass().getDeclaredField("context");
            f.setAccessible(true);
            org.apache.catalina.core.ApplicationContext ac = (org.apache.catalina.core.ApplicationContext) f.get(servletContext);
            f = ac.getClass().getDeclaredField("context");
            f.setAccessible(true);
            org.apache.catalina.core.StandardContext sc = (StandardContext) f.get(ac);
            sc.setUseHttpOnly(true);
        }
        catch (Exception e)
        {
            System.err.print("HttpOnlyConfig cant enable");
            e.printStackTrace();
        }
    }
}

Fastest way to convert string to integer in PHP

I personally feel casting is the prettiest.

$iSomeVar = (int) $sSomeOtherVar;

Should a string like 'Hello' be sent, it will be cast to integer 0. For a string such as '22 years old', it will be cast to integer 22. Anything it can't parse to a number becomes 0.

If you really do NEED the speed, I guess the other suggestions here are correct in assuming that coercion is the fastest.

How do you create optional arguments in php?

The default value of the argument must be a constant expression. It can't be a variable or a function call.

If you need this functionality however:

function foo($foo, $bar = false)
{
    if(!$bar)
    {
        $bar = $foo;
    }
}

Assuming $bar isn't expected to be a boolean of course.

Angular 2: Get Values of Multiple Checked Checkboxes

I just faced this issue, and decided to make everything work with as less variables as i can, to keep workspace clean. Here is example of my code

<input type="checkbox" (change)="changeModel($event, modelArr, option.value)" [checked]="modelArr.includes(option.value)" />

Method, which called on change is pushing value in model, or removing it.

public changeModel(ev, list, val) {
  if (ev.target.checked) {
    list.push(val);
  } else {
    let i = list.indexOf(val);
    list.splice(i, 1);
  }
}

Javascript one line If...else...else if statement

Sure, you can do nested ternary operators but they are hard to read.

var variable = (condition) ? (true block) : ((condition2) ? (true block2) : (else block2))

How to change DatePicker dialog color for Android 5.0

Just to mention, you can also use the default a theme like android.R.style.Theme_DeviceDefault_Light_Dialog instead.

new DatePickerDialog(MainActivity.this, android.R.style.Theme_DeviceDefault_Light_Dialog, new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
    //DO SOMETHING
    }
}, 2015, 02, 26).show();

How to pass an object from one activity to another on Android

Hello all I see a lot of good options but I was wondering why Binding hasn't been used?

Passing a reference to an object just seems more efficient to me than serializing and desterilizing objects, but I have not done a deep dive to see if that is what is going on behind the scenes.

Creating a Binder is simple enough...

public class MyBinder extends Binder {

    private Object myObject;

    public MyBinder(Object object) {
        myObject = object;
    }

    public Object getObject() {
        return myObject;
    }

}

And creating the parcelable to use it isn't that bad ether.

public class MyParcelable implements Parcelable {

    private Object myObject;

    public MyParcelable() {
    }

    public MyParcelable(Parcel parcel) {
        myObject = ((MyBinder)parcel.readStrongBinder()).getObject();
    }

    public void setObject(Object object) {
        myObject = object;
    }

    public Object getObject() {
        return myObject;
    }

    public void writeToParcel(Parcel parcel, int flags) {
        parcel.writeStrongBinder(new MyBinder(myObject));
    }

    public int describeContents() {
        return myObject == null ? 0 : 1;
    }

    public static final Parcelable.Creator<MyParcelable> CREATOR = new Parcelable.Creator<MyParcelable>() {

        public MyParcelable createFromParcel(Parcel parcel) {
            return new MyParcelable(parcel);
        }

        public MyParcelable[] newArray(int length) {
            return new MyParcelable[length];
        }

    };
}

This logic is really cool because you are actually passing a reference from activity to activity.

I would advise checking for nulls and if the instanceof Binder is MyBinder!

and to implement this you just...

Send it off

Object myObject = "some object";
MyParcelable myParcelable = new MyParcelable();
myParcelable.setObject(myObject);

intent.putExtra("MyParcelable", myParcelable);

Get it back

myParcelable = (MyParcelable) getIntent().getExtras().getParcelable("MyParcelable");
myObject = myParcelable.getObject();

Heck someone could get all crazy and make this sucker a true generic.

Download single files from GitHub

Go to the script and click "Raw"

Then copy the link and download it with the aria2c link.

Eg: aria2c https://raw.githubusercontent.com/kodamail/gscript/master/color.gsf

Trick: the file I wanted to download is, https://github.com/kodamail/gscript*/blob*/master/color.gsf

just modify the link into https://raw.githubusercontent.com/kodamail/gscript/master/color.gsf

Remove the italic texts and add bold texts in the same format, it will give you the right link.

which can be used with aria2c,wget or with curl, I used aria2c here.

How to get the max of two values in MySQL?

Use GREATEST()

E.g.:

SELECT GREATEST(2,1);

Note: Whenever if any single value contains null at that time this function always returns null (Thanks to user @sanghavi7)

Assigning variables with dynamic names in Java

You don't. The closest thing you can do is working with Maps to simulate it, or defining your own Objects to deal with.

syntaxerror: "unexpected character after line continuation character in python" math

The division operator is / rather than \.

Also, the backslash has a special meaning inside a Python string. Either escape it with another backslash:

"\\ 1.5 = "`

or use a raw string

r" \ 1.5 = "

How to remove empty cells in UITableView?

or you can call tableView method to set the footer height in 1 point, and it will add an last line, but you can hide it too, by setting footer background color.

code:

func tableView(tableView: UITableView,heightForFooterInSection section: Int) -> CGFloat {
     return 1
}

looks like last line

Import pfx file into particular certificate store from command line

Anchoring my findings here for future readers.

Import certificate to Trusted Root Certification Authorities on Local Machine:

CERTUTIL -addstore -enterprise -f -v root "somCertificat.cer"

Import pfx to Personal on local machine

CERTUTIL -f -p somePassword -importpfx "somePfx.pfx"

Import pfx to Trusted People on local machine - Link to importpfx.exe

importpfx.exe -f "somePfx.pfx" -p "somePassword" -t MACHINE -s "TRUSTEDPEOPLE"

Import certificate to Trusted People on local machine

Certutil -addstore -f "TRUSTEDPEOPLE" "someCertificate.cer"

What is the pythonic way to unpack tuples?

Generally, you can use the func(*tuple) syntax. You can even pass a part of the tuple, which seems like what you're trying to do here:

t = (2010, 10, 2, 11, 4, 0, 2, 41, 0)
dt = datetime.datetime(*t[0:7])

This is called unpacking a tuple, and can be used for other iterables (such as lists) too. Here's another example (from the Python tutorial):

>>> range(3, 6)             # normal call with separate arguments
[3, 4, 5]
>>> args = [3, 6]
>>> range(*args)            # call with arguments unpacked from a list
[3, 4, 5]

Purpose of #!/usr/bin/python3 shebang

This line helps find the program executable that will run the script. This shebang notation is fairly standard across most scripting languages (at least as used on grown-up operating systems).

An important aspect of this line is specifying which interpreter will be used. On many development-centered Linux distributions, for example, it is normal to have several versions of python installed at the same time.

Python 2.x and Python 3 are not 100% compatible, so this difference can be very important. So #! /usr/bin/python and #! /usr/bin/python3 are not the same (and neither are quite the same as #! /usr/bin/env python3 as noted elsewhere on this page.

How to read an excel file in C# without using Microsoft.Office.Interop.Excel libraries

var fileName = @"C:\ExcelFile.xlsx";
var connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=\"Excel 12.0;IMEX=1;HDR=NO;TypeGuessRows=0;ImportMixedTypes=Text\""; ;
using (var conn = new OleDbConnection(connectionString))
{
    conn.Open();

    var sheets = conn.GetOleDbSchemaTable(System.Data.OleDb.OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" });
    using (var cmd = conn.CreateCommand())
    {
        cmd.CommandText = "SELECT * FROM [" + sheets.Rows[0]["TABLE_NAME"].ToString() + "] ";

        var adapter = new OleDbDataAdapter(cmd);
        var ds = new DataSet();
        adapter.Fill(ds);
    }
}

Activity transition in Android

create res>anim>fadein.xml

<?xml version="1.0" encoding="utf-8"?>
    <alpha xmlns:android="http://schemas.android.com/apk/res/android"
       android:interpolator="@android:anim/accelerate_interpolator"
       android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="500" />

create res>anim>fadeout.xml

<?xml version="1.0" encoding="utf-8"?>
    <alpha xmlns:android="http://schemas.android.com/apk/res/android"
       android:interpolator="@android:anim/accelerate_interpolator"
       android:fromAlpha="1.0" android:toAlpha="0.0" android:duration="500" />

In res>values>styles.xml

<style name="Fade">
        <item name="android:windowEnterAnimation">@anim/fadein</item>
        <item name="android:windowExitAnimation">@anim/fadeout</item>
    </style>

In activities onCreate()

getWindow().getAttributes().windowAnimations = R.style.Fade;

How to provide a file download from a JSF backing bean?

Introduction

You can get everything through ExternalContext. In JSF 1.x, you can get the raw HttpServletResponse object by ExternalContext#getResponse(). In JSF 2.x, you can use the bunch of new delegate methods like ExternalContext#getResponseOutputStream() without the need to grab the HttpServletResponse from under the JSF hoods.

On the response, you should set the Content-Type header so that the client knows which application to associate with the provided file. And, you should set the Content-Length header so that the client can calculate the download progress, otherwise it will be unknown. And, you should set the Content-Disposition header to attachment if you want a Save As dialog, otherwise the client will attempt to display it inline. Finally just write the file content to the response output stream.

Most important part is to call FacesContext#responseComplete() to inform JSF that it should not perform navigation and rendering after you've written the file to the response, otherwise the end of the response will be polluted with the HTML content of the page, or in older JSF versions, you will get an IllegalStateException with a message like getoutputstream() has already been called for this response when the JSF implementation calls getWriter() to render HTML.

Turn off ajax / don't use remote command!

You only need to make sure that the action method is not called by an ajax request, but that it is called by a normal request as you fire with <h:commandLink> and <h:commandButton>. Ajax requests and remote commands are handled by JavaScript which in turn has, due to security reasons, no facilities to force a Save As dialogue with the content of the ajax response.

In case you're using e.g. PrimeFaces <p:commandXxx>, then you need to make sure that you explicitly turn off ajax via ajax="false" attribute. In case you're using ICEfaces, then you need to nest a <f:ajax disabled="true" /> in the command component.

Generic JSF 2.x example

public void download() throws IOException {
    FacesContext fc = FacesContext.getCurrentInstance();
    ExternalContext ec = fc.getExternalContext();

    ec.responseReset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
    ec.setResponseContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ExternalContext#getMimeType() for auto-detection based on filename.
    ec.setResponseContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
    ec.setResponseHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.

    OutputStream output = ec.getResponseOutputStream();
    // Now you can write the InputStream of the file to the above OutputStream the usual way.
    // ...

    fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}

Generic JSF 1.x example

public void download() throws IOException {
    FacesContext fc = FacesContext.getCurrentInstance();
    HttpServletResponse response = (HttpServletResponse) fc.getExternalContext().getResponse();

    response.reset(); // Some JSF component library or some Filter might have set some headers in the buffer beforehand. We want to get rid of them, else it may collide.
    response.setContentType(contentType); // Check http://www.iana.org/assignments/media-types for all types. Use if necessary ServletContext#getMimeType() for auto-detection based on filename.
    response.setContentLength(contentLength); // Set it with the file size. This header is optional. It will work if it's omitted, but the download progress will be unknown.
    response.setHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\""); // The Save As popup magic is done here. You can give it any file name you want, this only won't work in MSIE, it will use current request URL as file name instead.

    OutputStream output = response.getOutputStream();
    // Now you can write the InputStream of the file to the above OutputStream the usual way.
    // ...

    fc.responseComplete(); // Important! Otherwise JSF will attempt to render the response which obviously will fail since it's already written with a file and closed.
}

Common static file example

In case you need to stream a static file from the local disk file system, substitute the code as below:

File file = new File("/path/to/file.ext");
String fileName = file.getName();
String contentType = ec.getMimeType(fileName); // JSF 1.x: ((ServletContext) ec.getContext()).getMimeType(fileName);
int contentLength = (int) file.length();

// ...

Files.copy(file.toPath(), output);

Common dynamic file example

In case you need to stream a dynamically generated file, such as PDF or XLS, then simply provide output there where the API being used expects an OutputStream.

E.g. iText PDF:

String fileName = "dynamic.pdf";
String contentType = "application/pdf";

// ...

Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, output);
document.open();
// Build PDF content here.
document.close();

E.g. Apache POI HSSF:

String fileName = "dynamic.xls";
String contentType = "application/vnd.ms-excel";

// ...

HSSFWorkbook workbook = new HSSFWorkbook();
// Build XLS content here.
workbook.write(output);
workbook.close();

Note that you cannot set the content length here. So you need to remove the line to set response content length. This is technically no problem, the only disadvantage is that the enduser will be presented an unknown download progress. In case this is important, then you really need to write to a local (temporary) file first and then provide it as shown in previous chapter.

Utility method

If you're using JSF utility library OmniFaces, then you can use one of the three convenient Faces#sendFile() methods taking either a File, or an InputStream, or a byte[], and specifying whether the file should be downloaded as an attachment (true) or inline (false).

public void download() throws IOException {
    Faces.sendFile(file, true);
}

Yes, this code is complete as-is. You don't need to invoke responseComplete() and so on yourself. This method also properly deals with IE-specific headers and UTF-8 filenames. You can find source code here.

css overflow - only 1 line of text

If you want to indicate that there's still more content available in that div, you may probably want to show the "ellipsis":

text-overflow: ellipsis;

This should be in addition to white-space: nowrap; suggested by Septnuits.

Also, make sure you checkout this thread to handle this in Firefox.

enable/disable zoom in Android WebView

The solution you posted seems to work in stopping the zoom controls from appearing when the user drags, however there are situations where a user will pinch zoom and the zoom controls will appear. I've noticed that there are 2 ways that the webview will accept pinch zooming, and only one of them causes the zoom controls to appear despite your code:

User Pinch Zooms and controls appear:

ACTION_DOWN
getSettings().setBuiltInZoomControls(false); getSettings().setSupportZoom(false);
ACTION_POINTER_2_DOWN
getSettings().setBuiltInZoomControls(true); getSettings().setSupportZoom(true);
ACTION_MOVE (Repeat several times, as the user moves their fingers)
ACTION_POINTER_2_UP
ACTION_UP

User Pinch Zoom and Controls don't appear:

ACTION_DOWN
getSettings().setBuiltInZoomControls(false); getSettings().setSupportZoom(false);
ACTION_POINTER_2_DOWN
getSettings().setBuiltInZoomControls(true); getSettings().setSupportZoom(true);
ACTION_MOVE (Repeat several times, as the user moves their fingers)
ACTION_POINTER_1_UP
ACTION_POINTER_UP
ACTION_UP

Can you shed more light on your solution?

postgresql return 0 if returned value is null

(this answer was added to provide shorter and more generic examples to the question - without including all the case-specific details in the original question).


There are two distinct "problems" here, the first is if a table or subquery has no rows, the second is if there are NULL values in the query.

For all versions I've tested, postgres and mysql will ignore all NULL values when averaging, and it will return NULL if there is nothing to average over. This generally makes sense, as NULL is to be considered "unknown". If you want to override this you can use coalesce (as suggested by Luc M).

$ create table foo (bar int);
CREATE TABLE

$ select avg(bar) from foo;
 avg 
-----

(1 row)

$ select coalesce(avg(bar), 0) from foo;
 coalesce 
----------
        0
(1 row)

$ insert into foo values (3);
INSERT 0 1
$ insert into foo values (9);
INSERT 0 1
$ insert into foo values (NULL);
INSERT 0 1
$ select coalesce(avg(bar), 0) from foo;
      coalesce      
--------------------
 6.0000000000000000
(1 row)

of course, "from foo" can be replaced by "from (... any complicated logic here ...) as foo"

Now, should the NULL row in the table be counted as 0? Then coalesce has to be used inside the avg call.

$ select coalesce(avg(coalesce(bar, 0)), 0) from foo;
      coalesce      
--------------------
 4.0000000000000000
(1 row)

Cannot open include file with Visual Studio

I had this same issue going from e.g gcc to visual studio for C programming. Make sure your include file is actually in the directory -- not just shown in the VS project tree. For me in other languages copying into a folder in the project tree would indeed move the file in. With Visual Studio 2010, pasting into "Header Files" was NOT putting the .h file there.

Please check your actual directory for the presence of the include file. Putting it into the "header files" folder in project/solution explorer was not enough.

How to set radio button selected value using jquery

This is the only syntax that worked for me

$('input[name="assReq"][value="' + obj["AssociationReq"] + '"]').prop('checked', 'checked');

Python: "TypeError: __str__ returned non-string" but still prints to output?

Just Try this:

def __str__(self):
    return f'Memo={self.memo}, Tag={self.tags}'

In Ruby on Rails, what's the difference between DateTime, Timestamp, Time and Date?

Here is an awesome and precise explanation I found.

TIMESTAMP used to track changes of records, and update every time when the record is changed. DATETIME used to store specific and static value which is not affected by any changes in records.

TIMESTAMP also affected by different TIME ZONE related setting. DATETIME is constant.

TIMESTAMP internally converted a current time zone to UTC for storage, and during retrieval convert the back to the current time zone. DATETIME can not do this.

TIMESTAMP is 4 bytes and DATETIME is 8 bytes.

TIMESTAMP supported range: ‘1970-01-01 00:00:01' UTC to ‘2038-01-19 03:14:07' UTC DATETIME supported range: ‘1000-01-01 00:00:00' to ‘9999-12-31 23:59:59'

source: https://www.dbrnd.com/2015/09/difference-between-datetime-and-timestamp-in-mysql/#:~:text=DATETIME%20vs%20TIMESTAMP%3A,DATETIME%20is%20constant.

Also...

table with different column "date" types and corresponding rails migration types depending on the database

How to convert NUM to INT in R?

You can use convert from hablar to change a column of the data frame quickly.

library(tidyverse)
library(hablar)

x <- tibble(var = c(1.34, 4.45, 6.98))

x %>% 
  convert(int(var))

gives you:

# A tibble: 3 x 1
    var
  <int>
1     1
2     4
3     6

How to add a 'or' condition in #ifdef

I am really OCD about maintaining strict column limits, and not a fan of "\" line continuation because you can't put a comment after it, so here is my method.

//|¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯¯|//
#ifdef  CONDITION_01             //|       |//
#define             TEMP_MACRO   //|       |//
#endif                           //|       |//
#ifdef  CONDITION_02             //|       |//
#define             TEMP_MACRO   //|       |//
#endif                           //|       |//
#ifdef  CONDITION_03             //|       |//
#define             TEMP_MACRO   //|       |//
#endif                           //|       |//
#ifdef              TEMP_MACRO   //|       |//
//|-  --  --  --  --  --  --  --  --  --  -|//

printf("[IF_CONDITION:(1|2|3)]\n");

//|-  --  --  --  --  --  --  --  --  --  -|//
#endif                           //|       |//
#undef              TEMP_MACRO   //|       |//
//|________________________________________|//

Apache Server (xampp) doesn't run on Windows 10 (Port 80)

First, open regedit run as administrator see image open HKEY_LOCAL_MACHINE\SYSTEM\CurrentCurrentControlSet\Services\HTTP open Start, change value from 3 to 4 see image then restart your computer

Oracle database: How to read a BLOB?

If you use the Oracle native data provider rather than the Microsoft driver then you can get at all field types

Dim cn As New Oracle.DataAccess.Client.OracleConnection
Dim cm As New Oracle.DataAccess.Client.OracleCommand
Dim dr As Oracle.DataAccess.Client.OracleDataReader

The connection string does not require a Provider value so you would use something like:

"Data Source=myOracle;UserID=Me;Password=secret"

Open the connection:

cn.ConnectionString = "Data Source=myOracle;UserID=Me;Password=secret"
cn.Open()

Attach the command and set the Sql statement

cm.Connection = cn
cm.CommandText = strCommand

Set the Fetch size. I use 4000 because it's as big as a varchar can be

cm.InitialLONGFetchSize = 4000

Start the reader and loop through the records/columns

dr = cm.ExecuteReader

Do while dr.read()
    strMyLongString = dr(i)
Loop

You can be more specific with the read, eg dr.GetOracleString(i) dr.GetOracleClob(i) etc. if you first identify the data type in the column. If you're reading a LONG datatype then the simple dr(i) or dr.GetOracleString(i) works fine. The key is to ensure that the InitialLONGFetchSize is big enough for the datatype. Note also that the native driver does not support CommandBehavior.SequentialAccess for the data reader but you don't need it and also, the LONG field does not even have to be the last field in the select statement.

How to get a MemoryStream from a Stream in .NET?

How do I copy the contents of one stream to another?

see that. accept a stream and copy to memory. you should not use .Length for just Stream because it is not necessarily implemented in every concrete Stream.

AngularJS: Insert HTML from a string

Have a look at the example in this link :

http://docs.angularjs.org/api/ngSanitize.$sanitize

Basically, angular has a directive to insert html into pages. In your case you can insert the html using the ng-bind-html directive like so :

If you already have done all this :

// My magic HTML string function.
function htmlString (str) {
    return "<h1>" + str + "</h1>";
}

function Ctrl ($scope) {
  var str = "HELLO!";
  $scope.htmlString = htmlString(str);
}
Ctrl.$inject = ["$scope"];

Then in your html within the scope of that controller, you could

<div ng-bind-html="htmlString"></div>

How to query the permissions on an Oracle directory?

This should give you the roles, users and permissions granted on a directory:

SELECT * 
  FROM all_tab_privs 
 WHERE table_name = 'your_directory';  --> needs to be upper case

And yes, it IS in the all_TAB_privs view ;-) A better name for that view would be something like "ALL_OBJECT_PRIVS", since it also includes PL/SQL objects and their execute permissions as well.

Loop through files in a folder in matlab

At first, you must specify your path, the path that your *.csv files are in there

path = 'f:\project\dataset'

You can change it based on your system.

then,

use dir function :

files = dir (strcat(path,'\*.csv'))

L = length (files);

for i=1:L
   image{i}=csvread(strcat(path,'\',file(i).name));   
   % process the image in here
end

pwd also can be used.

android.content.res.Resources$NotFoundException: String resource ID Fatal Exception in Main

Other possible solution:

tv.setText(Integer.toString(a1));  // where a1 - int value

How to make a char string from a C macro's value?

@Jonathan Leffler: Thank you. Your solution works.

A complete working example:

/** compile-time dispatch 

   $ gcc -Wall -DTEST_FUN=another_func macro_sub.c -o macro_sub && ./macro_sub
*/
#include <stdio.h>

#define QUOTE(name) #name
#define STR(macro) QUOTE(macro)

#ifndef TEST_FUN
#  define TEST_FUN some_func
#endif

#define TEST_FUN_NAME STR(TEST_FUN)

void some_func(void)
{
  printf("some_func() called\n");
}

void another_func(void)
{
  printf("do something else\n");
}

int main(void)
{
  TEST_FUN();
  printf("TEST_FUN_NAME=%s\n", TEST_FUN_NAME);
  return 0;
}

Example:

$ gcc -Wall -DTEST_FUN=another_func macro_sub.c -o macro_sub && ./macro_sub
do something else
TEST_FUN_NAME=another_func

Batch command to move files to a new directory

Something like this might help:

SET Today=%Date:~10,4%%Date:~4,2%%Date:~7,2%
mkdir C:\Test\Backup-%Today%
move C:\Test\Log\*.* C:\Test\Backup-%Today%\
SET Today=

The important part is the first line. It takes the output of the internal DATE value and parses it into an environmental variable named Today, in the format CCYYMMDD, as in '20110407`.

The %Date:~10,4% says to extract a *substring of the Date environmental variable 'Thu 04/07/2011' (built in - type echo %Date% at a command prompt) starting at position 10 for 4 characters (2011). It then concatenates another substring of Date: starting at position 4 for 2 chars (04), and then concats two additional characters starting at position 7 (07).

*The substring value starting points are 0-based.

You may need to adjust these values depending on the date format in your locale, but this should give you a starting point.

Placeholder in IE9

Using mordernizr to detect browsers that are not supporting Placeholder, I created this short code to fix them.

//If placeholder is not supported
if (!Modernizr.input.placeholder){ 

    //Loops on inputs and place the placeholder attribute
    //in the textbox.
    $("input[type=text]").each( function() { 
       $(this).val($(this).attr('placeholder')); 
    })
}

Using LINQ to group a list of objects

The desired result can be obtained using IGrouping, which represents a collection of objects that have a common key in this case a GroupID

 var newCustomerList = CustomerList.GroupBy(u => u.GroupID)
                                                  .Select(group => new { GroupID = group.Key, Customers = group.ToList() })
                                                  .ToList();

Apache Tomcat :java.net.ConnectException: Connection refused

I've seen a lot of inadequate answers while trying to figure this one out. General response has been "you are trying to stop something that hasn't started" or "some other program is running on the port you need".

The problem for me turned out to be my firewall. I hadn't even considered this, but port 8005 (the port used for shutdown, thanks mindas), was blocked. I changed it, and now, no more error. Good luck.

In PHP, how can I add an object element to an array?

Something like:

class TestClass {
private $var1;
private $var2;

private function TestClass($var1, $var2){
    $this->var1 = $var1;
    $this->var2 = $var2;
}

public static function create($var1, $var2){
    if (is_numeric($var1)){
        return new TestClass($var1, $var2);
    }
    else return NULL;
}
}

$myArray = array();
$myArray[] = TestClass::create(15, "asdf");
$myArray[] = TestClass::create(20, "asdfa");
$myArray[] = TestClass::create("a", "abcd");

print_r($myArray);

$myArray = array_filter($myArray, function($e){ return !is_null($e);});

print_r($myArray);

I think that there are situations where this constructions are preferable to arrays. You can move all the checking logic to the class.

Here, before the call to array_filter $myArray has 3 elements. Two correct objects and a NULL. After the call, only the 2 correct elements persist.

I want to delete all bin and obj folders to force all projects to rebuild everything

We have a large .SLN files with many project files. I started the policy of having a "ViewLocal" directory where all non-sourcecontrolled files are located. Inside that directory is an 'Inter' and an 'Out' directory. For the intermediate files, and the output files, respectively.

This obviously makes it easy to just go to your 'viewlocal' directory and do a simple delete, to get rid of everything.

Before you spent time figuring out a way to work around this with scripts, you might think about setting up something similar.

I won't lie though, maintaining such a setup in a large organization has proved....interesting. Especially when you use technologies such as QT that like to process files and create non-sourcecontrolled source files. But that is a whole OTHER story!

Git: Create a branch from unstaged/uncommitted changes on master

If you are using the GitHub Windows client (as I am) and you are in the situation of having made uncommitted changes that you wish to move to a new branch, you can simply "Crate a new branch" via the GitHub client. It will switch to the newly created branch and preserve your changes.

enter image description here

Extracting numbers from vectors of strings

A stringr pipelined solution:

library(stringr)
years %>% str_match_all("[0-9]+") %>% unlist %>% as.numeric

ssh-copy-id no identities found error

Run following command

# ssh-add

If it gives following error: Could not open a connection to your authentication agent

To remove this error, Run following command:

# eval `ssh-agent`

Excel: last character/string match in a string

Considering a part of a Comment made by @SSilk my end goal has really been to get everything to the right of that last occurence an alternative approach with a very simple formula is to copy a column (say A) of strings and on the copy (say ColumnB) apply Find and Replace. For instance taking the example: Drive:\Folder\SubFolder\Filename.ext

Find what

This returns what remains (here Filename.ext) after the last instance of whatever character is chosen (here \) which is sometimes the objective anyway and facilitates finding the position of the last such character with a short formula such as:

=FIND(B1,A1)-1

How can I use JSON data to populate the options of a select box?

Why not just make the server return the names?

["Woodland Hills", "none", "Los Angeles", "Laguna Hills"]

Then create the <option> elements using JavaScript.

$.ajax({
    url:'suggest.html',
    type:'POST',
    data: 'q=' + str,
    dataType: 'json',
    success: function( json ) {
        $.each(json, function(i, value) {
            $('#myselect').append($('<option>').text(value).attr('value', value));
        });
    }
});

How to SHUTDOWN Tomcat in Ubuntu?

To stop apache process try this command

ps aux | grep tomcat | awk '{print $2}' | xargs kill -9

SQLSTATE[28000] [1045] Access denied for user 'root'@'localhost' (using password: YES) Symfony2

Try to login via the terminal using the following command:

mysql -u root -p

It will then prompt for your password. If this fails, then definitely the username or password is incorrect. If this works, then your database's password needs to be enclosed in quotes:

database_password: "0000"

How to Detect Browser Back Button event - Cross Browser

My variant:

const inFromBack = performance && performance.getEntriesByType( 'navigation' ).map( nav => nav.type ).includes( 'back_forward' )

Java : Cannot format given Object as a Date

public static String showDate(){
    SimpleDateFormat df=new SimpleDateFormat("\nTime:yyyy-MM-dd HH:mm:ss");
    System.out.println(df.format(new Date()));
    String s=df.format(new Date());
    return s;
}

I think this code may solve your problem.

Get child node index

Could you do something like this:

var index = Array.prototype.slice.call(element.parentElement.children).indexOf(element);

https://developer.mozilla.org/en-US/docs/Web/API/Node/parentElement

HTML - Display image after selecting filename

Here You Go:

HTML

<!DOCTYPE html>
<html>
<head>
<link class="jsbin" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script class="jsbin" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.0/jquery-ui.min.js"></script>
<meta charset=utf-8 />
<title>JS Bin</title>
<!--[if IE]>
  <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script>
<![endif]-->
<style>
  article, aside, figure, footer, header, hgroup, 
  menu, nav, section { display: block; }
</style>
</head>
<body>
  <input type='file' onchange="readURL(this);" />
    <img id="blah" src="#" alt="your image" />
</body>
</html>

Script:

function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $('#blah')
                    .attr('src', e.target.result)
                    .width(150)
                    .height(200);
            };

            reader.readAsDataURL(input.files[0]);
        }
    }

Live Demo

Best way to find the intersection of multiple sets?

As of 2.6, set.intersection takes arbitrarily many iterables.

>>> s1 = set([1, 2, 3])
>>> s2 = set([2, 3, 4])
>>> s3 = set([2, 4, 6])
>>> s1 & s2 & s3
set([2])
>>> s1.intersection(s2, s3)
set([2])
>>> sets = [s1, s2, s3]
>>> set.intersection(*sets)
set([2])

scp with port number specified

You know what's cooler than -P? nothing

If you use this server more than a few times, setup/create a ~/.ssh/config file with an entry like:

Host www.myserver.com
    Port 80

or

Host myserver myserver80 short any.name.u.want yes_anything well-within-reason
    HostName www.myserver.com
    Port 80
    User username

Then you can use:

scp [email protected]:/root/file.txt .

or

scp short:/root/file.txt .

You can use anything on the "Host" line with ssh, scp, rsync, git & more

There are MANY configuration option that you can use in config files, see:

man ssh_config

Split varchar into separate columns in Oracle

Simple way is to convert into column

SELECT COLUMN_VALUE FROM TABLE (SPLIT ('19869,19572,19223,18898,10155,'))

CREATE TYPE split_tbl as TABLE OF VARCHAR2(32767);

CREATE OR REPLACE FUNCTION split (p_list VARCHAR2, p_del VARCHAR2 := ',')
   RETURN split_tbl
   PIPELINED IS
   l_idx PLS_INTEGER;
   l_list VARCHAR2 (32767) := p_list;
   l_value VARCHAR2 (32767);
BEGIN
   LOOP
      l_idx := INSTR (l_list, p_del);

      IF l_idx > 0 THEN
         PIPE ROW (SUBSTR (l_list, 1, l_idx - 1));
         l_list := SUBSTR (l_list, l_idx + LENGTH (p_del));
      ELSE
         PIPE ROW (l_list);
         EXIT;
      END IF;
   END LOOP;

   RETURN;
END split;

How to style a div to have a background color for the entire width of the content, and not just for the width of the display?

It is because you set the width:100% which by definition only spans the width of the screen. You want to set the min-width:100% which sets it to the width of the screen... with the ability to grow beyond that.

Also make sure you set min-width:100% for body and html.

Run Stored Procedure in SQL Developer?

None of these other answers worked for me. Here's what I had to do to run a procedure in SQL Developer 3.2.20.10:

SET serveroutput on;
DECLARE
  testvar varchar(100);
BEGIN
  testvar := 'dude';
  schema.MY_PROC(testvar);
  dbms_output.enable;
  dbms_output.put_line(testvar);
END;

And then you'd have to go check the table for whatever your proc was supposed to do with that passed-in variable -- the output will just confirm that the variable received the value (and theoretically, passed it to the proc).

NOTE (differences with mine vs. others):

  • No : prior to the variable name
  • No putting .package. or .packages. between the schema name and the procedure name
  • No having to put an & in the variable's value.
  • No using print anywhere
  • No using var to declare the variable

All of these problems left me scratching my head for the longest and these answers that have these egregious errors out to be taken out and tarred and feathered.

Jackson - How to process (deserialize) nested JSON?

I'm quite late to the party, but one approach is to use a static inner class to unwrap values:

import com.fasterxml.jackson.annotation.JsonCreator;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;

class Scratch {
    private final String aString;
    private final String bString;
    private final String cString;
    private final static String jsonString;

    static {
        jsonString = "{\n" +
                "  \"wrap\" : {\n" +
                "    \"A\": \"foo\",\n" +
                "    \"B\": \"bar\",\n" +
                "    \"C\": \"baz\"\n" +
                "  }\n" +
                "}";
    }

    @JsonCreator
    Scratch(@JsonProperty("A") String aString,
            @JsonProperty("B") String bString,
            @JsonProperty("C") String cString) {
        this.aString = aString;
        this.bString = bString;
        this.cString = cString;
    }

    @Override
    public String toString() {
        return "Scratch{" +
                "aString='" + aString + '\'' +
                ", bString='" + bString + '\'' +
                ", cString='" + cString + '\'' +
                '}';
    }

    public static class JsonDeserializer {
        private final Scratch scratch;

        @JsonCreator
        public JsonDeserializer(@JsonProperty("wrap") Scratch scratch) {
            this.scratch = scratch;
        }

        public Scratch getScratch() {
            return scratch;
        }
    }

    public static void main(String[] args) throws JsonProcessingException {
        ObjectMapper objectMapper = new ObjectMapper();
        Scratch scratch = objectMapper.readValue(jsonString, Scratch.JsonDeserializer.class).getScratch();
        System.out.println(scratch.toString());
    }
}

However, it's probably easier to use objectMapper.configure(SerializationConfig.Feature.UNWRAP_ROOT_VALUE, true); in conjunction with @JsonRootName("aName"), as pointed out by pb2q

preferredStatusBarStyle isn't called

@serenn's answer above is still a great one for the case of UINavigationControllers. However, for swift 3 the childViewController functions have been changed to vars. So the UINavigationController extension code should be:

override open var childViewControllerForStatusBarStyle: UIViewController? {
  return topViewController
}

override open var childViewControllerForStatusBarHidden: UIViewController? {
  return topViewController
}

And then in the view controller that should dictate the status bar style:

override var preferredStatusBarStyle: UIStatusBarStyle {
   return .lightContent
}

Intellij Idea: Importing Gradle project - getting JAVA_HOME not defined yet

Try starting IntelliJ from terminal. You can find application file under: /Applications/IntelliJ\ IDEA\ 14.app/Contents/MacOS

How to rollback everything to previous commit

If you have pushed the commits upstream...

Select the commit you would like to roll back to and reverse the changes by clicking Reverse File, Reverse Hunk or Reverse Selected Lines. Do this for all the commits after the commit you would like to roll back to also.

reverse stuff reverse commit

If you have not pushed the commits upstream...

Right click on the commit and click on Reset current branch to this commit.

reset branch to commit

Javascript getElementsByName.value not working

Here is the example for having one or more checkboxes value. If you have two or more checkboxes and need values then this would really help.

_x000D_
_x000D_
function myFunction() {_x000D_
  var selchbox = [];_x000D_
  var inputfields = document.getElementsByName("myCheck");_x000D_
  var ar_inputflds = inputfields.length;_x000D_
_x000D_
  for (var i = 0; i < ar_inputflds; i++) {_x000D_
    if (inputfields[i].type == 'checkbox' && inputfields[i].checked == true)_x000D_
      selchbox.push(inputfields[i].value);_x000D_
  }_x000D_
  return selchbox;_x000D_
_x000D_
}_x000D_
_x000D_
document.getElementById('btntest').onclick = function() {_x000D_
  var selchb = myFunction();_x000D_
  console.log(selchb);_x000D_
}
_x000D_
Checkbox:_x000D_
<input type="checkbox" name="myCheck" value="UK">United Kingdom_x000D_
<input type="checkbox" name="myCheck" value="USA">United States_x000D_
<input type="checkbox" name="myCheck" value="IL">Illinois_x000D_
<input type="checkbox" name="myCheck" value="MA">Massachusetts_x000D_
<input type="checkbox" name="myCheck" value="UT">Utah_x000D_
_x000D_
<input type="button" value="Click" id="btntest" />
_x000D_
_x000D_
_x000D_

Storing Objects in HTML5 localStorage

Looking at the Apple, Mozilla and Mozilla again documentation, the functionality seems to be limited to handle only string key/value pairs.

A workaround can be to stringify your object before storing it, and later parse it when you retrieve it:

var testObject = { 'one': 1, 'two': 2, 'three': 3 };

// Put the object into storage
localStorage.setItem('testObject', JSON.stringify(testObject));

// Retrieve the object from storage
var retrievedObject = localStorage.getItem('testObject');

console.log('retrievedObject: ', JSON.parse(retrievedObject));

Run a Command Prompt command from Desktop Shortcut

This is an old post but I have issues with coming across posts that have some incorrect information/syntax...

If you wanted to do this with a shorcut icon you could just create a shortcut on your desktop for the cmd.exe application. Then append a /K {your command} to the shorcut path.

So a default shorcut target path may look like "%windir%\system32\cmd.exe", just change it to %windir%\system32\cmd.exe /k {commands}

example: %windir%\system32\cmd.exe /k powercfg -lastwake

In this case i would use /k (keep open) to display results.

Arlen was right about the /k (keep open) and /c (close)

You can open a command prompt and type "cmd /?" to see your options.

http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/cmd.mspx?mfr=true

A batch file is kind of overkill for a single command prompt command...

Hope this helps someone else

How to make html table vertically scrollable

Just add the display:block to the thead > tr and tbody. check the below example

http://www.imaputz.com/cssStuff/bigFourVersion.html

IIs Error: Application Codebehind=“Global.asax.cs” Inherits=“nadeem.MvcApplication”

You can change it by editing Globas.asax file (not Global.asax.cs). Find it in app folder in windows explorer then edit

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

to

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

document.getElementById vs jQuery $()

jQuery is built over JavaScript. This means that it's just javascript anyway.

document.getElementById()

The document.getElementById() method returns the element that has the ID attribute with the specified value and Returns null if no elements with the specified ID exists.An ID should be unique within a page.

Jquery $()

Calling jQuery() or $() with an id selector as its argument will return a jQuery object containing a collection of either zero or one DOM element.Each id value must be used only once within a document. If more than one element has been assigned the same ID, queries that use that ID will only select the first matched element in the DOM.

Setting UILabel text to bold

Use font property of UILabel:

label.font = UIFont(name:"HelveticaNeue-Bold", size: 16.0)

or use default system font to bold text:

label.font = UIFont.boldSystemFont(ofSize: 16.0)

org.hibernate.MappingException: Unknown entity

You can enable entity scan by adding below annotation on Application .java @EntityScan(basePackageClasses=YourEntityClassName.class)

Or you can set the packageToScan in your session factory. sessionFactory.setPackagesToScan(“com.all.entity”);

setting global sql_mode in mysql

In my case i have to change file /etc/mysql/mysql.conf.d/mysqld.cnf change this under [mysqld]

Paste this line on [mysqld] portion

sql_mode = "STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION"

Error "Metadata file '...\Release\project.dll' could not be found in Visual Studio"

I find that this usually occurs to me when i still have a method declaration in an interface, which a class implements, but that i had later removed and had forgotten to remove it from the interface as well. I usually just save the entire solution every 30mins n then just revert back to an earlier version if i cant find the error.

How do I copy the contents of a String to the clipboard in C#?

WPF: System.Windows.Clipboard (PresentationCore.dll)

Winforms: System.Windows.Forms.Clipboard

Both have a static SetText method.

Command not found error in Bash variable assignment

When you define any variable then you do not have to put in any extra spaces.

E.g.

name = "Stack Overflow"  
// it is not valid, you will get an error saying- "Command not found"

So remove spaces:

name="Stack Overflow" 

and it will work fine.

Rendering partial view on button click in ASP.NET MVC

Change the button to

<button id="search">Search</button>

and add the following script

var url = '@Url.Action("DisplaySearchResults", "Search")';
$('#search').click(function() {
  var keyWord = $('#Keyword').val();
  $('#searchResults').load(url, { searchText: keyWord });
})

and modify the controller method to accept the search text

public ActionResult DisplaySearchResults(string searchText)
{
  var model = // build list based on parameter searchText
   return PartialView("SearchResults", model);
}

The jQuery .load method calls your controller method, passing the value of the search text and updates the contents of the <div> with the partial view.

Side note: The use of a <form> tag and @Html.ValidationSummary() and @Html.ValidationMessageFor() are probably not necessary here. Your never returning the Index view so ValidationSummary makes no sense and I assume you want a null search text to return all results, and in any case you do not have any validation attributes for property Keyword so there is nothing to validate.

Edit

Based on OP's comments that SearchCriterionModel will contain multiple properties with validation attributes, then the approach would be to include a submit button and handle the forms .submit() event

<input type="submit" value="Search" />

var url = '@Url.Action("DisplaySearchResults", "Search")';
$('form').submit(function() {
  if (!$(this).valid()) { 
    return false; // prevent the ajax call if validation errors
  }
  var form = $(this).serialize();
  $('#searchResults').load(url, form);
  return false; // prevent the default submit action
})

and the controller method would be

public ActionResult DisplaySearchResults(SearchCriterionModel criteria)
{
  var model = // build list based on the properties of criteria
  return PartialView("SearchResults", model);
}

Convert HttpPostedFileBase to byte[]

As Darin says, you can read from the input stream - but I'd avoid relying on all the data being available in a single go. If you're using .NET 4 this is simple:

MemoryStream target = new MemoryStream();
model.File.InputStream.CopyTo(target);
byte[] data = target.ToArray();

It's easy enough to write the equivalent of CopyTo in .NET 3.5 if you want. The important part is that you read from HttpPostedFileBase.InputStream.

For efficient purposes you could check whether the stream returned is already a MemoryStream:

byte[] data;
using (Stream inputStream = model.File.InputStream)
{
    MemoryStream memoryStream = inputStream as MemoryStream;
    if (memoryStream == null)
    {
        memoryStream = new MemoryStream();
        inputStream.CopyTo(memoryStream);
    }
    data = memoryStream.ToArray();
}

Concatenate a list of pandas dataframes together

concat also works nicely with a list comprehension pulled using the "loc" command against an existing dataframe

df = pd.read_csv('./data.csv') # ie; Dataframe pulled from csv file with a "userID" column

review_ids = ['1','2','3'] # ie; ID values to grab from DataFrame

# Gets rows in df where IDs match in the userID column and combines them 

dfa = pd.concat([df.loc[df['userID'] == x] for x in review_ids])

Shared folder between MacOSX and Windows on Virtual Box

You should map your virtual network drive in Windows.

  1. Open command prompt in Windows (VirtualBox)
  2. Execute: net use x: \\vboxsvr\<your_shared_folder_name>
  3. You should see new drive X: in My Computer

In your case execute net use x: \\vboxsvr\win7

How to enable SOAP on CentOS

On CentOS 7, the following works:

yum install php-soap

This will automatically create a soap.ini under /etc/php.d.

The extension itself for me lives in /usr/lib64/php/modules. You can confirm your extension directory by doing:

php -i | grep extension_dir

Once this has been installed, you can simply restart Apache using the new service manager like so:

systemctl restart httpd

Thanks to Matt Browne for the info about /etc/php.d.

PHP PDO returning single row

Did you try:

$DBH = new PDO( "connection string goes here" );
$row = $DBH->query( "select figure from table1" )->fetch();
echo $row["figure"];
$DBH = null;

c++ custom compare function for std::sort()

std::pair already has the required comparison operators, which perform lexicographical comparisons using both elements of each pair. To use this, you just have to provide the comparison operators for types for types K and V.

Also bear in mind that std::sort requires a strict weak ordeing comparison, and <= does not satisfy that. You would need, for example, a less-than comparison < for K and V. With that in place, all you need is

std::vector<pair<K,V>> items; 
std::sort(items.begin(), items.end()); 

If you really need to provide your own comparison function, then you need something along the lines of

template <typename K, typename V>
bool comparePairs(const std::pair<K,V>& lhs, const std::pair<K,V>& rhs)
{
  return lhs.first < rhs.first;
}

How to Update/Drop a Hive Partition?

You can either copy files into the folder where external partition is located or use

INSERT OVERWRITE TABLE tablename1 PARTITION (partcol1=val1, partcol2=val2...)...

statement.

WPF: Create a dialog / prompt

I just add a static method to call it like a MessageBox:

<Window xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    x:Class="utils.PromptDialog"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    WindowStartupLocation="CenterScreen" 
    SizeToContent="WidthAndHeight"
    MinWidth="300"
    MinHeight="100"
    WindowStyle="SingleBorderWindow"
    ResizeMode="CanMinimize">
<StackPanel Margin="5">
    <TextBlock Name="txtQuestion" Margin="5"/>
    <TextBox Name="txtResponse" Margin="5"/>
    <PasswordBox Name="txtPasswordResponse" />
    <StackPanel Orientation="Horizontal" Margin="5" HorizontalAlignment="Right">
        <Button Content="_Ok" IsDefault="True" Margin="5" Name="btnOk" Click="btnOk_Click" />
        <Button Content="_Cancel" IsCancel="True" Margin="5" Name="btnCancel" Click="btnCancel_Click" />
    </StackPanel>
</StackPanel>
</Window>

And the code behind:

public partial class PromptDialog : Window
{
    public enum InputType
    {
        Text,
        Password
    }

    private InputType _inputType = InputType.Text;

    public PromptDialog(string question, string title, string defaultValue = "", InputType inputType = InputType.Text)
    {
        InitializeComponent();
        this.Loaded += new RoutedEventHandler(PromptDialog_Loaded);
        txtQuestion.Text = question;
        Title = title;
        txtResponse.Text = defaultValue;
        _inputType = inputType;
        if (_inputType == InputType.Password)
            txtResponse.Visibility = Visibility.Collapsed;
        else
            txtPasswordResponse.Visibility = Visibility.Collapsed;
    }

    void PromptDialog_Loaded(object sender, RoutedEventArgs e)
    {
        if (_inputType == InputType.Password)
            txtPasswordResponse.Focus();
        else
            txtResponse.Focus();
    }

    public static string Prompt(string question, string title, string defaultValue = "", InputType inputType = InputType.Text)
    {
        PromptDialog inst = new PromptDialog(question, title, defaultValue, inputType);
        inst.ShowDialog();
        if (inst.DialogResult == true)
            return inst.ResponseText;
        return null;
    }

    public string ResponseText
    {
        get
        {
            if (_inputType == InputType.Password)
                return txtPasswordResponse.Password;
            else
                return txtResponse.Text;
        }
    }

    private void btnOk_Click(object sender, RoutedEventArgs e)
    {
        DialogResult = true;
        Close();
    }

    private void btnCancel_Click(object sender, RoutedEventArgs e)
    {
        Close();
    }
}

So you can call it like:

string repeatPassword = PromptDialog.Prompt("Repeat password", "Password confirm", inputType: PromptDialog.InputType.Password);

How do I get video durations with YouTube API version 3?

You can get the duration from the 'contentDetails' field in the json response.

enter image description here

Fix columns in horizontal scrolling

SOLVED

http://jsfiddle.net/DJqPf/7/

.table-wrapper { 
    overflow-x:scroll;
    overflow-y:visible;
    width:250px;
    margin-left: 120px;
}
td, th {
    padding: 5px 20px;
    width: 100px;
}
th:first-child {
    position: fixed;
    left: 5px
}

UPDATE

_x000D_
_x000D_
$(function () {  _x000D_
  $('.table-wrapper tr').each(function () {_x000D_
    var tr = $(this),_x000D_
        h = 0;_x000D_
    tr.children().each(function () {_x000D_
      var td = $(this),_x000D_
          tdh = td.height();_x000D_
      if (tdh > h) h = tdh;_x000D_
    });_x000D_
    tr.css({height: h + 'px'});_x000D_
  });_x000D_
});
_x000D_
body {_x000D_
    position: relative;_x000D_
}_x000D_
.table-wrapper { _x000D_
    overflow-x:scroll;_x000D_
    overflow-y:visible;_x000D_
    width:200px;_x000D_
    margin-left: 120px;_x000D_
}_x000D_
_x000D_
_x000D_
td, th {_x000D_
    padding: 5px 20px;_x000D_
    width: 100px;_x000D_
}_x000D_
tbody tr {_x000D_
  _x000D_
}_x000D_
th:first-child {_x000D_
    position: absolute;_x000D_
    left: 5px_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<script src="https://code.jquery.com/jquery-2.2.3.min.js"></script>_x000D_
  <meta charset="utf-8">_x000D_
  <title>JS Bin</title>_x000D_
</head>_x000D_
<body>_x000D_
<div>_x000D_
    <h1>SOME RANDOM TEXT</h1>_x000D_
</div>_x000D_
<div class="table-wrapper">_x000D_
    <table id="consumption-data" class="data">_x000D_
        <thead class="header">_x000D_
            <tr>_x000D_
                <th>Month</th>_x000D_
                <th>Item 1</th>_x000D_
                <th>Item 2</th>_x000D_
                <th>Item 3</th>_x000D_
                <th>Item 4</th>_x000D_
            </tr>_x000D_
        </thead>_x000D_
        <tbody class="results">_x000D_
            <tr>_x000D_
                <th>Jan is an awesome month</th>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <th>Feb</th>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <th>Mar</th>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <th>Apr</th>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>  _x000D_
            </tr>_x000D_
            <tr>    _x000D_
                <th>May</th>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
            </tr>_x000D_
            <tr>_x000D_
                <th>Jun</th>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
                <td>3163</td>_x000D_
            </tr>_x000D_
_x000D_
            <tr>_x000D_
                <th>...</th>_x000D_
                <td>...</td>_x000D_
                <td>...</td>_x000D_
                <td>...</td>_x000D_
                <td>...</td>_x000D_
            </tr>_x000D_
        </tbody>_x000D_
    </table>_x000D_
</div>_x000D_
_x000D_
<div>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Example: Communication between Activity and Service using Messaging

Note: You don't need to check if your service is running, CheckIfServiceIsRunning(), because bindService() will start it if it isn't running.

Also: if you rotate the phone you don't want it to bindService() again, because onCreate() will be called again. Be sure to define onConfigurationChanged() to prevent this.

Programmatically add new column to DataGridView

Here's a sample method that adds two extra columns programmatically to the grid view:

    private void AddColumnsProgrammatically()
    {
        // I created these columns at function scope but if you want to access 
        // easily from other parts of your class, just move them to class scope.
        // E.g. Declare them outside of the function...
        var col3 = new DataGridViewTextBoxColumn();
        var col4 = new DataGridViewCheckBoxColumn();

        col3.HeaderText = "Column3";
        col3.Name = "Column3";

        col4.HeaderText = "Column4";
        col4.Name = "Column4";

        dataGridView1.Columns.AddRange(new DataGridViewColumn[] {col3,col4});
    }

A great way to figure out how to do this kind of process is to create a form, add a grid view control and add some columns. (This process will actually work for ANY kind of form control. All instantiation and initialization happens in the Designer.) Then examine the form's Designer.cs file to see how the construction takes place. (Visual Studio does everything programmatically but hides it in the Form Designer.)

For this example I created two columns for the view named Column1 and Column2 and then searched Form1.Designer.cs for Column1 to see everywhere it was referenced. The following information is what I gleaned and, copied and modified to create two more columns dynamically:

// Note that this info scattered throughout the designer but can easily collected.

        System.Windows.Forms.DataGridViewTextBoxColumn Column1;
        System.Windows.Forms.DataGridViewCheckBoxColumn Column2;

        this.Column1 = new System.Windows.Forms.DataGridViewTextBoxColumn();
        this.Column2 = new System.Windows.Forms.DataGridViewCheckBoxColumn();

        this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] {
        this.Column1,
        this.Column2});

        this.Column1.HeaderText = "Column1";
        this.Column1.Name = "Column1";

        this.Column2.HeaderText = "Column2";
        this.Column2.Name = "Column2";

Choosing a jQuery datagrid plugin?

The three most used and well supported jQuery grid plugins today are SlickGrid, jqGrid and DataTables. See http://wiki.jqueryui.com/Grid-OtherGrids for more info.

Preventing an image from being draggable or selectable without using JS

You could probably just resort to

<img src="..." style="pointer-events: none;">

How to navigate through a vector using iterators? (C++)

In C++-11 you can do:

std::vector<int> v = {0, 1, 2, 3, 4, 5};
for (auto i : v)
{
   // access by value, the type of i is int
   std::cout << i << ' ';
}
std::cout << '\n';

See here for variations: https://en.cppreference.com/w/cpp/language/range-for

How to unzip a list of tuples into individual lists?

If you want a list of lists:

>>> [list(t) for t in zip(*l)]
[[1, 3, 8], [2, 4, 9]]

If a list of tuples is OK:

>>> zip(*l)
[(1, 3, 8), (2, 4, 9)]

LDAP root query syntax to search more than one specific OU

After speaking with an LDAP expert, it's not possible this way. One query can't search more than one DC or OU.

Your options are:

  1. Run more then 1 query and parse the result.
  2. Use a filter to find the desired users/objects based off a different attribute like an AD group or by name.

How to find serial number of Android device?

Another way is to use /sys/class/android_usb/android0/iSerial in an App with no permissions whatsoever.

user@creep:~$ adb shell ls -l /sys/class/android_usb/android0/iSerial
-rw-r--r-- root     root         4096 2013-01-10 21:08 iSerial
user@creep:~$ adb shell cat /sys/class/android_usb/android0/iSerial
0A3CXXXXXXXXXX5

To do this in java one would just use a FileInputStream to open the iSerial file and read out the characters. Just be sure you wrap it in an exception handler because not all devices have this file.

At least the following devices are known to have this file world-readable:

  • Galaxy Nexus
  • Nexus S
  • Motorola Xoom 3g
  • Toshiba AT300
  • HTC One V
  • Mini MK802
  • Samsung Galaxy S II

You can also see my blog post here: http://insitusec.blogspot.com/2013/01/leaking-android-hardware-serial-number.html where I discuss what other files are available for info.

How can I get a specific number child using CSS?

For IE 7 & 8 (and other browsers without CSS3 support not including IE6) you can use the following to get the 2nd and 3rd children:

2nd Child:

td:first-child + td

3rd Child:

td:first-child + td + td

Then simply add another + td for each additional child you wish to select.

If you want to support IE6 that can be done too! You simply need to use a little javascript (jQuery in this example):

$(function() {
    $('td:first-child').addClass("firstChild");
    $(".table-class tr").each(function() {
        $(this).find('td:eq(1)').addClass("secondChild");
        $(this).find('td:eq(2)').addClass("thirdChild");
    });
});

Then in your css you simply use those class selectors to make whatever changes you like:

table td.firstChild { /*stuff here*/ }
table td.secondChild { /*stuff to apply to second td in each row*/ }

Use a JSON array with objects with javascript

_x000D_
_x000D_
var datas = [{"id":28,"Title":"Sweden"}, {"id":56,"Title":"USA"}, {"id":89,"Title":"England"}];_x000D_
document.writeln("<table border = '1' width = 100 >");_x000D_
document.writeln("<tr><td>No Id</td><td>Title</td></tr>"); _x000D_
for(var i=0;i<datas.length;i++){_x000D_
document.writeln("<tr><td>"+datas[i].id+"</td><td>"+datas[i].Title+"</td></tr>");_x000D_
}_x000D_
document.writeln("</table>");
_x000D_
_x000D_
_x000D_

Difference between numpy.array shape (R, 1) and (R,)

The data structure of shape (n,) is called a rank 1 array. It doesn't behave consistently as a row vector or a column vector which makes some of its operations and effects non intuitive. If you take the transpose of this (n,) data structure, it'll look exactly same and the dot product will give you a number and not a matrix. The vectors of shape (n,1) or (1,n) row or column vectors are much more intuitive and consistent.

SeekBar and media player in android

To add on to @hardartcore's answer.

  1. Instead of calling postDelayed on a Handler, the best approach would be to get callbacks from the MediaPlayer during play-back and then accordingly update the seekBar with the progress.

  2. Also, pause your MediaPlayer at onStartTrackingTouch(SeekBar seekBar) of the OnSeekBarChangeListener and then re-start it on onStopTrackingTouch(SeekBar seekBar).

Allow docker container to connect to a local/host postgres database

for docker-compose you can try just add

network_mode: "host"

example :

version: '2'
services:
  feedx:
    build: web
    ports:
    - "127.0.0.1:8000:8000"
    network_mode: "host"

https://docs.docker.com/compose/compose-file/#network_mode

Getting the names of all files in a directory with PHP

You need to surround $file = readdir($handle) with parentheses.

Here you go:

$log_directory = 'your_dir_name_here';

$results_array = array();

if (is_dir($log_directory))
{
        if ($handle = opendir($log_directory))
        {
                //Notice the parentheses I added:
                while(($file = readdir($handle)) !== FALSE)
                {
                        $results_array[] = $file;
                }
                closedir($handle);
        }
}

//Output findings
foreach($results_array as $value)
{
    echo $value . '<br />';
}

Using PowerShell credentials without being prompted for a password

I saw one example that uses Import/Export-CLIXML.

These are my favorite commands for the issue you're trying to resolve. And the simplest way to use them is.

$passwordPath = './password.txt'
if (-not (test-path $passwordPath)) {
    $cred = Get-Credential -Username domain\username -message 'Please login.'
    Export-CliXML -InputObject $cred -Path $passwordPath
}
$cred = Import-CliXML -path $passwordPath

So if the file doesn't locally exist it will prompt for the credentials and store them. This will take a [pscredential] object without issue and will hide the credentials as a secure string.

Finally just use the credential like you normally do.

Restart-Computer -ComputerName ... -Credentail $cred

Note on Securty:

Securely store credentials on disk

When reading the Solution, you might at first be wary of storing a password on disk. While it is natural (and prudent) to be cautious of littering your hard drive with sensitive information, the Export-CliXml cmdlet encrypts credential objects using the Windows standard Data Protection API. This ensures that only your user account can properly decrypt its contents. Similarly, the ConvertFrom-SecureString cmdlet also encrypts the password you provide.

Edit: Just reread the original question. The above will work so long as you've initialized the [pscredential] to the hard disk. That is if you drop that in your script and run the script once it will create that file and then running the script unattended will be simple.

How to check if any flags of a flag combination are set?

Sorry, but i will show it in VB :)

   <Flags()> Public Enum Cnt As Integer
        None = 0
        One = 1
        Two = 2
        Three = 4
        Four = 8    
    End Enum

    Sub Test()
    Dim CntValue As New Cnt
    CntValue += Cnt.One
    CntValue += Cnt.Three
    Console.WriteLine(CntValue)
    End Sub

CntValue = 5 So the enum contains 1 + 4

Using headers with the Python requests library's get method

Seems pretty straightforward, according to the docs on the page you linked (emphasis mine).

requests.get(url, params=None, headers=None, cookies=None, auth=None, timeout=None)

Sends a GET request. Returns Response object.

Parameters:

  • url – URL for the new Request object.
  • params – (optional) Dictionary of GET Parameters to send with the Request.
  • headers – (optional) Dictionary of HTTP Headers to send with the Request.
  • cookies – (optional) CookieJar object to send with the Request.
  • auth – (optional) AuthObject to enable Basic HTTP Auth.
  • timeout – (optional) Float describing the timeout of the request.

What is the difference between a definition and a declaration?

A declaration presents a symbol name to the compiler. A definition is a declaration that allocates space for the symbol.

int f(int x); // function declaration (I know f exists)

int f(int x) { return 2*x; } // declaration and definition

iPad browser WIDTH & HEIGHT standard

You can try this:

    /*iPad landscape oriented styles */

    @media only screen and (device-width:768px)and (orientation:landscape){
        .yourstyle{

        }

    }

    /*iPad Portrait oriented styles */

    @media only screen and (device-width:768px)and (orientation:portrait){
        .yourstyle{

        }
    }

WebDriver: check if an element exists?

I extended Selenium WebDriver implementation, in my case HtmlUnitDriver to expose a method

public boolean isElementPresent(By by){}

like this:

  1. check if page is loaded within a timeout period.
  2. Once page is loaded, I lower the implicitly wait time of the WebDriver to some milliseconds, in my case 100 mills, probably should work with 0 mills too.
  3. call findElements(By), the WebDriver even if will not find the element will wait only the amount of time from above.
  4. rise back the implicitly wait time for future page loading

Here is my code:

import java.util.concurrent.TimeUnit;
import org.openqa.selenium.By;
import org.openqa.selenium.JavascriptExecutor;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.htmlunit.HtmlUnitDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;

public class CustomHtmlUnitDriver extends HtmlUnitDriver {

    public static final long DEFAULT_TIMEOUT_SECONDS = 30;
    private long timeout = DEFAULT_TIMEOUT_SECONDS;

    public long getTimeout() {
        return timeout;
    }
    public void setTimeout(long timeout) {
        this.timeout = timeout;
    }

    public boolean isElementPresent(By by) {
        boolean isPresent = true;
        waitForLoad();
        //search for elements and check if list is empty
        if (this.findElements(by).isEmpty()) {
            isPresent = false;
        }
        //rise back implicitly wait time
        this.manage().timeouts().implicitlyWait(timeout, TimeUnit.SECONDS);
        return isPresent;
    }

    public void waitForLoad() {
        ExpectedCondition<Boolean> pageLoadCondition = new ExpectedCondition<Boolean>() {
            public Boolean apply(WebDriver wd) {
                //this will tel if page is loaded
                return "complete".equals(((JavascriptExecutor) wd).executeScript("return document.readyState"));
            }
        };
        WebDriverWait wait = new WebDriverWait(this, timeout);
        //wait for page complete
        wait.until(pageLoadCondition);
        //lower implicitly wait time
        this.manage().timeouts().implicitlyWait(100, TimeUnit.MILLISECONDS);
    }   
}

Usage:

CustomHtmlUnitDriver wd = new CustomHtmlUnitDriver();
wd.get("http://example.org");
if (wd.isElementPresent(By.id("Accept"))) {
    wd.findElement(By.id("Accept")).click();
}
else {
    System.out.println("Accept button not found on page");
}

How to extract text from a PDF?

An efficient command line tool, open source, free of any fee, available on both linux & windows : simply named pdftotext. This tool is a part of the xpdf library.

http://en.wikipedia.org/wiki/Pdftotext