Programs & Examples On #Freebasic

FreeBASIC is a free/open source (the compiler is GPL and the runtime library is LGPL with static linking exception), 32-bit & 64-bit BASIC compiler for Microsoft Windows and LInux and a 32-bit compiler for protected-mode extended DOS.

How to pass a value from one jsp to another jsp page?

Suppose we want to pass three values(u1,u2,u3) from say 'show.jsp' to another page say 'display.jsp' Make three hidden text boxes and a button that is click automatically(using javascript). //Code to written in 'show.jsp'

<body>
<form action="display.jsp" method="post">
 <input type="hidden" name="u1" value="<%=u1%>"/>
 <input type="hidden" name="u2" value="<%=u2%>" />
 <input type="hidden" name="u3" value="<%=u3%>" />
 <button type="hidden" id="qq" value="Login" style="display: none;"></button>
</form>
  <script type="text/javascript">
     document.getElementById("qq").click();
  </script>
</body>

// Code to be written in 'display.jsp'

 <% String u1 = request.getParameter("u1").toString();
    String u2 = request.getParameter("u2").toString();
    String u3 = request.getParameter("u3").toString();
 %>

If you want to use these variables of servlets in javascript then simply write

<script type="text/javascript">
 var a=<%=u1%>;
</script>

Hope it helps :)

The application was unable to start correctly (0xc000007b)

A load time dependency could not be resolved. The easiest way to debug this is to use Dependency Walker. Use the Profile option to get diagnostics output of the load process. This will identify the point of failure and should guide you to a solution.

The most common cause of this error is trying to load a 64 bit DLL into a 32 bit process, or vice versa.

How can I strip first and last double quotes?

I have some code that needs to strip single or double quotes, and I can't simply ast.literal_eval it.

if len(arg) > 1 and arg[0] in ('"\'') and arg[-1] == arg[0]:
    arg = arg[1:-1]

This is similar to ToolmakerSteve's answer, but it allows 0 length strings, and doesn't turn the single character " into an empty string.

How to connect to remote Oracle DB with PL/SQL Developer?

In addition to Richard Cresswells and dpbradleys answer: If you neither want to create a TNS name nor the '//123.45.67.89:1521/Test' input works (some configurations wont), you can put

(DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = 123.45.67.89)(PORT = 1521)) (CONNECT_DATA = (SID = TEST)(SERVER = DEDICATED)))

(as one line) into the 'database' section of the login dialog.

Populating a data frame in R in a loop

It is often preferable to avoid loops and use vectorized functions. If that is not possible there are two approaches:

  1. Preallocate your data.frame. This is not recommended because indexing is slow for data.frames.
  2. Use another data structure in the loop and transform into a data.frame afterwards. A list is very useful here.

Example to illustrate the general approach:

mylist <- list() #create an empty list

for (i in 1:5) {
  vec <- numeric(5) #preallocate a numeric vector
  for (j in 1:5) { #fill the vector
    vec[j] <- i^j 
  }
  mylist[[i]] <- vec #put all vectors in the list
}
df <- do.call("rbind",mylist) #combine all vectors into a matrix

In this example it is not necessary to use a list, you could preallocate a matrix. However, if you do not know how many iterations your loop will need, you should use a list.

Finally here is a vectorized alternative to the example loop:

outer(1:5,1:5,function(i,j) i^j)

As you see it's simpler and also more efficient.

Oracle TNS names not showing when adding new connection to SQL Developer

SQL Developer will look in the following location in this order for a tnsnames.ora file

  1. $HOME/.tnsnames.ora
  2. $TNS_ADMIN/tnsnames.ora
  3. TNS_ADMIN lookup key in the registry
  4. /etc/tnsnames.ora ( non-windows )
  5. $ORACLE_HOME/network/admin/tnsnames.ora
  6. LocalMachine\SOFTWARE\ORACLE\ORACLE_HOME_KEY
  7. LocalMachine\SOFTWARE\ORACLE\ORACLE_HOME

To see which one SQL Developer is using, issue the command show tns in the worksheet

If your tnsnames.ora file is not getting recognized, use the following procedure:

  1. Define an environmental variable called TNS_ADMIN to point to the folder that contains your tnsnames.ora file.

    In Windows, this is done by navigating to Control Panel > System > Advanced system settings > Environment Variables...

    In Linux, define the TNS_ADMIN variable in the .profile file in your home directory.

  2. Confirm the os is recognizing this environmental variable

    From the Windows command line: echo %TNS_ADMIN%

    From linux: echo $TNS_ADMIN

  3. Restart SQL Developer

  4. Now in SQL Developer right click on Connections and select New Connection.... Select TNS as connection type in the drop down box. Your entries from tnsnames.ora should now display here.

System.Security.SecurityException when writing to Event Log

A new key with source name used need to be created under HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\eventlog\Application in the regEdit when you use System.Diagnostics.EventLog.WriteEntry("SourceName", "ErrorMessage", EventLogEntryType.Error);

So basically your user does not have permission to create the key. The can do the following depending of the user that you are using from the Identity value in the Application Pool Advanced settings:

  1. Run RegEdit and go to HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\eventlog
  2. Right click in EventLog key and the select Permissions... option 3.Add your user with full Control access.

    -If you are using "NetworkService" add NETWORK SERVICE user

    -If you are usinf "ApplicationPoolIdentity" add IIS APPPOL{name of your app pool} (use local machine location when search the user).

    -If you are using "LocalSystem" make sure that the user has Administrator permissions. It is not recommend for vulnerabilities.

  3. Repeat the steps from 1 to 3 for HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\services\eventlog\Security

For debugging with Visual Studio I use "NetworkService" (it is ASP.NET user) and when the site is published I used "AppicationPoolIdentity".

Simple JavaScript problem: onClick confirm not preventing default action

First of all, delete is a reserved word in javascript, I'm surprised this even executes for you (When I test it in Firefox, I get a syntax error)

Secondly, your HTML looks weird - is there a reason you're closing the opening anchor tags with /> instead of just > ?

Hide strange unwanted Xcode logs

Please note that for iOS 14 Simulator, the OS_ACTIVITY_MODE=disable will not show any logs using the new Swift Logger. You will have to remove or enable it.

Python No JSON object could be decoded

It seems that you have invalid JSON. In that case, that's totally dependent on the data the server sends you which you have not shown. I would suggest running the response through a JSON validator.

How to kill all processes matching a name?

You can also evaluate your output as a sub-process, by surrounding everything with back ticks or with putting it inside $():

`ps aux | grep -ie amarok | awk '{print "kill -9 " $2}'`

 $(ps aux | grep -ie amarok | awk '{print "kill -9 " $2}')     

Where does the slf4j log file get saved?

As already mentioned its just a facade and it helps to switch between different logger implementation easily. For example if you want to use log4j implementation.

A sample code would looks like below.

If you use maven get the dependencies

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-api</artifactId>
        <version>1.7.6</version>
    </dependency>
    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>slf4j-log4j12</artifactId>
        <version>1.7.5</version>
    </dependency>

Have the below in log4j.properties in location src/main/resources/log4j.properties

            log4j.rootLogger=DEBUG, STDOUT, file

            log4j.appender.STDOUT=org.apache.log4j.ConsoleAppender
            log4j.appender.STDOUT.layout=org.apache.log4j.PatternLayout
            log4j.appender.STDOUT.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n

            log4j.appender.file=org.apache.log4j.RollingFileAppender
            log4j.appender.file.File=mylogs.log
            log4j.appender.file.layout=org.apache.log4j.PatternLayout
            log4j.appender.file.layout.ConversionPattern=%d{dd-MM-yyyy HH:mm:ss} %-5p %c{1}:%L - %m%n

Hello world code below would prints in console and to a log file as per above configuration.

            import org.slf4j.Logger;
            import org.slf4j.LoggerFactory;

            public class HelloWorld {
              public static void main(String[] args) {
                Logger logger = LoggerFactory.getLogger(HelloWorld.class);
                logger.info("Hello World");
              }
            }

enter image description here

Error in your SQL syntax; check the manual that corresponds to your MySQL server version

