Programs & Examples On #Pdcurses

When and why to 'return false' in JavaScript?

I think a better question is, why in a case where you're evaluating a boolean set of return values, would you NOT use true/false? I mean, you could probably have true/null, true/-1, other misc. Javascript "falsy" values to substitute, but why would you do that?

How to iterate std::set?

One more thing that might be useful for beginners is , since std::set is not allocated with contiguous memory chunks , if someone want to iterate till kth element normal way will not work. example:

std::vector<int > vec{1,2,3,4,5};
int k=3;
for(auto itr=vec.begin();itr<vec.begin()+k;itr++) cout<<*itr<<" ";

std::unordered_set<int > s{1,2,3,4,5};
int k=3;
int index=0;
auto itr=s.begin();
while(true){
   if(index==k) break;
   cout<<*itr++<<" ";
   index++;
}

How to change the default charset of a MySQL table?

You can change the default with an alter table set default charset but that won't change the charset of the existing columns. To change that you need to use a alter table modify column.

Changing the charset of a column only means that it will be able to store a wider range of characters. Your application talks to the db using the mysql client so you may need to change the client encoding as well.

how to call an ASP.NET c# method using javascript

I'm going to go right ahead and offer a solution using jQuery, which means you will need to import the library if you haven't already...

Import the jQuery library in your page mark-up:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js" type="text/javascript"></script>

Then create another *.js script file (I call mine ExecutePageMethod, since that is the only method it is going to expose) and import it:

<script type="text/javascript" src="/ExecutePageMethod.js" ></script>

Within the newly added file, add the following code (I remember pulling this from elsewhere, so someone else deserves credit for it really):

function ExecutePageMethod(page, fn, paramArray, successFn, errorFn) {
    var paramList = '';
    if (paramArray.length > 0) {
        for (var i = 0; i < paramArray.length; i += 2) {
            if (paramList.length > 0) paramList += ',';
            paramList += '"' + paramArray[i] + '":"' + paramArray[i + 1] + '"';
        }
    }
    paramList = '{' + paramList + '}';
    $.ajax({
        type: "POST",
        url: page + "/" + fn,
        contentType: "application/json; charset=utf-8",
        data: paramList,
        dataType: "json",
        success: successFn,
        error: errorFn
    });
}

You will then need to augment your .NET page method with the appropriate attributes, as such:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string MyMethod()
{
    return "Yay!";
}

Now, within your page mark-up, within a script block or from another script file, you can call the method, like so:

ExecutePageMethod("PageName.aspx", "MyMethod", [], OnSuccess, OnFailure);

Obviously you will need to implement the OnSuccess and OnFailure methods.

To consume the results, say in the OnSuccess method, you can use the parseJSON method, which, if the results become more complex (in the case or returning an array of types, for instance) this method will parse it into objects:

function OnSuccess(result) {
    var parsedResult = jQuery.parseJSON(result.d);
}

This ExecutePageMethod code is particularly useful since it it reusable, so rather than having to manage an $.ajax call for each page method you might want to execute, you just need to pass the page, method name and arguments to this method.

MySQL SELECT query string matching

You can use regular expressions like this:

SELECT * FROM pet WHERE name REGEXP 'Bob|Smith'; 

set font size in jquery

Not saying this is better, just another way:

$("#elem")[0].style.fontSize="20px";

Auto height div with overflow and scroll when needed

Quick Answer with Main Points

Pretty much the same answer as the best chosen answer from @Joum, to quicken your quest of trying to achieve the answer to the posted question and save time from deciphering whats going on in the syntax --

Answer

Set position attribute to fixed, set the top and bottom attributes to your liking for the element or div that you want to have an "auto" size of in comparison to its parent element and then set overflow to hidden.

.YourClass && || #YourId{
   position:fixed;
   top:10px;
   bottom:10px;
   width:100%; //Do not forget width
   overflow-y:auto;
}

Wallah! This is all you need for your special element that you want to have a dynamic height according to screen size and or dynamic incoming content while maintaining the opportunity to scroll.

set background color: Android

This question is a old one but it can help for others too.

Try this :

    li.setBackgroundColor(getResources().getColor(R.color.blue));

    or

    li.setBackgroundColor(getResources().getColor(android.R.color.red));

    or

    li.setBackgroundColor(Color.rgb(226, 11, 11));


    or
    li.setBackgroundColor(Color.RED)

Typescript: TS7006: Parameter 'xxx' implicitly has an 'any' type

Minimal error reproduction

export const users = require('../data'); // presumes @types/node are installed
const foundUser = users.find(user => user.id === 42); 
// error: Parameter 'user' implicitly has an 'any' type.ts(7006)

Recommended solution: --resolveJsonModule

The simplest way for your case is to use --resolveJsonModule compiler option:
import users from "./data.json" // `import` instead of `require`
const foundUser = users.find(user => user.id === 42); // user is strongly typed, no `any`!

There are some alternatives for other cases than static JSON import.

Option 1: Explicit user type (simple, no checks)

type User = { id: number; name: string /* and others */ }
const foundUser = users.find((user: User) => user.id === 42)

Option 2: Type guards (middleground)

Type guards are a good middleground between simplicity and strong types:
function isUserArray(maybeUserArr: any): maybeUserArr is Array<User> {
  return Array.isArray(maybeUserArr) && maybeUserArr.every(isUser)
}

function isUser(user: any): user is User {
  return "id" in user && "name" in user
}

if (isUserArray(users)) {
  const foundUser = users.find((user) => user.id === 42)
}
You can even switch to assertion functions (TS 3.7+) to get rid of if and throw an error instead.
function assertIsUserArray(maybeUserArr: any): asserts maybeUserArr is Array<User> {
  if(!isUserArray(maybeUserArr)) throw Error("wrong json type")
}

assertIsUserArray(users)
const foundUser = users.find((user) => user.id === 42) // works

Option 3: Runtime type system library (sophisticated)

A runtime type check library like io-ts or ts-runtime can be integrated for more complex cases.


Not recommended solutions

noImplicitAny: false undermines many useful checks of the type system:
function add(s1, s2) { // s1,s2 implicitely get `any` type
  return s1 * s2 // `any` type allows string multiplication and all sorts of types :(
}
add("foo", 42)

Also better provide an explicit User type for user. This will avoid propagating any to inner layer types. Instead typing and validating is kept in the JSON processing code of the outer API layer.

Iterating over and deleting from Hashtable in Java

You can use Enumeration:

Hashtable<Integer, String> table = ...

Enumeration<Integer> enumKey = table.keys();
while(enumKey.hasMoreElements()) {
    Integer key = enumKey.nextElement();
    String val = table.get(key);
    if(key==0 && val.equals("0"))
        table.remove(key);
}

What do pty and tty mean?

If you run the mount command with no command-line arguments, which displays the file systems mounted on your system, you’ll notice a line that looks something like this: none on /dev/pts type devpts (rw,gid=5,mode=620) This indicates that a special type of file system, devpts , is mounted at /dev/pts .This file system, which isn’t associated with any hardware device, is a “magic” file system that is created by the Linux kernel. It’s similar to the /proc file system

Like the /dev directory, /dev/pts contains entries corresponding to devices. But unlike /dev , which is an ordinary directory, /dev/pts is a special directory that is cre- ated dynamically by the Linux kernel.The contents of the directory vary with time and reflect the state of the running system. The entries in /dev/pts correspond to pseudo-terminals (or pseudo-TTYs, or PTYs).

Linux creates a PTY for every new terminal window you open and displays a corre- sponding entry in /dev/pts .The PTY device acts like a terminal device—it accepts input from the keyboard and displays text output from the programs that run in it. PTYs are numbered, and the PTY number is the name of the corresponding entry in /dev/pts .

For example, if the new terminal window’s PTY number is 7, invoke this command from another window: % echo ‘I am a virtual di ’ > /dev/pts/7 The output appears in the new terminal window.

Relay access denied on sending mail, Other domain outside of network

Configuring $mail->SMTPAuth = true; was the solution for me. The reason why is because without authentication the mail server answers with 'Relay access denied'. Since putting this in my code, all mails work fine.

How to remove trailing and leading whitespace for user-provided input in a batch file?

The solution below works very well for me.

Only 4 lines and works with most (all?) characters.


Solution:

:Trim
SetLocal EnableDelayedExpansion
set Params=%*
for /f "tokens=1*" %%a in ("!Params!") do EndLocal & set %1=%%b
exit /b

Test:

@echo off

call :Test1 & call :Test2 & call :Test3 & exit /b

:Trim
SetLocal EnableDelayedExpansion
set Params=%*
for /f "tokens=1*" %%a in ("!Params!") do EndLocal & set %1=%%b
exit /b

:Test1
set Value=   a b c   
set Expected=a b c
call :Trim Actual %Value%
if "%Expected%" == "%Actual%" (echo Test1 passed) else (echo Test1 failed)
exit /b

:Test2
SetLocal EnableDelayedExpansion
set Value=   a \ / : * ? " ' < > | ` ~ @ # $ [ ] & ( ) + - _ = z    
set Expected=a \ / : * ? " ' < > | ` ~ @ # $ [ ] & ( ) + - _ = z
call :Trim Actual !Value!
if !Expected! == !Actual! (echo Test2 passed) else (echo Test2 failed)
exit /b

:Test3
set /p Value="Enter string to trim: " %=%
echo Before: [%Value%]
call :Trim Value %Value%
echo After : [%Value%]
exit /b

How to clamp an integer to some range?

sorted((minval, value, maxval))[1]

for example:

>>> minval=3
>>> maxval=7
>>> for value in range(10):
...   print sorted((minval, value, maxval))[1]
... 
3
3
3
3
4
5
6
7
7
7

getString Outside of a Context or Activity

You can do this in Kotlin by creating a class that extends Application and then use its context to call the resources anywhere in your code

Your App class will look like this

 class App : Application() {
    override fun onCreate() {
        super.onCreate()
        context = this
    }

    companion object {
        var context: Context? = null
            private set
    }
}

Declare your Application class in AndroidManifest.xml (very important)

<application
        android:allowBackup="true"
        android:name=".App" //<--Your declaration Here
        ...>
        <activity
            android:name=".SplashActivity"  android:theme="@style/SplashTheme">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name=".MainActivity"/>
    </application>

To access e.g. a string file use the following code

App.context?.resources?.getText(R.string.mystring)

javax.faces.application.ViewExpiredException: View could not be restored

I ran into this problem myself and realized that it was because of a side-effect of a Filter that I created which was filtering all requests on the appliation. As soon as I modified the filter to pick only certain requests, this problem did not occur. It maybe good to check for such filters in your application and see how they behave.

Version vs build in Xcode

Thanks to @nekno and @ale84 for great answers.

However, I modified @ale84's script it little to increment build numbers for floating point.

the value of incl can be changed according to your floating format requirements. For eg: if incl = .01, output format would be ... 1.19, 1.20, 1.21 ...

buildNumber=$(/usr/libexec/PlistBuddy -c "Print CFBundleVersion" "$INFOPLIST_FILE")
incl=.01
buildNumber=`echo $buildNumber + $incl|bc`
/usr/libexec/PlistBuddy -c "Set :CFBundleVersion $buildNumber" "$INFOPLIST_FILE"

Equal sized table cells to fill the entire width of the containing table

You don't even have to set a specific width for the cells, table-layout: fixed suffices to spread the cells evenly.

_x000D_
_x000D_
ul {_x000D_
    width: 100%;_x000D_
    display: table;_x000D_
    table-layout: fixed;_x000D_
    border-collapse: collapse;_x000D_
}_x000D_
li {_x000D_
    display: table-cell;_x000D_
    text-align: center;_x000D_
    border: 1px solid hotpink;_x000D_
    vertical-align: middle;_x000D_
    word-wrap: break-word;_x000D_
}
_x000D_
<ul>_x000D_
  <li>foo<br>foo</li>_x000D_
  <li>barbarbarbarbar</li>_x000D_
  <li>baz</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Note that for table-layout to work the table styled element must have a width set (100% in my example).

How to determine the first and last iteration in a foreach loop?

I came across this thread when I have the same problem. I only need to get the first element then I re-analyze my code until this came up to my mind.

$firstElement = true;

foreach ($reportData->result() as $row) 
{
       if($firstElement) { echo "first element"; $firstElement=false; }
       // Other lines of codes here
}

The above codes are great and complete but if you only need just the first element then you may try this code.

Check if a user has scrolled to the bottom

Nick Craver's answer works fine, spare the issue that the value of $(document).height() varies by browser.

To make it work on all browsers, use this function from James Padolsey:

function getDocHeight() {
    var D = document;
    return Math.max(
        D.body.scrollHeight, D.documentElement.scrollHeight,
        D.body.offsetHeight, D.documentElement.offsetHeight,
        D.body.clientHeight, D.documentElement.clientHeight
    );
}

in place of $(document).height(), so that the final code is:

$(window).scroll(function() {
       if($(window).scrollTop() + $(window).height() == getDocHeight()) {
           alert("bottom!");
       }
   });

jQuery .val change doesn't change input value

<script src="//code.jquery.com/jquery.min.js"></script>
<script>
function changes() {
$('#link').val('new value');
}
</script>
<button onclick="changes()">a</button>
<input type='text' value='http://www.link.com' id='link'>

Change Name of Import in Java, or import two classes with the same name

As the other answers already stated, Java does not provide this feature.

Implementation of this feature has been requested multiple times, e.g. as JDK-4194542: class name aliasing or JDK-4214789: Extend import to allow renaming of imported type.

From the comments:

This is not an unreasonable request, though hardly essential. The occasional use of fully qualified names is not an undue burden (unless the library really reuses the same simple names right and left, which is bad style).

In any event, it doesn't pass the bar of price/performance for a language change.

So I guess we will not see this feature in Java anytime soon :-P

Fatal error: "No Target Architecture" in Visual Studio

If you are using Resharper make sure it does not add the wrong header for you, very common cases with ReSharper are:

  • #include <consoleapi2.h
  • #include <apiquery2.h>
  • #include <fileapi.h>

UPDATE:
Another suggestion is to check if you are including a "partial Windows.h", what I mean is that if you include for example winbase.h or minwindef.h you may end up with that error, add "the big" Windows.h instead. There are also some less obvious cases that I went through, the most notable was when I only included synchapi.h, the docs clearly state that is the header to be included for some functions like AcquireSRWLockShared but it triggered the No target architecture, the fix was to remove the synchapi.h and include "the big" Windows.h.

The Windows.h is huge, it defines macros(many of them remove the No target arch error) and includes many other headers. In summary, always check if you are including some header that could be replaced by Windows.h because it is not unusual to include a header that relies on some constants that are defined by Windows.h, so if you fail to include this header your compilation may fail.

Calling one Activity from another in Android

check the following code to open new activit.

Intent f = new Intent(MainActivity.this, SecondActivity.class);

startActivity(f);

Focus Input Box On Load

This is what works fine for me:

<form name="f" action="/search">
    <input name="q" onfocus="fff=1" />
</form>

fff will be a global variable which name is absolutely irrelevant and which aim will be to stop the generic onload event to force focus in that input.

<body onload="if(!this.fff)document.f.q.focus();">
    <!-- ... the rest of the page ... -->
</body>

From: http://webreflection.blogspot.com.br/2009/06/inputfocus-something-really-annoying.html

Adding an onclick event to a table row

Simple way is generating code as bellow:

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
_x000D_
<style>_x000D_
  table, td {_x000D_
      border:1px solid black;_x000D_
  }_x000D_
</style>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
<p>Click on each tr element to alert its index position in the table:</p>_x000D_
<table>_x000D_
  <tr onclick="myFunction(this)">_x000D_
    <td>Click to show rowIndex</td>_x000D_
  </tr>_x000D_
  <tr onclick="myFunction(this)">_x000D_
    <td>Click to show rowIndex</td>_x000D_
  </tr>_x000D_
  <tr onclick="myFunction(this)">_x000D_
    <td>Click to show rowIndex</td>_x000D_
  </tr>_x000D_
</table>_x000D_
_x000D_
<script>_x000D_
  function myFunction(x) {_x000D_
      alert("Row index is: " + x.rowIndex);_x000D_
  }_x000D_
</script>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to handle change of checkbox using jQuery?

$("input[type=checkbox]").on("change", function() { 

    if (this.checked) {

      //do your stuff

     }
});

How to generate .angular-cli.json file in Angular Cli?

Since Angular version 6 .angular-cli.json is deprecated. That file was replaced by angular.json file which supports workspaces.

Node.js: socket.io close client connection

socket.disconnect()

Only reboots the connection firing disconnect event on client side. But gets connected again.

socket.close()

Disconnect the connection from client. The client will keep trying to connect.

How to add new line in Markdown presentation?

You could use &nbsp; in R markdown to create a new blank line.

For example, in your .Rmd file:

I want 3 new lines: 

&nbsp;
&nbsp;
&nbsp;

End of file. 

Return array in a function

the Simplest way to do this ,is to return it by reference , even if you don't write the '&' symbol , it is automatically returned by reference

     void fillarr(int arr[5])
  {
       for(...);

  }

How to remove non-alphanumeric characters?

I was looking for the answer too and my intention was to clean every non-alpha and there shouldn't have more than one space.
So, I modified Alex's answer to this, and this is working for me preg_replace('/[^a-z|\s+]+/i', ' ', $name)
The regex above turned sy8ed sirajul7_islam to sy ed sirajul islam
Explanation: regex will check NOT ANY from a to z in case insensitive way or more than one white spaces, and it will be converted to a single space.

Getting the parameters of a running JVM

I am adding this new answer because as per JDK8 documentation jcmd is suggested approach now.

It is suggested to use the latest utility, jcmd instead of the previous jstack, jinfo, and jmap utilities for enhanced diagnostics and reduced performance overhead.

Below are commands to get your properties/flags you want.

jcmd pid VM.system_properties
jcmd pid VM.flags

We need pid, for this use jcmd -l, like below

username@users-Air:~/javacode$ jcmd -l 
11441 Test 
6294 Test 
29197 jdk.jcmd/sun.tools.jcmd.JCmd -l 

Now time to use these pids to get properties/flags you want

Command: jcmd 11441 VM.system_properties