Use ` backticks for MYSQL reserved words...

table name "table" is reserved word for MYSQL...

so your query should be as follows...

$sql="INSERT INTO `table` (`username`, `password`)
VALUES
('$_POST[username]','$_POST[password]')";

Counting the number of elements in array

Just use the length filter on the whole array. It works on more than just strings:

{{ notcount|length }}

Replacing &nbsp; from javascript dom text node

This is much easier than you're making it. The text node will not have the literal string "&nbsp;" in it, it'll have have the corresponding character with code 160.

function replaceNbsps(str) {
  var re = new RegExp(String.fromCharCode(160), "g");
  return str.replace(re, " ");
}

textNode.nodeValue = replaceNbsps(textNode.nodeValue);

UPDATE

Even easier:

textNode.nodeValue = textNode.nodeValue.replace(/\u00a0/g, " ");

How to delete/unset the properties of a javascript object?

To blank it:

myObject["myVar"]=null;

To remove it:

delete myObject["myVar"]

as you can see in duplicate answers

How to remove array element in mongodb?

This below code will remove the complete object element from the array, where the phone number is '+1786543589455'

db.collection.update(
  { _id: id },
  { $pull: { 'contact': { number: '+1786543589455' } } }
);

css divide width 100% to 3 column

Just in case someone is still looking for the answer,

let the browser take care of that. Try this:

  • display: table on the container element.
  • display: table-cell on the child elements.

The browser will evenly divide it whether you have 3 or 10 columns.

EDIT

the container element should also have: table-layout: fixed otherwise the browser will determine the width of each element (most of the time not that bad).

Are there any log file about Windows Services Status?

The most likely place to find this sort of information is in the event viewer (under Administrative tools in XP or run eventvwr) This is where most services log warnings errors etc.

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

The erudite suggestions mentioned above will solve the problem in 99.99% of the cases. It was my luck that they did not. In my case it turned out I was including a header file from a different Windows project. Sure enough, at the very bottom of that file I found the directive:

#pragma comment(linker, "/subsystem:Windows")

Needless to say, removing this line solved my problem.

Git: Pull from other remote

git pull is really just a shorthand for git pull <remote> <branchname>, in most cases it's equivalent to git pull origin master. You will need to add another remote and pull explicitly from it. This page describes it in detail:

http://help.github.com/forking/

Make a borderless form movable?

public Point mouseLocation;
private void frmInstallDevice_MouseDown(object sender, MouseEventArgs e)
{
  mouseLocation = new Point(-e.X, -e.Y);
}

private void frmInstallDevice_MouseMove(object sender, MouseEventArgs e)
{
  if (e.Button == MouseButtons.Left)
  {
    Point mousePos = Control.MousePosition;
    mousePos.Offset(mouseLocation.X, mouseLocation.Y);
    Location = mousePos;
  }
}

this can solve ur problem....

Execute a shell script in current shell with sudo permission

If you really want to "ExecuteCall a shell script in current shell with sudo permission" you can use exec to...

replace the shell with a given program (executing it, not as new process)

I insist on replacing "execute" with "call" because the former has a meaning that includes creating a new process and ID, where the latter is ambiguous and leaves room for creativity, of which I am full.

Consider this test case and look closely at pid 1337

# Don't worry, the content of this script is cat'ed below
$ ./test.sh -o foo -p bar

User ubuntu is running...
 PID TT       USER     COMMAND
 775 pts/1    ubuntu   -bash
1408 pts/1    ubuntu    \_ bash ./test.sh -o foo -p bar
1411 pts/1    ubuntu        \_ ps -t /dev/pts/1 -fo pid,tty,user,args

User root is running...
 PID TT       USER     COMMAND
 775 pts/1    ubuntu   -bash
1337 pts/1    root      \_ sudo ./test.sh -o foo -p bar
1412 pts/1    root          \_ bash ./test.sh -o foo -p bar
1415 pts/1    root              \_ ps -t /dev/pts/1 -fo pid,tty,user,args

Take 'exec' out of the command and this script would get cat-ed twice. (Try it.)

#!/usr/bin/env bash

echo; echo "User $(whoami) is running..."
ps -t $(tty) -fo pid,tty,user,args

if [[ $EUID > 0 ]]; then
    # exec replaces the current process effectively ending execution so no exit is needed.
    exec sudo "$0" "$@"
fi

echo; echo "Take 'exec' out of the command and this script would get cat-ed twice. (Try it.)"; echo
cat $0

Here is another test using sudo -s

$ ps -fo pid,tty,user,args; ./test2.sh
  PID TT       USER     COMMAND
10775 pts/1    ubuntu   -bash
11496 pts/1    ubuntu    \_ ps -fo pid,tty,user,args

User ubuntu is running...
  PID TT       USER     COMMAND
10775 pts/1    ubuntu   -bash
11497 pts/1    ubuntu    \_ bash ./test2.sh
11500 pts/1    ubuntu        \_ ps -fo pid,tty,user,args

User root is running...
  PID TT       USER     COMMAND
11497 pts/1    root     sudo -s
11501 pts/1    root      \_ /bin/bash
11503 pts/1    root          \_ ps -fo pid,tty,user,args

$ cat test2.src
echo; echo "User $(whoami) is running..."
ps -fo pid,tty,user,args

$ cat test2.sh
#!/usr/bin/env bash

source test2.src

exec sudo -s < test2.src

And a simpler test using sudo -s

$ ./exec.sh
bash's PID:25194    user ID:7809
systemd(1)---bash(23064)---bash(25194)---pstree(25196)

Finally...
bash's PID:25199    user ID:0
systemd(1)---bash(23064)---sudo(25194)---bash(25199)---pstree(25201)

$ cat exec.sh
#!/usr/bin/env bash

pid=$$
id=$(id -u)
echo "bash's PID:$pid    user ID:$id"
pstree -ps $pid

# the quoted EOF is important to prevent shell expansion of the $...
exec sudo -s <<EOF
echo
echo "Finally..."
echo "bash's PID:\$\$    user ID:\$(id -u)"
pstree -ps $pid
EOF

Apply style to only first level of td tags

Is there a way to apply a Class' style to only ONE level of td tags?

Yes*:

.MyClass>tbody>tr>td { border: solid 1px red; }

But! The ‘>’ direct-child selector does not work in IE6. If you need to support that browser (which you probably do, alas), all you can do is select the inner element separately and un-set the style:

.MyClass td { border: solid 1px red; }
.MyClass td td { border: none; }

*Note that the first example references a tbody element not found in your HTML. It should have been in your HTML, but browsers are generally ok with leaving it out... they just add it in behind the scenes.

How does "304 Not Modified" work exactly?

When the browser puts something in its cache, it also stores the Last-Modified or ETag header from the server.

The browser then sends a request with the If-Modified-Since or If-None-Match header, telling the server to send a 304 if the content still has that date or ETag.

The server needs some way of calculating a date-modified or ETag for each version of each resource; this typically comes from the filesystem or a separate database column.

Where is svn.exe in my machine?

Generally, you can find the svn.exe on this location:

C:\Program Files\TortoiseSVN\bin

If you have already installed TortoiseSVN and still can't find the file the svn.exe on the given location, then you need to rerun the TortoiseSVN installer, click on 'Modify' and select Command Line Tools and after installation is successfully finished, you can now find the 'svn.exe' on given location on your drive.

How to access a property of an object (stdClass Object) member/element of an array?

You have an array. A PHP array is basically a "list of things". Your array has one thing in it. That thing is a standard class. You need to either remove the thing from your array

$object = array_shift($array);
var_dump($object->id);

Or refer to the thing by its index in the array.

var_dump( $array[0]->id );

Or, if you're not sure how many things are in the array, loop over the array

foreach($array as $key=>$value)
{
    var_dump($value->id);
    var_dump($array[$key]->id);
}

Adding 'serial' to existing column in Postgres

TL;DR

Here's a version where you don't need a human to read a value and type it out themselves.

CREATE SEQUENCE foo_a_seq OWNED BY foo.a;
SELECT setval('foo_a_seq', coalesce(max(a), 0) + 1, false) FROM foo;
ALTER TABLE foo ALTER COLUMN a SET DEFAULT nextval('foo_a_seq'); 

Another option would be to employ the reusable Function shared at the end of this answer.


A non-interactive solution

Just adding to the other two answers, for those of us who need to have these Sequences created by a non-interactive script, while patching a live-ish DB for instance.

That is, when you don't wanna SELECT the value manually and type it yourself into a subsequent CREATE statement.

In short, you can not do:

CREATE SEQUENCE foo_a_seq
    START WITH ( SELECT max(a) + 1 FROM foo );

... since the START [WITH] clause in CREATE SEQUENCE expects a value, not a subquery.

Note: As a rule of thumb, that applies to all non-CRUD (i.e.: anything other than INSERT, SELECT, UPDATE, DELETE) statements in pgSQL AFAIK.

However, setval() does! Thus, the following is absolutely fine:

SELECT setval('foo_a_seq', max(a)) FROM foo;

If there's no data and you don't (want to) know about it, use coalesce() to set the default value:

SELECT setval('foo_a_seq', coalesce(max(a), 0)) FROM foo;
--                         ^      ^         ^
--                       defaults to:       0

However, having the current sequence value set to 0 is clumsy, if not illegal.
Using the three-parameter form of setval would be more appropriate:

--                                             vvv
SELECT setval('foo_a_seq', coalesce(max(a), 0) + 1, false) FROM foo;
--                                                  ^   ^
--                                                is_called

Setting the optional third parameter of setval to false will prevent the next nextval from advancing the sequence before returning a value, and thus:

the next nextval will return exactly the specified value, and sequence advancement commences with the following nextval.

— from this entry in the documentation

On an unrelated note, you also can specify the column owning the Sequence directly with CREATE, you don't have to alter it later:

CREATE SEQUENCE foo_a_seq OWNED BY foo.a;

In summary:

CREATE SEQUENCE foo_a_seq OWNED BY foo.a;
SELECT setval('foo_a_seq', coalesce(max(a), 0) + 1, false) FROM foo;
ALTER TABLE foo ALTER COLUMN a SET DEFAULT nextval('foo_a_seq'); 

Using a Function

Alternatively, if you're planning on doing this for multiple columns, you could opt for using an actual Function.

CREATE OR REPLACE FUNCTION make_into_serial(table_name TEXT, column_name TEXT) RETURNS INTEGER AS $$
DECLARE
    start_with INTEGER;
    sequence_name TEXT;
BEGIN
    sequence_name := table_name || '_' || column_name || '_seq';
    EXECUTE 'SELECT coalesce(max(' || column_name || '), 0) + 1 FROM ' || table_name
            INTO start_with;
    EXECUTE 'CREATE SEQUENCE ' || sequence_name ||
            ' START WITH ' || start_with ||
            ' OWNED BY ' || table_name || '.' || column_name;
    EXECUTE 'ALTER TABLE ' || table_name || ' ALTER COLUMN ' || column_name ||
            ' SET DEFAULT nextVal(''' || sequence_name || ''')';
    RETURN start_with;
END;
$$ LANGUAGE plpgsql VOLATILE;

Use it like so:

INSERT INTO foo (data) VALUES ('asdf');
-- ERROR: null value in column "a" violates not-null constraint

SELECT make_into_serial('foo', 'a');
INSERT INTO foo (data) VALUES ('asdf');
-- OK: 1 row(s) affected

How to count the number of occurrences of an element in a List

To achieve that one can do it in several ways, namely:

Methods that return the number of occurrence of a single element:

Collection Frequency

Collections.frequency(animals, "bat");

Java Stream:

Filter

animals.stream().filter("bat"::equals).count();

Just iteration thought the list

public static long manually(Collection<?> c, Object o){
    int count = 0;
    for(Object e : c)
        if(e.equals(o))
            count++;
    return count;
}

Methods that create a map of frequencies:

Collectors.groupingBy

Map<String, Long> counts = 
       animals.stream()
              .collect(Collectors.groupingBy(Function.identity(), Collectors.counting()));

merge

Map<String, Long> map = new HashMap<>();
c.forEach(e -> map.merge(e, 1L, Long::sum));

Manually

Map<String, Integer> mp = new HashMap<>();
        animals.forEach(animal -> mp.compute(animal, (k, v) -> (v == null) ? 1 : v + 1));

A running example with all the methods:

public class Frequency {

    public static int frequency(Collection<?> c, Object o){
        return Collections.frequency(c, o);
    }

    public static long filter(Collection<?> c, Object o){
        return c.stream().filter(o::equals).count();
    }

    public static long manually(Collection<?> c, Object o){
        int count = 0;
        for(Object e : c)
            if(e.equals(o))
                count++;
        return count;
    }

    public static Map<?, Long> mapGroupBy(Collection<?> c){
        return c.stream()
                .collect(Collectors.groupingBy(Function.identity() , Collectors.counting()));
    }

    public static Map<Object, Long> mapMerge(Collection<?> c){
         Map<Object, Long> map = new HashMap<>();
         c.forEach(e -> map.merge(e, 1L, Long::sum));
         return map;
    }

    public static Map<Object, Long> manualMap(Collection<?> c){
        Map<Object, Long> map = new HashMap<>();
        c.forEach(e -> map.compute(e, (k, v) -> (v == null) ? 1 : v + 1));
        return map;
    }


    public static void main(String[] args){
        List<String> animals = new ArrayList<>();
        animals.add("bat");
        animals.add("owl");
        animals.add("bat");
        animals.add("bat");

        System.out.println(frequency(animals, "bat"));
        System.out.println(filter(animals,"bat"));
        System.out.println(manually(animals,"bat"));
        mapGroupBy(animals).forEach((k, v) -> System.out.println(k + " -> "+v));
        mapMerge(animals).forEach((k, v) -> System.out.println(k + " -> "+v));
        manualMap(animals).forEach((k, v) -> System.out.println(k + " -> "+v));
    }
}

The methods name should have reflected what those methods are doing, however, I used the name to reflect the approach being used instead (given that in the current context it is okey).

Use own username/password with git and bitbucket

I had to merge some of those good answers here! This works for me:

git remote set-url origin 'https://bitbucket.org/teamName/repo.git'

In the end, it will always prompt anyone who wants to pull from it

How can I get CMake to find my alternative Boost installation?

I had a similar issue, and I could use customized Boost libraries by adding the below lines to my CMakeLists.txt file:

set(Boost_NO_SYSTEM_PATHS TRUE)
if (Boost_NO_SYSTEM_PATHS)
  set(BOOST_ROOT "${CMAKE_CURRENT_SOURCE_DIR}/../../3p/boost")
  set(BOOST_INCLUDE_DIRS "${BOOST_ROOT}/include")
  set(BOOST_LIBRARY_DIRS "${BOOST_ROOT}/lib")
endif (Boost_NO_SYSTEM_PATHS)
find_package(Boost REQUIRED regex date_time system filesystem thread graph program_options)
include_directories(${BOOST_INCLUDE_DIRS})

How to get the number of columns in a matrix?

While size(A,2) is correct, I find it's much more readable to first define

rows = @(x) size(x,1); 
cols = @(x) size(x,2);

and then use, for example, like this:

howManyColumns_in_A = cols(A)
howManyRows_in_A    = rows(A)

It might appear as a small saving, but size(.., 1) and size(.., 2) must be some of the most commonly used functions, and they are not optimally readable as-is.

How to flush route table in windows?

route -f causes damage. So we need to either disconnect the correct parts of the routing table or find out how to rebuild it.

How to read multiple text files into a single RDD?

rdd = textFile('/data/{1.txt,2.txt}')

When to use AtomicReference in Java?

When do we use AtomicReference?

AtomicReference is flexible way to update the variable value atomically without use of synchronization.

AtomicReference support lock-free thread-safe programming on single variables.

There are multiple ways of achieving Thread safety with high level concurrent API. Atomic variables is one of the multiple options.

Lock objects support locking idioms that simplify many concurrent applications.

Executors define a high-level API for launching and managing threads. Executor implementations provided by java.util.concurrent provide thread pool management suitable for large-scale applications.

Concurrent collections make it easier to manage large collections of data, and can greatly reduce the need for synchronization.

Atomic variables have features that minimize synchronization and help avoid memory consistency errors.

Provide a simple example where AtomicReference should be used.

Sample code with AtomicReference:

String initialReference = "value 1";

AtomicReference<String> someRef =
    new AtomicReference<String>(initialReference);

String newReference = "value 2";
boolean exchanged = someRef.compareAndSet(initialReference, newReference);
System.out.println("exchanged: " + exchanged);

Is it needed to create objects in all multithreaded programs?

You don't have to use AtomicReference in all multi threaded programs.

If you want to guard a single variable, use AtomicReference. If you want to guard a code block, use other constructs like Lock /synchronized etc.

Can the Unix list command 'ls' output numerical chmod permissions?

Use this to display the Unix numerical permission values (octal values) and file name.

stat -c '%a %n' *

Use this to display the Unix numerical permission values (octal values) and the folder's sgid and sticky bit, user name of the owner, group name, total size in bytes and file name.

stat -c '%a %A %U %G %s %n' *

enter image description here

Add %y if you need time of last modification in human-readable format. For more options see stat.

Better version using an Alias

Using an alias is a more efficient way to accomplish what you need and it also includes color. The following displays your results organized by group directories first, display in color, print sizes in human readable format (e.g., 1K 234M 2G) edit your ~/.bashrc and add an alias for your account or globally by editing /etc/profile.d/custom.sh

Typing cls displays your new LS command results.

alias cls="ls -lha --color=always -F --group-directories-first |awk '{k=0;s=0;for(i=0;i<=8;i++){;k+=((substr(\$1,i+2,1)~/[rwxst]/)*2^(8-i));};j=4;for(i=4;i<=10;i+=3){;s+=((substr(\$1,i,1)~/[stST]/)*j);j/=2;};if(k){;printf(\"%0o%0o \",s,k);};print;}'"

Alias is the most efficient solution

Folder Tree

While you are editing your bashrc or custom.sh include the following alias to see a graphical representation where typing lstree will display your current folder tree structure

alias lstree="ls -R | grep ":$" | sed -e 's/:$//' -e 's/[^-][^\/]*\//--/g' -e 's/^/   /' -e 's/-/|/'"

It would display:

   |-scripts
   |--mod_cache_disk
   |--mod_cache_d
   |---logs
   |-run_win
   |-scripts.tar.gz

jQuery Scroll to bottom of page/iframe

If you want a nice slow animation scroll, for any anchor with href="#bottom" this will scroll you to the bottom:

$("a[href='#bottom']").click(function() {
  $("html, body").animate({ scrollTop: $(document).height() }, "slow");
  return false;
});

Feel free to change the selector.

What is log4j's default log file dumping path

You can see the log info in the console view of your IDE if you are not using any log4j properties to generate log file. You can define log4j.properties in your project so that those properties would be used to generate log file. A quick sample is listed below.

# Global logging configuration
log4j.rootLogger=DEBUG, stdout, R

# SQL Map logging configuration...
log4j.logger.com.ibatis=INFO
log4j.logger.com.ibatis.common.jdbc.SimpleDataSource=INFO
log4j.logger.com.ibatis.common.jdbc.ScriptRunner=INFO
log4j.logger.com.ibatis.SQLMap.engine.impl.SQL MapClientDelegate=INFO

log4j.logger.java.sql.Connection=INFO
log4j.logger.java.sql.Statement=DEBUG
log4j.logger.java.sql.PreparedStatement=DEBUG
log4j.logger.java.sql.ResultSet=INFO

log4j.logger.org.apache.http=ERROR

log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

# Pattern to output the caller's file name and line number.
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] (%F:%L) - %m%n

log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=MyLog.log
log4j.appender.R.MaxFileSize=50000KB
log4j.appender.R.Encoding=UTF-8

# Keep one backup file
log4j.appender.R.MaxBackupIndex=1

log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%d %5p [%t] (%F\:%L) - %m%n

PHP Unset Array value effect on other indexes

Test it yourself, but here's the output.

php -r '$a=array("a","b","c"); print_r($a); unset($a[1]); print_r($a);'
Array
(
    [0] => a
    [1] => b
    [2] => c
)
Array
(
    [0] => a
    [2] => c
)

Inserting NOW() into Database with CodeIgniter's Active Record

Using the date helper worked for me

$this->load->helper('date');

You can find documentation for date_helper here.

$data = array(
  'created' => now(),
  'modified' => now()
);

$this->db->insert('TABLENAME', $data);

Android get Current UTC time

see my answer here:

How can I get the current date and time in UTC or GMT in Java?

I've fully tested it by changing the timezones on the emulator

How to write a full path in a batch file having a folder name with space?

Put double quotes around the path that has spaces like this:

REGSVR32 "E:\Documents and Settings\All Users\Application Data\xyz.dll"

Server configuration by allow_url_fopen=0 in

Use this code in your php script (first lines)

ini_set('allow_url_fopen',1);

How to redirect to a route in laravel 5 by using href tag if I'm not using blade or any template?

In you app config file change the url to localhost/example/public

Then when you want to link to something

<a href="{{ url('page') }}">Some Text</a>

without blade

<a href="<?php echo url('page') ?>">Some Text</a>

Do you have to include <link rel="icon" href="favicon.ico" type="image/x-icon" />?

Many people set their cookie path to /. That will cause every favicon request to send a copy of the sites cookies, at least in chrome. Addressing your favicon to your cookieless domain should correct this.

<link rel="icon" href="https://cookieless.MySite.com/favicon.ico" type="image/x-icon" />

Depending on how much traffic you get, this may be the most practical reason for adding the link.

Info on setting up a cookieless domain:

http://www.ravelrumba.com/blog/static-cookieless-domain/

JavaScript window resize event

var EM = new events_managment();

EM.addEvent(window, 'resize', function(win,doc, event_){
    console.log('resized');
    //EM.removeEvent(win,doc, event_);
});

function events_managment(){
    this.events = {};
    this.addEvent = function(node, event_, func){
        if(node.addEventListener){
            if(event_ in this.events){
                node.addEventListener(event_, function(){
                    func(node, event_);
                    this.events[event_](win_doc, event_);
                }, true);
            }else{
                node.addEventListener(event_, function(){
                    func(node, event_);
                }, true);
            }
            this.events[event_] = func;
        }else if(node.attachEvent){

            var ie_event = 'on' + event_;
            if(ie_event in this.events){
                node.attachEvent(ie_event, function(){
                    func(node, ie_event);
                    this.events[ie_event]();
                });
            }else{
                node.attachEvent(ie_event, function(){
                    func(node, ie_event);
                });
            }
            this.events[ie_event] = func;
        }
    }
    this.removeEvent = function(node, event_){
        if(node.removeEventListener){
            node.removeEventListener(event_, this.events[event_], true);
            this.events[event_] = null;
            delete this.events[event_];
        }else if(node.detachEvent){
            node.detachEvent(event_, this.events[event_]);
            this.events[event_] = null;
            delete this.events[event_];
        }
    }
}

The matching wildcard is strict, but no declaration can be found for element 'tx:annotation-driven'

You have some errors in your appcontext.xml:

  • Use *-2.5.xsd

    xsi:schemaLocation="http://www.springframework.org/schema/beans 
      http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
      http://www.springframework.org/schema/aop 
      http://www.springframework.org/schema/aop/spring-aop-2.5.xsd
      http://www.springframework.org/schema/context 
      http://www.springframework.org/schema/context/spring-context-2.5.xsd
      http://www.springframework.org/schema/tx 
      http://www.springframework.org/schema/tx/spring-tx-2.5.xsd"
    
  • Typos in tx:annotation-driven and context:component-scan (. instead of -)

    <tx:annotation-driven transaction-manager="transactionManager" />
    <context:component-scan base-package="com.mmycompany" />
    

How to get file URL using Storage facade in laravel 5?

If you need absolute URL of the file, use below code:

$file_path = \Storage::url($filename);
$url = asset($file_path);
// Output: http://example.com/storage/filename.jpg

UILabel text margin

Just add spaces to the left if it's a single line, more than 1 line will have 0 padding again.

[self.myLabel setText:[NSString stringWithFormat:@"   %@", self.myShortString]];

Docker - Bind for 0.0.0.0:4000 failed: port is already allocated

It might be a conflict with the same port specified in docker-compose.yml and docker-compose.override.yml or the same port specified explicitly and using an environment variable.

I had a docker-compose.yml with ports on a container specified using environment variables, and a docker-compose.override.yml with one of the same ports specified explicitly. Apparently docker tried to open both on the same container. docker container ls -a listed neither because the container could not start and list the ports.

How to wait until an element is present in Selenium?

FluentWait throws a NoSuchElementException is case of the confusion

org.openqa.selenium.NoSuchElementException;     

with

java.util.NoSuchElementException

in

.ignoring(NoSuchElementException.class)

How to consume REST in Java

Apache Http Client APIs are very commonly used for calling HTTP Rest services.

Here is one of example of consuming HTTP GET call.

import java.io.IOException;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.impl.client.HttpClientBuilder;

public class CallHTTPGetService {

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


    HttpClient client = HttpClientBuilder.create().build();
    HttpUriRequest httpUriRequest = new HttpGet("URL");

    HttpResponse response = client.execute(httpUriRequest);
    System.out.println(response);

}
}

Use following maven dependency if using Maven project.

<dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpclient</artifactId>
        <version>4.5.1</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.apache.httpcomponents/httpmime -->
    <dependency>
        <groupId>org.apache.httpcomponents</groupId>
        <artifactId>httpmime</artifactId>
        <version>4.5.1</version>
    </dependency>

How to increase Heap size of JVM

Use -Xms1024m -Xmx1024m to control your heap size (1024m is only for demonstration, the exact number depends your system memory). Setting minimum and maximum heap size to the same is usually a best practice since JVM doesn't have to increase heap size at runtime.

Make $JAVA_HOME easily changable in Ubuntu

I know this is a long cold question, but it comes up every time there is a new or recent major Java release. Now this would easily apply to 6 and 7 swapping.

I have done this in the past with update-java-alternatives: http://manpages.ubuntu.com/manpages/hardy/man8/update-java-alternatives.8.html

Find the index of a dict within a list, by matching the dict's value

I needed a more general solution to account for the possibility of multiple dictionaries in the list having the key value, and a straightforward implementation using list comprehension:

dict_indices = [i for i, d in enumerate(dict_list) if d[dict_key] == key_value] 

NameError: name 'datetime' is not defined

It can also be used as below:

from datetime import datetime
start_date = datetime(2016,3,1)
end_date = datetime(2016,3,10)

Align two inline-blocks left and right on same line

If you're already using JavaScript to center stuff when the screen is too small (as per your comment for your header), why not just undo floats/margins with JavaScript while you're at it and use floats and margins normally.

You could even use CSS media queries to reduce the amount JavaScript you're using.

How to convert JSON to a Ruby hash

You could also use Rails' with_indifferent_access method so you could access the body with either symbols or strings.

value = '{"val":"test","val1":"test1","val2":"test2"}'
json = JSON.parse(value).with_indifferent_access

then

json[:val] #=> "test"

json["val"] #=> "test"

MySQL CURRENT_TIMESTAMP on create and on update

I would say you don't need to have the DEFAULT CURRENT_TIMESTAMP on your ts_update: if it is empty, then it is not updated, so your 'last update' is the ts_create.

Undoing a git rebase

The easiest way would be to find the head commit of the branch as it was immediately before the rebase started in the reflog...

git reflog

and to reset the current branch to it (with the usual caveats about being absolutely sure before reseting with the --hard option).

Suppose the old commit was HEAD@{5} in the ref log:

git reset --hard HEAD@{5}

In Windows, you may need to quote the reference:

git reset --hard "HEAD@{5}"

You can check the history of the candidate old head by just doing a git log HEAD@{5} (Windows: git log "HEAD@{5}").

If you've not disabled per branch reflogs you should be able to simply do git reflog branchname@{1} as a rebase detaches the branch head before reattaching to the final head. I would double check this, though as I haven't verified this recently.

Per default, all reflogs are activated for non-bare repositories:

[core]
    logAllRefUpdates = true

jQuery - Sticky header that shrinks when scrolling down

This should be what you are looking for using jQuery.

$(function(){
  $('#header_nav').data('size','big');
});

$(window).scroll(function(){
  if($(document).scrollTop() > 0)
{
    if($('#header_nav').data('size') == 'big')
    {
        $('#header_nav').data('size','small');
        $('#header_nav').stop().animate({
            height:'40px'
        },600);
    }
}
else
  {
    if($('#header_nav').data('size') == 'small')
      {
        $('#header_nav').data('size','big');
        $('#header_nav').stop().animate({
            height:'100px'
        },600);
      }  
  }
});

Demonstration: http://jsfiddle.net/jezzipin/JJ8Jc/

How do I import a .dmp file into Oracle?

I am Using Oracle Database Express Edition 11g Release 2.

Follow the Steps:

Open run SQl Command Line

Step 1: Login as system user

       SQL> connect system/tiger

Step 2 : SQL> CREATE USER UserName IDENTIFIED BY Password;

Step 3 : SQL> grant dba to UserName ;

Step 4 : SQL> GRANT UNLIMITED TABLESPACE TO UserName;

Step 5:

        SQL> CREATE BIGFILE TABLESPACE TSD_UserName
             DATAFILE 'tbs_perm_03.dat'
             SIZE 8G
             AUTOEXTEND ON;

Open Command Prompt in Windows or Terminal in Ubuntu. Then Type:

Note : if you Use Ubuntu then replace " \" to " /" in path.

Step 6: C:\> imp UserName/password@localhost file=D:\abc\xyz.dmp log=D:\abc\abc_1.log full=y;

Done....

I hope you Find Right solution here.

Thanks.

How to input automatically when running a shell over SSH?

For general command-line automation, Expect is the classic tool. Or try pexpect if you're more comfortable with Python.

Here's a similar question that suggests using Expect: Use expect in bash script to provide password to SSH command

Can you have a <span> within a <span>?

Yes. You can have a span within a span. Your problem stems from something else.

XMLHttpRequest blocked by CORS Policy

I believe sideshowbarker 's answer here has all the info you need to fix this. If your problem is just No 'Access-Control-Allow-Origin' header is present on the response you're getting, you can set up a CORS proxy to get around this. Way more info on it in the linked answer

What does appending "?v=1" to CSS and JavaScript URLs in link and script tags do?

Javascript files are often cached by the browser for a lot longer than you might expect.

This can often result in unexpected behaviour when you release a new version of your JS file.

Therefore, it is common practice to add a QueryString parameter to the URL for the javascript file. That way, the browser caches the Javascript file with v=1. When you release a new version of your javascript file you change the url's to v=2 and the browser will be forced to download a new copy.

How can I combine multiple rows into a comma-delimited list in Oracle?

I have always had to write some PL/SQL for this or I just concatenate a ',' to the field and copy into an editor and remove the CR from the list giving me the single line.

That is,

select country_name||', ' country from countries

A little bit long winded both ways.

If you look at Ask Tom you will see loads of possible solutions but they all revert to type declarations and/or PL/SQL

Ask Tom

Use JSTL forEach loop's varStatus as an ID

Its really helped me to dynamically generate ids of showDetailItem for the below code.

<af:forEach id="fe1" items="#{viewScope.bean.tranTypeList}" var="ttf" varStatus="ttfVs" > 
<af:showDetailItem  id ="divIDNo${ttfVs.count}" text="#{ttf.trandef}"......>

if you execute this line <af:outputText value="#{ttfVs}"/> prints the below:

{index=3, count=4, last=false, first=false, end=8, step=1, begin=0}

Static nested class in Java, why?

Well, for one thing, non-static inner classes have an extra, hidden field that points to the instance of the outer class. So if the Entry class weren't static, then besides having access that it doesn't need, it would carry around four pointers instead of three.

As a rule, I would say, if you define a class that's basically there to act as a collection of data members, like a "struct" in C, consider making it static.

How do I find numeric columns in Pandas?

Simple one-liner:

df.select_dtypes('number').columns

Deserializing JSON array into strongly typed .NET object

try

List<TheUser> friends = jsonSerializer.Deserialize<List<TheUser>>(response);

Regular Expression: Allow letters, numbers, and spaces (with at least one letter or number)

Simply u can add this to jquery.validationEngine-en.js file

    "onlyLetterNumberSp": {
                "regex": ^[A-Za-z0-9 _]*[A-Za-z0-9][A-Za-z0-9 _]*$,
                "alertText": "* No special characters allowed"
          },

and call it in text field as

<input type="text" class="form-control validate[required,custom[onlyLetterNumberSp]]"  id="title" name="title" placeholder="Title"/>

Making PHP var_dump() values display one line per value

Personally I like the replacement function provided by Symfony's var dumper component

Install with composer require symfony/var-dumper and just use dump($var)

It takes care of the rest. I believe there's also a bit of JS injected there to allow you to interact with the output a bit.

How to add a TextView to a LinearLayout dynamically in Android?

TextView rowTextView = (TextView)getLayoutInflater().inflate(R.layout.yourTextView, null);
        rowTextView.setText(text);
        layout.addView(rowTextView);

This is how I'm using this:

 private List<Tag> tags = new ArrayList<>();


if(tags.isEmpty()){
        Gson gson = new Gson();
        Type listType = new TypeToken<List<Tag>>() {
        }.getType();
        tags = gson.fromJson(tour.getTagsJSONArray(), listType);
    }



if (flowLayout != null) {
        if(!tags.isEmpty()) {
            Log.e(TAG, "setTags: "+ flowLayout.getChildCount() );
            flowLayout.removeAllViews();
            for (Tag tag : tags) {
                FlowLayout.LayoutParams lparams = new FlowLayout.LayoutParams(FlowLayout.LayoutParams.WRAP_CONTENT, FlowLayout.LayoutParams.WRAP_CONTENT);
                lparams.setMargins(PixelUtil.dpToPx(this, 0), PixelUtil.dpToPx(this, 5), PixelUtil.dpToPx(this, 10), PixelUtil.dpToPx(this, 5));// llp.setMargins(left, top, right, bottom);
                TextView rowTextView = (TextView) getLayoutInflater().inflate(R.layout.tag, null);
                rowTextView.setText(tag.getLabel());
                rowTextView.setLayoutParams(lparams);
                flowLayout.addView(rowTextView);
            }
        }
        Log.e(TAG, "setTags: after "+ flowLayout.getChildCount() );
    }

And this is my custom TextView named tag:

<?xml version="1.0" encoding="utf-8"?><TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"    
android:textSize="10dp"
android:textAllCaps="true"
fontPath="@string/font_light"
android:background="@drawable/tag_shape"
android:paddingLeft="11dp"
android:paddingTop="6dp"
android:paddingRight="11dp"
android:paddingBottom="6dp">

this is my tag_shape:

<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="#f2f2f2" />
<corners android:radius="15dp" />
</shape>

efect:

enter image description here

In other place I'm adding textviews with language names from dialog with listview:

enter image description here

enter image description here

Querying Datatable with where condition

something like this ? :

DataTable dt = ...
DataView dv = new DataView(dt);
dv.RowFilter = "(EmpName != 'abc' or EmpName != 'xyz') and (EmpID = 5)"

Is it what you are searching for?

How to export dataGridView data Instantly to Excel on button click?

I did not intend to steal @Jake and @Cornelius's answer, so i tried editing it. but it was rejected. Anyways, the only improvement I have to point out is about avoiding extra blank column in excel after paste. Adding one line dataGridView1.RowHeadersVisible = false; hides so called "Row Header" which appears on the left most part of DataGridView, and so it is not selected and copied to clipboard when you do dataGridView1.SelectAll();

private void copyAlltoClipboard()
    {
        //to remove the first blank column from datagridview
        dataGridView1.RowHeadersVisible = false;
        dataGridView1.SelectAll();
        DataObject dataObj = dataGridView1.GetClipboardContent();
        if (dataObj != null)
            Clipboard.SetDataObject(dataObj);
    }
    private void button3_Click_1(object sender, EventArgs e)
    {
        copyAlltoClipboard();
        Microsoft.Office.Interop.Excel.Application xlexcel;
        Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
        Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
        object misValue = System.Reflection.Missing.Value;
        xlexcel = new Excel.Application();
        xlexcel.Visible = true;
        xlWorkBook = xlexcel.Workbooks.Add(misValue);
        xlWorkSheet = (Excel.Worksheet)xlWorkBook.Worksheets.get_Item(1);
        Excel.Range CR = (Excel.Range)xlWorkSheet.Cells[1, 1];
        CR.Select();
        xlWorkSheet.PasteSpecial(CR, Type.Missing, Type.Missing, Type.Missing, Type.Missing, Type.Missing, true);          
    }

What is the proper declaration of main in C++?

The exact wording of the latest published standard (C++14) is:

An implementation shall allow both

  • a function of () returning int and

  • a function of (int, pointer to pointer to char) returning int

as the type of main.

This makes it clear that alternative spellings are permitted so long as the type of main is the type int() or int(int, char**). So the following are also permitted:

  • int main(void)
  • auto main() -> int
  • int main ( )
  • signed int main()
  • typedef char **a; typedef int b, e; e main(b d, a c)

Batch file include external file for variables

:: savevars.bat
:: Use $ to prefix any important variable to save it for future runs.

@ECHO OFF
SETLOCAL

REM Load variables
IF EXIST config.txt FOR /F "delims=" %%A IN (config.txt) DO SET "%%A"

REM Change variables
IF NOT DEFINED $RunCount (
    SET $RunCount=1
) ELSE SET /A $RunCount+=1

REM Display variables
SET $

REM Save variables
SET $>config.txt

ENDLOCAL
PAUSE
EXIT /B

Output:

$RunCount=1

$RunCount=2

$RunCount=3

The technique outlined above can also be used to share variables among multiple batch files.

Source: http://www.incodesystems.com/products/batchfi1.htm

How do I implement Cross Domain URL Access from an Iframe using Javascript?

You might want to take a look at these questions/answers ; they could give you some informations concerning your problem :

To make things short : accessing iframe from another domain is not possible, for security reasons -- which explains the error message you are getting.


The Same origin policy page on wikipedia brings some informations about that security measure :

In a nutshell, the policy permits scripts running on pages originating from the same site to access each other's methods and properties with no specific restrictions — but prevents access to most methods and properties across pages on different sites.

A strict separation between content provided by unrelated sites must be maintained on client side to prevent the loss of data confidentiality or integrity.

How do you clear your Visual Studio cache on Windows Vista?

I had the same issue but when i deleted the cached items from Temp folder the build failed.

In order to make the build work again I had to close the project and reopen it.

Adding a Button to a WPF DataGrid

XAML :

<DataGrid x:Name="dgv_Students" AutoGenerateColumns="False"  ItemsSource="{Binding People}" Margin="10,20,10,0" Style="{StaticResource AzureDataGrid}" FontFamily="B Yekan" Background="#FFB9D1BA" >
                <DataGrid.Columns>
                    <DataGridTemplateColumn>
                        <DataGridTemplateColumn.CellTemplate>
                            <DataTemplate>
                                <Button Click="Button_Click_dgvs">Text</Button>
                            </DataTemplate>
                        </DataGridTemplateColumn.CellTemplate>
                    </DataGridTemplateColumn>
                    </DataGrid.Columns>

Code Behind :

       private IEnumerable<DataGridRow> GetDataGridRowsForButtons(DataGrid grid)
{ //IQueryable 
    var itemsSource = grid.ItemsSource as IEnumerable;
    if (null == itemsSource) yield return null;
    foreach (var item in itemsSource)
    {
        var row = grid.ItemContainerGenerator.ContainerFromItem(item) as DataGridRow;
        if (null != row & row.IsSelected) yield return row;
    }
}

void Button_Click_dgvs(object sender, RoutedEventArgs e)
{

    for (var vis = sender as Visual; vis != null; vis = VisualTreeHelper.GetParent(vis) as Visual)
        if (vis is DataGridRow)
        {
           // var row = (DataGrid)vis;

            var rows = GetDataGridRowsForButtons(dgv_Students);
            string id;
            foreach (DataGridRow dr in rows)
            {
                id = (dr.Item as tbl_student).Identification_code;
                MessageBox.Show(id);
                 break;
            }
            break;
        }
}

After clicking on the Button, the ID of that row is returned to you and you can use it for your Button name.

Select first empty cell in column F starting from row 1. (without using offset )

I found this thread while trying to carry out a similar task. In the end, I used

Range("F:F").SpecialCells(xlBlanks).Areas(1)(1).Select

Which works fine as long as there is a blank cell in the intersection of the specified range and the used range of the worksheet.

The areas property is not needed to find the absolute first blank in the range, but is useful for finding subsequent non consecutive blanks.

Random number generator only generating one random number

I solved the problem by using the Rnd() function:

Function RollD6() As UInteger
        RollD6 = (Math.Floor(6 * Rnd())) + 1
        Return RollD6
End Function

When the form loads, I use the Randomize() method to make sure I don't always get the same sequence of random numbers from run to run.

How to get the indexpath.row when an element is activated?

Since the sender of the event handler is the button itself, I'd use the button's tag property to store the index, initialized in cellForRowAtIndexPath.

But with a little more work I'd do in a completely different way. If you are using a custom cell, this is how I would approach the problem:

  • add an 'indexPath` property to the custom table cell
  • initialize it in cellForRowAtIndexPath
  • move the tap handler from the view controller to the cell implementation
  • use the delegation pattern to notify the view controller about the tap event, passing the index path

Playing sound notifications using Javascript?

Following code might help you to play sound in a web page using javascript only. You can see further details at http://sourcecodemania.com/playing-sound-javascript-flash-player/

<script>
function getPlayer(pid) {
    var obj = document.getElementById(pid);
    if (obj.doPlay) return obj;
    for(i=0; i<obj.childNodes.length; i++) {
        var child = obj.childNodes[i];
        if (child.tagName == "EMBED") return child;
    }
}
function doPlay(fname) {
    var player=getPlayer("audio1");
    player.play(fname);
}
function doStop() {
    var player=getPlayer("audio1");
    player.doStop();
}
</script>

<form>
<input type="button" value="Play Sound" onClick="doPlay('texi.wav')">
<a href="#" onClick="doPlay('texi.wav')">[Play]</a>
<object classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
    width="40"
    height="40"
    id="audio1"
    align="middle">
    <embed src="wavplayer.swf?h=20&w=20"
        bgcolor="#ffffff"
        width="40"
        height="40"
        allowScriptAccess="always"
        type="application/x-shockwave-flash"
        pluginspage="http://www.macromedia.com/go/getflashplayer"
    />
</object>

<input type="button" value="Stop Sound" onClick="doStop()">
</form>

What are NR and FNR and what does "NR==FNR" imply?