11441:
#Tue Oct 17 12:44:50 IST 2017
gopherProxySet=false
awt.toolkit=sun.lwawt.macosx.LWCToolkit
file.encoding.pkg=sun.io
java.specification.version=9
sun.cpu.isalist=
sun.jnu.encoding=UTF-8
java.class.path=.
java.vm.vendor=Oracle Corporation
sun.arch.data.model=64
java.vendor.url=http\://java.oracle.com/
user.timezone=Asia/Kolkata
java.vm.specification.version=9
os.name=Mac OS X
sun.java.launcher=SUN_STANDARD
user.country=US
sun.boot.library.path=/Library/Java/JavaVirtualMachines/jdk-9.jdk/Contents/Home/lib
sun.java.command=Test
http.nonProxyHosts=local|*.local|169.254/16|*.169.254/16
jdk.debug=release
sun.cpu.endian=little
user.home=/Users/XXXX
user.language=en
java.specification.vendor=Oracle Corporation
java.home=/Library/Java/JavaVirtualMachines/jdk-9.jdk/Contents/Home
file.separator=/
java.vm.compressedOopsMode=Zero based
line.separator=\n
java.specification.name=Java Platform API Specification
java.vm.specification.vendor=Oracle Corporation
java.awt.graphicsenv=sun.awt.CGraphicsEnvironment
sun.management.compiler=HotSpot 64-Bit Tiered Compilers
ftp.nonProxyHosts=local|*.local|169.254/16|*.169.254/16
java.runtime.version=9+181
user.name=XXXX
path.separator=\:
os.version=10.12.6
java.runtime.name=Java(TM) SE Runtime Environment
file.encoding=UTF-8
java.vm.name=Java HotSpot(TM) 64-Bit Server VM
java.vendor.url.bug=http\://bugreport.java.com/bugreport/
java.io.tmpdir=/var/folders/dm/gd6lc90d0hg220lzw_m7krr00000gn/T/
java.version=9
user.dir=/Users/XXXX/javacode
os.arch=x86_64
java.vm.specification.name=Java Virtual Machine Specification
java.awt.printerjob=sun.lwawt.macosx.CPrinterJob
sun.os.patch.level=unknown
MyParam=2
java.library.path=/Users/XXXX/Library/Java/Extensions\:/Library/Java/Extensions\:/Network/Library/Java/Extensions\:/System/Library/Java/Extensions\:/usr/lib/java\:.
java.vm.info=mixed mode
java.vendor=Oracle Corporation
java.vm.version=9+181
sun.io.unicode.encoding=UnicodeBig
java.class.version=53.0
socksNonProxyHosts=local|*.local|169.254/16|*.169.254/16

Command : jcmd 11441 VM.flags output:

11441:
-XX:CICompilerCount=3 -XX:ConcGCThreads=1 -XX:G1ConcRefinementThreads=4 -XX:G1HeapRegionSize=1048576 -XX:InitialHeapSize=67108864 -XX:MarkStackSize=4194304 -XX:MaxHeapSize=1073741824 -XX:MaxNewSize=643825664 -XX:MinHeapDeltaBytes=1048576 -XX:NonNMethodCodeHeapSize=5830092 -XX:NonProfiledCodeHeapSize=122914074 -XX:ProfiledCodeHeapSize=122914074 -XX:ReservedCodeCacheSize=251658240 -XX:+SegmentedCodeCache -XX:-UseAOT -XX:+UseCompressedClassPointers -XX:+UseCompressedOops -XX:+UseFastUnorderedTimeStamps -XX:+UseG1GC 

For more instructions of usages of jcmd, see my blog post

select rows in sql with latest date for each ID repeated multiple times

You can use a join to do this

SELECT t1.* from myTable t1
LEFT OUTER JOIN myTable t2 on t2.ID=t1.ID AND t2.`Date` > t1.`Date`
WHERE t2.`Date` IS NULL;

Only rows which have the latest date for each ID with have a NULL join to t2.

How to get current formatted date dd/mm/yyyy in Javascript and append it to an input

   const monthNames = ["January", "February", "March", "April", "May", "June",
        "July", "August", "September", "October", "November", "December"];
    const dateObj = new Date();
    const month = monthNames[dateObj.getMonth()];
    const day = String(dateObj.getDate()).padStart(2, '0');
    const year = dateObj.getFullYear();
    const output = month  + '\n'+ day  + ',' + year;

    document.querySelector('.date').textContent = output; 

UnicodeEncodeError: 'ascii' codec can't encode character u'\xa0' in position 20: ordinal not in range(128)

Here's a rehashing of some other so-called "cop out" answers. There are situations in which simply throwing away the troublesome characters/strings is a good solution, despite the protests voiced here.

def safeStr(obj):
    try: return str(obj)
    except UnicodeEncodeError:
        return obj.encode('ascii', 'ignore').decode('ascii')
    except: return ""

Testing it:

if __name__ == '__main__': 
    print safeStr( 1 ) 
    print safeStr( "test" ) 
    print u'98\xb0'
    print safeStr( u'98\xb0' )

Results:

1
test
98°
98

UPDATE: My original answer was written for Python 2. For Python 3:

def safeStr(obj):
    try: return str(obj).encode('ascii', 'ignore').decode('ascii')
    except: return ""

Note: if you'd prefer to leave a ? indicator where the "unsafe" unicode characters are, specify replace instead of ignore in the call to encode for the error handler.

Suggestion: you might want to name this function toAscii instead? That's a matter of preference...

Finally, here's a more robust PY2/3 version using six, where I opted to use replace, and peppered in some character swaps to replace fancy unicode quotes and apostrophes which curl left or right with the simple vertical ones that are part of the ascii set. You might expand on such swaps yourself:

from six import PY2, iteritems 

CHAR_SWAP = { u'\u201c': u'"'
            , u'\u201D': u'"' 
            , u'\u2018': u"'" 
            , u'\u2019': u"'" 
}

def toAscii( text ) :    
    try:
        for k,v in iteritems( CHAR_SWAP ): 
            text = text.replace(k,v)
    except: pass     
    try: return str( text ) if PY2 else bytes( text, 'replace' ).decode('ascii')
    except UnicodeEncodeError:
        return text.encode('ascii', 'replace').decode('ascii')
    except: return ""

if __name__ == '__main__':     
    print( toAscii( u'testin\u2019' ) )

running a command as a super user from a python script

You have to use Popen like this:

cmd = ['sudo', 'apache2ctl', 'restart']
proc = subprocess.Popen(cmd, shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

It expects a list.

How do I create a SQL table under a different schema?

The default schema for the user could be changed with the following query and avoids changing the property every time a table is to be created.

USE [DBName] 
GO 
ALTER USER [YourUserName] WITH DEFAULT_SCHEMA = [YourSchema] 
GO

How to find all occurrences of an element in a list

occurrences = lambda s, lst: (i for i,e in enumerate(lst) if e == s)
list(occurrences(1, [1,2,3,1])) # = [0, 3]

Changing default startup directory for command prompt in Windows 7

Make a shortcut pointing to cmd.exe somwhere (e.g. desktop) then right-click on the copy and select "properties". Navigate to the "Shortcut" menu and change the "Start in:" directory.

How do I use InputFilter to limit characters in an EditText in Android?

I have done something like this to keep it simple:

edit_text.filters = arrayOf(object : InputFilter {
    override fun filter(
        source: CharSequence?,
        start: Int,
        end: Int,
        dest: Spanned?,
        dstart: Int,
        dend: Int
    ): CharSequence? {
        return source?.subSequence(start, end)
            ?.replace(Regex("[^A-Za-z0-9 ]"), "")
    }
})

This way we are replacing all the unwanted characters in the new part of the source string with an empty string.

The edit_text variable is the EditText object we are referring to.

The code is written in kotlin.

How to get the location of the DLL currently executing?

If you're working with an asp.net application and you want to locate assemblies when using the debugger, they are usually put into some temp directory. I wrote the this method to help with that scenario.

private string[] GetAssembly(string[] assemblyNames)
{
    string [] locations = new string[assemblyNames.Length];


    for (int loop = 0; loop <= assemblyNames.Length - 1; loop++)       
    {
         locations[loop] = AppDomain.CurrentDomain.GetAssemblies().Where(a => !a.IsDynamic && a.ManifestModule.Name == assemblyNames[loop]).Select(a => a.Location).FirstOrDefault();
    }
    return locations;
}

For more details see this blog post http://nodogmablog.bryanhogan.net/2015/05/finding-the-location-of-a-running-assembly-in-net/

If you can't change the source code, or redeploy, but you can examine the running processes on the computer use Process Explorer. I written a detailed description here.

It will list all executing dlls on the system, you may need to determine the process id of your running application, but that is usually not too difficult.

I've written a full description of how do this for a dll inside IIS - http://nodogmablog.bryanhogan.net/2016/09/locating-and-checking-an-executing-dll-on-a-running-web-server/

Break when a value changes using the Visual Studio debugger

You can optionally overload the = operator for the variable and can put the breakpoint inside the overloaded function on specific condition.

Java String array: is there a size of method?

Yes, .length (property-like, not a method):

String[] array = new String[10];
int size = array.length;

EOFError: end of file reached issue with Net::HTTP

I ran into this recently and eventually found that this was caused by a network timeout from the endpoint we were hitting. Fortunately for us we were able to increase the timeout duration.

To verify this was our issue (and actually not an issue with net http), I made the same request with curl and confirmed that the request was being terminated.

Detect all Firefox versions in JS

This script detects all versions of Firefox, for Desktop, from version 1 to 46.

It's the third time I've tried to answer this question on StackOverflow because I kept finding new ways to break my script. However, I think it's working now. It's a great exercise to learn about Firefox features and interesting to see how things have evolved. The script can be rewritten with different features, I chose ones I thought would be most useful, I would love for someone else to rewrite with other more useful features and post here, and compare results.

I placed the script in a try statement in case the user has any disabled settings in about.config. Otherwise I tested on every version of Firefox and it detects each one. I gave a brief description of what each feature is used for in the comments. I would like to do this for Webkit too but find the documentation not as good. Mozilla has easy to download previous versions and detailed releases.

_x000D_
_x000D_
// Element to display version_x000D_
var outputVersion = document.getElementById("displayFoxVersion");_x000D_
_x000D_
try {_x000D_
    // Match UserAgent string with Firefox Desktop_x000D_
    // Detect hybrid Gecko browsers and mobile_x000D_
    if (navigator.userAgent.match(/firefox/i) &&_x000D_
        !navigator.userAgent.match(/mobi|tablet|fennec|android|netscape|seamonkey|iceweasel|iceape|icecat|waterfox|gnuzilla|shadowfox|swiftfox/i)) {_x000D_
_x000D_
        // Create Element and Array to test availability  _x000D_
        var createdElement = document.createElement('div'),_x000D_
            createdArray = [],_x000D_
            firefoxVersion = "0";_x000D_
_x000D_
        // Firefox 1.0 released November 9, 2004 _x000D_
        // Check a current feature as being true, or NOT undefined _x000D_
        // AND check future features as EQUAL undefined_x000D_
        if (typeof window.alert !== "undefined" &&_x000D_
            typeof window.XPCNativeWrapper === "undefined" &&_x000D_
            typeof window.URL === "undefined") {_x000D_
            firefoxVersion = "1";_x000D_
        }_x000D_
_x000D_
        // Firefox 1.5 released October 15, 2003 _x000D_
        // XPCNativeWrapper used to create security wrapper_x000D_
        else if (typeof window.XPCNativeWrapper !== "undefined" &&_x000D_
            typeof window.globalStorage === "undefined" &&_x000D_
            typeof window.devicePixelRatio === "undefined" &&_x000D_
            typeof createdElement.style.animation === "undefined" &&_x000D_
            typeof document.querySelector === "undefined") {_x000D_
            firefoxVersion = "1.5";_x000D_
        }_x000D_
_x000D_
        // Firefox 2 released October 24, 2006_x000D_
        // globalStorage later deprecated in favor of localstorage_x000D_
        else if (typeof window.globalStorage !== "undefined" &&_x000D_
            typeof window.postMessage === "undefined") {_x000D_
            firefoxVersion = "2";_x000D_
        }_x000D_
_x000D_
        // Firefox 3 released June 17, 2008_x000D_
        // postMessage for cross window messaging_x000D_
        else if (typeof window.postMessage !== "undefined" &&_x000D_
            typeof document.querySelector === "undefined") {_x000D_
            firefoxVersion = "3";_x000D_
        }_x000D_
_x000D_
        // Firefox 3.5 released June 30, 2009_x000D_
        // querySelector returns list of the elements from document_x000D_
        else if (typeof document.querySelector !== "undefined" &&_x000D_
            typeof window.mozRequestAnimationFrame === "undefined" &&_x000D_
            typeof Reflect === "undefined") {_x000D_
            firefoxVersion = "3.5";_x000D_
        }_x000D_
_x000D_
        // Firefox 4 released March 22, 2011_x000D_
        // window.URL is Gecko, Webkit is window.webkitURL, manages object URLs_x000D_
        else if (typeof window.URL !== "undefined" &&_x000D_
            typeof createdElement.style.MozAnimation === "undefined") {_x000D_
            firefoxVersion = "4";_x000D_
        }_x000D_
_x000D_
        // After April 2011 releases every six weeks on Tuesday_x000D_
_x000D_
        // Firefox 5 released June 21, 2011_x000D_
        // style.MozAnimation for CSS animation, renamed to style.animation_x000D_
        else if (typeof createdElement.style.MozAnimation !== "undefined" &&_x000D_
            typeof WeakMap === "undefined") {_x000D_
            firefoxVersion = "5";_x000D_
        }_x000D_
_x000D_
        // Firefox 6 released August 16, 2011_x000D_
        // WeakMap collects key value pairs weakly referenced_x000D_
        else if (typeof WeakMap !== "undefined" &&_x000D_
            typeof createdElement.style.textOverflow === "undefined") {_x000D_
            firefoxVersion = "6";_x000D_
        }_x000D_
_x000D_
        // Firefox 7 released September 27, 2011_x000D_
        // textOverflow manages overflowed non displayed content_x000D_
        else if (typeof createdElement.style.textOverflow !== "undefined" &&_x000D_
            typeof createdElement.insertAdjacentHTML === "undefined") {_x000D_
            firefoxVersion = "7";_x000D_
        }_x000D_
_x000D_
        // Firefox 8 released November 8, 2011_x000D_
        // insertAdjacentHTML parses as HTML and inserts into specified position_x000D_
        // faster than direct innerHTML manipulation and_x000D_
        // appends without affecting other elements under the same parent_x000D_
        else if (typeof createdElement.insertAdjacentHTML !== "undefined" &&_x000D_
            typeof navigator.doNotTrack === "undefined") {_x000D_
            firefoxVersion = "8";_x000D_
        }_x000D_
_x000D_
        // Firefox 9 released December 20, 2011_x000D_
        // mozIndexedDB dropped ver 16, renamed window.indexedDB _x000D_
        // IndexDB improved functionality than localstorage_x000D_
        else if (typeof window.mozIndexedDB !== "undefined" &&_x000D_
            typeof document.mozFullScreenEnabled === "undefined") {_x000D_
            firefoxVersion = "9";_x000D_
        }_x000D_
_x000D_
        // Firefox 10 released January 31, 2012_x000D_
        // mozFullScreenEnabled reports if full-screen mode is available_x000D_
        else if (typeof document.mozFullScreenEnabled !== "undefined" &&_x000D_
            typeof window.mozCancelAnimationFrame === "undefined" &&_x000D_
            typeof Reflect === "undefined") {_x000D_
            firefoxVersion = "10";_x000D_
        }_x000D_
_x000D_
        // Firefox 11 released March 13, 2012_x000D_
        // mozCancelAnimationFrame prior to Firefox 23 prefixed with moz_x000D_
        // Cancels an animation frame request_x000D_
        else if (typeof window.mozCancelAnimationFrame !== "undefined" &&_x000D_
            typeof createdElement.style.MozTextAlignLast === "undefined") {_x000D_
            firefoxVersion = "11";_x000D_
        }_x000D_
_x000D_
        // Firefox 12 released April 24, 2012_x000D_
        // MozTextAlignLast how the last line is aligned_x000D_
        else if (typeof createdElement.style.MozTextAlignLast !== "undefined" &&_x000D_
            typeof createdElement.style.MozOpacity !== "undefined") {_x000D_
            firefoxVersion = "12";_x000D_
        }_x000D_
_x000D_
        // Firefox 13 released June 5, 2012_x000D_
        // MozOpacity dropped from this version_x000D_
        else if (typeof createdElement.style.MozOpacity === "undefined" &&_x000D_
            typeof window.globalStorage !== "undefined") {_x000D_
            firefoxVersion = "13";_x000D_
        }_x000D_
_x000D_
        // Firefox 14 released June 26, 2012_x000D_
        // globalStorage dropped from this version_x000D_
        else if (typeof window.globalStorage === "undefined" &&_x000D_
            typeof createdElement.style.borderImage === "undefined" &&_x000D_
            typeof document.querySelector !== "undefined") {_x000D_
            firefoxVersion = "14";_x000D_
        }_x000D_
_x000D_
        // Firefox 15 released August 28, 2012_x000D_
        // borderImage allows drawing an image on the borders of elements_x000D_
        else if (typeof createdElement.style.borderImage !== "undefined" &&_x000D_
            typeof createdElement.style.animation === "undefined") {_x000D_
            firefoxVersion = "15";_x000D_
        }_x000D_
_x000D_
        // Firefox 16 released October 9, 2012_x000D_
        // animation was MozAnimation_x000D_
        else if (typeof createdElement.style.animation !== "undefined" &&_x000D_
            typeof createdElement.style.iterator === "undefined" &&_x000D_
            typeof Math.hypot === "undefined") {_x000D_
            firefoxVersion = "16";_x000D_
        }_x000D_
_x000D_
        // Firefox 17 released November 20, 2012_x000D_
        // version 27 drops iterator and renames italic_x000D_
        // Used to iterate over enumerable properties of an object_x000D_
        else if (typeof createdElement.style.iterator !== "undefined" &&_x000D_
            typeof window.devicePixelRatio === "undefined") {_x000D_
            firefoxVersion = "17";_x000D_
        }_x000D_
_x000D_
        // Firefox 18 released January 8, 2013_x000D_
        // devicePixelRatio returns ratio of one vertical pixel between devices_x000D_
        else if (typeof window.devicePixelRatio !== "undefined" &&_x000D_
            typeof window.getInterface === "undefined" &&_x000D_
            typeof createdElement.style.mixBlendMode === "undefined") {_x000D_
            firefoxVersion = "18";_x000D_
        }_x000D_
_x000D_
        // Firefox 19 released February 19, 2013_x000D_
        // getInterface dropped and renamed in version 32_x000D_
        // Retrieves specified interface pointers_x000D_
        else if (typeof window.getInterface !== "undefined" &&_x000D_
            typeof Math.imul === "undefined") {_x000D_
            firefoxVersion = "19";_x000D_
        }_x000D_
_x000D_
        // Firefox 20 released April 2, 2013_x000D_
        // Math.imul provides fast 32 bit integer multiplication_x000D_
        else if (typeof Math.imul !== "undefined" &&_x000D_
            typeof window.crypto.getRandomValues === "undefined") {_x000D_
            firefoxVersion = "20";_x000D_
        }_x000D_
_x000D_
        // Firefox 21 released May 14, 2013_x000D_
        // getRandomValues lets you get cryptographically random values_x000D_
        else if (typeof window.crypto.getRandomValues !== "undefined" &&_x000D_
            typeof createdElement.style.flex === "undefined") {_x000D_
            firefoxVersion = "21";_x000D_
        }_x000D_
_x000D_
        // Firefox 22 released June 25, 2013_x000D_
        // flex can alter dimensions to fill available space_x000D_
        else if (typeof createdElement.style.flex !== "undefined" &&_x000D_
            typeof window.cancelAnimationFrame === "undefined") {_x000D_
            firefoxVersion = "22";_x000D_
        }_x000D_
_x000D_
        // Firefox 23 released August 6, 2013_x000D_
        // cancelAnimationFrame was mozCancelAnimationFrame_x000D_
        else if (typeof window.cancelAnimationFrame !== "undefined" &&_x000D_
            typeof document.loadBindingDocument !== "undefined" &&_x000D_
            typeof Math.trunc === "undefined") {_x000D_
            firefoxVersion = "23";_x000D_
        }_x000D_
_x000D_
        // Firefox 24 released September 17, 2013_x000D_
        // loadBindingDocument dropped_x000D_
        // loadBindingDocument reintroduced in 25 then dropped again in 26 _x000D_
        else if (typeof document.loadBindingDocument === "undefined" &&_x000D_
            typeof Math.trunc === "undefined") {_x000D_
            firefoxVersion = "24";_x000D_
        }_x000D_
_x000D_
        // Firefox 25 released October 29, 2013_x000D_
        // Math.trunc returns number removing fractional digits_x000D_
        else if (typeof Math.trunc !== "undefined" &&_x000D_
            typeof document.loadBindingDocument !== "undefined") {_x000D_
            firefoxVersion = "25";_x000D_
        }_x000D_
_x000D_
        // Firefox 26 released December 10, 2013_x000D_
        // loadBindingDocument dropped_x000D_
        else if (typeof Math.trunc !== "undefined" &&_x000D_
            typeof Math.hypot === "undefined") {_x000D_
            firefoxVersion = "26";_x000D_
        }_x000D_
_x000D_
        // Firefox 27 released February 4, 2014_x000D_
        // Math.hypot returns square root of the sum of squares_x000D_
        else if (typeof Math.hypot !== "undefined" &&_x000D_
            typeof createdArray.entries === "undefined") {_x000D_
            firefoxVersion = "27";_x000D_
        }_x000D_
_x000D_
        // Firefox 28 released March 18, 2014_x000D_
        // entries returns key value pairs for arrays_x000D_
        else if (typeof createdArray.entries !== "undefined" &&_x000D_
            typeof createdElement.style.boxSizing === "undefined") {_x000D_
            firefoxVersion = "28";_x000D_
        }_x000D_
_x000D_
        // Firefox 29 released April 29, 2014_x000D_
        // boxSizing alters CSS box model, calculates width and height of elements_x000D_
        else if (typeof createdElement.style.boxSizing != "undefined" &&_x000D_
            typeof createdElement.style.backgroundBlendMode === "undefined") {_x000D_
            firefoxVersion = "29";_x000D_
        }_x000D_
_x000D_
        // Firefox 30 released June 10, 2014_x000D_
        // backgroundBlendMode blends elements background images_x000D_
        else if (typeof createdElement.style.backgroundBlendMode !== "undefined" &&_x000D_
            typeof createdElement.style.paintOrder === "undefined") {_x000D_
            firefoxVersion = "30";_x000D_
        }_x000D_
_x000D_
        // Firefox 31 released July 22, 2014_x000D_
        // paintOrder specifies the order fill, stroke, markers of shape or element_x000D_
        else if (typeof createdElement.style.paintOrder !== "undefined" &&_x000D_
            typeof createdElement.style.mixBlendMode === "undefined") {_x000D_
            firefoxVersion = "31";_x000D_
        }_x000D_
_x000D_
        // Firefox 32 released September 2, 2014_x000D_
        // mixBlendMode how an element should blend _x000D_
        else if (typeof createdElement.style.mixBlendMode !== "undefined" &&_x000D_
            typeof Number.toInteger !== "undefined") {_x000D_
            firefoxVersion = "32";_x000D_
        }_x000D_
_x000D_
        // Firefox 33 released October 14, 2014_x000D_
        // numberToIntger dropped, used to convert values to integer_x000D_
        else if (typeof Number.toInteger === "undefined" &&_x000D_
            typeof createdElement.style.fontFeatureSettings === "undefined") {_x000D_
            firefoxVersion = "33";_x000D_
        }_x000D_
_x000D_
        // Firefox 34 released December 1, 2014_x000D_
        // fontFeatureSettings control over advanced typographic features_x000D_
        else if (typeof createdElement.style.fontFeatureSettings !== "undefined" &&_x000D_
            typeof navigator.mozIsLocallyAvailable !== "undefined") {_x000D_
            firefoxVersion = "34";_x000D_
        }_x000D_
_x000D_
        // Firefox 35 released January 13, 2015_x000D_
        // mozIsLocallyAvailable dropped_x000D_
        else if (typeof navigator.mozIsLocallyAvailable === "undefined" &&_x000D_
            typeof createdElement.style.MozWindowDragging === "undefined") {_x000D_
            firefoxVersion = "35";_x000D_
        }_x000D_
_x000D_
        // Firefox 36 released February 24, 2015_x000D_
        // quote returns a copy of the string_x000D_
        else if (typeof String.quote !== "undefined" &&_x000D_
            typeof createdElement.style.MozWindowDragging !== "undefined") {_x000D_
            firefoxVersion = "36";_x000D_
        }_x000D_
_x000D_
        // Firefox 37 released March 31, 2015_x000D_
        // quote quickly dropped_x000D_
        else if (typeof String.quote === "undefined" &&_x000D_
            typeof createdElement.style.rubyPosition === "undefined") {_x000D_
            firefoxVersion = "37";_x000D_
        }_x000D_
_x000D_
        // Firefox 38 released May 12, 2015_x000D_
        // rubyPosition defines position of a ruby element relative to its base element_x000D_
        else if (typeof createdElement.style.rubyPosition !== "undefined" &&_x000D_
            typeof window.Headers === "undefined") {_x000D_
            firefoxVersion = "38";_x000D_
        }_x000D_
_x000D_
        // Firefox 39 released July 2, 2015_x000D_
        // Headers allows us to create our own headers objects _x000D_
        else if (typeof window.Headers !== "undefined" &&_x000D_
            typeof Symbol.match === "undefined") {_x000D_
            firefoxVersion = "39";_x000D_
        }_x000D_
_x000D_
        // Firefox 40 released August 11, 2015_x000D_
        // match matches a regular expression against a string_x000D_
        else if (typeof Symbol.match !== "undefined" &&_x000D_
            typeof Symbol.species === "undefined") {_x000D_
            firefoxVersion = "40";_x000D_
        }_x000D_
_x000D_
        // Firefox 41 released September 22, 2015_x000D_
        // species allows subclasses to over ride the default constructor_x000D_
        else if (typeof Symbol.species !== "undefined" &&_x000D_
            typeof Reflect === "undefined") {_x000D_
            firefoxVersion = "41";_x000D_
        }_x000D_
_x000D_
        // Firefox 42 released November 3, 2015_x000D_
        // mozRequestAnimationFrame and mozFullScreenEnabled dropped_x000D_
        // Reflect offers methods for interceptable JavaScript operations_x000D_
        else if (typeof Reflect !== "undefined" &&_x000D_
            typeof window.screen.orientation === "undefined") {_x000D_
            firefoxVersion = "42";_x000D_
        }_x000D_
_x000D_
        // Firefox 43 released December 15, 2015_x000D_
        // orientation is mozOrientation in B2G and Android_x000D_
        else if (typeof window.screen.orientation !== "undefined" &&_x000D_
            typeof document.charset === "undefined") {_x000D_
            firefoxVersion = "43";_x000D_
        }_x000D_
_x000D_
        // Firefox 44 released January 26, 2016_x000D_
        // charset is for legacy, use document.characterSet_x000D_
        else if (typeof document.charset !== "undefined" &&_x000D_
            typeof window.onstorage === "undefined") {_x000D_
            firefoxVersion = "44";_x000D_
        }_x000D_
_x000D_
        // Firefox 45 released March 8, 2016_x000D_
        // onstorage contains an event handler that runs when the storage event fires_x000D_
        else if (typeof window.onstorage !== "undefined" &&_x000D_
            typeof window.onabsolutedeviceorientation === "undefined") {_x000D_
            firefoxVersion = "45";_x000D_
        }_x000D_
_x000D_
        // Firefox 46 - beta_x000D_
        // onabsolutedeviceorientation_x000D_
        else if (typeof window.onabsolutedeviceorientation !== "undefined") {_x000D_
            firefoxVersion = "46 or above";_x000D_
        }_x000D_
_x000D_
        // Else could not verify_x000D_
        else {_x000D_
            outputVersion.innerHTML = "Could not verify Mozilla Firefox";_x000D_
        }_x000D_
_x000D_
        // Display Firefox version_x000D_
        outputVersion.innerHTML = "Verified as Mozilla Firefox " + firefoxVersion;_x000D_
_x000D_
        // Else not detected_x000D_
    } else {_x000D_
        outputVersion.innerHTML = "Mozilla Firefox not detected";_x000D_
    }_x000D_
} catch (e) {_x000D_
    // Statement to handle exceptions_x000D_
    outputVersion.innerHTML = "An error occured. This could be because the default settings in Firefox have changed. Check about.config ";_x000D_
}
_x000D_
<div id="displayFoxVersion"></div>
_x000D_
_x000D_
_x000D_

implements Closeable or implements AutoCloseable

It seems to me that you are not very familiar with interfaces. In the code you have posted, you don't need to implement AutoCloseable.

You only have to (or should) implement Closeable or AutoCloseable if you are about to implement your own PrintWriter, which handles files or any other resources which needs to be closed.

In your implementation, it is enough to call pw.close(). You should do this in a finally block:

PrintWriter pw = null;
try {
   File file = new File("C:\\test.txt");
   pw = new PrintWriter(file);
} catch (IOException e) {
   System.out.println("bad things happen");
} finally {
   if (pw != null) {
      try {
         pw.close();
      } catch (IOException e) {
      }
   }
}

The code above is Java 6 related. In Java 7 this can be done more elegantly (see this answer).

R : how to simply repeat a command?

It's not clear whether you're asking this because you are new to programming, but if that's the case then you should probably read this article on loops and indeed read some basic materials on programming.

If you already know about control structures and you want the R-specific implementation details then there are dozens of tutorials around, such as this one. The other answer uses replicate and colMeans, which is idiomatic when writing in R and probably blazing fast as well, which is important if you want 10,000 iterations.

However, one more general and (for beginners) straightforward way to approach problems of this sort would be to use a for loop.

> for (ii in 1:5) { + print(ii) + } [1] 1 [1] 2 [1] 3 [1] 4 [1] 5 > 

So in your case, if you just wanted to print the mean of your Tandem object 5 times:

for (ii in 1:5) {     Tandem <- sample(OUT, size = 815, replace = TRUE, prob = NULL)     TandemMean <- mean(Tandem)     print(TandemMean) } 

As mentioned above, replicate is a more natural way to deal with this specific problem using R. Either way, if you want to store the results - which is surely the case - you'll need to start thinking about data structures like vectors and lists. Once you store something you'll need to be able to access it to use it in future, so a little knowledge is vital.

set.seed(1234) OUT <- runif(100000, 1, 2) tandem <- list() for (ii in 1:10000) {     tandem[[ii]] <- mean(sample(OUT, size = 815, replace = TRUE, prob = NULL)) }  tandem[1] tandem[100] tandem[20:25] 

...creates this output:

> set.seed(1234) > OUT <- runif(100000, 1, 2) > tandem <- list() > for (ii in 1:10000) { +     tandem[[ii]] <- mean(sample(OUT, size = 815, replace = TRUE, prob = NULL)) + } >  > tandem[1] [[1]] [1] 1.511923  > tandem[100] [[1]] [1] 1.496777  > tandem[20:25] [[1]] [1] 1.500669  [[2]] [1] 1.487552  [[3]] [1] 1.503409  [[4]] [1] 1.501362  [[5]] [1] 1.499728  [[6]] [1] 1.492798  >  

How to overcome TypeError: unhashable type: 'list'

You're trying to use k (which is a list) as a key for d. Lists are mutable and can't be used as dict keys.

Also, you're never initializing the lists in the dictionary, because of this line:

if k not in d == False:

Which should be:

if k not in d == True:

Which should actually be:

if k not in d:

getColor(int id) deprecated on Android 6.0 Marshmallow (API 23)

If your current min. API level is 23, you can simply use getColor() like we are using to get string resources by getString():

//example
textView.setTextColor(getColor(R.color.green));
// if `Context` is not available, use with context.getColor()

You can constraint for API Levels below 23:

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
    textView.setTextColor(getColor(R.color.green));
} else {
    textView.setTextColor(getResources().getColor(R.color.green));
}

but to keep it simple, you can do like below as accepted answer:

textView.setTextColor(ContextCompat.getColor(context, R.color.green))

From Resources.

From ContextCompat AndroidX.

From ContextCompat Support

When to use IList and when to use List

You are most often better of using the most general usable type, in this case the IList or even better the IEnumerable interface, so that you can switch the implementation conveniently at a later time.

However, in .NET 2.0, there is an annoying thing - IList does not have a Sort() method. You can use a supplied adapter instead:

ArrayList.Adapter(list).Sort()

How to get Printer Info in .NET?

As an alternative to WMI you can get fast accurate results by tapping in to WinSpool.drv (i.e. Windows API) - you can get all the details on the interfaces, structs & constants from pinvoke.net, or I've put the code together at http://delradiesdev.blogspot.com/2012/02/accessing-printer-status-using-winspool.html

How do I check if a type is a subtype OR the type of an object?

I'm posting this answer with the hope of someone sharing with me if and why it would be a bad idea. In my application, I have a property of Type that I want to check to be sure it is typeof(A) or typeof(B), where B is any class derived from A. So my code:

public class A
{
}

public class B : A
{
}

public class MyClass
{
    private Type _helperType;
    public Type HelperType
    {
        get { return _helperType; }
        set 
        {
            var testInstance = (A)Activator.CreateInstance(value);
            if (testInstance==null)
                throw new InvalidCastException("HelperType must be derived from A");
            _helperType = value;
        }
    }
}

I feel like I might be a bit naive here so any feedback would be welcome.

'const int' vs. 'int const' as function parameters in C++ and C

Prakash is correct that the declarations are the same, although a little more explanation of the pointer case might be in order.

"const int* p" is a pointer to an int that does not allow the int to be changed through that pointer. "int* const p" is a pointer to an int that cannot be changed to point to another int.

See https://isocpp.org/wiki/faq/const-correctness#const-ptr-vs-ptr-const.

Java creating .jar file

Often you need to put more into the manifest than what you get with the -e switch, and in that case, the syntax is:

jar -cvfm myJar.jar myManifest.txt myApp.class

Which reads: "create verbose jarFilename manifestFilename", followed by the files you want to include.

Note that the name of the manifest file you supply can be anything, as jar will automatically rename it and put it into the right place within the jar file.

Format date and time in a Windows batch script

@ECHO OFF
: Sets the proper date and time stamp with 24Hr Time for log file naming
: convention

SET HOUR=%time:~0,2%
SET dtStamp9=%date:~-4%%date:~4,2%%date:~7,2%_0%time:~1,1%%time:~3,2%%time:~6,2% 
SET dtStamp24=%date:~-4%%date:~4,2%%date:~7,2%_%time:~0,2%%time:~3,2%%time:~6,2%

if "%HOUR:~0,1%" == " " (SET dtStamp=%dtStamp9%) else (SET dtStamp=%dtStamp24%)

ECHO %dtStamp%

PAUSE

Shift elements in a numpy array

One way to do it without spilt the code into cases

with array:

def shift(arr, dx, default_value):
    result = np.empty_like(arr)
    get_neg_or_none = lambda s: s if s < 0 else None
    get_pos_or_none = lambda s: s if s > 0 else None
    result[get_neg_or_none(dx): get_pos_or_none(dx)] = default_value
    result[get_pos_or_none(dx): get_neg_or_none(dx)] = arr[get_pos_or_none(-dx): get_neg_or_none(-dx)]     
    return result

with matrix it can be done like this:

def shift(image, dx, dy, default_value):
    res = np.full_like(image, default_value)

    get_neg_or_none = lambda s: s if s < 0 else None
    get_pos_or_none = lambda s : s if s > 0 else None

    res[get_pos_or_none(-dy): get_neg_or_none(-dy), get_pos_or_none(-dx): get_neg_or_none(-dx)] = \
        image[get_pos_or_none(dy): get_neg_or_none(dy), get_pos_or_none(dx): get_neg_or_none(dx)]
    return res

$(document).ready equivalent without jQuery

Try this:

function ready(callback){
    if(typeof callback === "function"){
        document.addEventListener("DOMContentLoaded", callback);
        window.addEventListener("load", callback);
    }else{
        throw new Error("Sorry, I can not run this!");
    }
}
ready(function(){
    console.log("It worked!");
});

C++ Cout & Cin & System "Ambiguous"

This kind of thing doesn't just magically happen on its own; you changed something! In industry we use version control to make regular savepoints, so when something goes wrong we can trace back the specific changes we made that resulted in that problem.