Look up NR and FNR in the awk manual and then ask yourself what is the condition under which NR==FNR in the following example:

$ cat file1
a
b
c

$ cat file2
d
e

$ awk '{print FILENAME, NR, FNR, $0}' file1 file2
file1 1 1 a
file1 2 2 b
file1 3 3 c
file2 4 1 d
file2 5 2 e

How to call a function after delay in Kotlin?

You can use Schedule

inline fun Timer.schedule(
    delay: Long, 
    crossinline action: TimerTask.() -> Unit
): TimerTask (source)

example (thanks @Nguyen Minh Binh - found it here: http://jamie.mccrindle.org/2013/02/exploring-kotlin-standard-library-part-3.html)

import java.util.Timer
import kotlin.concurrent.schedule

Timer("SettingUp", false).schedule(500) { 
   doSomething()
}

Express.js req.body undefined

Use app.use(bodyparser.json()); before routing. // . app.use("/api", routes);

Fixed size div?

.myDiv { height: 150px; width 150px; }

<div class="mainDiv">
   <div class="myDiv"></div>
   <div class="myDiv"></div>
   <div class="myDiv"></div>
</div>

How to change cursor from pointer to finger using jQuery?

Update! New & improved! Find plugin @ GitHub!


On another note, while that method is simple, I've created a jQuery plug (found at this jsFiddle, just copy and past code between comment lines) that makes changing the cursor on any element as simple as $("element").cursor("pointer").

But that's not all! Act now and you'll get the hand functions position & ishover for no extra charge! That's right, 2 very handy cursor functions ... FREE!

They work as simple as seen in the demo:

$("h3").cursor("isHover"); // if hovering over an h3 element, will return true, 
    // else false
// also handy as
$("h2, h3").cursor("isHover"); // unless your h3 is inside an h2, this will be 
    // false as it checks to see if cursor is hovered over both elements, not just the last!
//  And to make this deal even sweeter - use the following to get a jQuery object
//       of ALL elements the cursor is currently hovered over on demand!
$.cursor("isHover");

Also:

$.cursor("position"); // will return the current cursor position as { x: i, y: i }
    // at anytime you call it!

Supplies are limited, so Act Now!

A Parser-blocking, cross-origin script is invoked via document.write - how to circumvent it?

Don't use document.write, here is workaround:

var script = document.createElement('script');  
script.src = "....";  
document.head.appendChild(script);

Constructors in Go

There are some equivalents of constructors for when the zero values can't make sensible default values or for when some parameter is necessary for the struct initialization.

Supposing you have a struct like this :

type Thing struct {
    Name  string
    Num   int
}

then, if the zero values aren't fitting, you would typically construct an instance with a NewThing function returning a pointer :

func NewThing(someParameter string) *Thing {
    p := new(Thing)
    p.Name = someParameter
    p.Num = 33 // <- a very sensible default value
    return p
}

When your struct is simple enough, you can use this condensed construct :

func NewThing(someParameter string) *Thing {
    return &Thing{someParameter, 33}
}

If you don't want to return a pointer, then a practice is to call the function makeThing instead of NewThing :

func makeThing(name string) Thing {
    return Thing{name, 33}
}

Reference : Allocation with new in Effective Go.

How to suppress binary file matching results in grep

There are three options, that you can use. -I is to exclude binary files in grep. Other are for line numbers and file names.

grep -I -n -H 


-I -- process a binary file as if it did not contain matching data; 
-n -- prefix each line of output with the 1-based line number within its input file
-H -- print the file name for each match

So this might be a way to run grep:

grep -InH your-word *

Google Maps API v2: How to make markers clickable?

All markers in Google Android Maps Api v2 are clickable. You don't need to set any additional properties to your marker. What you need to do - is to register marker click callback to your googleMap and handle click within callback:

public class MarkerDemoActivity extends android.support.v4.app.FragmentActivity
    implements OnMarkerClickListener
{
    private Marker myMarker;    

    private void setUpMap()
    {
        .......
        googleMap.setOnMarkerClickListener(this);

        myMarker = googleMap.addMarker(new MarkerOptions()
                    .position(latLng)
                    .title("My Spot")
                    .snippet("This is my spot!")
                    .icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_AZURE)));
        ......
    }

    @Override
    public boolean onMarkerClick(final Marker marker) {

        if (marker.equals(myMarker)) 
        {
            //handle click here
        }
    }
}