Since you haven't done that here, we can only really guess. In Visual Studio, Intellisense (the technology that gives you auto-complete dropdowns and those squiggly red lines) works separately from the actual C++ compiler under the bonnet, and sometimes gets things a bit wrong.

In this case I'd ask why you're including both cstdlib and stdlib.h; you should only use one of them, and I recommend the former. They are basically the same header, a C header, but cstdlib puts them in the namespace std in order to "C++-ise" them. In theory, including both wouldn't conflict but, well, this is Microsoft we're talking about. Their C++ toolchain sometimes leaves something to be desired. Any time the Intellisense disagrees with the compiler has to be considered a bug, whichever way you look at it!

Anyway, your use of using namespace std (which I would recommend against, in future) means that std::system from cstdlib now conflicts with system from stdlib.h. I can't explain what's going on with std::cout and std::cin.

Try removing #include <stdlib.h> and see what happens.

If your program is building successfully then you don't need to worry too much about this, but I can imagine the false positives being annoying when you're working in your IDE.

Collision resolution in Java HashMap

In a HashMap the key is an object, that contains hashCode() and equals(Object) methods.

When you insert a new entry into the Map, it checks whether the hashCode is already known. Then, it will iterate through all objects with this hashcode, and test their equality with .equals(). If an equal object is found, the new value replaces the old one. If not, it will create a new entry in the map.

Usually, talking about maps, you use collision when two objects have the same hashCode but they are different. They are internally stored in a list.

Python Brute Force algorithm

A solution using recursion:

def brute(string, length, charset):
    if len(string) == length:
        return
    for char in charset:
        temp = string + char
        print(temp)
        brute(temp, length, charset)

Usage:

brute("", 4, "rce")

Peak-finding algorithm for Python/SciPy

To detect both positive and negative peaks, PeakDetect is helpful.

from peakdetect import peakdetect

peaks = peakdetect(data, lookahead=20) 
# Lookahead is the distance to look ahead from a peak to determine if it is the actual peak. 
# Change lookahead as necessary 
higherPeaks = np.array(peaks[0])
lowerPeaks = np.array(peaks[1])
plt.plot(data)
plt.plot(higherPeaks[:,0], higherPeaks[:,1], 'ro')
plt.plot(lowerPeaks[:,0], lowerPeaks[:,1], 'ko')

PeakDetection

Variables not showing while debugging in Eclipse

Like with every bad software the treatment for this wrong behaivier does not exist. What is good for one does not work for others.

I let the debuger to stop on a brakepoint once, then again second time and on the third time the beast has shown the Variable View with all data in it.

fatal: bad default revision 'HEAD'

just do an initial commit and the error will go away:

git commit -m "initial commit"

How to clear Flutter's Build cache?

I tried flutter clean and that didn't work for me. Then I went to wipe the emulator's data and voila, the cached issue was gone. If you have Android Studio you can launch the AVD Manager by following this Create and Manage virtual machine. Otherwise you can wipe the emulator's data using the emulator.exe command line that's included in the android SDK. Simply follow this instructions here Start the emulator from the command line.

How to change the display name for LabelFor in razor in mvc3?

@Html.LabelFor(model => model.SomekingStatus, "foo bar")

How can I add a .npmrc file?

In MacOS Catalina 10.15.5 the .npmrc file path can be found at

/Users/<user-name>/.npmrc

Open in it in (for first time users, create a new file) any editor and copy-paste your token. Save it.

You are ready to go.

Note: As mentioned by @oligofren, the command npm config ls -l will npm configurations. You will get the .npmrc file from config parameter userconfig

PRINT statement in T-SQL

The Print statement in TSQL is a misunderstood creature, probably because of its name. It actually sends a message to the error/message-handling mechanism that then transfers it to the calling application. PRINT is pretty dumb. You can only send 8000 characters (4000 unicode chars). You can send a literal string, a string variable (varchar or char) or a string expression. If you use RAISERROR, then you are limited to a string of just 2,044 characters. However, it is much easier to use it to send information to the calling application since it calls a formatting function similar to the old printf in the standard C library. RAISERROR can also specify an error number, a severity, and a state code in addition to the text message, and it can also be used to return user-defined messages created using the sp_addmessage system stored procedure. You can also force the messages to be logged.

Your error-handling routines won’t be any good for receiving messages, despite messages and errors being so similar. The technique varies, of course, according to the actual way you connect to the database (OLBC, OLEDB etc). In order to receive and deal with messages from the SQL Server Database Engine, when you’re using System.Data.SQLClient, you’ll need to create a SqlInfoMessageEventHandler delegate, identifying the method that handles the event, to listen for the InfoMessage event on the SqlConnection class. You’ll find that message-context information such as severity and state are passed as arguments to the callback, because from the system perspective, these messages are just like errors.

It is always a good idea to have a way of getting these messages in your application, even if you are just spooling to a file, because there is always going to be a use for them when you are trying to chase a really obscure problem. However, I can’t think I’d want the end users to ever see them unless you can reserve an informational level that displays stuff in the application.

Write single CSV file using spark-csv

repartition/coalesce to 1 partition before you save (you'd still get a folder but it would have one part file in it)

How to fix/convert space indentation in Sublime Text?

I also followed Josh Frankel's advice and created a Sublime Macro + added key binding. The difference is that this script ensures that spacing is first set to tabs and set to a tab size of 2. The macro won't work if that's not the starting point.

Here's a gist of the macro: https://gist.github.com/drivelous/aa8dc907de34efa3e462c65a96e05f09

In Mac, to use the macro + key binding:

  1. Create a file called spaces2to4.sublime-macro and copy/paste the code from the gist. For me this is located at:

/Library/Application\ Support/Sublime\ Text\ 3/Packages/User/spaces2to4.sublime-macro

  1. Select Sublime Text > Preferences > Key Bindings
  2. Add this command to the User specified sublime-keymap (it's in an array -- it may be empty):
{
    "keys": ["super+shift+o"],
    "command": "run_macro_file",
    "args": {
        "file":"Packages/User/spaces2to4.sublime-macro"
    }
}

Now ? + shift + o now automatically converts each file from 2 space indentation to 4 (but will keep indenting if you run it further)

How is the AND/OR operator represented as in Regular Expressions?

Or you can use this:

^(?:part[12]|(part)1,\12)$

Does hosts file exist on the iPhone? How to change it?

It might exist, but you cannot change it on a non-jailbreaked iPhone.

Assuming that your development webserver is on a Mac, why don't you simply use its Bonjour name (e.g. MyMac.local.) instead of myrealwebserverontheinternet.com?

Detect Safari browser

As other people have already noted, feature detection is preferred over checking for a specific browser. One reason is that the user agent string can be altered. Another reason is that the string may change and break your code in newer versions.

If you still want to do it and test for any Safari version, I'd suggest using this

var isSafari = navigator.vendor && navigator.vendor.indexOf('Apple') > -1 &&
               navigator.userAgent &&
               navigator.userAgent.indexOf('CriOS') == -1 &&
               navigator.userAgent.indexOf('FxiOS') == -1;

This will work with any version of Safari across all devices: Mac, iPhone, iPod, iPad.

Edit

To test in your current browser: https://jsfiddle.net/j5hgcbm2/

Edit 2

Updated according to Chrome docs to detect Chrome on iOS correctly

It's worth noting that all Browsers on iOS are just wrappers for Safari and use the same engine. See bfred.it's comment on his own answer in this thread.

Edit 3

Updated according to Firefox docs to detect Firefox on iOS correctly

Iterate over values of object

EcmaScript 2017 introduced Object.entries that allows you to iterate over values and keys. Documentation

var map = { key1 : 'value1', key2 : 'value2' }

for (let [key, value] of Object.entries(map)) {
    console.log(`${key}: ${value}`);
}

The result will be:

key1: value1
key2: value2

How do I increase the scrollback buffer in a running screen session?

For posterity, this answer is incorrect as noted by Steven Lu. Leaving original text however.

Original answer:

To those arriving via web search (several years later)...

When using screen, your scrollback buffer is a combination of both the screen scrollback buffer as the two previous answers have noted, as well as your putty scrollback buffer.

Be sure that you are increasing BOTH the putty scrollback buffer as well as the screen scrollback buffer, else your putty window itself won't let you scroll back to see your screen's scrollback history (overcome by scrolling within screen with ctrl+a->ctrl+u)

You can change your putty scrollback limit under the "Window" category in the settings. Exiting and reopening a putty session to your screen won't close your screen (assuming you just close the putty window and don't type exit), as the OP asked for.

Hope that helps identify why increasing the screen's scrollback buffer doesn't solve someone's problem.

SQL Server 2008 can't login with newly created user

You'll likely need to check the SQL Server error logs to determine the actual state (it's not reported to the client for security reasons.) See here for details.

how to find my angular version in my project?

define VERSION variable and import version into it.

import { VERSION } from '@angular/core';

Now you can use VERSION variable in your code to print version For example,

console.log(VERSION.full); 

update query with join on two tables

update addresses set cid=id where id in (select id from customers)

How to vertically center an image inside of a div element in HTML using CSS?

div {

width:200px; 
height:150px; 

display:-moz-box; 
-moz-box-pack:center; 
-moz-box-align:center; 

display:-webkit-box; 
-webkit-box-pack:center; 
-webkit-box-align:center; 

display:box; 
box-pack:center; 
box-align:center;

}

<div>
<img src="images/logo.png" />
</div>

How to set environment variables in Python?

You should assign string value to environment variable.

os.environ["DEBUSSY"] = "1"

If you want to read or print the environment variable just use

print os.environ["DEBUSSY"]

This changes will be effective only for the current process where it was assigned, it will no change the value permanently. The child processes will automatically inherit the environment of the parent process.

enter image description here

Support for the experimental syntax 'classProperties' isn't currently enabled

First install the: @babel/plugin-proposal-class-properties as dev dependency:

npm install @babel/plugin-proposal-class-properties --save-dev

Then edit your .babelrc so it will be exact like this:

{
  "presets": [
      "@babel/preset-env",
      "@babel/preset-react"
  ],
  "plugins": [
      [
        "@babel/plugin-proposal-class-properties"
      ]
  ]
}

.babelrc file located in the root directory, where package.json is.

Note that you should re-start your webpack dev server to changes take affect.

How to make node.js require absolute? (instead of relative)

Just want to follow up on the great answer from Paolo Moretti and Browserify. If you are using a transpiler (e.g., babel, typescript) and you have separate folders for source and transpiled code like src/ and dist/, you could use a variation of the solutions as

node_modules

With the following directory structure:

app
  node_modules
    ... // normal npm dependencies for app
  src
    node_modules
      app
        ... // source code
  dist
    node_modules
      app
        ... // transpiled code

you can then let babel etc to transpile src directory to dist directory.

symlink

Using symlink we can get rid some levels of nesting:

app
  node_modules
    ... // normal npm dependencies for app
  src
    node_modules
      app // symlinks to '..'
    ... // source code
  dist
    node_modules
      app // symlinks to '..'
    ... // transpiled code

A caveat with babel --copy-files The --copy-files flag of babel does not deal with symlinks well. It may keep navigating into the .. symlink and recusively seeing endless files. A workaround is to use the following directory structure:

app
  node_modules
    app // symlink to '../src'
    ... // normal npm dependencies for app
  src
    ... // source code
  dist
    node_modules
      app // symlinks to '..'
    ... // transpiled code

In this way, code under src will still have app resolved to src, whereas babel would not see symlinks anymore.

How to declare Global Variables in Excel VBA to be visible across the Workbook

Your question is: are these not modules capable of declaring variables at global scope?

Answer: YES, they are "capable"

The only point is that references to global variables in ThisWorkbook or a Sheet module have to be fully qualified (i.e., referred to as ThisWorkbook.Global1, e.g.) References to global variables in a standard module have to be fully qualified only in case of ambiguity (e.g., if there is more than one standard module defining a variable with name Global1, and you mean to use it in a third module).

For instance, place in Sheet1 code

Public glob_sh1 As String

Sub test_sh1()
    Debug.Print (glob_mod)
    Debug.Print (ThisWorkbook.glob_this)
    Debug.Print (Sheet1.glob_sh1)
End Sub

place in ThisWorkbook code

Public glob_this As String

Sub test_this()
    Debug.Print (glob_mod)
    Debug.Print (ThisWorkbook.glob_this)
    Debug.Print (Sheet1.glob_sh1)
End Sub

and in a Standard Module code

Public glob_mod As String

Sub test_mod()
    glob_mod = "glob_mod"
    ThisWorkbook.glob_this = "glob_this"
    Sheet1.glob_sh1 = "glob_sh1"
    Debug.Print (glob_mod)
    Debug.Print (ThisWorkbook.glob_this)
    Debug.Print (Sheet1.glob_sh1)
End Sub

All three subs work fine.

PS1: This answer is based essentially on info from here. It is much worth reading (from the great Chip Pearson).

PS2: Your line Debug.Print ("Hello") will give you the compile error Invalid outside procedure.

PS3: You could (partly) check your code with Debug -> Compile VBAProject in the VB editor. All compile errors will pop.

PS4: Check also Put Excel-VBA code in module or sheet?.