here is a good guide on google about marker customization

How can I create a dynamically sized array of structs?

You've tagged this as C++ as well as C.

If you're using C++ things are a lot easier. The standard template library has a template called vector which allows you to dynamically build up a list of objects.

#include <stdio.h>
#include <vector>

typedef std::vector<char*> words;

int main(int argc, char** argv) {

        words myWords;

        myWords.push_back("Hello");
        myWords.push_back("World");

        words::iterator iter;
        for (iter = myWords.begin(); iter != myWords.end(); ++iter) {
                printf("%s ", *iter);
        }

        return 0;
}

If you're using C things are a lot harder, yes malloc, realloc and free are the tools to help you. You might want to consider using a linked list data structure instead. These are generally easier to grow but don't facilitate random access as easily.

#include <stdio.h>
#include <stdlib.h>

typedef struct s_words {
        char* str;
        struct s_words* next;
} words;

words* create_words(char* word) {
        words* newWords = malloc(sizeof(words));
        if (NULL != newWords){
                newWords->str = word;
                newWords->next = NULL;
        }
        return newWords;
}

void delete_words(words* oldWords) {
        if (NULL != oldWords->next) {
                delete_words(oldWords->next);
        }
        free(oldWords);
}

words* add_word(words* wordList, char* word) {
        words* newWords = create_words(word);
        if (NULL != newWords) {
                newWords->next = wordList;
        }
        return newWords;
}

int main(int argc, char** argv) {

        words* myWords = create_words("Hello");
        myWords = add_word(myWords, "World");

        words* iter;
        for (iter = myWords; NULL != iter; iter = iter->next) {
                printf("%s ", iter->str);
        }
        delete_words(myWords);
        return 0;
}

Yikes, sorry for the worlds longest answer. So WRT to the "don't want to use a linked list comment":

#include <stdio.h>  
#include <stdlib.h>

typedef struct {
    char** words;
    size_t nWords;
    size_t size;
    size_t block_size;
} word_list;

word_list* create_word_list(size_t block_size) {
    word_list* pWordList = malloc(sizeof(word_list));
    if (NULL != pWordList) {
        pWordList->nWords = 0;
        pWordList->size = block_size;
        pWordList->block_size = block_size;
        pWordList->words = malloc(sizeof(char*)*block_size);
        if (NULL == pWordList->words) {
            free(pWordList);
            return NULL;    
        }
    }
    return pWordList;
}

void delete_word_list(word_list* pWordList) {
    free(pWordList->words);
    free(pWordList);
}

int add_word_to_word_list(word_list* pWordList, char* word) {
    size_t nWords = pWordList->nWords;
    if (nWords >= pWordList->size) {
        size_t newSize = pWordList->size + pWordList->block_size;
        void* newWords = realloc(pWordList->words, sizeof(char*)*newSize); 
        if (NULL == newWords) {
            return 0;
        } else {    
            pWordList->size = newSize;
            pWordList->words = (char**)newWords;
        }

    }

    pWordList->words[nWords] = word;
    ++pWordList->nWords;


    return 1;
}

char** word_list_start(word_list* pWordList) {
        return pWordList->words;
}

char** word_list_end(word_list* pWordList) {
        return &pWordList->words[pWordList->nWords];
}

int main(int argc, char** argv) {

        word_list* myWords = create_word_list(2);
        add_word_to_word_list(myWords, "Hello");
        add_word_to_word_list(myWords, "World");
        add_word_to_word_list(myWords, "Goodbye");

        char** iter;
        for (iter = word_list_start(myWords); iter != word_list_end(myWords); ++iter) {
                printf("%s ", *iter);
        }

        delete_word_list(myWords);

        return 0;
}

Add User to Role ASP.NET Identity

I had the same challenge. This is the solution I found to add users to roles.

internal class Security
{
    ApplicationDbContext context = new ApplicationDbContext();

    internal void AddUserToRole(string userName, string roleName)
    {
        var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));

        try
        {
            var user = UserManager.FindByName(userName);
            UserManager.AddToRole(user.Id, roleName);
            context.SaveChanges();
        }
        catch
        {
            throw;
        }
    }
}

Flexbox: 4 items per row

Add a width to the .child elements. I personally would use percentages on the margin-left if you want to have it always 4 per row.

DEMO

.child {
    display: inline-block;
    background: blue;
    margin: 10px 0 0 2%;
    flex-grow: 1;
    height: 100px;
    width: calc(100% * (1/4) - 10px - 1px);
}

Get number of digits with JavaScript

Problem statement: Count number/string not using string.length() jsfunction. Solution: we could do this through the Forloop. e.g

for (x=0; y>=1 ; y=y/=10){
  x++;
}

if (x <= 10) {
  this.y = this.number;                
}   

else{
  this.number = this.y;
}    

}

Java string replace and the NUL (NULL, ASCII 0) character?

Does replacing a character in a String with a null character even work in Java?

No.

Would this be the culprit to the funky characters?

Quite likely.

How to convert SecureString to System.String?

In my opinion, extension methods are the most comfortable way to solve this.

I took Steve in CO's excellent answer and put it into an extension class as follows, together with a second method I added to support the other direction (string -> secure string) as well, so you can create a secure string and convert it into a normal string afterwards:

public static class Extensions
{
    // convert a secure string into a normal plain text string
    public static String ToPlainString(this System.Security.SecureString secureStr)
    {
        String plainStr=new System.Net.NetworkCredential(string.Empty, secureStr).Password;
        return plainStr;
    }

    // convert a plain text string into a secure string
    public static System.Security.SecureString ToSecureString(this String plainStr)
    {
        var secStr = new System.Security.SecureString(); secStr.Clear();
        foreach (char c in plainStr.ToCharArray())
        {
            secStr.AppendChar(c);
        }
        return secStr;
    }
}

With this, you can now simply convert your strings back and forth like so:

// create a secure string
System.Security.SecureString securePassword = "MyCleverPwd123".ToSecureString(); 
// convert it back to plain text
String plainPassword = securePassword.ToPlainString();  // convert back to normal string

But keep in mind the decoding method should only be used for testing.

How to use z-index in svg elements?

Another solution would be to use divs, which do use zIndex to contain the SVG elements.As here: https://stackoverflow.com/a/28904640/4552494

SQL Stored Procedure set variables using SELECT

select @currentTerm = CurrentTerm, @termID = TermID, @endDate = EndDate
    from table1
    where IsCurrent = 1

JS regex: replace all digits in string

The /g modifier is used to perform a global match (find all matches rather than stopping after the first)

You can use \d for digit, as it is shorter than [0-9].

JavaScript:

var s = "04.07.2012"; 
echo(s.replace(/\d/g, "X"));

Output:

XX.XX.XXXX

How to figure out the SMTP server host?

You could send yourself an email an look in the email header (In Outlook: Open the mail, View->Options, there is 'Internet headers)

How to dispatch a Redux action with a timeout?

You can do this with redux-thunk. There is a guide in redux document for async actions like setTimeout.

What is the convention in JSON for empty vs. null?

Empty array for empty collections and null for everything else.

Make div scrollable

Place this into your DIV style

overflow:scroll;

Update multiple values in a single statement

Try this:

update MasterTbl M,
       (select sum(X) as sX,
               sum(Y) as sY,
               sum(Z) as sZ,
               MasterID
        from   DetailTbl
        group by MasterID) A
set
  M.TotalX=A.sX,
  M.TotalY=A.sY,
  M.TotalZ=A.sZ
where
  M.ID=A.MasterID

Selecting default item from Combobox C#

this is the correct form:

comboBox1.Text = comboBox1.Items[0].ToString();

U r welcome

How to force a hover state with jQuery?

Also, you could try triggering a mouseover.

$("#btn").click(function() {
   $("#link").trigger("mouseover");
});

Not sure if this will work for your specific scenario, but I've had success triggering mouseover instead of hover for various cases.

Check if a column contains text using SQL

Try this:

SElECT * FROM STUDENTS WHERE LEN(CAST(STUDENTID AS VARCHAR)) > 0

With this you get the rows where STUDENTID contains text

Returning http status code from Web Api controller

You can also do the following if you want to preserve the action signature as returning User:

public User GetUser(int userId, DateTime lastModifiedAtClient) 

If you want to return something other than 200 then you throw an HttpResponseException in your action and pass in the HttpResponseMessage you want to send to the client.

How to find all combinations of coins when given some dollar value

The below java solution which will print the different combinations as well. Easy to understand. Idea is

for sum 5

The solution is

    5 - 5(i) times 1 = 0
        if(sum = 0)
           print i times 1
    5 - 4(i) times 1 = 1
    5 - 3 times 1 = 2
        2 -  1(j) times 2 = 0
           if(sum = 0)
              print i times 1 and j times 2
    and so on......

If the remaining sum in each loop is lesser than the denomination ie if remaining sum 1 is lesser than 2, then just break the loop

The complete code below

Please correct me in case of any mistakes

public class CoinCombinbationSimple {
public static void main(String[] args) {
    int sum = 100000;
    printCombination(sum);
}

static void printCombination(int sum) {
    for (int i = sum; i >= 0; i--) {
        int sumCopy1 = sum - i * 1;
        if (sumCopy1 == 0) {
            System.out.println(i + " 1 coins");
        }
        for (int j = sumCopy1 / 2; j >= 0; j--) {
            int sumCopy2 = sumCopy1;
            if (sumCopy2 < 2) {
                break;
            }
            sumCopy2 = sumCopy1 - 2 * j;
            if (sumCopy2 == 0) {
                System.out.println(i + " 1 coins " + j + " 2 coins ");
            }
            for (int k = sumCopy2 / 5; k >= 0; k--) {
                int sumCopy3 = sumCopy2;
                if (sumCopy2 < 5) {
                    break;
                }
                sumCopy3 = sumCopy2 - 5 * k;
                if (sumCopy3 == 0) {
                    System.out.println(i + " 1 coins " + j + " 2 coins "
                            + k + " 5 coins");
                }
            }
        }
    }
}

}

Remove Object from Array using JavaScript

Returns only objects from the array whose property name is not "Kristian"

var noKristianArray = $.grep(someArray, function (el) { return el.name!= "Kristian"; });


Demo:

_x000D_
_x000D_
 var someArray = [_x000D_
                {name:"Kristian", lines:"2,5,10"},_x000D_
                {name:"John", lines:"1,19,26,96"},_x000D_
                {name:"Kristian", lines:"2,58,160"},_x000D_
                {name:"Felix", lines:"1,19,26,96"}_x000D_
                ];_x000D_
    _x000D_
var noKristianArray = $.grep(someArray, function (el) { return el.name!= "Kristian"; });_x000D_
_x000D_
console.log(noKristianArray);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

How to prevent page scrolling when scrolling a DIV element?

Use below CSS property overscroll-behavior: contain; to child element

SQL Server 2008 Insert with WHILE LOOP

First of all I'd like to say that I 100% agree with John Saunders that you must avoid loops in SQL in most cases especially in production.

But occasionally as a one time thing to populate a table with a hundred records for testing purposes IMHO it's just OK to indulge yourself to use a loop.

For example in your case to populate your table with records with hospital ids between 16 and 100 and make emails and descriptions distinct you could've used

CREATE PROCEDURE populateHospitals
AS
DECLARE @hid INT;
SET @hid=16;
WHILE @hid < 100
BEGIN 
    INSERT hospitals ([Hospital ID], Email, Description) 
    VALUES(@hid, 'user' + LTRIM(STR(@hid)) + '@mail.com', 'Sample Description' + LTRIM(STR(@hid))); 
    SET @hid = @hid + 1;
END

And result would be

ID   Hospital ID Email            Description          
---- ----------- ---------------- ---------------------
1    16          [email protected]  Sample Description16 
2    17          [email protected]  Sample Description17 
...                                                    
84   99          [email protected]  Sample Description99 

How can I clear an HTML file input with JavaScript?

Try this easy and it works

let input = elem.querySelector('input[type="file"]');
input.outerHTML=input.outerHTML;

this will reset the input

Bootstrap row class contains margin-left and margin-right which creates problems

I was facing this same issue and initially, I removed the row's right and left -ve margin and it removed the horizontal scroll, but it wasn't good. Then after 45 minutes of inspecting and searching, I found out that I was using container-fluid and was removing the padding and its inner row had left and right negative margins. So I gave container-fluid it's padding back and everything went back to normal.

If you do need to remove container-fluid padding, don't just remove every row's left and right negative margin in your project instead introduce a class and use that on your desired container

good postgresql client for windows?

phpPgAdmin is PostgreSQL web frontend which is quite good.

How do I sort a two-dimensional (rectangular) array in C#?

Array.Sort(array, (a, b) => { return a[0] - b[0]; });

SQL: How do I SELECT only the rows with a unique value on certain column?

I'm a fan of NOT EXISTS

SELECT DISTINCT contract, activity FROM table t1
WHERE NOT EXISTS (
  SELECT * FROM table t2
  WHERE t2.contract = t1.contract AND t2.activity != t1.activity
)

OpenCV get pixel channel value from Mat image

The below code works for me, for both accessing and changing a pixel value.

For accessing pixel's channel value :

for (int i = 0; i < image.cols; i++) {
    for (int j = 0; j < image.rows; j++) {
        Vec3b intensity = image.at<Vec3b>(j, i);
        for(int k = 0; k < image.channels(); k++) {
            uchar col = intensity.val[k]; 
        }   
    }
}

For changing a pixel value of a channel :

uchar pixValue;
for (int i = 0; i < image.cols; i++) {
    for (int j = 0; j < image.rows; j++) {
        Vec3b &intensity = image.at<Vec3b>(j, i);
        for(int k = 0; k < image.channels(); k++) {
            // calculate pixValue
            intensity.val[k] = pixValue;
        }
     }
}

`

Source : Accessing pixel value

Gradle project refresh failed after Android Studio update

SDK wasn't downloaded

so turned on the internet connection and after restarting the Android Studio

it showed a pop up to download 800mb data click on yes and issue gets resolved

"Object doesn't support this property or method" error in IE11

I face the similar issue and surprisingly meta tag didn't work this time. Turns out the company I currently cooperate with has this enterprise mode setting which has priority over meta tag.

We can't change the setting cause policy issue. Luckily I don't really need any fancy features but basic usage of jQuery so my final solution is to switch its version to 1.12 for better compatibility.

ref: jQuery - Browser support

In Python, how do I determine if an object is iterable?

According to the Python 2 Glossary, iterables are

all sequence types (such as list, str, and tuple) and some non-sequence types like dict and file and objects of any classes you define with an __iter__() or __getitem__() method. Iterables can be used in a for loop and in many other places where a sequence is needed (zip(), map(), ...). When an iterable object is passed as an argument to the built-in function iter(), it returns an iterator for the object.

Of course, given the general coding style for Python based on the fact that it's “Easier to ask for forgiveness than permission.”, the general expectation is to use

try:
    for i in object_in_question:
        do_something
except TypeError:
    do_something_for_non_iterable

But if you need to check it explicitly, you can test for an iterable by hasattr(object_in_question, "__iter__") or hasattr(object_in_question, "__getitem__"). You need to check for both, because strs don't have an __iter__ method (at least not in Python 2, in Python 3 they do) and because generator objects don't have a __getitem__ method.

COPYing a file in a Dockerfile, no such file or directory?

Seems that the commands:

docker build -t imagename .

and:

docker build -t imagename - < Dockerfile2

are not executed the same way. If you want to build 2 docker images from within one folder with Dockerfile and Dockerfile2, the COPY command cannot be used in the second example using stdin (< Dockerfile2). Instead you have to use:

docker build -t imagename -f Dockerfile2 .

Then COPY does work as expected.

Where can I find the assembly System.Web.Extensions dll?

EDIT:

The info below is only applicable to VS2008 and the 3.5 framework. VS2010 has a new registry location. Further details can be found on MSDN: How to Add or Remove References in Visual Studio.

ORIGINAL

It should be listed in the .NET tab of the Add Reference dialog. Assemblies that appear there have paths in registry keys under:

HKLM\Software\Microsoft\.NETFramework\AssemblyFolders\

I have a key there named Microsoft .NET Framework 3.5 Reference Assemblies with a string value of:

C:\Program Files\Reference Assemblies\Microsoft\Framework\v3.5\

Navigating there I can see the actual System.Web.Extensions dll.

EDIT:

I found my .NET 4.0 version in:

C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework\.NETFramework\v4.0\System.Web.Extensions.dll

I'm running Win 7 64 bit, so if you're on a 32 bit OS drop the (x86).

How can I check if given int exists in array?

You do need to loop through it. C++ does not implement any simpler way to do this when you are dealing with primitive type arrays.

also see this answer: C++ check if element exists in array

Open fancybox from function

What you need is:

$.fancybox.open({ .... });

See the "API methods" section at the bottom of here:

http://fancyapps.com/fancybox/

write newline into a file

the other answers should work. however I wanna mention

from java doc:

FileWriter is meant for writing streams of characters. For writing streams of raw bytes, consider using a FileOutputStream.

reading your method codes, you are about to write String to the file, what you were doing is convert String to raw bytes, then write so I think using FileWriter is not a bad idea.

And for the newline problem, Writer has method .write(String), which is convenient to use.

Code for a simple JavaScript countdown timer?

Expanding upon the accepted answer, your machine going to sleep, etc. may delay the timer from working. You can get a true time, at the cost of a little processing. This will give a true time left.

<span id="timer"></span>

<script>
var now = new Date();
var timeup = now.setSeconds(now.getSeconds() + 30);
//var timeup = now.setHours(now.getHours() + 1);

var counter = setInterval(timer, 1000);

function timer() {
  now = new Date();
  count = Math.round((timeup - now)/1000);
  if (now > timeup) {
      window.location = "/logout"; //or somethin'
      clearInterval(counter);
      return;
  }
  var seconds = Math.floor((count%60));
  var minutes = Math.floor((count/60) % 60);
  document.getElementById("timer").innerHTML = minutes + ":" + seconds;
}
</script>

Maven Install on Mac OS X

If using MacPorts on OS X 10.9 Mavericks, you can simply do:

sudo port install maven3
sudo port select --set maven maven3

How can I test a PDF document if it is PDF/A compliant?

The 3-Heights™ PDF Validator Online Tool provides good feedback for different PDF/A conformance levels and versions.

  • PDF/A1-a
  • PDF/A2-a
  • PDF/A2-b
  • PDF/A1-b
  • PDF/A2-u

Key Value Pair List

Using one of the subsets method in this question

var list = new List<KeyValuePair<string, int>>() { 
    new KeyValuePair<string, int>("A", 1),
    new KeyValuePair<string, int>("B", 0),
    new KeyValuePair<string, int>("C", 0),
    new KeyValuePair<string, int>("D", 2),
    new KeyValuePair<string, int>("E", 8),
};

int input = 11;
var items = SubSets(list).FirstOrDefault(x => x.Sum(y => y.Value)==input);

EDIT

a full console application:

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            var list = new List<KeyValuePair<string, int>>() { 
                new KeyValuePair<string, int>("A", 1),
                new KeyValuePair<string, int>("B", 2),
                new KeyValuePair<string, int>("C", 3),
                new KeyValuePair<string, int>("D", 4),
                new KeyValuePair<string, int>("E", 5),
                new KeyValuePair<string, int>("F", 6),
            };

            int input = 12;
            var alternatives = list.SubSets().Where(x => x.Sum(y => y.Value) == input);

            foreach (var res in alternatives)
            {
                Console.WriteLine(String.Join(",", res.Select(x => x.Key)));
            }
            Console.WriteLine("END");
            Console.ReadLine();
        }
    }

    public static class Extenions
    {
        public static IEnumerable<IEnumerable<T>> SubSets<T>(this IEnumerable<T> enumerable)
        {
            List<T> list = enumerable.ToList();
            ulong upper = (ulong)1 << list.Count;

            for (ulong i = 0; i < upper; i++)
            {
                List<T> l = new List<T>(list.Count);
                for (int j = 0; j < sizeof(ulong) * 8; j++)
                {
                    if (((ulong)1 << j) >= upper) break;

                    if (((i >> j) & 1) == 1)
                    {
                        l.Add(list[j]);
                    }
                }

                yield return l;
            }
        }
    }
}

How do I make this file.sh executable via double click?

By default, *.sh files are opened in a text editor (Xcode or TextEdit). To create a shell script that will execute in Terminal when you open it, name it with the “command” extension, e.g., file.command. By default, these are sent to Terminal, which will execute the file as a shell script.

You will also need to ensure the file is executable, e.g.:

chmod +x file.command

Without this, Terminal will refuse to execute it.

Note that the script does not have to begin with a #! prefix in this specific scenario, because Terminal specifically arranges to execute it with your default shell. (Of course, you can add a #! line if you want to customize which shell is used or if you want to ensure that you can execute it from the command line while using a different shell.)

Also note that Terminal executes the shell script without changing the working directory. You’ll need to begin your script with a cd command if you actually need it to run with a particular working directory.

What does ==$0 (double equals dollar zero) mean in Chrome Developer Tools?

$0 returns the most recently selected element or JavaScript object, $1 returns the second most recently selected one, and so on.

Refer : Command Line API Reference

Regular Expression to match string starting with a specific word

If you want to match anything after a word stop an not only at the start of the line you may use : \bstop.*\b - word followed by line

Word till the end of string

Or if you want to match the word in the string use \bstop[a-zA-Z]* - only the words starting with stop

Only the words starting with stop

Or the start of lines with stop ^stop[a-zA-Z]* for the word only - first word only
The whole line ^stop.* - first line of the string only

And if you want to match every string starting with stop including newlines use : /^stop.*/s - multiline string starting with stop

HTML not loading CSS file

Not sure this is valuable, but I will leave this here for others. Making sure that "Anonymous Authentication" was set to "Enabled" loaded my CSS file correctly.

To do that in Visual Studio 2019:

  1. Select your solution's name, right click, and hit "properties"
  2. Navigate to the "Properties" frame, typically in the bottom right corner
  3. Ensure that "Anonymous authentication" is set to "Enabled" as shown below

enter image description here

How can I wait for 10 second without locking application UI in android

You can use this:

Handler handler = new Handler();
handler.postDelayed(new Runnable() {
    public void run() {
     // Actions to do after 10 seconds
    }
}, 10000);

For Stop the Handler, You can try this: handler.removeCallbacksAndMessages(null);

Change Orientation of Bluestack : portrait/landscape mode

The newest version of BlueStacks has the ability to rotate the screen. Open the app and there's an icon in the lower right to rotate.

How to embed a SWF file in an HTML page?

This is suitable for application from root environment.

<object type="application/x-shockwave-flash" data="/dir/application.swf" 
id="applicationID" style="margin:0 10px;width:auto;height:auto;">

<param name="movie" value="/dir/application.swf" />
<param name="wmode" value="transparent" /> <!-- Or opaque, etc. -->

<!-- ? Required paramter or not, depends on application -->
<param name="FlashVars" value="" />

<param name="quality" value="high" />
<param name="menu" value="false" />

</object>

Additional parameters should be/can be added which depends on .swf it self. No embed, just object and parameters within, so, it remains valid, working and usable everywhere, it doesn't matter which !DOCTYPE is all about. :)

Matching exact string with JavaScript

Either modify the pattern beforehand so that it only matches the entire string:

var r = /^a$/

or check afterward whether the pattern matched the whole string:

function matchExact(r, str) {
   var match = str.match(r);
   return match && str === match[0];
}

calling a function from class in python - different way

Your methods don't refer to an object (that is, self), so you should use the @staticmethod decorator:

class MathsOperations:
    @staticmethod
    def testAddition (x, y):
        return x + y

    @staticmethod
    def testMultiplication (a, b):
        return a * b

T-SQL datetime rounded to nearest minute and nearest hours with using functions

"Rounded" down as in your example. This will return a varchar value of the date.

DECLARE @date As DateTime2
SET @date = '2007-09-22 15:07:38.850'

SELECT CONVERT(VARCHAR(16), @date, 120) --2007-09-22 15:07
SELECT CONVERT(VARCHAR(13), @date, 120) --2007-09-22 15

How do I make the return type of a method generic?

There are many ways of doing this(listed by priority, specific to the OP's problem)

  1. Option 1: Straight approach - Create multiple functions for each type you expect rather than having one generic function.

    public static bool ConfigSettingInt(string settingName)
    {  
         return Convert.ToBoolean(ConfigurationManager.AppSettings[settingName]);
    }
    
  2. Option 2: When you don't want to use fancy methods of conversion - Cast the value to object and then to generic type.

    public static T ConfigSetting<T>(string settingName)
    {  
         return (T)(object)ConfigurationManager.AppSettings[settingName];
    }
    

    Note - This will throw an error if the cast is not valid(your case). I would not recommend doing this if you are not sure about the type casting, rather go for option 3.

  3. Option 3: Generic with type safety - Create a generic function to handle type conversion.

    public static T ConvertValue<T,U>(U value) where U : IConvertible
    {
        return (T)Convert.ChangeType(value, typeof(T));
    } 
    

    Note - T is the expected type, note the where constraint here(type of U must be IConvertible to save us from the errors)

HashMap allows duplicates?

Code example:

HashMap<Integer,String> h = new HashMap<Integer,String> ();

h.put(null,null);
h.put(null, "a");

System.out.println(h);

Output:

{null=a}

It overrides the value at key null.

Picking a random element from a set

In C#

        Random random = new Random((int)DateTime.Now.Ticks);

        OrderedDictionary od = new OrderedDictionary();

        od.Add("abc", 1);
        od.Add("def", 2);
        od.Add("ghi", 3);
        od.Add("jkl", 4);


        int randomIndex = random.Next(od.Count);

        Console.WriteLine(od[randomIndex]);

        // Can access via index or key value:
        Console.WriteLine(od[1]);
        Console.WriteLine(od["def"]);

Mysql - How to quit/exit from stored procedure

This works for me :

 CREATE DEFINER=`root`@`%` PROCEDURE `save_package_as_template`( IN package_id int , 
IN bus_fun_temp_id int  , OUT o_message VARCHAR (50) ,
            OUT o_number INT )
 BEGIN

DECLARE  v_pkg_name  varchar(50) ;

DECLARE  v_pkg_temp_id  int(10)  ; 

DECLARE  v_workflow_count INT(10);

-- checking if workflow created for package
select count(*)  INTO v_workflow_count from workflow w where w.package_id = 
package_id ;

this_proc:BEGIN   -- this_proc block start here 

 IF  v_workflow_count = 0 THEN
   select 'no work flow ' as 'workflow_status' ;
    SET o_message ='Work flow is not created for this package.';
    SET  o_number = -2 ;
      LEAVE this_proc;
 END IF;

select 'work flow  created ' as 'workflow_status' ;
-- To  send some message
SET o_message ='SUCCESSFUL';
SET  o_number = 1 ;

  END ;-- this_proc block end here 

END

iCheck check if checkbox is checked

For those who struggle with this:

const value = $('SELECTOR').iCheck('update')[0].checked;

This directly returns true or false as boolean.

What's wrong with overridable method calls in constructors?

Here's an example which helps to understand this:

public class Main {
    static abstract class A {
        abstract void foo();
        A() {
            System.out.println("Constructing A");
            foo();
        }
    }

    static class C extends A {
        C() { 
            System.out.println("Constructing C");
        }
        void foo() { 
            System.out.println("Using C"); 
        }
    }

    public static void main(String[] args) {
        C c = new C(); 
    }
}

If you run this code, you get the following output:

Constructing A
Using C
Constructing C

You see? foo() makes use of C before C's constructor has been run. If foo() requires C to have a defined state (i.e. the constructor has finished), then it will encounter an undefined state in C and things might break. And since you can't know in A what the overwritten foo() expects, you get a warning.

What causes a TCP/IP reset (RST) flag to be sent?

If there is a router doing NAT, especially a low end router with few resources, it will age the oldest TCP sessions first. To do this it sets the RST flag in the packet that effectively tells the receiving station to (very ungracefully) close the connection. this is done to save resources.

What is cURL in PHP?

cURL is a library that lets you make HTTP requests in PHP. Everything you need to know about it (and most other extensions) can be found in the PHP manual.

In order to use PHP's cURL functions you need to install the » libcurl package. PHP requires that you use libcurl 7.0.2-beta or higher. In PHP 4.2.3, you will need libcurl version 7.9.0 or higher. From PHP 4.3.0, you will need a libcurl version that's 7.9.8 or higher. PHP 5.0.0 requires a libcurl version 7.10.5 or greater.

You can make HTTP requests without cURL, too, though it requires allow_url_fopen to be enabled in your php.ini file.

// Make a HTTP GET request and print it (requires allow_url_fopen to be enabled)
print file_get_contents('http://www.example.com/');

how to bold words within a paragraph in HTML/CSS?

I know this question is old but I ran across it and I know other people might have the same problem. All these answers are okay but do not give proper detail or actual TRUE advice.

When wanting to style a specific section of a paragraph use the span tag.

<p><span style="font-weight:900">Andy Warhol</span> (August 6, 1928 - February 22, 1987) 

was an American artist who was a leading figure in the visual art movement known as pop 

art.</p>

Andy Warhol (August 6, 1928 - February 22, 1987) was an American artist who was a leading figure in the visual art movement known as pop art.

As the code shows, the span tag styles on the specified words: "Andy Warhol". You can further style a word using any CSS font styling codes.

{font-weight; font-size; text-decoration; font-family; margin; color}, etc. 

Any of these and more can be used to style a word, group of words, or even specified paragraphs without having to add a class to the CSS Style Sheet Doc. I hope this helps someone!

Add line break to 'git commit -m' from the command line

I don't see anyone mentioning that if you don't provide a message it will open nano for you (at least in Linux) where you can write multiple lines...

Only this is needed:

git commit

Best way to list files in Java, sorted by Date Modified?

I came to this post when i was searching for the same issue but in android. I don't say this is the best way to get sorted files by last modified date, but its the easiest way I found yet.

Below code may be helpful to someone-

File downloadDir = new File("mypath");    
File[] list = downloadDir.listFiles();
    for (int i = list.length-1; i >=0 ; i--) {
        //use list.getName to get the name of the file
    }

Thanks

glob exclude pattern

Compare with glob, I recommend pathlib, filter one pattern is very simple.

from pathlib import Path

p = Path(YOUR_PATH)
filtered = [x for x in p.glob("**/*") if not x.name.startswith("eph")]

and if you want to filter more complex pattern, you can define a function to do that, just like:

def not_in_pattern(x):
    return (not x.name.startswith("eph")) and not x.name.startswith("epi")


filtered = [x for x in p.glob("**/*") if not_in_pattern(x)]

use that code, you can filter all files that start with eph or start with epi.

How to redirect DNS to different ports

Use SRV record. If you are using freenom go to cloudflare.com and connect your freenom server to cloudflare (freenom doesn't support srv records) use _minecraft as service tcp as protocol and your ip as target (you need "a" record to use your ip. I recommend not using your "Arboristal.com" domain as "a" record. If you use "Arboristal.com" as your "a" record hackers can go in your router settings and hack your network) priority - 0, weight - 0 and port - the port you want to use.(i know this because i was in the same situation) Do the same for any domain provider. (sorry if i made spell mistakes)

Sending mass email using PHP

Also the Pear packages:

http://pear.php.net/package/Mail_Mime http://pear.php.net/package/Mail http://pear.php.net/package/Mail_Queue

sob.

PS: DO NOT use mail() to send those 5000 emails. In addition to what everyone else said, it is extremely inefficient since mail() creates a separate socket per email set, even to the same MTA.

Using Alert in Response.Write Function in ASP.NET

You can simply write

try
 {
    //Your Logic and code
 }
 catch (Exception ex)
 {
    //Error message in  alert box
    Response.Write("<script>alert('Error :" +ex.Message+"');</script>");
 }

it will work fine

Httpd returning 503 Service Unavailable with mod_proxy for Tomcat 8

this worked for me:

ProxyRequests     Off
ProxyPreserveHost On
RewriteEngine On

<Proxy http://localhost:8123>
Order deny,allow
Allow from all
</Proxy>

ProxyPass         /node  http://localhost:8123  
ProxyPassReverse  /node  http://localhost:8123

How do I use arrays in cURL POST requests

You are just creating your array incorrectly. You could use http_build_query:

$fields = array(
            'username' => "annonymous",
            'api_key' => urlencode("1234"),
            'images' => array(
                 urlencode(base64_encode('image1')),
                 urlencode(base64_encode('image2'))
            )
        );
$fields_string = http_build_query($fields);

So, the entire code that you could use would be:

<?php
//extract data from the post
extract($_POST);

//set POST variables
$url = 'http://api.example.com/api';
$fields = array(
            'username' => "annonymous",
            'api_key' => urlencode("1234"),
            'images' => array(
                 urlencode(base64_encode('image1')),
                 urlencode(base64_encode('image2'))
            )
        );

//url-ify the data for the POST
$fields_string = http_build_query($fields);

//open connection
$ch = curl_init();

//set the url, number of POST vars, POST data
curl_setopt($ch,CURLOPT_URL, $url);
curl_setopt($ch,CURLOPT_POST, 1);
curl_setopt($ch,CURLOPT_POSTFIELDS, $fields_string);

//execute post
$result = curl_exec($ch);
echo $result;

//close connection
curl_close($ch);
?>

What are the differences between .so and .dylib on osx?

The file .so is not a UNIX file extension for shared library.

It just happens to be a common one.

Check line 3b at ArnaudRecipes sharedlib page

Basically .dylib is the mac file extension used to indicate a shared lib.

Java: Convert String to TimeStamp

import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class Util {
  public static Timestamp convertStringToTimestamp(String strDate) {
    try {
      DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
       // you can change format of date
      Date date = formatter.parse(strDate);
      Timestamp timeStampDate = new Timestamp(date.getTime());

      return timeStampDate;
    } catch (ParseException e) {
      System.out.println("Exception :" + e);
      return null;
    }
  }
}

Accessing Object Memory Address

You can get something suitable for that purpose with:

id(self)

C# Iterating through an enum? (Indexing a System.Array)

Array values = Enum.GetValues(typeof(myEnum));

foreach( MyEnum val in values )
{
   Console.WriteLine (String.Format("{0}: {1}", Enum.GetName(typeof(MyEnum), val), val));
}

Or, you can cast the System.Array that is returned:

string[] names = Enum.GetNames(typeof(MyEnum));
MyEnum[] values = (MyEnum[])Enum.GetValues(typeof(MyEnum));

for( int i = 0; i < names.Length; i++ )
{
    print(names[i], values[i]);
}

But, can you be sure that GetValues returns the values in the same order as GetNames returns the names ?

Running a cron every 30 seconds

No need for two cron entries, you can put it into one with:

* * * * * /bin/bash -l -c "/path/to/executable; sleep 30 ; /path/to/executable"

so in your case:

* * * * * /bin/bash -l -c "cd /srv/last_song/releases/20120308133159 && script/rails runner -e production '\''Song.insert_latest'\'' ; sleep 30 ; cd /srv/last_song/releases/20120308133159 && script/rails runner -e production '\''Song.insert_latest'\''"

How to get Url Hash (#) from server side

Possible solution for GET requests:

New Link format: http://example.com/yourDirectory?hash=video01

Call this function toward top of controller or http://example.com/yourDirectory/index.php:

function redirect()
{
    if (!empty($_GET['hash'])) {
        /** Sanitize & Validate $_GET['hash']
               If valid return string
               If invalid: return empty or false
        ******************************************************/
        $validHash = sanitizeAndValidateHashFunction($_GET['hash']);
        if (!empty($validHash)) {
            $url = './#' . $validHash;
        } else {
            $url = '/your404page.php';
        }
        header("Location: $url");
    }
}

Clearing content of text file using php

To add button you may use either jQuery libraries or simple Javascript script as shown below:

HTML link or button:

<a href="#" onClick="goclear()" id="button">click event</a>

Javascript:

<script type="text/javascript">
var btn = document.getElementById('button');
function goclear() { 
alert("Handler called. Page will redirect to clear.php");
document.location.href = "clear.php";
};
</script>

Use PHP to clear a file content. For instance you can use the fseek($fp, 0); or ftruncate ( resource $file , int $size ) as below:

<?php
//open file to write
$fp = fopen("/tmp/file.txt", "r+");
// clear content to 0 bits
ftruncate($fp, 0);
//close file
fclose($fp);
?>

Redirect PHP - you can use header ( string $string [, bool $replace = true [, int $http_response_code ]] )

<?php
header('Location: getbacktoindex.html');
?>

I hope it's help.

Send an Array with an HTTP Get

That depends on what the target server accepts. There is no definitive standard for this. See also a.o. Wikipedia: Query string:

While there is no definitive standard, most web frameworks allow multiple values to be associated with a single field (e.g. field1=value1&field1=value2&field2=value3).[4][5]

Generally, when the target server uses a strong typed programming language like Java (Servlet), then you can just send them as multiple parameters with the same name. The API usually offers a dedicated method to obtain multiple parameter values as an array.

foo=value1&foo=value2&foo=value3
String[] foo = request.getParameterValues("foo"); // [value1, value2, value3]

The request.getParameter("foo") will also work on it, but it'll return only the first value.

String foo = request.getParameter("foo"); // value1

And, when the target server uses a weak typed language like PHP or RoR, then you need to suffix the parameter name with braces [] in order to trigger the language to return an array of values instead of a single value.

foo[]=value1&foo[]=value2&foo[]=value3
$foo = $_GET["foo"]; // [value1, value2, value3]
echo is_array($foo); // true

In case you still use foo=value1&foo=value2&foo=value3, then it'll return only the first value.

$foo = $_GET["foo"]; // value1
echo is_array($foo); // false

Do note that when you send foo[]=value1&foo[]=value2&foo[]=value3 to a Java Servlet, then you can still obtain them, but you'd need to use the exact parameter name including the braces.

String[] foo = request.getParameterValues("foo[]"); // [value1, value2, value3]

psql: FATAL: Peer authentication failed for user "dev"

This works for me when I run into it:

sudo -u username psql

HTML character codes for this ? or this ?

&#9650; is the Unicode black up-pointing triangle (?) while &#9660; is the black down-pointing triangle (?).

You can just plug the characters (copied from the web) into this site for a lookup.

Error handling with PHPMailer

Just had to fix this myself. The above answers don't seem to take into account the $mail->SMTPDebug = 0; option. It may not have been available when the question was first asked.

If you got your code from the PHPMail site, the default will be $mail->SMTPDebug = 2; // enables SMTP debug information (for testing)

https://github.com/Synchro/PHPMailer/blob/master/examples/test_smtp_gmail_advanced.php

Set the value to 0 to suppress the errors and edit the 'catch' part of your code as explained above.

What are queues in jQuery?

Function makeRed and makeBlack use queue and dequeue to execute each other. The effect is that, the '#wow' element blinks continuously.

<html>
  <head>
    <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
    <script type="text/javascript">
      $(document).ready(function(){
          $('#wow').click(function(){
            $(this).delay(200).queue(makeRed);
            });
          });

      function makeRed(){
        $('#wow').css('color', 'red');
        $('#wow').delay(200).queue(makeBlack);
        $('#wow').dequeue();
      }

      function makeBlack(){
        $('#wow').css('color', 'black');
        $('#wow').delay(200).queue(makeRed);
        $('#wow').dequeue();
      }
    </script>
  </head>
  <body>
    <div id="wow"><p>wow</p></div>
  </body>
</html>

How to use Python to execute a cURL command?

Some background: I went looking for exactly this question because I had to do something to retrieve content, but all I had available was an old version of python with inadequate SSL support. If you're on an older MacBook, you know what I'm talking about. In any case, curl runs fine from a shell (I suspect it has modern SSL support linked in) so sometimes you want to do this without using requests or urllib2.

You can use the subprocess module to execute curl and get at the retrieved content:

import subprocess

// 'response' contains a []byte with the retrieved content.
// use '-s' to keep curl quiet while it does its job, but
// it's useful to omit that while you're still writing code
// so you know if curl is working
response = subprocess.check_output(['curl', '-s', baseURL % page_num])

Python 3's subprocess module also contains .run() with a number of useful options. I'll leave it to someone who is actually running python 3 to provide that answer.

SQL Server 2005 Setting a variable to the result of a select query

What do you mean exactly? Do you want to reuse the result of your query for an other query?

In that case, why don't you combine both queries, by making the second query search inside the results of the first one (SELECT xxx in (SELECT yyy...)

Adding JPanel to JFrame

public class Test{

Test2 test = new Test2();
JFrame frame = new JFrame();

Test(){
...
frame.setLayout(new BorderLayout());
frame.add(test, BorderLayout.CENTER);
...
}

//main
...
}

//public class Test2{
public class Test2 extends JPanel {

//JPanel test2 = new JPanel();

Test2(){
...
}

StringStream in C#

You have a number of options:

One is to not use streams, but use the TextWriter

   void Print(TextWriter writer) 
   {
   }

   void Main() 
  {
    var textWriter = new StringWriter();
    Print(writer);
    string myString = textWriter.ToString();
   }

It's likely that TextWriter is the appropriate level of abstraction for your print function. Streams are aimed at writing binary data, while TextWriter works at a higher abstraction level, specifically geared towards outputting strings.

If your motivation is that you also want your Print function to write to files, you can get a text writer from a filestream as well.

void Print(TextWriter writer) 
{
}

void PrintToFile(string filePath) 
{
     using(var textWriter = new StreamWriter(filePath))
     {
         Print(writer);
     }
}

If you REALLY want a stream you can look at MemoryStream.

Cannot import scipy.misc.imread

If you have Pillow installed with scipy and it is still giving you error then check your scipy version because it has been removed from scipy since 1.3.0rc1.

rather install scipy 1.1.0 by :

pip install scipy==1.1.0

check https://github.com/scipy/scipy/issues/6212


The method imread in scipy.misc requires the forked package of PIL named Pillow. If you are having problem installing the right version of PIL try using imread in other packages:

from matplotlib.pyplot import imread
im = imread(image.png)

To read jpg images without PIL use:

import cv2 as cv
im = cv.imread(image.jpg)

You can try from scipy.misc.pilutil import imread instead of from scipy.misc import imread

Please check the GitHub page : https://github.com/amueller/mglearn/issues/2 for more details.

How to prevent browser to invoke basic auth popup and handle 401 error using Jquery?

Use X-Requested-With: XMLHttpRequest with your request header. So the response header will not contain WWW-Authenticate:Basic.

beforeSend: function (xhr) {
                    xhr.setRequestHeader('Authorization', ("Basic "
                        .concat(btoa(key))));
                    xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
                },

What is the difference between ndarray and array in numpy?

numpy.array is just a convenience function to create an ndarray; it is not a class itself.

You can also create an array using numpy.ndarray, but it is not the recommended way. From the docstring of numpy.ndarray:

Arrays should be constructed using array, zeros or empty ... The parameters given here refer to a low-level method (ndarray(...)) for instantiating an array.

Most of the meat of the implementation is in C code, here in multiarray, but you can start looking at the ndarray interfaces here:

https://github.com/numpy/numpy/blob/master/numpy/core/numeric.py

bind/unbind service example (android)

Add these methods to your Activity:

private MyService myServiceBinder;
public ServiceConnection myConnection = new ServiceConnection() {

    public void onServiceConnected(ComponentName className, IBinder binder) {
        myServiceBinder = ((MyService.MyBinder) binder).getService();
        Log.d("ServiceConnection","connected");
        showServiceData();
    }

    public void onServiceDisconnected(ComponentName className) {
        Log.d("ServiceConnection","disconnected");
        myService = null;
    }
};

public Handler myHandler = new Handler() {
    public void handleMessage(Message message) {
        Bundle data = message.getData();
    }
};

public void doBindService() {
    Intent intent = null;
    intent = new Intent(this, BTService.class);
    // Create a new Messenger for the communication back
    // From the Service to the Activity
    Messenger messenger = new Messenger(myHandler);
    intent.putExtra("MESSENGER", messenger);

    bindService(intent, myConnection, Context.BIND_AUTO_CREATE);
}

And you can bind to service by ovverriding onResume(), and onPause() at your Activity class.

@Override
protected void onResume() {

    Log.d("activity", "onResume");
    if (myService == null) {
        doBindService();
    }
    super.onResume();
}

@Override
protected void onPause() {
    //FIXME put back

    Log.d("activity", "onPause");
    if (myService != null) {
        unbindService(myConnection);
        myService = null;
    }
    super.onPause();
}

Note, that when binding to a service only the onCreate() method is called in the service class. In your Service class you need to define the myBinder method:

private final IBinder mBinder = new MyBinder();
private Messenger outMessenger;

@Override
public IBinder onBind(Intent arg0) {
    Bundle extras = arg0.getExtras();
    Log.d("service","onBind");
    // Get messager from the Activity
    if (extras != null) {
        Log.d("service","onBind with extra");
        outMessenger = (Messenger) extras.get("MESSENGER");
    }
    return mBinder;
}

public class MyBinder extends Binder {
    MyService getService() {
        return MyService.this;
    }
}

After you defined these methods you can reach the methods of your service at your Activity:

private void showServiceData() {  
    myServiceBinder.myMethod();
}

and finally you can start your service when some event occurs like _BOOT_COMPLETED_

public class MyReciever  extends BroadcastReceiver {
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (action.equals("android.intent.action.BOOT_COMPLETED")) {
            Intent service = new Intent(context, myService.class);
            context.startService(service);
        }
    }
}

note that when starting a service the onCreate() and onStartCommand() is called in service class and you can stop your service when another event occurs by stopService() note that your event listener should be registerd in your Android manifest file:

<receiver android:name="MyReciever" android:enabled="true" android:exported="true">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
</receiver>

Javascript onclick hide div

Simple & Best way:

onclick="parentNode.remove()"

Deletes the complete parent from html

Fast and Lean PDF Viewer for iPhone / iPad / iOS - tips and hints?

I have build such kind of application using approximatively the same approach except :

  • I cache the generated image on the disk and always generate two to three images in advance in a separate thread.
  • I don't overlay with a UIImage but instead draw the image in the layer when zooming is 1. Those tiles will be released automatically when memory warnings are issued.

Whenever the user start zooming, I acquire the CGPDFPage and render it using the appropriate CTM. The code in - (void)drawLayer: (CALayer*)layer inContext: (CGContextRef) context is like :

CGAffineTransform currentCTM = CGContextGetCTM(context);    
if (currentCTM.a == 1.0 && baseImage) {
    //Calculate ideal scale
    CGFloat scaleForWidth = baseImage.size.width/self.bounds.size.width;
    CGFloat scaleForHeight = baseImage.size.height/self.bounds.size.height; 
    CGFloat imageScaleFactor = MAX(scaleForWidth, scaleForHeight);

    CGSize imageSize = CGSizeMake(baseImage.size.width/imageScaleFactor, baseImage.size.height/imageScaleFactor);
    CGRect imageRect = CGRectMake((self.bounds.size.width-imageSize.width)/2, (self.bounds.size.height-imageSize.height)/2, imageSize.width, imageSize.height);
    CGContextDrawImage(context, imageRect, [baseImage CGImage]);
} else {
    @synchronized(issue) { 
        CGPDFPageRef pdfPage = CGPDFDocumentGetPage(issue.pdfDoc, pageIndex+1);
        pdfToPageTransform = CGPDFPageGetDrawingTransform(pdfPage, kCGPDFMediaBox, layer.bounds, 0, true);
        CGContextConcatCTM(context, pdfToPageTransform);    
        CGContextDrawPDFPage(context, pdfPage);
    }
}

issue is the object containg the CGPDFDocumentRef. I synchronize the part where I access the pdfDoc property because I release it and recreate it when receiving memoryWarnings. It seems that the CGPDFDocumentRef object do some internal caching that I did not find how to get rid of.

What is the difference between bool and Boolean types in C#

They are one in the same. bool is just an alias for Boolean.

What data is stored in Ephemeral Storage of Amazon EC2 instance?

To be clear and answer @Dean's question: EBS-type root storage doesn't seem to be ephemeral. Data is persistent across reboots and actually it doesn't make any sense to use ebs-backed root volume which is 'ephemeral'. This wouldn't be different from image-based root volume.

How to install and run Typescript locally in npm?

tsc requires a config file or .ts(x) files to compile.

To solve both of your issues, create a file called tsconfig.json with the following contents:

{
    "compilerOptions": {
        "outFile": "../../built/local/tsc.js"
    },
    "exclude": [
        "node_modules"
    ]
}

Also, modify your npm run with this

tsc --config /path/to/a/tsconfig.json

How to remove whitespace from a string in typescript?

Problem

The trim() method removes whitespace from both sides of a string.

Source

Solution

You can use a Javascript replace method to remove white space like

"hello world".replace(/\s/g, "");

Example

_x000D_
_x000D_
var out = "hello world".replace(/\s/g, "");_x000D_
console.log(out);
_x000D_
_x000D_
_x000D_

How can I find the maximum value and its index in array in MATLAB?

For a matrix you can use this:

[M,I] = max(A(:))

I is the index of A(:) containing the largest element.

Now, use the ind2sub function to extract the row and column indices of A corresponding to the largest element.

[I_row, I_col] = ind2sub(size(A),I)

source: https://www.mathworks.com/help/matlab/ref/max.html

WARNING: Setting property 'source' to 'org.eclipse.jst.jee.server:appname' did not find a matching property

Despite this question being rather old, I had to deal with a similar warning and wanted to share what I found out.

First of all this is a warning and not an error. So there is no need to worry too much about it. Basically it means, that Tomcat does not know what to do with the source attribute from context.

This source attribute is set by Eclipse (or to be more specific the Eclipse Web Tools Platform) to the server.xml file of Tomcat to match the running application to a project in workspace.

Tomcat generates a warning for every unknown markup in the server.xml (i.e. the source attribute) and this is the source of the warning. You can safely ignore it.

Check if record exists from controller in Rails

with 'exists?':

Business.exists? user_id: current_user.id #=> 1 or nil

with 'any?':

Business.where(:user_id => current_user.id).any? #=> true or false

If you use something with .where, be sure to avoid trouble with scopes and better use .unscoped

Business.unscoped.where(:user_id => current_user.id).any?

How to fix getImageData() error The canvas has been tainted by cross-origin data?

As matt burns says in his answer, you may need to enable CORS on the server where the problem images are hosted.

If the server is Apache, this can be done by adding the following snippet (from here) to either your VirtualHost config or an .htaccess file:

<IfModule mod_setenvif.c>
    <IfModule mod_headers.c>
        <FilesMatch "\.(cur|gif|ico|jpe?g|png|svgz?|webp)$">
            SetEnvIf Origin ":" IS_CORS
            Header set Access-Control-Allow-Origin "*" env=IS_CORS
        </FilesMatch>
    </IfModule>
</IfModule>

...if adding it to a VirtualHost, you'll probably need to reload Apache's config too (eg. sudo service apache2 reload if Apache's running on a Linux server)

Hiding a form and showing another when a button is clicked in a Windows Forms application

To link to a form you need:

Form2 form2 = new Form2();
        form2.show();

this.hide();

then hide the previous form

When to use RabbitMQ over Kafka?

Scaling both is hard in a distributed fault tolerant way but I'd make a case that it's much harder at massive scale with RabbitMQ. It's not trivial to understand Shovel, Federation, Mirrored Msg Queues, ACK, Mem issues, Fault tollerance etc. Not to say you won't also have specific issues with Zookeeper etc on Kafka but there are less moving parts to manage. That said, you get a Polyglot exchange with RMQ which you don't with Kafka. If you want streaming, use Kafka. If you want simple IoT or similar high volume packet delivery, use Kafka. It's about smart consumers. If you want msg flexibility and higher reliability with higher costs and possibly some complexity, use RMQ.

How to get the azure account tenant Id?

Just to add a new method to an old (but still relevant question). In the new portal, clicking the help icon from any screen and selecting 'Show Diagnostics' will show you a JSON document containing all your tenant information including TenantId, Tenant Name, and much, much more useful information

enter image description here