PS5: You might be not able to declare a global variable in, say, Sheet1, and use it in code from other workbook (reading http://msdn.microsoft.com/en-us/library/office/gg264241%28v=office.15%29.aspx#sectionSection0; I did not test this point, so this issue is yet to be confirmed as such). But you do not mean to do that in your example, anyway.

PS6: There are several cases that lead to ambiguity in case of not fully qualifying global variables. You may tinker a little to find them. They are compile errors.

How to access private data members outside the class without making "friend"s?


EDIT:
Just saw you edited the question to say that you don't want to use friend.
Then the answer is:

NO you can't, atleast not in a portable way approved by the C++ standard.


The later part of the Answer, was previous to the Q edit & I leave it here for benefit of >those who would want to understand a few concepts & not just looking an Answer to the >Question.


If you have members under a Private access specifier then those members are only accessible from within the class. No outside Access is allowed.

An Source Code Example:

class MyClass
{
    private:
        int c;
    public:
    void doSomething()
    {
        c = 10;    //Allowed 
    }
};

int main()
{
    MyClass obj;
    obj.c = 30;     //Not Allowed, gives compiler error
    obj.doSomething();  //Allowed
}

A Workaround: friend to rescue
To access the private member, you can declare a function/class as friend of that particular class, and then the member will be accessible inside that function or class object without access specifier check.

Modified Code Sample:

class MyClass
{
    private:
        int c;

    public:
    void doSomething()
    {
        c = 10;    //Allowed 
    }

    friend void MytrustedFriend();    
};

void MytrustedFriend()
{
        MyClass obj;
        obj.c = 10; //Allowed
}

int main()
{
    MyClass obj;
    obj.c = 30;     //Not Allowed, gives compiler error
    obj.doSomething();  //Allowed
    //Call the friend function
    MytrustedFriend();
    return 0;
}

Proper way to exit command line program?

Take a look at Job Control on UNIX systems

If you don't have control of your shell, simply hitting ctrl + C should stop the process. If that doesn't work, you can try ctrl + Z and using the jobs and kill -9 %<job #> to kill it. The '-9' is a type of signal. You can man kill to see a list of signals.

C compile : collect2: error: ld returned 1 exit status

sometimes this error came beacause failed to compile in middlest of any build. The best way to try is by doing make clean and again make the whole code .

how to display none through code behind

I believe this should work:

login_div.Attributes.Add("style","display:none");

Is there an "if -then - else " statement in XPath?

The official language specification for XPath 2.0 on W3.org details that the language does indeed support if statements. See Section 3.8 Conditional Expressions, in particular. Along with the syntax format and explanation, it gives the following example:

if ($widget1/unit-cost < $widget2/unit-cost) 
  then $widget1
  else $widget2

This would suggest that you shouldn't have brackets surrounding your expressions (otherwise the syntax looks correct). I'm not wholly confident, but it's surely worth a try. So you'll want to change your query to look like this:

if (fn:ends-with(//div [@id='head']/text(),': '))
  then fn:substring-before(//div [@id='head']/text(),': ')
  else //div [@id='head']/text()

I do strongly suspect this may fix it however, as the fact that your XPath engine seems to be trying to interpret if as a function, where it is in fact a special construct of the language.

Finally, to point out the obvious, insure that your XPath engine does in fact support XPath 2.0 (as opposed to an earlier version)! I don't believe conditional expressions are part of previous versions of XPath.

In Eclipse, what can cause Package Explorer "red-x" error-icon when all Java sources compile without errors?

You can go to project-> Buildpath-> Library

If there is any library that is X marked ie [cross marked] removed it and again try to build. It worked for me as well/

"R cannot be resolved to a variable"?

I got similar problem and solution I found out was in resources any of the file aka background, sound etc must not contain capital letters or any special symbol other than _

Python MySQLdb TypeError: not all arguments converted during string formatting

cur.execute( "SELECT * FROM records WHERE email LIKE %s", (search,) )

I do not why, but this works for me . rather than use '%s'.

Can you break from a Groovy "each" closure?

You can't break from a Groovy each loop, but you can break from a java "enhanced" for loop.

def a = [1, 2, 3, 4, 5, 6, 7]

for (def i : a) {
    if (i < 2)
        continue
    if (i > 5)
        break
    println i
}

Output:

2
3
4
5

This might not fit for absolutely every situation but it's helped for me :)

Replace new lines with a comma delimiter with Notepad++?

This might sound strange but you can remove next line by copying the whole text and pasting it in firefox search bar, and then re-pasting it in notepad++

step 1

step 2

What is the SSIS package and what does it do?

SSIS (SQL Server Integration Services) is an upgrade of DTS (Data Transformation Services), which is a feature of the previous version of SQL Server. SSIS packages can be created in BIDS (Business Intelligence Development Studio). These can be used to merge data from heterogeneous data sources into SQL Server. They can also be used to populate data warehouses, to clean and standardize data, and to automate administrative tasks.

SQL Server Integration Services (SSIS) is a component of Microsoft SQL Server 2005. It replaces Data Transformation Services, which has been a feature of SQL Server since Version 7.0. Unlike DTS, which was included in all versions, SSIS is only available in the "Standard" and "Enterprise" editions. Integration Services provides a platform to build data integration and workflow applications. The primary use for SSIS is data warehousing as the product features a fast and flexible tool for data extraction, transformation, and loading (ETL).). The tool may also be used to automate maintenance of SQL Server databases, update multidimensional cube data, and perform other functions.

How do I drop table variables in SQL-Server? Should I even do this?

Indeed, you don't need to drop a @local_variable.

But if you use #local_table, it can be done, e.g. it's convenient to be able to re-execute a query several times.

SELECT *
INTO #recent_records
FROM dbo.my_table t
WHERE t.CreatedOn > '2021-01-01'
;

SELECT *
FROM #recent_records
;

/*
  can DROP here, otherwise will fail with the following error
  on re-execution in the same window (I use SSMS DB client):

  Msg 2714, Level ..., State ..., Line ...
  There is already an object named '#recent_records' in the database.
*/
DROP TABLE #recent_records
;

You can also put your SELECT statement in a TRANSACTION to be able to re-execute without an explicit DROP:

BEGIN TRANSACTION

  SELECT *
  INTO #recent_records
  FROM dbo.my_table t
  WHERE t.CreatedOn > '2021-01-01'
  ;

  SELECT *
  FROM #recent_records
  ;

ROLLBACK

CSS Always On Top

Assuming that your markup looks like:

<div id="header" style="position: fixed;"></div>
<div id="content" style="position: relative;"></div>

Now both elements are positioned; in which case, the element at the bottom (in source order) will cover element above it (in source order).

Add a z-index on header; 1 should be sufficient.

Proper way to wait for one function to finish before continuing?

An elegant way to wait for one function to complete first is to use Promises with async/await function.


  1. Firstly, create a Promise. The function I created will be completed after 2s. I used setTimeout in order to demonstrate the situation where the instructions would take some time to execute.
  2. For the second function, you can use async/await function where you will await for the first function to complete before proceeding with the instructions.

Example:

_x000D_
_x000D_
    //1. Create a new function that returns a promise
    function firstFunction() {
      return new Promise((resolve, reject) => {
          let y = 0
          setTimeout(() => {
            for(i=0; i<10; i++){
               y++
            }
             console.log('loop completed')  
             resolve(y)
          }, 2000)
      })
    }
    
    //2. Create an async function
    async function secondFunction() {
        console.log('before promise call')
        //3. Await for the first function to complete
        let result = await firstFunction()
        console.log('promise resolved: ' + result)
        console.log('next step')
    }; 

    secondFunction()
_x000D_
_x000D_
_x000D_


Note:

You could simply resolve the Promise without any value like so resolve(). In my example, I resolved the Promise with the value of y that I can then use in the second function.

How do I unlock a SQLite database?

I just had something similar happen to me - my web application was able to read from the database, but could not perform any inserts or updates. A reboot of Apache solved the issue at least temporarily.

It'd be nice, however, to be able to track down the root cause.

Can someone explain how to implement the jQuery File Upload plugin?

This is good Angular plugin for uploading files, and its free!

angular file upload

Express-js wildcard routing to cover everything under and including a path

It is not necessary to have two routes.

Simply add (/*)? at the end of your path string.

For example, app.get('/hello/world(/*)?' /* ... */)

Here is a fully working example, feel free to copy and paste this into a .js file to run with node, and play with it in a browser (or curl):

const app = require('express')()

// will be able to match all of the following
const test1 = 'http://localhost:3000/hello/world'
const test2 = 'http://localhost:3000/hello/world/'
const test3 = 'http://localhost:3000/hello/world/with/more/stuff'

// but fail at this one
const failTest = 'http://localhost:3000/foo/world'

app.get('/hello/world(/*)?', (req, res) => res.send(`
    This will match at example endpoints: <br><br>
    <pre><a href="${test1}">${test1}</a></pre>
    <pre><a href="${test2}">${test2}</a></pre>
    <pre><a href="${test3}">${test3}</a></pre>

    <br><br> Will NOT match at: <pre><a href="${failTest}">${failTest}</a></pre>
`))

app.listen(3000, () => console.log('Check this out in a browser at http://localhost:3000/hello/world!'))

Find a string by searching all tables in SQL Server Management Studio 2008

There's no need for nested looping (outer looping through tables and inner looping through all table columns). One can retrieve all (or arbitrary selected/filtered) table-column combinations from INFORMATION_SCHEMA.COLUMNS and in one loop simply pass through (search) all of them:

DECLARE @search VARCHAR(100), @table SYSNAME, @column SYSNAME

DECLARE curTabCol CURSOR FOR
    SELECT c.TABLE_SCHEMA + '.' + c.TABLE_NAME, c.COLUMN_NAME
    FROM INFORMATION_SCHEMA.COLUMNS c
    JOIN INFORMATION_SCHEMA.TABLES t 
      ON t.TABLE_NAME=c.TABLE_NAME AND t.TABLE_TYPE='BASE TABLE' -- avoid views
    WHERE c.DATA_TYPE IN ('varchar','nvarchar') -- searching only in these column types
    --AND c.COLUMN_NAME IN ('NAME','DESCRIPTION') -- searching only in these column names

SET @search='john'

OPEN curTabCol
FETCH NEXT FROM curTabCol INTO @table, @column

WHILE (@@FETCH_STATUS = 0)
BEGIN
    EXECUTE('IF EXISTS 
             (SELECT * FROM ' + @table + ' WHERE ' + @column + ' = ''' + @search + ''') 
             PRINT ''' + @table + '.' + @column + '''')
    FETCH NEXT FROM curTabCol INTO @table, @column
END

CLOSE curTabCol
DEALLOCATE curTabCol

SQL Server - calculate elapsed time between two datetime stamps in HH:MM:SS format

The best and simple way:

Convert(varchar, {EndTime} - {StartTime}, 108)

Just like Anri noted.

How to increment a JavaScript variable using a button press event

I needed to see the results of this script and was able to do so by incorporating the below:

var i=0;

function increase()
{
i++;
document.getElementById('boldstuff').innerHTML= +i;
}

<p>var = <b id="boldstuff">0</b></p>
<input type="button" onclick="increase();">

add the "script" tag above all and a closing script tag below the function end curly brace. Returning false caused firefox to hang when I tried it. All other solutions didn't show the result of the increment, in my experience.

How do I tell a Python script to use a particular version

While the OP may be working on a nix platform this answer could help non-nix platforms. I have not experienced the shebang approach work in Microsoft Windows.

Rephrased: The shebang line answers your question of "within my script" but I believe only for Unix-like platforms. Even though it is the Unix shell, outside the script, that actually interprets the shebang line to determine which version of Python interpreter to call. I am not sure, but I believe that solution does not solve the problem for Microsoft Windows platform users.

In the Microsoft Windows world, the simplify the way to run a specific Python version, without environment variables setup specifically for each specific version of Python installed, is just by prefixing the python.exe with the path you want to run it from, such as C:\Python25\python.exe mymodule.py or D:\Python27\python.exe mymodule.py

However you'd need to consider the PYTHONPATH and other PYTHON... environment variables that would point to the wrong version of Python libraries.

For example, you might run: C:\Python2.5.2\python.exe mymodule

Yet, the environment variables may point to the wrong version as such:

PYTHONPATH = D:\Python27

PYTHONLIB = D:\Python27\lib

Loads of horrible fun!

So a non-virtualenv way, in Windows, would be to use a batch file that sets up the environment and calls a specific Python executable via prefixing the python.exe with the path it resides in. This way has additional details you'll have to manage though; such as using command line arguments for either of the "start" or "cmd.exe" command to "save and replace the "console" environment" if you want the console to stick around after the application exits.

Your question leads me to believe you have several Python modules, each expecting a certain version of Python. This might be solvable "within" the script by having a launching module which uses the subprocess module. Instead of calling mymodule.py you would call a module that calls your module; perhaps launch_mymodule.py

launch_mymodule.py

import sys
import subprocess
if sys.argv[2] == '272':
  env272 = {
    'PYTHONPATH': 'blabla',
    'PYTHONLIB': 'blabla', }
  launch272 = subprocess.Popen('D:\\Python272\\python.exe mymodule.py', env=env272)

if sys.argv[1] == '252'
  env252 = {
    'PYTHONPATH': 'blabla',
    'PYTHONLIB': 'blabla', }
  launch252 = subprocess.Popen('C:\\Python252\\python.exe mymodule.py', env=env252)

I have not tested this.

Validate fields after user has left a field

ng-model-options in AngularJS 1.3 (beta as of this writing) is documented to support {updateOn: 'blur'}. For earlier versions, something like the following worked for me:

myApp.directive('myForm', function() {
  return {
    require: 'form',
    link: function(scope, element, attrs, formController) {
      scope.validate = function(name) {
        formController[name].isInvalid
            = formController[name].$invalid;
      };
    }
  };
});

With a template like this:

<form name="myForm" novalidate="novalidate" data-my-form="">
<input type="email" name="eMail" required="required" ng-blur="validate('eMail')" />
<span ng-show="myForm.eMail.isInvalid">Please enter a valid e-mail address.</span>
<button type="submit">Submit Form</button>
</form>

TypeError: 'str' does not support the buffer interface

There is an easier solution to this problem.

You just need to add a t to the mode so it becomes wt. This causes Python to open the file as a text file and not binary. Then everything will just work.

The complete program becomes this:

plaintext = input("Please enter the text you want to compress")
filename = input("Please enter the desired filename")
with gzip.open(filename + ".gz", "wt") as outfile:
    outfile.write(plaintext)

How to write inside a DIV box with javascript

_x000D_
_x000D_
document.getElementById('log').innerHTML += '<br>Some new content!';
_x000D_
<div id="log">initial content</div>
_x000D_
_x000D_
_x000D_

How to unpack an .asar file?

https://www.electronjs.org/apps/asarui

UI for Asar, Extract All, or drag extract file/directory

Stopword removal with NLTK

@alvas's answer does the job but it can be done way faster. Assuming that you have documents: a list of strings.

from nltk.corpus import stopwords
from nltk.tokenize import wordpunct_tokenize

stop_words = set(stopwords.words('english'))
stop_words.update(['.', ',', '"', "'", '?', '!', ':', ';', '(', ')', '[', ']', '{', '}']) # remove it if you need punctuation 

for doc in documents:
    list_of_words = [i.lower() for i in wordpunct_tokenize(doc) if i.lower() not in stop_words]

Notice that due to the fact that here you are searching in a set (not in a list) the speed would be theoretically len(stop_words)/2 times faster, which is significant if you need to operate through many documents.

For 5000 documents of approximately 300 words each the difference is between 1.8 seconds for my example and 20 seconds for @alvas's.

P.S. in most of the cases you need to divide the text into words to perform some other classification tasks for which tf-idf is used. So most probably it would be better to use stemmer as well:

from nltk.stem.porter import PorterStemmer
porter = PorterStemmer()

and to use [porter.stem(i.lower()) for i in wordpunct_tokenize(doc) if i.lower() not in stop_words] inside of a loop.

COUNT(*) vs. COUNT(1) vs. COUNT(pk): which is better?

Asked and answered before...

Books on line says "COUNT ( { [ [ ALL | DISTINCT ] expression ] | * } )"

"1" is a non-null expression so it's the same as COUNT(*). The optimiser recognises it as trivial so gives the same plan. A PK is unique and non-null (in SQL Server at least) so COUNT(PK) = COUNT(*)

This is a similar myth to EXISTS (SELECT * ... or EXISTS (SELECT 1 ...

And see the ANSI 92 spec, section 6.5, General Rules, case 1

        a) If COUNT(*) is specified, then the result is the cardinality
          of T.

        b) Otherwise, let TX be the single-column table that is the
          result of applying the <value expression> to each row of T
          and eliminating null values. If one or more null values are
          eliminated, then a completion condition is raised: warning-
          null value eliminated in set function.

Connection failed: SQLState: '01000' SQL Server Error: 10061

To create a new Data source to SQL Server, do the following steps:

  1. In host computer/server go to Sql server management studio --> open Security Section on left hand --> right click on Login, select New Login and then create a new account for your database which you want to connect to.

  2. Check the TCP/IP Protocol is Enable. go to All programs --> Microsoft SQL server 2008 --> Configuration Tools --> open Sql server configuration manager. On the left hand select client protocols (based on your operating system 32/64 bit). On the right hand, check TCP/IP Protocol be Enabled.

  3. In Remote computer/server, open Data source administrator. Control panel --> Administrative tools --> Data sources (ODBC).

  4. In User DSN or System DSN , click Add button and select Sql Server driver and then press Finish.

  5. Enter Name.

  6. Enter Server, note that: if you want to enter host computer address, you should enter that`s IP address without "\\". eg. 192.168.1.5 and press Next.

  7. Select With SQL Server authentication using a login ID and password entered by the user.

  8. At the bellow enter your login ID and password which you created on first step. and then click Next.

  9. If shown Database is your database, click Next and then Finish.

iPhone: Setting Navigation Bar Title

UINavigationItem* item = [[UINavigationItem alloc] initWithTitle:@"title text"];
...
[bar pushNavigationItem:item animated:YES];
[item release];

This code worked.

.NET console application as Windows service

You can use

reg add HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run /v ServiceName /d "c:\path\to\service\file\exe"

And it will appear int the service list. I do not know, whether that works correctly though. A service usually has to listen to several events.

There are several service wrapper though, that can run any application as a real service. For Example Microsofts SrvAny from the Win2003 Resource Kit

How to put img inline with text

Images have display: inline by default.
You might want to put the image inside the paragraph.
<p><img /></p>

Can I call a base class's virtual function if I'm overriding it?

The C++ syntax is like this:

class Bar : public Foo {
  // ...

  void printStuff() {
    Foo::printStuff(); // calls base class' function
  }
};

How to add number of days to today's date?

Here is a solution that worked for me.

function calduedate(ndays){

    var newdt = new Date(); var chrday; var chrmnth;
    newdt.setDate(newdt.getDate() + parseInt(ndays));

    var newdate = newdt.getFullYear();
    if(newdt.getMonth() < 10){
        newdate = newdate+'-'+'0'+newdt.getMonth();
    }else{
        newdate = newdate+'-'+newdt.getMonth();
    }
    if(newdt.getDate() < 10){
        newdate = newdate+'-'+'0'+newdt.getDate();
    }else{
        newdate = newdate+'-'+newdt.getDate();
    }

    alert("newdate="+newdate);

}

Python, Matplotlib, subplot: How to set the axis range?

Sometimes you really want to set the axes limits before you plot the data. In that case, you can set the "autoscaling" feature of the Axes or AxesSubplot object. The functions of interest are set_autoscale_on, set_autoscalex_on, and set_autoscaley_on.

In your case, you want to freeze the y axis' limits, but allow the x axis to expand to accommodate your data. Therefore, you want to change the autoscaley_on property to False. Here is a modified version of the FFT subplot snippet from your code:

fft_axes = pylab.subplot(h,w,2)
pylab.title("FFT")
fft = scipy.fft(rawsignal)
pylab.ylim([0,1000])
fft_axes.set_autoscaley_on(False)
pylab.plot(abs(fft))

Bootstrap 3 scrollable div for table

Well one way to do it is set the height of your body to the height that you want your page to be. In this example I did 600px.

Then set your wrapper height to a percentage of the body here I did 70% This will adjust your table so that it does not fill up the whole screen but in stead just takes up a percentage of the specified page height.

body {
   padding-top: 70px;
   border:1px solid black;
   height:600px;
}

.mygrid-wrapper-div {
   border: solid red 5px;
   overflow: scroll;
   height: 70%;
}

http://jsfiddle.net/4NB2N/7/

Update How about a jQuery approach.

$(function() {  
   var window_height = $(window).height(),
   content_height = window_height - 200;
   $('.mygrid-wrapper-div').height(content_height);
});

$( window ).resize(function() {
   var window_height = $(window).height(),
   content_height = window_height - 200;
   $('.mygrid-wrapper-div').height(content_height);
});

http://jsfiddle.net/4NB2N/11/

Editing the git commit message in GitHub

I was facing the same problem.

See in your github for a particular branch and you will come to know the commit id of the very first commit in that branch. do a rebase to that:

git rebase -i

editor will open up. Do a track of your commits from github UI and opened editor and change the messages.

How do I get HTTP Request body content in Laravel?

I don't think you want the data from your Request, I think you want the data from your Response. The two are different. Also you should build your response correctly in your controller.

Looking at the class in edit #2, I would make it look like this:

class XmlController extends Controller
{
    public function index()
    {
        $content = Request::all();
        return Response::json($content);
    }
}

Once you've gotten that far you should check the content of your response in your test case (use print_r if necessary), you should see the data inside.

More information on Laravel responses here:

http://laravel.com/docs/5.0/responses

Unable to obtain LocalDateTime from TemporalAccessor when parsing LocalDateTime (Java 8)

This is a really unclear and unhelpful error message. After much trial and error I found that LocalDateTime will give the above error if you do not attempt to parse a time. By using LocalDate instead, it works without erroring.

This is poorly documented and the related exception is very unhelpful.

importing external ".txt" file in python

This answer is modified from infrared's answer at Splitting large text file by a delimiter in Python

with open('words.txt') as fp:
    contents = fp.read()
    for entry in contents:
        # do something with entry  

Field 'id' doesn't have a default value?

There are 2 solutions mentioned below:

Solution 1

MySQL is most likely in STRICT SQL mode. Try to execute SQL query SET GLOBAL sql_mode='' or edit your my.cnf / my.ini to make sure you aren't setting STRICT_ALL_TABLES and/or STRICT_TRANS_TABLES.

Solution 2

If Solution-1 is not working then try Solution-2 as given in below steps:

  1. Run MySQL Administrator tool as Administrator.
  2. Then go to Startup Variable.
  3. Then go to the Advance tab.
  4. find SQL Mode and remove the STRICT_ALL_TABLES and/or STRICT_TRANS_TABLES and then Click on Apply Changes.
  5. Restart MySQL Server.
  6. Done.

Note: I have tested these solutions in MySQL Server 5.7

HttpRequest maximum allowable size in tomcat?

The connector section has the parameter

maxPostSize

The maximum size in bytes of the POST which will be handled by the container FORM URL parameter parsing. The limit can be disabled by setting this attribute to a value less than or equal to 0. If not specified, this attribute is set to 2097152 (2 megabytes).

Another Limit is:

maxHttpHeaderSize The maximum size of the request and response HTTP header, specified in bytes. If not specified, this attribute is set to 4096 (4 KB).

You find them in

$TOMCAT_HOME/conf/server.xml

How to bind Close command to a button

I think that in real world scenarios a simple click handler is probably better than over-complicated command-based systems but you can do something like that:

using RelayCommand from this article http://msdn.microsoft.com/en-us/magazine/dd419663.aspx

public class MyCommands
{
    public static readonly ICommand CloseCommand =
        new RelayCommand( o => ((Window)o).Close() );
}
<Button Content="Close Window"
        Command="{X:Static local:MyCommands.CloseCommand}"
        CommandParameter="{Binding RelativeSource={RelativeSource FindAncestor, 
                           AncestorType={x:Type Window}}}"/>

return in for loop or outside loop

The code is valid (i.e, will compile and execute) in both cases.

One of my lecturers at Uni told us that it is not desirable to have continue, return statements in any loop - for or while. The reason for this is that when examining the code, it is not not immediately clear whether the full length of the loop will be executed or the return or continue will take effect.

See Why is continue inside a loop a bad idea? for an example.

The key point to keep in mind is that for simple scenarios like this it doesn't (IMO) matter but when you have complex logic determining the return value, the code is 'generally' more readable if you have a single return statement instead of several.

With regards to the Garbage Collection - I have no idea why this would be an issue.

Get file size, image width and height before upload

So I started experimenting with the different things that FileReader API had to offer and could create an IMG tag with a DATA URL.

Drawback: It doesn't work on mobile phones, but it works fine on Google Chrome.

_x000D_
_x000D_
$('input').change(function() {_x000D_
    _x000D_
    var fr = new FileReader;_x000D_
    _x000D_
    fr.onload = function() {_x000D_
        var img = new Image;_x000D_
        _x000D_
        img.onload = function() { _x000D_
//I loaded the image and have complete control over all attributes, like width and src, which is the purpose of filereader._x000D_
            $.ajax({url: img.src, async: false, success: function(result){_x000D_
              $("#result").html("READING IMAGE, PLEASE WAIT...")_x000D_
              $("#result").html("<img src='" + img.src + "' />");_x000D_
                console.log("Finished reading Image");_x000D_
          }});_x000D_
        };_x000D_
        _x000D_
        img.src = fr.result;_x000D_
    };_x000D_
    _x000D_
    fr.readAsDataURL(this.files[0]);_x000D_
    _x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="file" accept="image/*" capture="camera">_x000D_
<div id='result'>Please choose a file to view it. <br/>(Tested successfully on Chrome - 100% SUCCESS RATE)</div>
_x000D_
_x000D_
_x000D_

(see this on a jsfiddle at http://jsfiddle.net/eD2Ez/530/)
(see the original jsfiddle that i added upon to at http://jsfiddle.net/eD2Ez/)

C# Checking if button was clicked

Click is an event that fires immediately after you release the mouse button. So if you want to check in the handler for button2.Click if button1 was clicked before, all you could do is have a handler for button1.Click which sets a bool flag of your own making to true.

private bool button1WasClicked = false;

private void button1_Click(object sender, EventArgs e)
{
    button1WasClicked = true;
}

private void button2_Click(object sender, EventArgs e)
{
    if (textBox2.Text == textBox3.Text && button1WasClicked)
    { 
        StreamWriter myWriter = File.CreateText(@"c:\Program Files\text.txt");
        myWriter.WriteLine(textBox1.Text);
        myWriter.WriteLine(textBox2.Text);
        button1WasClicked = false;
    }
}

Controlling mouse with Python

As of 2021, you can use mouse:

import mouse
mouse.move("500", "500")
mouse.left_click()

Features

  • Global event hook on all mice devices (captures events regardless of focus).
  • Listen and sends mouse events.
  • Works with Windows and Linux (requires sudo).
  • Pure Python, no C modules to be compiled.
  • Zero dependencies. Trivial to install and deploy, just copy the files.
  • Python 2 and 3
  • Includes high level API (e.g. record and play).
  • Events automatically captured in separate thread, doesn't block main program.
  • Tested and documented.

How to manually set an authenticated user in Spring Security / SpringMVC

Turn on debug logging to get a better picture of what is going on.

You can tell if the session cookies are being set by using a browser-side debugger to look at the headers returned in HTTP responses. (There are other ways too.)

One possibility is that SpringSecurity is setting secure session cookies, and your next page requested has an "http" URL instead of an "https" URL. (The browser won't send a secure cookie for an "http" URL.)

How to connect android emulator to the internet

I had the same problem on my virtual windows 7.

  1. Go to Network Connections
  2. Alt > Advanced > Advanced Settings...
  3. In the second tab bring the internet networks interface on the top

hope it's helpful thanks to

Checking for empty or null List<string>

If you want a single line condition that checks both null and empty, you can use

if (list == null ? true : (!list.Any()))

This will work in older framework versions where the null-conditional operator is not available.

Polynomial time and exponential time

O(n^2) is polynomial time. The polynomial is f(n) = n^2. On the other hand, O(2^n) is exponential time, where the exponential function implied is f(n) = 2^n. The difference is whether the function of n places n in the base of an exponentiation, or in the exponent itself.

Any exponential growth function will grow significantly faster (long term) than any polynomial function, so the distinction is relevant to the efficiency of an algorithm, especially for large values of n.

macOS on VMware doesn't recognize iOS device

If you went throught alot of pain installing macos on vmware I recommend this tutorial which also provides you with all the file you need. it's straight forward tutorial and works all the way without any problem.

How to get current time and date in C++?

New answer for an old question:

The question does not specify in what timezone. There are two reasonable possibilities:

  1. In UTC.
  2. In the computer's local timezone.

For 1, you can use this date library and the following program:

#include "date.h"
#include <iostream>

int
main()
{
    using namespace date;
    using namespace std::chrono;
    std::cout << system_clock::now() << '\n';
}

Which just output for me:

2015-08-18 22:08:18.944211

The date library essentially just adds a streaming operator for std::chrono::system_clock::time_point. It also adds a lot of other nice functionality, but that is not used in this simple program.

If you prefer 2 (the local time), there is a timezone library that builds on top of the date library. Both of these libraries are open source and cross platform, assuming the compiler supports C++11 or C++14.

#include "tz.h"
#include <iostream>

int
main()
{
    using namespace date;
    using namespace std::chrono;
    auto local = make_zoned(current_zone(), system_clock::now());
    std::cout << local << '\n';
}

Which for me just output:

2015-08-18 18:08:18.944211 EDT

The result type from make_zoned is a date::zoned_time which is a pairing of a date::time_zone and a std::chrono::system_clock::time_point. This pair represents a local time, but can also represent UTC, depending on how you query it.

With the above output, you can see that my computer is currently in a timezone with a UTC offset of -4h, and an abbreviation of EDT.

If some other timezone is desired, that can also be accomplished. For example to find the current time in Sydney , Australia just change the construction of the variable local to:

auto local = make_zoned("Australia/Sydney", system_clock::now());

And the output changes to:

2015-08-19 08:08:18.944211 AEST

Update for C++20

This library is now largely adopted for C++20. The namespace date is gone and everything is in namespace std::chrono now. And use zoned_time in place of make_time. Drop the headers "date.h" and "tz.h" and just use <chrono>.

As I write this, partial implementations are just beginning to emerge on some platforms.

JQuery How to extract value from href tag?

if ($('a').on('Clicked').text().search('1') == -1)
{
    //Page == 1
}
else
{
    //Page != 1
}

Subtract two dates in SQL and get days of the result

Syntax

DATEDIFF(expr1,expr2)

Description

DATEDIFF() returns (expr1 – expr2) expressed as a value in days from one date to the other. expr1 and expr2 are date or date-and-time expressions. Only the date parts of the values are used in the calculation.

@D Stanley

Counting words in string

One more way to count words in a string. This code counts words that contain only alphanumeric characters and "_", "’", "-", "'" chars.

function countWords(str) {
  var matches = str.match(/[\w\d\’\'-]+/gi);
  return matches ? matches.length : 0;
}

How to find all the dependencies of a table in sql server

The following SQL lists all object dependencies across all databases and servers:

IF(OBJECT_ID('tempdb..#Obj_Dep_Details') IS NOT NULL)
BEGIN
    DROP TABLE #Obj_Dep_Details
END
CREATE TABLE #Obj_Dep_Details
(
   [Database]               nvarchar(128)
  ,[Schema]                 nvarchar(128)
  ,dependent_object         nvarchar(128)
  ,dependent_object_type    nvarchar(60)
  ,referenced_server_name   nvarchar(128)
  ,referenced_database_name nvarchar(128)
  ,referenced_schema_name   nvarchar(128)
  ,referenced_entity_name   nvarchar(128)
  ,referenced_id            int
  ,referenced_object_db     nvarchar(128)
  ,referenced_object_type   nvarchar(60)
  ,referencing_id           int
  ,SchemaDep                nvarchar(128)
)
EXEC sp_MSForEachDB @command1='USE [?];
INSERT INTO #Obj_Dep_Details
SELECT DISTINCT
       DB_NAME()                          AS [Database]
      ,SCHEMA_NAME(od.[schema_id])        AS [Schema]
      ,OBJECT_NAME(d1.referencing_id)     AS dependent_object
      ,od.[type_desc]                     AS dependent_object_type
      ,COALESCE(d1.referenced_server_name, @@SERVERNAME)                AS referenced_server_name
      ,COALESCE(d1.referenced_database_name, DB_NAME())                 AS referenced_database_name
      ,COALESCE(d1.referenced_schema_name, SCHEMA_NAME(ro.[schema_id])) AS referenced_schema_name
      ,d1.referenced_entity_name
      ,d1.referenced_id
      ,DB_NAME(ro.parent_object_id)        AS referenced_object_db
      ,ro.[type_desc]                      AS referenced_object_type
      ,d1.referencing_id
      ,SCHEMA_NAME(od.[schema_id])         AS SchemaDep
  FROM sys.sql_expression_dependencies d1
  LEFT OUTER JOIN sys.all_objects od
    ON d1.referencing_id = od.[object_id]
  LEFT OUTER JOIN sys.objects ro
    ON d1.referenced_id = ro.[object_id]'

SELECT [Database]                                       AS [Dep_Object_DB]
      ,[Schema]                                         AS [Dep_Object_Schema]
      ,dependent_object                                 AS [Dep_Object_Name]
      ,LOWER(REPLACE(dependent_object_type, '_', ' '))  AS [Dep_Object_Type]
      ,referenced_server_name                           AS [Ref_Object_Server_Name]
      ,referenced_database_name                         AS [Ref_Object_DB]
      ,referenced_schema_name                           AS [Ref_Object_Schema]
      ,referenced_entity_name                           AS [Ref_Object_Name]
      ,referenced_id                                    AS [Ref_Object_ID]
      ,LOWER(REPLACE(referenced_object_type, '_', ' ')) AS [Ref_Object_Type]
      ,referencing_id                                   AS [Dep_Object_ID]
  FROM #Obj_Dep_Details WITH(NOLOCK)
 WHERE referenced_entity_name = 'TableName'
ORDER BY [Dep_Object_DB]
        ,[Dep_Object_Name]
        ,[Ref_Object_Name]
        ,[Ref_Object_DB]

TableName Dependencies

How to assign execute permission to a .sh file in windows to be executed in linux

This is not possible. Linux permissions and windows permissions do not translate. They are machine specific. It would be a security hole to allow permissions to be set on files before they even arrive on the target system.

Android Studio - How to Change Android SDK Path

I Configured in this way

on

Welcome to Android Studio Screen

Click Configure Then

Project Defaults and then Project Structure

Then Android SDK and Selected the path to my current location of Android SDK enter image description here

enter image description here

Iterating through all the cells in Excel VBA or VSTO 2005

If you only need to look at the cells that are in use you can use:

sub IterateCells()

   For Each Cell in ActiveSheet.UsedRange.Cells
      'do some stuff
   Next

End Sub

that will hit everything in the range from A1 to the last cell with data (the bottom right-most cell)

Adding custom HTTP headers using JavaScript

I think the easiest way to accomplish it is to use querystring instead of HTTP headers.

angular 2 ngIf and CSS transition/animation

Am using angular 5 and for an ngif to work for me that is in a ngfor, I had to use animateChild and in the user-detail component I used the *ngIf="user.expanded" to show hide user and it worked for entering a leaving

 <div *ngFor="let user of users" @flyInParent>
  <ly-user-detail [user]= "user" @flyIn></user-detail>
</div>

//the animation file


export const FLIP_TRANSITION = [ 
trigger('flyInParent', [
    transition(':enter, :leave', [
      query('@*', animateChild())
    ])
  ]),
  trigger('flyIn', [
    state('void', style({width: '100%', height: '100%'})),
    state('*', style({width: '100%', height: '100%'})),
    transition(':enter', [
      style({
        transform: 'translateY(100%)',
        position: 'fixed'
      }),
      animate('0.5s cubic-bezier(0.35, 0, 0.25, 1)', style({transform: 'translateY(0%)'}))
    ]),
    transition(':leave', [
      style({
        transform: 'translateY(0%)',
        position: 'fixed'
      }),
      animate('0.5s cubic-bezier(0.35, 0, 0.25, 1)', style({transform: 'translateY(100%)'}))
    ])
  ])
];

When does SQLiteOpenHelper onCreate() / onUpgrade() run?

May be I am too late but I would like to share my short and sweet answer. Please check Answer for a same problem. It will definitely help you. No more deep specifications.

If you are confident about syntax for creating table, than it may happen when you add new column in your same table, for that...

1) Uninstall from your device and run it again.

OR

2) Setting -> app -> ClearData

OR

3) Change DATABASE_VERSION in your "DatabaseHandler" class (If you have added new column than it will upgrade automatically)

public DatabaseHandler(Context context) {
    super(context, DATABASE_NAME, null, DATABASE_VERSION);
}

OR

4) Change DATABASE_NAME in your "DatabaseHandler" class (I faced same problem. But I succeed by changing DATABASE_NAME.)

jQuery-UI datepicker default date

$("#birthdate" ).datepicker("setDate", new Date(1985,01,01))

How to overlay one div over another div

The accepted solution works great, but IMO lacks an explanation as to why it works. The example below is boiled down to the basics and separates the important CSS from the non-relevant styling CSS. As a bonus, I've also included a detailed explanation of how CSS positioning works.

TLDR; if you only want the code, scroll down to The Result.

The Problem

There are two separate, sibling, elements and the goal is to position the second element (with an id of infoi), so it appears within the previous element (the one with a class of navi). The HTML structure cannot be changed.

Proposed Solution

To achieve the desired result we're going to move, or position, the second element, which we'll call #infoi so it appears within the first element, which we'll call .navi. Specifically, we want #infoi to be positioned in the top-right corner of .navi.

CSS Position Required Knowledge

CSS has several properties for positioning elements. By default, all elements are position: static. This means the element will be positioned according to its order in the HTML structure, with few exceptions.

The other position values are relative, absolute, sticky, and fixed. By setting an element's position to one of these other values it's now possible to use a combination of the following four properties to position the element:

  • top
  • right
  • bottom
  • left

In other words, by setting position: absolute, we can add top: 100px to position the element 100 pixels from the top of the page. Conversely, if we set bottom: 100px the element would be positioned 100 pixels from the bottom of the page.

Here's where many CSS newcomers get lost - position: absolute has a frame of reference. In the example above, the frame of reference is the body element. position: absolute with top: 100px means the element is positioned 100 pixels from the top of the body element.

The position frame of reference, or position context, can be altered by setting the position of a parent element to any value other than position: static. That is, we can create a new position context by giving a parent element:

  • position: relative;
  • position: absolute;
  • position: sticky;
  • position: fixed;

For example, if a <div class="parent"> element is given position: relative, any child elements use the <div class="parent"> as their position context. If a child element were given position: absolute and top: 100px, the element would be positioned 100 pixels from the top of the <div class="parent"> element, because the <div class="parent"> is now the position context.

The other factor to be aware of is stack order - or how elements are stacked in the z-direction. The must-know here is the stack order of elements are, by default, defined by the reverse of their order in the HTML structure. Consider the following example:

<body>
  <div>Bottom</div>
  <div>Top</div>
</body>

In this example, if the two <div> elements were positioned in the same place on the page, the <div>Top</div> element would cover the <div>Bottom</div> element. Since <div>Top</div> comes after <div>Bottom</div> in the HTML structure it has a higher stacking order.

_x000D_
_x000D_
div {_x000D_
  position: absolute;_x000D_
  width: 50%;_x000D_
  height: 50%;_x000D_
}_x000D_
_x000D_
#bottom {_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  background-color: blue;_x000D_
}_x000D_
_x000D_
#top {_x000D_
  top: 25%;_x000D_
  left: 25%;_x000D_
  background-color: red;_x000D_
}
_x000D_
<div id="bottom">Bottom</div>_x000D_
<div id="top">Top</div>
_x000D_
_x000D_
_x000D_

The stacking order can be changed with CSS using the z-index or order properties.

We can ignore the stacking order in this issue as the natural HTML structure of the elements means the element we want to appear on top comes after the other element.

So, back to the problem at hand - we'll use position context to solve this issue.

The Solution

As stated above, our goal is to position the #infoi element so it appears within the .navi element. To do this, we'll wrap the .navi and #infoi elements in a new element <div class="wrapper"> so we can create a new position context.

<div class="wrapper">
  <div class="navi"></div>
  <div id="infoi"></div>
</div>

Then create a new position context by giving .wrapper a position: relative.

.wrapper {
  position: relative;
}

With this new position context, we can position #infoi within .wrapper. First, give #infoi a position: absolute, allowing us to position #infoi absolutely in .wrapper.

Then add top: 0 and right: 0 to position the #infoi element in the top-right corner. Remember, because the #infoi element is using .wrapper as its position context, it will be in the top-right of the .wrapper element.

#infoi {
  position: absolute;
  top: 0;
  right: 0;
}

Because .wrapper is merely a container for .navi, positioning #infoi in the top-right corner of .wrapper gives the effect of being positioned in the top-right corner of .navi.

And there we have it, #infoi now appears to be in the top-right corner of .navi.

The Result

The example below is boiled down to the basics, and contains some minimal styling.

_x000D_
_x000D_
/*_x000D_
*  position: relative gives a new position context_x000D_
*/_x000D_
.wrapper {_x000D_
  position: relative;_x000D_
}_x000D_
_x000D_
/*_x000D_
*  The .navi properties are for styling only_x000D_
*  These properties can be changed or removed_x000D_
*/_x000D_
.navi {_x000D_
  background-color: #eaeaea;_x000D_
  height: 40px;_x000D_
}_x000D_
_x000D_
_x000D_
/*_x000D_
*  Position the #infoi element in the top-right_x000D_
*  of the .wrapper element_x000D_
*/_x000D_
#infoi {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  right: 0;_x000D_
_x000D_
  /*_x000D_
  *  Styling only, the below can be changed or removed_x000D_
  *  depending on your use case_x000D_
  */_x000D_
  height: 20px;_x000D_
  padding: 10px 10px;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <div class="navi"></div>_x000D_
  <div id="infoi">_x000D_
    <img src="http://via.placeholder.com/32x20/000000/ffffff?text=?" height="20" width="32"/>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

An Alternate (Grid) Solution

Here's an alternate solution using CSS Grid to position the .navi element with the #infoi element in the far right. I've used the verbose grid properties to make it as clear as possible.

_x000D_
_x000D_
:root {_x000D_
  --columns: 12;_x000D_
}_x000D_
_x000D_
/*_x000D_
*  Setup the wrapper as a Grid element, with 12 columns, 1 row_x000D_
*/_x000D_
.wrapper {_x000D_
  display: grid;_x000D_
  grid-template-columns: repeat(var(--columns), 1fr);_x000D_
  grid-template-rows: 40px;_x000D_
}_x000D_
_x000D_
/*_x000D_
*  Position the .navi element to span all columns_x000D_
*/_x000D_
.navi {_x000D_
  grid-column-start: 1;_x000D_
  grid-column-end: span var(--columns);_x000D_
  grid-row-start: 1;_x000D_
  grid-row-end: 2;_x000D_
  _x000D_
  /*_x000D_
  *  Styling only, the below can be changed or removed_x000D_
  *  depending on your use case_x000D_
  */_x000D_
  background-color: #eaeaea;_x000D_
}_x000D_
_x000D_
_x000D_
/*_x000D_
*  Position the #infoi element in the last column, and center it_x000D_
*/_x000D_
#infoi {_x000D_
  grid-column-start: var(--columns);_x000D_
  grid-column-end: span 1;_x000D_
  grid-row-start: 1;_x000D_
  place-self: center;_x000D_
}
_x000D_
<div class="wrapper">_x000D_
  <div class="navi"></div>_x000D_
  <div id="infoi">_x000D_
    <img src="http://via.placeholder.com/32x20/000000/ffffff?text=?" height="20" width="32"/>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

An Alternate (No Wrapper) Solution

In the case we can't edit any HTML, meaning we can't add a wrapper element, we can still achieve the desired effect.

Instead of using position: absolute on the #infoi element, we'll use position: relative. This allows us to reposition the #infoi element from its default position below the .navi element. With position: relative we can use a negative top value to move it up from its default position, and a left value of 100% minus a few pixels, using left: calc(100% - 52px), to position it near the right-side.

_x000D_
_x000D_
/*_x000D_
*  The .navi properties are for styling only_x000D_
*  These properties can be changed or removed_x000D_
*/_x000D_
.navi {_x000D_
  background-color: #eaeaea;_x000D_
  height: 40px;_x000D_
  width: 100%;_x000D_
}_x000D_
_x000D_
_x000D_
/*_x000D_
*  Position the #infoi element in the top-right_x000D_
*  of the .wrapper element_x000D_
*/_x000D_
#infoi {_x000D_
  position: relative;_x000D_
  display: inline-block;_x000D_
  top: -40px;_x000D_
  left: calc(100% - 52px);_x000D_
_x000D_
  /*_x000D_
  *  Styling only, the below can be changed or removed_x000D_
  *  depending on your use case_x000D_
  */_x000D_
  height: 20px;_x000D_
  padding: 10px 10px;_x000D_
}
_x000D_
<div class="navi"></div>_x000D_
<div id="infoi">_x000D_
  <img src="http://via.placeholder.com/32x20/000000/ffffff?text=?" height="20" width="32"/>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Copying PostgreSQL database to another server

You don't need to create an intermediate file. You can do

pg_dump -C -h localhost -U localuser dbname | psql -h remotehost -U remoteuser dbname

or

pg_dump -C -h remotehost -U remoteuser dbname | psql -h localhost -U localuser dbname

using psql or pg_dump to connect to a remote host.

With a big database or a slow connection, dumping a file and transfering the file compressed may be faster.

As Kornel said there is no need to dump to a intermediate file, if you want to work compressed you can use a compressed tunnel

pg_dump -C dbname | bzip2 | ssh  remoteuser@remotehost "bunzip2 | psql dbname"

or

pg_dump -C dbname | ssh -C remoteuser@remotehost "psql dbname"

but this solution also requires to get a session in both ends.

Note: pg_dump is for backing up and psql is for restoring. So, the first command in this answer is to copy from local to remote and the second one is from remote to local. More -> https://www.postgresql.org/docs/9.6/app-pgdump.html

Access Google's Traffic Data through a Web Service

There is a project called Open Traffic which is not fully functional right now but seems to be the right answer in the future.

OpenTraffic is a global data platform to process anonymous positions of vehicles and smartphones into real-time and historical traffic statistics. We're building this in the open, using fully open-source software, with involvement from a growing list of partners.

Can I extend a class using more than 1 class in PHP?

Always good idea is to make parent class, with functions ... i.e. add this all functionality to parent.

And "move" all classes that use this hierarchically down. I need - rewrite functions, which are specific.

Infinity symbol with HTML

8

This does not require a HTML entity if you are using a modern encoding (such as UTF-8). And if you're not already, you probably should be.

File opens instead of downloading in internet explorer in a href link

Zip your file (.zip) and IE will give the user the option to open or download the file.

Using an Alias in a WHERE clause

This is not possible directly, because chronologically, WHERE happens before SELECT, which always is the last step in the execution chain.

You can do a sub-select and filter on it:

SELECT * FROM
(
  SELECT A.identifier
    , A.name
    , TO_NUMBER(DECODE( A.month_no
      , 1, 200803 
      , 2, 200804 
      , 3, 200805 
      , 4, 200806 
      , 5, 200807 
      , 6, 200808 
      , 7, 200809 
      , 8, 200810 
      , 9, 200811 
      , 10, 200812 
      , 11, 200701 
      , 12, 200702
      , NULL)) as MONTH_NO
    , TO_NUMBER(TO_CHAR(B.last_update_date, 'YYYYMM')) as UPD_DATE
  FROM table_a A
    , table_b B
  WHERE A.identifier = B.identifier
) AS inner_table
WHERE 
  MONTH_NO > UPD_DATE

Interesting bit of info moved up from the comments:

There should be no performance hit. Oracle does not need to materialize inner queries before applying outer conditions -- Oracle will consider transforming this query internally and push the predicate down into the inner query and will do so if it is cost effective. – Justin Cave

Errors in pom.xml with dependencies (Missing artifact...)

It seemed that a lot of dependencies were incorrect.

enter image description here

Download the whole POM here

A good place to look for the correct dependencies is the Maven Repository website.

TypeScript and array reduce function

It's actually the JavaScript array reduce function rather than being something specific to TypeScript.

As described in the docs: Apply a function against an accumulator and each value of the array (from left-to-right) as to reduce it to a single value.

Here's an example which sums up the values of an array:

_x000D_
_x000D_
let total = [0, 1, 2, 3].reduce((accumulator, currentValue) => accumulator + currentValue);_x000D_
console.log(total);
_x000D_
_x000D_
_x000D_

The snippet should produce 6.

How to set width of mat-table column in angular?

using css we can adjust specific column width which i put in below code.

user.component.css

table{
 width: 100%;
}

.mat-column-username {
  word-wrap: break-word !important;
  white-space: unset !important;
  flex: 0 0 28% !important;
  width: 28% !important;
  overflow-wrap: break-word;
  word-wrap: break-word;

  word-break: break-word;

  -ms-hyphens: auto;
  -moz-hyphens: auto;
  -webkit-hyphens: auto;
  hyphens: auto;
}

.mat-column-emailid {
  word-wrap: break-word !important;
  white-space: unset !important;
  flex: 0 0 25% !important;
  width: 25% !important;
  overflow-wrap: break-word;
  word-wrap: break-word;

  word-break: break-word;

  -ms-hyphens: auto;
  -moz-hyphens: auto;
  -webkit-hyphens: auto;
  hyphens: auto;
}

.mat-column-contactno {
  word-wrap: break-word !important;
  white-space: unset !important;
  flex: 0 0 17% !important;
  width: 17% !important;
  overflow-wrap: break-word;
  word-wrap: break-word;

  word-break: break-word;

  -ms-hyphens: auto;
  -moz-hyphens: auto;
  -webkit-hyphens: auto;
  hyphens: auto;
}

.mat-column-userimage {
  word-wrap: break-word !important;
  white-space: unset !important;
  flex: 0 0 8% !important;
  width: 8% !important;
  overflow-wrap: break-word;
  word-wrap: break-word;

  word-break: break-word;

  -ms-hyphens: auto;
  -moz-hyphens: auto;
  -webkit-hyphens: auto;
  hyphens: auto;
}

.mat-column-userActivity {
  word-wrap: break-word !important;
  white-space: unset !important;
  flex: 0 0 10% !important;
  width: 10% !important;
  overflow-wrap: break-word;
  word-wrap: break-word;

  word-break: break-word;

  -ms-hyphens: auto;
  -moz-hyphens: auto;
  -webkit-hyphens: auto;
  hyphens: auto;
}

How to completely hide the navigation bar in iPhone / HTML5

The problem with all of the answers given so far is that on the something borrowed site, the Mac bar remains totally hidden when scrolling up, and the provided answers don't accomplish that.

If you just use scrollTo and then the user later scrolls up, the nav bar is revealed again, so it seems you have to put the whole site inside of a div and force scrolling to happen inside of that div rather than on the body which keeps the nav bar hidden during scrolling in any direction.

You can, however, still reveal the nav bar by touching near the top of the screen on apple devices.

Can we import XML file into another XML file?

The other answers cover the 2 most common approaches, Xinclude and XML external entities. Microsoft has a really great writeup on why one should prefer Xinclude, as well as several example implementations. I've quoted the comparison below:

Per http://msdn.microsoft.com/en-us/library/aa302291.aspx

Why XInclude?

The first question one may ask is "Why use XInclude instead of XML external entities?" The answer is that XML external entities have a number of well-known limitations and inconvenient implications, which effectively prevent them from being a general-purpose inclusion facility. Specifically:

  • An XML external entity cannot be a full-blown independent XML document—neither standalone XML declaration nor Doctype declaration is allowed. That effectively means an XML external entity itself cannot include other external entities.
  • An XML external entity must be well formed XML (not so bad at first glance, but imagine you want to include sample C# code into your XML document).
  • Failure to load an external entity is a fatal error; any recovery is strictly forbidden.
  • Only the whole external entity may be included, there is no way to include only a portion of a document. -External entities must be declared in a DTD or an internal subset. This opens a Pandora's Box full of implications, such as the fact that the document element must be named in Doctype declaration and that validating readers may require that the full content model of the document be defined in DTD among others.

The deficiencies of using XML external entities as an inclusion mechanism have been known for some time and in fact spawned the submission of the XML Inclusion Proposal to the W3C in 1999 by Microsoft and IBM. The proposal defined a processing model and syntax for a general-purpose XML inclusion facility.

Four years later, version 1.0 of the XML Inclusions, also known as Xinclude, is a Candidate Recommendation, which means that the W3C believes that it has been widely reviewed and satisfies the basic technical problems it set out to solve, but is not yet a full recommendation.

Another good site which provides a variety of example implementations is https://www.xml.com/pub/a/2002/07/31/xinclude.html. Below is a common use case example from their site:

<book xmlns:xi="http://www.w3.org/2001/XInclude">

  <title>The Wit and Wisdom of George W. Bush</title>

  <xi:include href="malapropisms.xml"/>

  <xi:include href="mispronunciations.xml"/>

  <xi:include href="madeupwords.xml"/>

</book>

Returning multiple objects in an R function

Similarly in Java, you can create a S4 class in R that encapsulates your information:

setClass(Class="Person",
         representation(
            height="numeric",
            age="numeric"
          )
)

Then your function can return an instance of this class:

myFunction = function(age=28, height=176){
  return(new("Person",
          age=age,
          height=height))
}

and you can access your information:

aPerson = myFunction()

aPerson@age
aPerson@height

calling parent class method from child class object in java

Use the keyword super within the overridden method in the child class to use the parent class method. You can only use the keyword within the overridden method though. The example below will help.

public class Parent {
    public int add(int m, int n){
        return m+n;
    }
}


public class Child extends Parent{
    public int add(int m,int n,int o){
        return super.add(super.add(m, n),0);
    }

}


public class SimpleInheritanceTest {
    public static void main(String[] a){
        Child child = new Child();
        child.add(10, 11);
    }
}

The add method in the Child class calls super.add to reuse the addition logic.

Spring Boot: Is it possible to use external application.properties files in arbitrary directories with a fat jar?

I know it is a pointed question, and the op wanted to load different properties file.

My answer is, doing custom hacks like this is a terrible idea.

If you are using spring-boot with a cloud provider such as cloud foundry, please do yourself a favor and use cloud config services

https://spring.io/projects/spring-cloud-config

It loads and merges default/dev/project-default/project-dev specific properties like magic

Again, Spring boot already gives you enough ways to do this right https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html

Please do not re-invent the wheel.

Set the text in a span

Use .text() instead, and change your selector:

$(".ui-datepicker-prev .ui-icon.ui-icon-circle-triangle-w").text('<<');

-- VIEW DEMO --

Appending pandas dataframes generated in a for loop

you can try this.

data_you_need=pd.DataFrame()
for infile in glob.glob("*.xlsx"):
    data = pandas.read_excel(infile)
    data_you_need=data_you_need.append(data,ignore_index=True)

I hope it can help.

Removing an element from an Array (Java)

Your question isn't very clear. From your own answer, I can tell better what you are trying to do:

public static String[] removeElements(String[] input, String deleteMe) {
    List result = new LinkedList();

    for(String item : input)
        if(!deleteMe.equals(item))
            result.add(item);

    return result.toArray(input);
}

NB: This is untested. Error checking is left as an exercise to the reader (I'd throw IllegalArgumentException if either input or deleteMe is null; an empty list on null list input doesn't make sense. Removing null Strings from the array might make sense, but I'll leave that as an exercise too; currently, it will throw an NPE when it tries to call equals on deleteMe if deleteMe is null.)

Choices I made here:

I used a LinkedList. Iteration should be just as fast, and you avoid any resizes, or allocating too big of a list if you end up deleting lots of elements. You could use an ArrayList, and set the initial size to the length of input. It likely wouldn't make much of a difference.

What is the meaning of the CascadeType.ALL for a @ManyToOne JPA association

The meaning of CascadeType.ALL is that the persistence will propagate (cascade) all EntityManager operations (PERSIST, REMOVE, REFRESH, MERGE, DETACH) to the relating entities.

It seems in your case to be a bad idea, as removing an Address would lead to removing the related User. As a user can have multiple addresses, the other addresses would become orphans. However the inverse case (annotating the User) would make sense - if an address belongs to a single user only, it is safe to propagate the removal of all addresses belonging to a user if this user is deleted.

BTW: you may want to add a mappedBy="addressOwner" attribute to your User to signal to the persistence provider that the join column should be in the ADDRESS table.

How to have the cp command create any necessary folders for copying a file to a destination

rsync is work!

#file:
rsync -aqz _vimrc ~/.vimrc

#directory:
rsync -aqz _vim/ ~/.vim

Chmod 777 to a folder and all contents

If you are going for a console command it would be:

chmod -R 777 /www/store. The -R (or --recursive) options make it recursive.

Or if you want to make all the files in the current directory have all permissions type:

chmod -R 777 ./

If you need more info about chmod command see: File permission

TCP: can two different sockets share a port?

TCP / HTTP Listening On Ports: How Can Many Users Share the Same Port

So, what happens when a server listen for incoming connections on a TCP port? For example, let's say you have a web-server on port 80. Let's assume that your computer has the public IP address of 24.14.181.229 and the person that tries to connect to you has IP address 10.1.2.3. This person can connect to you by opening a TCP socket to 24.14.181.229:80. Simple enough.

Intuitively (and wrongly), most people assume that it looks something like this:

    Local Computer    | Remote Computer
    --------------------------------
    <local_ip>:80     | <foreign_ip>:80

    ^^ not actually what happens, but this is the conceptual model a lot of people have in mind.

This is intuitive, because from the standpoint of the client, he has an IP address, and connects to a server at IP:PORT. Since the client connects to port 80, then his port must be 80 too? This is a sensible thing to think, but actually not what happens. If that were to be correct, we could only serve one user per foreign IP address. Once a remote computer connects, then he would hog the port 80 to port 80 connection, and no one else could connect.

Three things must be understood:

1.) On a server, a process is listening on a port. Once it gets a connection, it hands it off to another thread. The communication never hogs the listening port.

2.) Connections are uniquely identified by the OS by the following 5-tuple: (local-IP, local-port, remote-IP, remote-port, protocol). If any element in the tuple is different, then this is a completely independent connection.

3.) When a client connects to a server, it picks a random, unused high-order source port. This way, a single client can have up to ~64k connections to the server for the same destination port.

So, this is really what gets created when a client connects to a server:

    Local Computer   | Remote Computer           | Role
    -----------------------------------------------------------
    0.0.0.0:80       | <none>                    | LISTENING
    127.0.0.1:80     | 10.1.2.3:<random_port>    | ESTABLISHED

Looking at What Actually Happens

First, let's use netstat to see what is happening on this computer. We will use port 500 instead of 80 (because a whole bunch of stuff is happening on port 80 as it is a common port, but functionally it does not make a difference).

    netstat -atnp | grep -i ":500 "

As expected, the output is blank. Now let's start a web server:

    sudo python3 -m http.server 500

Now, here is the output of running netstat again:

    Proto Recv-Q Send-Q Local Address           Foreign Address         State  
    tcp        0      0 0.0.0.0:500             0.0.0.0:*               LISTEN      - 

So now there is one process that is actively listening (State: LISTEN) on port 500. The local address is 0.0.0.0, which is code for "listening for all ip addresses". An easy mistake to make is to only listen on port 127.0.0.1, which will only accept connections from the current computer. So this is not a connection, this just means that a process requested to bind() to port IP, and that process is responsible for handling all connections to that port. This hints to the limitation that there can only be one process per computer listening on a port (there are ways to get around that using multiplexing, but this is a much more complicated topic). If a web-server is listening on port 80, it cannot share that port with other web-servers.

So now, let's connect a user to our machine:

    quicknet -m tcp -t localhost:500 -p Test payload.

This is a simple script (https://github.com/grokit/quickweb) that opens a TCP socket, sends the payload ("Test payload." in this case), waits a few seconds and disconnects. Doing netstat again while this is happening displays the following:

    Proto Recv-Q Send-Q Local Address           Foreign Address         State  
    tcp        0      0 0.0.0.0:500             0.0.0.0:*               LISTEN      -
    tcp        0      0 192.168.1.10:500        192.168.1.13:54240      ESTABLISHED -

If you connect with another client and do netstat again, you will see the following:

    Proto Recv-Q Send-Q Local Address           Foreign Address         State  
    tcp        0      0 0.0.0.0:500             0.0.0.0:*               LISTEN      -
    tcp        0      0 192.168.1.10:500        192.168.1.13:26813      ESTABLISHED -

... that is, the client used another random port for the connection. So there is never confusion between the IP addresses.

Pythonic way to create a long multi-line string

This approach uses:

  • almost no internal punctuation by using a triple quoted string
  • strips away local indentation using the inspect module
  • uses Python 3.6 formatted string interpolation ('f') for the account_id and def_id variables.

This way looks the most Pythonic to me.

import inspect

query = inspect.cleandoc(f'''
    SELECT action.descr as "action",
    role.id as role_id,
    role.descr as role
    FROM
    public.role_action_def,
    public.role,
    public.record_def,
    public.action
    WHERE role.id = role_action_def.role_id AND
    record_def.id = role_action_def.def_id AND
    action.id = role_action_def.action_id AND
    role_action_def.account_id = {account_id} AND
    record_def.account_id={account_id} AND
    def_id={def_id}'''
)

Why do package names often begin with "com"

From the Wikipedia article on Java package naming:

In general, a package name begins with the top level domain name of the organization and then the organization's domain and then any subdomains, listed in reverse order. The organization can then choose a specific name for its package. Package names should be all lowercase characters whenever possible.
For example, if an organization in Canada called MySoft creates a package to deal with fractions, naming the package ca.mysoft.fractions distinguishes the fractions package from another similar package created by another company. If a US company named MySoft also creates a fractions package, but names it us.mysoft.fractions, then the classes in these two packages are defined in a unique and separate namespace.

The EntityManager is closed

I had the same error using Symfony 5 / Doctrine 2. One of my fields was named using a MySQL reserved word "order", causing a DBALException. When you want to use a reserved word, you have to escape it's name using back-ticks. In annotation form :

@ORM\Column(name="`order`", type="integer", nullable=false)

Difference between .on('click') vs .click()

NEW ELEMENTS

As an addendum to the comprehensive answers above to highlight critical points if you want the click to attach to new elements:

  1. elements selected by the first selector eg $("body") must exist at the time the declaration is made otherwise there is nothing to attach to.
  2. you must use the three arguments in the .on() function including the valid selector for your target elements as the second argument.

Check if string contains only whitespace

You want to use the isspace() method

str.isspace()

Return true if there are only whitespace characters in the string and there is at least one character, false otherwise.

That's defined on every string object. Here it is an usage example for your specific use case:

if aStr and (not aStr.isspace()):
    print aStr

When using Spring Security, what is the proper way to obtain current username (i.e. SecurityContext) information in a bean?

If you are using Spring Security ver >= 3.2, you can use the @AuthenticationPrincipal annotation:

@RequestMapping(method = RequestMethod.GET)
public ModelAndView showResults(@AuthenticationPrincipal CustomUser currentUser, HttpServletRequest request) {
    String currentUsername = currentUser.getUsername();
    // ...
}

Here, CustomUser is a custom object that implements UserDetails that is returned by a custom UserDetailsService.

More information can be found in the @AuthenticationPrincipal chapter of the Spring Security reference docs.

Can you overload controller methods in ASP.NET MVC?

You could use a single ActionResult to deal with both Post and Get:

public ActionResult Example() {
   if (Request.HttpMethod.ToUpperInvariant() == "GET") {
    // GET
   }
   else if (Request.HttpMethod.ToUpperInvariant() == "POST") {
     // Post  
   }
}

Useful if your Get and Post methods have matching signatures.

Passing data to components in vue.js

A global JS variable (object) can be used to pass data between components. Example: Passing data from Ammlogin.vue to Options.vue. In Ammlogin.vue rspData is set to the response from the server. In Options.vue the response from the server is made available via rspData.

index.html:

<script>
    var rspData; // global - transfer data between components
</script>

Ammlogin.vue:

....    
export default {
data: function() {return vueData}, 
methods: {
    login: function(event){
        event.preventDefault(); // otherwise the page is submitted...
        vueData.errortxt = "";
        axios.post('http://vueamm...../actions.php', { action: this.$data.action, user: this.$data.user, password: this.$data.password})
            .then(function (response) {
                vueData.user = '';
                vueData.password = '';
                // activate v-link via JS click...
                // JSON.parse is not needed because it is already an object
                if (response.data.result === "ok") {
                    rspData = response.data; // set global rspData
                    document.getElementById("loginid").click();
                } else {
                    vueData.errortxt = "Felaktig avändare eller lösenord!"
                }
            })
            .catch(function (error) {
                // Wu oh! Something went wrong
                vueData.errortxt = error.message;
            });
    },
....

Options.vue:

<template>
<main-layout>
  <p>Alternativ</p>
  <p>Resultat: {{rspData.result}}</p>
  <p>Meddelande: {{rspData.data}}</p>
  <v-link href='/'>Logga ut</v-link>
</main-layout>
</template>
<script>
 import MainLayout from '../layouts/Main.vue'
 import VLink from '../components/VLink.vue'
 var optData = { rspData: rspData}; // rspData is global
 export default {
   data: function() {return optData},
   components: {
     MainLayout,
     VLink
   }
 }
</script>

wait process until all subprocess finish?

A Popen object has a .wait() method exactly defined for this: to wait for the completion of a given subprocess (and, besides, for retuning its exit status).

If you use this method, you'll prevent that the process zombies are lying around for too long.

(Alternatively, you can use subprocess.call() or subprocess.check_call() for calling and waiting. If you don't need IO with the process, that might be enough. But probably this is not an option, because your if the two subprocesses seem to be supposed to run in parallel, which they won't with (check_)call().)

If you have several subprocesses to wait for, you can do

exit_codes = [p.wait() for p in p1, p2]

which returns as soon as all subprocesses have finished. You then have a list of return codes which you maybe can evaluate.

how to get current month and year

using System.Globalization;

LblMonth.Text = DateTime.Now.Month.ToString();

DateTimeFormatInfo dinfo = new DateTimeFormatInfo();
int month = Convert.ToInt16(LblMonth.Text);

LblMonth.Text = dinfo.GetMonthName(month);

How do you get the list of targets in a makefile?

This is an attempt to improve on Brent Bradburn's great approach as follows:

  • uses a more robust command to extract the target names, which hopefully prevents any false positives (and also does away with the unnecessary sh -c)
  • does not invariably target the makefile in the current directory; respects makefiles explicitly specified with -f <file>
  • excludes hidden targets - by convention, these are targets whose name starts neither with a letter nor a digit
  • makes do with a single phony target
  • prefixes the command with @ to prevent it from being echoed before execution

Curiously, GNU make has no feature for listing just the names of targets defined in a makefile. While the -p option produces output that includes all targets, it buries them in a lot of other information and also executes the default target (which could be suppressed with -f/dev/null).

Place the following rule in a makefile for GNU make to implement a target named list that simply lists all target names in alphabetical order - i.e.: invoke as make list:

.PHONY: list
list:
    @$(MAKE) -pRrq -f $(lastword $(MAKEFILE_LIST)) : 2>/dev/null | awk -v RS= -F: '/^# File/,/^# Finished Make data base/ {if ($$1 !~ "^[#.]") {print $$1}}' | sort | egrep -v -e '^[^[:alnum:]]' -e '^$@$$'

Important: On pasting this, make sure that the last line is indented by exactly 1 actual tab char. (spaces do not work).

Note that sorting the resulting list of targets is the best option, since not sorting doesn't produce a helpful ordering in that the order in which the targets appear in the makefile is not preserved.
Also, the sub-targets of a rule comprising multiple targets are invariably output separately and will therefore, due to sorting, usually not appear next to one another; e.g., a rule starting with a z: will not have targets a and z listed next to each other in the output, if there are additional targets.

Explanation of the rule:

  • .PHONY: list

    • declares target list a phony target, i.e., one not referring to a file, which should therefore have its recipe invoked unconditionally
  • $(MAKE) -pRrq -f $(lastword $(MAKEFILE_LIST)) : 2>/dev/null

    • Invokes make again in order to print and parse the database derived from the makefile:
      • -p prints the database
      • -Rr suppresses inclusion of built-in rules and variables
      • -q only tests the up-to-date-status of a target (without remaking anything), but that by itself doesn't prevent execution of recipe commands in all cases; hence:
      • -f $(lastword $(MAKEFILE_LIST)) ensures that the same makefile is targeted as in the original invocation, regardless of whether it was targeted implicitly or explicitly with -f ....
        Caveat: This will break if your makefile contains include directives; to address this, define variable THIS_FILE := $(lastword $(MAKEFILE_LIST)) before any include directives and use -f $(THIS_FILE) instead.
      • : is a deliberately invalid target that is meant to ensure that no commands are executed; 2>/dev/null suppresses the resulting error message. Note: This relies on -p printing the database nonetheless, which is the case as of GNU make 3.82. Sadly, GNU make offers no direct option to just print the database, without also executing the default (or given) task; if you don't need to target a specific Makefile, you may use make -p -f/dev/null, as recommended in the man page.
  • -v RS=

    • This is an awk idiom that breaks the input into blocks of contiguous non-empty lines.
  • /^# File/,/^# Finished Make data base/

    • Matches the range of lines in the output that contains all targets (true as of GNU make 3.82) - by limiting parsing to this range, there is no need to deal with false positives from other output sections.
  • if ($$1 !~ "^[#.]")

    • Selectively ignores blocks:
      • # ... ignores non-targets, whose blocks start with # Not a target:
      • . ... ignores special targets
    • All other blocks should each start with a line containing only the name of an explicitly defined target followed by :
  • egrep -v -e '^[^[:alnum:]]' -e '^$@$$' removes unwanted targets from the output:

    • '^[^[:alnum:]]' ... excludes hidden targets, which - by convention - are targets that start neither with a letter nor a digit.
    • '^$@$$' ... excludes the list target itself

Running make list then prints all targets, each on its own line; you can pipe to xargs to create a space-separated list instead.

Passing variables to the next middleware using next() in Express.js

Attach your variable to the req object, not res.

Instead of

res.somevariable = variable1;

Have:

req.somevariable = variable1;

As others have pointed out, res.locals is the recommended way of passing data through middleware.

Combining C++ and C - how does #ifdef __cplusplus work?

A couple of gotchas that are colloraries to Andrew Shelansky's excellent answer and to disagree a little with doesn't really change the way that the compiler reads the code

Because your function prototypes are compiled as C, you can't have overloading of the same function names with different parameters - that's one of the key features of the name mangling of the compiler. It is described as a linkage issue but that is not quite true - you will get errors from both the compiler and the linker.

The compiler errors will be if you try to use C++ features of prototype declaration such as overloading.

The linker errors will occur later because your function will appear to not be found, if you do not have the extern "C" wrapper around declarations and the header is included in a mixture of C and C++ source.

One reason to discourage people from using the compile C as C++ setting is because this means their source code is no longer portable. That setting is a project setting and so if a .c file is dropped into another project, it will not be compiled as c++. I would rather people take the time to rename file suffixes to .cpp.

Export from pandas to_excel without row names (index)?

Example: index = False

import pandas as pd

writer = pd.ExcelWriter("dataframe.xlsx", engine='xlsxwriter')
dataframe.to_excel(writer,sheet_name = dataframe, index=False)
writer.save() 

How to set a value to a file input in HTML?

You cannot, due to security reasons.

Imagine:

<form name="foo" method="post" enctype="multipart/form-data">
    <input type="file" value="c:/passwords.txt">
</form>
<script>document.foo.submit();</script>

You don't want the websites you visit to be able to do this, do you? =)

Python - PIP install trouble shooting - PermissionError: [WinError 5] Access is denied

TL;DR: python -m pip install -U pip, then try again.


I was already using a venv (virtualenv) in PyCharm.

Creating it I clicked inherit global site packages checkbox, to allow packages installed via an installer to work. Now inside my venv there was no pip installed, so it would use the inherited global pip.

Here is how the error went:

(venv) D:\path\to\my\project> pip install certifi  # or any other package

Would fail with

PermissionError: [WinError 5] Access denied: 'c:\\program files\\python36\\Lib\\site-packages\\certifi'

Notice how that is the path of the system python, not the venv one. However we want it to execute in the right environment.

Here some more digging:

(venv) D:\path\to\my\project> which pip
/c/Program Files/Python36/Scripts/pip

(venv) D:\path\to\my\project> which python
/d/path/to/my/project/venv/Scripts/python

So python is using the correct path, but pip is not? Let's install pip here in the correct one as well:

(venv) D:\path\to\my\project> python -m pip install -U pip
... does stuff ...
Successfully installed pip

Now that's better. Running the original failing command again now works, as it is using the correct pip.

(venv) D:\path\to\my\project> pip install certifi  # or any other package
... install noise ...
Successfully installed certifi-2019.9.11 chardet-3.0.4 idna-2.8 requests-2.22.0 urllib3-1.25.7

How can I mock an ES6 module import using Jest?

Fast forwarding to 2020, I found this blog post to be the solution: Jest mock default and named export

Using only ES6 module syntax:

// esModule.js
export default 'defaultExport';
export const namedExport = () => {};

// esModule.test.js
jest.mock('./esModule', () => ({
  __esModule: true, // this property makes it work
  default: 'mockedDefaultExport',
  namedExport: jest.fn(),
}));

import defaultExport, { namedExport } from './esModule';
defaultExport; // 'mockedDefaultExport'
namedExport; // mock function

Also one thing you need to know (which took me a while to figure out) is that you can't call jest.mock() inside the test; you must call it at the top level of the module. However, you can call mockImplementation() inside individual tests if you want to set up different mocks for different tests.

How Do I Make Glyphicons Bigger? (Change Size?)

Fontawesome has a perfect solution to this.

I implemented the same. just on your main .css file add this

.gi-2x{font-size: 2em;}
.gi-3x{font-size: 3em;}
.gi-4x{font-size: 4em;}
.gi-5x{font-size: 5em;}

In your example you just have to do this.

<div class = "jumbotron">
    <span class="glyphicon glyphicon-globe gi-5x"></span>
</div>  

Typescript es6 import module "File is not a module error"

How can I accomplish that?

Your example declares a TypeScript < 1.5 internal module, which is now called a namespace. The old module App {} syntax is now equivalent to namespace App {}. As a result, the following works:

// test.ts
export namespace App {
    export class SomeClass {
        getName(): string {
            return 'name';
        }
    }
}

// main.ts
import { App } from './test';
var a = new App.SomeClass();

That being said...

Try to avoid exporting namespaces and instead export modules (which were previously called external modules). If needs be you can use a namespace on import with the namespace import pattern like this:

// test.ts
export class SomeClass {
    getName(): string {
        return 'name';
    }
}

// main.ts
import * as App from './test'; // namespace import pattern
var a = new App.SomeClass();

How to create module-wide variables in Python?

You are falling for a subtle quirk. You cannot re-assign module-level variables inside a python function. I think this is there to stop people re-assigning stuff inside a function by accident.

You can access the module namespace, you just shouldn't try to re-assign. If your function assigns something, it automatically becomes a function variable - and python won't look in the module namespace.

You can do:

__DB_NAME__ = None

def func():
    if __DB_NAME__:
        connect(__DB_NAME__)
    else:
        connect(Default_value)

but you cannot re-assign __DB_NAME__ inside a function.

One workaround:

__DB_NAME__ = [None]

def func():
    if __DB_NAME__[0]:
        connect(__DB_NAME__[0])
    else:
        __DB_NAME__[0] = Default_value

Note, I'm not re-assigning __DB_NAME__, I'm just modifying its contents.

iPhone Debugging: How to resolve 'failed to get the task for process'?

As stated by Buffernet, you cannot use a distribution provisioning profile to debug. When I switched to a developer provisioning profile, I got the error "A Valid Provisioning Profile For This Executable Was Not Found".

A quick google for this lead me to the article listed below. From there, I realised that I hadn't got a valid development provisioning profile as my iPhone hadn't been added to the Provisioning Portal and all the other stuff involved.

Make sure you run an iPhone developer provisioning profile and your device has been added to the provisioning portal!

http://iosdevelopertips.com/xcode/a-valid-provisioning-profile-for-this-executable-was-not-found.html

How to declare an array in Python?

Following on from Lennart, there's also numpy which implements homogeneous multi-dimensional arrays.

Convert Pandas Column to DateTime

raw_data['Mycol'] =  pd.to_datetime(raw_data['Mycol'], format='%d%b%Y:%H:%M:%S.%f')

works, however it results in a Python warning of A value is trying to be set on a copy of a slice from a DataFrame. Try using .loc[row_indexer,col_indexer] = value instead

I would guess this is due to some chaining indexing.

org.springframework.beans.factory.CannotLoadBeanClassException: Cannot find class

I have the same problem. I checked my /WEB-INF/classes based on Stephen's recommendation:

the class is not in your webapp's /WEB-INF/classes directory tree or a JAR file in the /WEB-INF/lib directory.

I discovered I have an outdated jar file. Replacing it with the latest jar file solved the issue.

$.focus() not working

I tested code from Chrome's DevTool Console and the focus part not worked. I found out later the issue is only present if i run it from DevTool and if i implement the code to the website it works fine. Actually, the element got focused but the DevTool removed it immediately.