Programs & Examples On #Quicklook

QuickLook an objective-c framework used in iOS and MacOS application development typically for previews.

Adding backslashes without escaping [Python]

Python treats \ in literal string in a special way.
This is so you can type '\n' to mean newline or '\t' to mean tab
Since '\&' doesn't mean anything special to Python, instead of causing an error, the Python lexical analyser implicitly adds the extra \ for you.

Really it is better to use \\& or r'\&' instead of '\&'

The r here means raw string and means that \ isn't treated specially unless it is right before the quote character at the start of the string.

In the interactive console, Python uses repr to display the result, so that is why you see the double '\'. If you print your string or use len(string) you will see that it is really only the 2 characters

Some examples

>>> 'Here\'s a backslash: \\'
"Here's a backslash: \\"
>>> print 'Here\'s a backslash: \\'
Here's a backslash: \
>>> 'Here\'s a backslash: \\. Here\'s a double quote: ".'
'Here\'s a backslash: \\. Here\'s a double quote: ".'
>>> print 'Here\'s a backslash: \\. Here\'s a double quote: ".'
Here's a backslash: \. Here's a double quote ".

To Clarify the point Peter makes in his comment see this link

Unlike Standard C, all unrecognized escape sequences are left in the string unchanged, i.e., the backslash is left in the string. (This behavior is useful when debugging: if an escape sequence is mistyped, the resulting output is more easily recognized as broken.) It is also important to note that the escape sequences marked as β€œ(Unicode only)” in the table above fall into the category of unrecognized escapes for non-Unicode string literals.

HTML/CSS: how to put text both right and left aligned in a paragraph

Ok what you probably want will be provide to you by result of:

  1. in CSS:

    div { column-count: 2; }

  2. in html:

    <div> some text, bla bla bla </div>

In CSS you make div to split your paragraph on to column, you can make them 3, 4...

If you want to have many differend paragraf like that, then put id or class in your div:

how to parse JSON file with GSON

just parse as an array:

Review[] reviews = new Gson().fromJson(jsonString, Review[].class);

then if you need you can also create a list in this way:

List<Review> asList = Arrays.asList(reviews);

P.S. your json string should be look like this:

[
    {
        "reviewerID": "A2SUAM1J3GNN3B1",
        "asin": "0000013714",
        "reviewerName": "J. McDonald",
        "helpful": [2, 3],
        "reviewText": "I bought this for my husband who plays the piano.",
        "overall": 5.0,
        "summary": "Heavenly Highway Hymns",
        "unixReviewTime": 1252800000,
        "reviewTime": "09 13, 2009"
    },
    {
        "reviewerID": "A2SUAM1J3GNN3B2",
        "asin": "0000013714",
        "reviewerName": "J. McDonald",
        "helpful": [2, 3],
        "reviewText": "I bought this for my husband who plays the piano.",
        "overall": 5.0,
        "summary": "Heavenly Highway Hymns",
        "unixReviewTime": 1252800000,
        "reviewTime": "09 13, 2009"
    },

    [...]
]

Java: set timeout on a certain block of code?

Here's the simplest way that I know of to do this:

final Runnable stuffToDo = new Thread() {
  @Override 
  public void run() { 
    /* Do stuff here. */ 
  }
};

final ExecutorService executor = Executors.newSingleThreadExecutor();
final Future future = executor.submit(stuffToDo);
executor.shutdown(); // This does not cancel the already-scheduled task.

try { 
  future.get(5, TimeUnit.MINUTES); 
}
catch (InterruptedException ie) { 
  /* Handle the interruption. Or ignore it. */ 
}
catch (ExecutionException ee) { 
  /* Handle the error. Or ignore it. */ 
}
catch (TimeoutException te) { 
  /* Handle the timeout. Or ignore it. */ 
}
if (!executor.isTerminated())
    executor.shutdownNow(); // If you want to stop the code that hasn't finished.

Alternatively, you can create a TimeLimitedCodeBlock class to wrap this functionality, and then you can use it wherever you need it as follows:

new TimeLimitedCodeBlock(5, TimeUnit.MINUTES) { @Override public void codeBlock() {
    // Do stuff here.
}}.run();

python: create list of tuples from lists

Use the builtin function zip():

In Python 3:

z = list(zip(x,y))

In Python 2:

z = zip(x,y)

How to replace list item in best way

i find best for do it fast and simple

  1. find ur item in list

    var d = Details.Where(x => x.ProductID == selectedProduct.ID).SingleOrDefault();
    
  2. make clone from current

    OrderDetail dd = d;
    
  3. Update ur clone

    dd.Quantity++;
    
  4. find index in list

    int idx = Details.IndexOf(d);
    
  5. remove founded item in (1)

      Details.Remove(d);
    
  6. insert

     if (idx > -1)
          Details.Insert(idx, dd);
      else
          Details.Insert(Details.Count, dd);
    

Subtracting time.Duration from time in Go

There's time.ParseDuration which will happily accept negative durations, as per manual. Otherwise put, there's no need to negate a duration where you can get an exact duration in the first place.

E.g. when you need to substract an hour and a half, you can do that like so:

package main

import (
    "fmt"
    "time"
)

func main() {
    now := time.Now()

    fmt.Println("now:", now)

    duration, _ := time.ParseDuration("-1.5h")

    then := now.Add(duration)

    fmt.Println("then:", then)
}

https://play.golang.org/p/63p-T9uFcZo

How does String substring work in Swift

I'm really frustrated at Swift's String access model: everything has to be an Index. All I want is to access the i-th character of the string using Int, not the clumsy index and advancing (which happens to change with every major release). So I made an extension to String:

extension String {
    func index(from: Int) -> Index {
        return self.index(startIndex, offsetBy: from)
    }

    func substring(from: Int) -> String {
        let fromIndex = index(from: from)
        return String(self[fromIndex...])
    }

    func substring(to: Int) -> String {
        let toIndex = index(from: to)
        return String(self[..<toIndex])
    }

    func substring(with r: Range<Int>) -> String {
        let startIndex = index(from: r.lowerBound)
        let endIndex = index(from: r.upperBound)
        return String(self[startIndex..<endIndex])
    }
}

let str = "Hello, playground"
print(str.substring(from: 7))         // playground
print(str.substring(to: 5))           // Hello
print(str.substring(with: 7..<11))    // play

How to use Redirect in the new react-router-dom of Reactjs

Alternatively, you can use React conditional rendering.

import { Redirect } from "react-router";
import React, { Component } from 'react';

class UserSignup extends Component {
  constructor(props) {
    super(props);
    this.state = {
      redirect: false
    }
  }
render() {
 <React.Fragment>
   { this.state.redirect && <Redirect to="/signin" /> }   // you will be redirected to signin route
}
</React.Fragment>
}

How can I create a "Please Wait, Loading..." animation using jQuery?

Per https://www.w3schools.com/howto/howto_css_loader.asp, this is a 2-step process with no JS:

1.Add this HTML where you want the spinner: <div class="loader"></div>

2.Add this CSS to make the actual spinner:

.loader {
    border: 16px solid #f3f3f3; /* Light grey */
    border-top: 16px solid #3498db; /* Blue */
    border-radius: 50%;
    width: 120px;
    height: 120px;
    animation: spin 2s linear infinite;
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}

ng-options with simple array init

If you setup your select like the following:

<select ng-model="myselect" ng-options="b for b in options track by b"></select>

you will get:

<option value="var1">var1</option>
<option value="var2">var2</option>
<option value="var3">var3</option>

working fiddle: http://jsfiddle.net/x8kCZ/15/

Do I need Content-Type: application/octet-stream for file download?

No.

The content-type should be whatever it is known to be, if you know it. application/octet-stream is defined as "arbitrary binary data" in RFC 2046, and there's a definite overlap here of it being appropriate for entities whose sole intended purpose is to be saved to disk, and from that point on be outside of anything "webby". Or to look at it from another direction; the only thing one can safely do with application/octet-stream is to save it to file and hope someone else knows what it's for.

You can combine the use of Content-Disposition with other content-types, such as image/png or even text/html to indicate you want saving rather than display. It used to be the case that some browsers would ignore it in the case of text/html but I think this was some long time ago at this point (and I'm going to bed soon so I'm not going to start testing a whole bunch of browsers right now; maybe later).

RFC 2616 also mentions the possibility of extension tokens, and these days most browsers recognise inline to mean you do want the entity displayed if possible (that is, if it's a type the browser knows how to display, otherwise it's got no choice in the matter). This is of course the default behaviour anyway, but it means that you can include the filename part of the header, which browsers will use (perhaps with some adjustment so file-extensions match local system norms for the content-type in question, perhaps not) as the suggestion if the user tries to save.

Hence:

Content-Type: application/octet-stream
Content-Disposition: attachment; filename="picture.png"

Means "I don't know what the hell this is. Please save it as a file, preferably named picture.png".

Content-Type: image/png
Content-Disposition: attachment; filename="picture.png"

Means "This is a PNG image. Please save it as a file, preferably named picture.png".

Content-Type: image/png
Content-Disposition: inline; filename="picture.png"

Means "This is a PNG image. Please display it unless you don't know how to display PNG images. Otherwise, or if the user chooses to save it, we recommend the name picture.png for the file you save it as".

Of those browsers that recognise inline some would always use it, while others would use it if the user had selected "save link as" but not if they'd selected "save" while viewing (or at least IE used to be like that, it may have changed some years ago).

Adding gif image in an ImageView in android

I would suggest you to use Glide library. To use Glide you need to add this to add these dependencies

compile 'com.github.bumptech.glide:glide:3.7.0'
compile 'com.android.support:support-v4:23.4.0'

to your grandle (Module:app) file.

Then use this line of code to load your gif image

Glide.with(context).load(R.drawable.loading).asGif().diskCacheStrategy(DiskCacheStrategy.SOURCE).crossFade().into(loadingImageView);

More Information on Glide

First Heroku deploy failed `error code=H10`

I had a typo

const PORT = process.env.PORT||'8080';

used to be

const PORT = process.env.port||'8080';

Double free or corruption after queue::push

The problem is that your class contains a managed RAW pointer but does not implement the rule of three (five in C++11). As a result you are getting (expectedly) a double delete because of copying.

If you are learning you should learn how to implement the rule of three (five). But that is not the correct solution to this problem. You should be using standard container objects rather than try to manage your own internal container. The exact container will depend on what you are trying to do but std::vector is a good default (and you can change afterwords if it is not opimal).

#include <queue>
#include <vector>

class Test{
    std::vector<int> myArray;

    public:
    Test(): myArray(10){
    }    
};

int main(){
    queue<Test> q
    Test t;
    q.push(t);
}

The reason you should use a standard container is the separation of concerns. Your class should be concerned with either business logic or resource management (not both). Assuming Test is some class you are using to maintain some state about your program then it is business logic and it should not be doing resource management. If on the other hand Test is supposed to manage an array then you probably need to learn more about what is available inside the standard library.

Can I set an unlimited length for maxJsonLength in web.config?

if you are still getting error after web.config setting like following:

<configuration> 
   <system.web.extensions>
       <scripting>
           <webServices>
               <jsonSerialization maxJsonLength="50000000"/>
           </webServices>
       </scripting>
   </system.web.extensions>
</configuration> 

I solved it by following:

   public ActionResult/JsonResult getData()
   {
      var jsonResult = Json(superlargedata, JsonRequestBehavior.AllowGet);
      jsonResult.MaxJsonLength = int.MaxValue;
      return jsonResult;
    }

I hope this should help.

How to upload files to server using Putty (ssh)

"C:\Program Files\PuTTY\pscp.exe" -scp file.py server.com:

file.py will be uploaded into your HOME dir on remote server.

or when the remote server has a different user, use "C:\Program Files\PuTTY\pscp.exe" -l username -scp file.py server.com:

After connecting to the server pscp will ask for a password.

How to read a .xlsx file using the pandas Library in iPython?

If you use read_excel() on a file opened using the function open(), make sure to add rb to the open function to avoid encoding errors

Changing user agent on urllib2.urlopen

headers = { 'User-Agent' : 'Mozilla/5.0' }
req = urllib2.Request('www.example.com', None, headers)
html = urllib2.urlopen(req).read()

Or, a bit shorter:

req = urllib2.Request('www.example.com', headers={ 'User-Agent': 'Mozilla/5.0' })
html = urllib2.urlopen(req).read()

How to open a web page automatically in full screen mode

You can go fullscreen automatically by putting this code in:

var elem = document.documentElement; if (elem.requestFullscreen) { elem.requestFullscreen() }

demo: https://codepen.io/ConfidentCoding/pen/ewLyPX

note: does not always work for security reasons. but it works for me at least. does not work when inspecting and pasting the code.

No newline at end of file

For what it's worth, I encountered this when I created an IntelliJ project on a Mac, and then moved the project over to my Windows machine. I had to manually open every file and change the encoding setting at the bottom right of the IntelliJ window. Probably not happening to most if any who read this question but that could have saved me a couple of hours of work...

batch file to check 64bit or 32bit OS

This is a one-liner that will have %errorlevel% of 0 for 64-bit, 1 for non-64-bit. I can't vouch for it working on all versions of Windows, but demonstrates one method for determining it. You can add multiple findstrqueries if you know all the possibilities to look for.

set | findstr /i processo.*64 > nul 2>&1

Basically, you're dumping the environment variables, and using a regular expression to search for something that has "processo" + "64" somewhere in its line. The piping is just to suppress the matching lines. If I changed it to set | findstr /i processo.*64 on my current rig, this would be the result:

 C:\Windows\System32>set | findstr /i processo.*64
PROCESSOR_ARCHITECTURE=AMD64
PROCESSOR_IDENTIFIER=Intel64 Family 6 Model 158 Stepping 9, GenuineIntel

This is a one-liner to see if your processor is a 64-bit AMD

set | findstr /i processo.*amd.*64 > nul 2>&1

You can take these as a starting point and refine them for your requirements. I ended up using this over known environment variable names due to it being more reliable across different major versions of Windows that I was working with.

what is the difference between json and xml

The fundamental difference, which no other answer seems to have mentioned, is that XML is a markup language (as it actually says in its name), whereas JSON is a way of representing objects (as also noted in its name).

A markup language is a way of adding extra information to free-flowing plain text, e.g

Here is some text.

With XML (using a certain element vocabulary) you can put:

<Document>
    <Paragraph Align="Center">
        Here <Bold>is</Bold> some text.
    </Paragraph>
</Document>

This is what makes markup languages so useful for representing documents.

An object notation like JSON is not as flexible. But this is usually a good thing. When you're representing objects, you simply don't need the extra flexibility. To represent the above example in JSON, you'd actually have to solve some problems manually that XML solves for you.

{
    "Paragraphs": [
        {
            "align": "center",
            "content": [
                "Here ", {
                    "style" : "bold",
                    "content": [ "is" ]
                },
                " some text."
            ]
        }
    ]
}

It's not as nice as the XML, and the reason is that we're trying to do markup with an object notation. So we have to invent a way to scatter snippets of plain text around our objects, using "content" arrays that can hold a mixture of strings and nested objects.

On the other hand, if you have typical a hierarchy of objects and you want to represent them in a stream, JSON is better suited to this task than HTML.

{
    "firstName": "Homer",
    "lastName": "Simpson",
    "relatives": [ "Grandpa", "Marge", "The Boy", "Lisa", "I think that's all of them" ]
} 

Here's the logically equivalent XML:

<Person>
    <FirstName>Homer</FirstName>
    <LastName>Simpsons</LastName>
    <Relatives>
        <Relative>Grandpa</Relative>
        <Relative>Marge</Relative>
        <Relative>The Boy</Relative>
        <Relative>Lisa</Relative>
        <Relative>I think that's all of them</Relative>
    </Relatives>
</Person>

JSON looks more like the data structures we declare in programming languages. Also it has less redundant repetition of names.

But most importantly of all, it has a defined way of distinguishing between a "record" (items unordered, identified by names) and a "list" (items ordered, identified by position). An object notation is practically useless without such a distinction. And XML has no such distinction! In my XML example <Person> is a record and <Relatives> is a list, but they are not identified as such by the syntax.

Instead, XML has "elements" versus "attributes". This looks like the same kind of distinction, but it's not, because attributes can only have string values. They cannot be nested objects. So I couldn't have applied this idea to <Person>, because I shouldn't have to turn <Relatives> into a single string.

By using an external schema, or extra user-defined attributes, you can formalise a distinction between lists and records in XML. The advantage of JSON is that the low-level syntax has that distinction built into it, so it's very succinct and universal. This means that JSON is more "self describing" by default, which is an important goal of both formats.

So JSON should be the first choice for object notation, where XML's sweet spot is document markup.

Unfortunately for XML, we already have HTML as the world's number one rich text markup language. An attempt was made to reformulate HTML in terms of XML, but there isn't much advantage in this.

So XML should (in my opinion) have been a pretty limited niche technology, best suited only for inventing your own rich text markup languages if you don't want to use HTML for some reason. The problem was that in 1998 there was still a lot of hype about the Web, and XML became popular due to its superficial resemblance to HTML. It was a strange design choice to try to apply to hierarchical data a syntax actually designed for convenient markup.

Java - Including variables within strings?

you can use String format to include variables within strings

i use this code to include 2 variable in string:

String myString = String.format("this is my string %s %2d", variable1Name, variable2Name);

ArrayAdapter in android to create simple listview

If you have more than one view in the layout file android.R.layout.simple_list_item_1 then you'll have to pass the third argument android.R.id.text1 to specify the view that should be filled with the array elements (values). But if you have just one view in your layout file, there is no need to specify the third argument.

spark submit add multiple jars in classpath

You can use --jars $(echo /Path/To/Your/Jars/*.jar | tr ' ' ',') to include entire folder of Jars. So, spark-submit -- class com.yourClass \ --jars $(echo /Path/To/Your/Jars/*.jar | tr ' ' ',') \ ...

Mockito: Trying to spy on method is calling the original method

Bit late to the party but above solutions did not work for me , so sharing my 0.02$

Mokcito version: 1.10.19

MyClass.java

private int handleAction(List<String> argList, String action)

Test.java

MyClass spy = PowerMockito.spy(new MyClass());

Following did NOT work for me (actual method was being called):

1.

doReturn(0).when(spy , "handleAction", ListUtils.EMPTY_LIST, new String());

2.

doReturn(0).when(spy , "handleAction", any(), anyString());

3.

doReturn(0).when(spy , "handleAction", null, null);

Following WORKED:

doReturn(0).when(spy , "handleAction", any(List.class), anyString());

"And" and "Or" troubles within an IF statement

The problem is probably somewhere else. Try this code for example:

Sub test()

  origNum = "006260006"
  creditOrDebit = "D"

  If (origNum = "006260006" Or origNum = "30062600006") And creditOrDebit = "D" Then
    MsgBox "OK"
  End If

End Sub

And you will see that your Or works as expected. Are you sure that your ElseIf statement is executed (it will not be executed if any of the if/elseif before is true)?

What are the calling conventions for UNIX & Linux system calls (and user-space functions) on i386 and x86-64

Linux kernel 5.0 source comments

I knew that x86 specifics are under arch/x86, and that syscall stuff goes under arch/x86/entry. So a quick git grep rdi in that directory leads me to arch/x86/entry/entry_64.S:

/*
 * 64-bit SYSCALL instruction entry. Up to 6 arguments in registers.
 *
 * This is the only entry point used for 64-bit system calls.  The
 * hardware interface is reasonably well designed and the register to
 * argument mapping Linux uses fits well with the registers that are
 * available when SYSCALL is used.
 *
 * SYSCALL instructions can be found inlined in libc implementations as
 * well as some other programs and libraries.  There are also a handful
 * of SYSCALL instructions in the vDSO used, for example, as a
 * clock_gettimeofday fallback.
 *
 * 64-bit SYSCALL saves rip to rcx, clears rflags.RF, then saves rflags to r11,
 * then loads new ss, cs, and rip from previously programmed MSRs.
 * rflags gets masked by a value from another MSR (so CLD and CLAC
 * are not needed). SYSCALL does not save anything on the stack
 * and does not change rsp.
 *
 * Registers on entry:
 * rax  system call number
 * rcx  return address
 * r11  saved rflags (note: r11 is callee-clobbered register in C ABI)
 * rdi  arg0
 * rsi  arg1
 * rdx  arg2
 * r10  arg3 (needs to be moved to rcx to conform to C ABI)
 * r8   arg4
 * r9   arg5
 * (note: r12-r15, rbp, rbx are callee-preserved in C ABI)
 *
 * Only called from user space.
 *
 * When user can change pt_regs->foo always force IRET. That is because
 * it deals with uncanonical addresses better. SYSRET has trouble
 * with them due to bugs in both AMD and Intel CPUs.
 */

and for 32-bit at arch/x86/entry/entry_32.S:

/*
 * 32-bit SYSENTER entry.
 *
 * 32-bit system calls through the vDSO's __kernel_vsyscall enter here
 * if X86_FEATURE_SEP is available.  This is the preferred system call
 * entry on 32-bit systems.
 *
 * The SYSENTER instruction, in principle, should *only* occur in the
 * vDSO.  In practice, a small number of Android devices were shipped
 * with a copy of Bionic that inlined a SYSENTER instruction.  This
 * never happened in any of Google's Bionic versions -- it only happened
 * in a narrow range of Intel-provided versions.
 *
 * SYSENTER loads SS, ESP, CS, and EIP from previously programmed MSRs.
 * IF and VM in RFLAGS are cleared (IOW: interrupts are off).
 * SYSENTER does not save anything on the stack,
 * and does not save old EIP (!!!), ESP, or EFLAGS.
 *
 * To avoid losing track of EFLAGS.VM (and thus potentially corrupting
 * user and/or vm86 state), we explicitly disable the SYSENTER
 * instruction in vm86 mode by reprogramming the MSRs.
 *
 * Arguments:
 * eax  system call number
 * ebx  arg1
 * ecx  arg2
 * edx  arg3
 * esi  arg4
 * edi  arg5
 * ebp  user stack
 * 0(%ebp) arg6
 */

glibc 2.29 Linux x86_64 system call implementation

Now let's cheat by looking at a major libc implementations and see what they are doing.

What could be better than looking into glibc that I'm using right now as I write this answer? :-)

glibc 2.29 defines x86_64 syscalls at sysdeps/unix/sysv/linux/x86_64/sysdep.h and that contains some interesting code, e.g.:

/* The Linux/x86-64 kernel expects the system call parameters in
   registers according to the following table:

    syscall number  rax
    arg 1       rdi
    arg 2       rsi
    arg 3       rdx
    arg 4       r10
    arg 5       r8
    arg 6       r9

    The Linux kernel uses and destroys internally these registers:
    return address from
    syscall     rcx
    eflags from syscall r11

    Normal function call, including calls to the system call stub
    functions in the libc, get the first six parameters passed in
    registers and the seventh parameter and later on the stack.  The
    register use is as follows:

     system call number in the DO_CALL macro
     arg 1      rdi
     arg 2      rsi
     arg 3      rdx
     arg 4      rcx
     arg 5      r8
     arg 6      r9

    We have to take care that the stack is aligned to 16 bytes.  When
    called the stack is not aligned since the return address has just
    been pushed.


    Syscalls of more than 6 arguments are not supported.  */

and:

/* Registers clobbered by syscall.  */
# define REGISTERS_CLOBBERED_BY_SYSCALL "cc", "r11", "cx"

#undef internal_syscall6
#define internal_syscall6(number, err, arg1, arg2, arg3, arg4, arg5, arg6) \
({                                  \
    unsigned long int resultvar;                    \
    TYPEFY (arg6, __arg6) = ARGIFY (arg6);              \
    TYPEFY (arg5, __arg5) = ARGIFY (arg5);              \
    TYPEFY (arg4, __arg4) = ARGIFY (arg4);              \
    TYPEFY (arg3, __arg3) = ARGIFY (arg3);              \
    TYPEFY (arg2, __arg2) = ARGIFY (arg2);              \
    TYPEFY (arg1, __arg1) = ARGIFY (arg1);              \
    register TYPEFY (arg6, _a6) asm ("r9") = __arg6;            \
    register TYPEFY (arg5, _a5) asm ("r8") = __arg5;            \
    register TYPEFY (arg4, _a4) asm ("r10") = __arg4;           \
    register TYPEFY (arg3, _a3) asm ("rdx") = __arg3;           \
    register TYPEFY (arg2, _a2) asm ("rsi") = __arg2;           \
    register TYPEFY (arg1, _a1) asm ("rdi") = __arg1;           \
    asm volatile (                          \
    "syscall\n\t"                           \
    : "=a" (resultvar)                          \
    : "0" (number), "r" (_a1), "r" (_a2), "r" (_a3), "r" (_a4),     \
      "r" (_a5), "r" (_a6)                      \
    : "memory", REGISTERS_CLOBBERED_BY_SYSCALL);            \
    (long int) resultvar;                       \
})

which I feel are pretty self explanatory. Note how this seems to have been designed to exactly match the calling convention of regular System V AMD64 ABI functions: https://en.wikipedia.org/wiki/X86_calling_conventions#List_of_x86_calling_conventions

Quick reminder of the clobbers:

  • cc means flag registers. But Peter Cordes comments that this is unnecessary here.
  • memory means that a pointer may be passed in assembly and used to access memory

For an explicit minimal runnable example from scratch see this answer: How to invoke a system call via syscall or sysenter in inline assembly?

Make some syscalls in assembly manually

Not very scientific, but fun:

  • x86_64.S

    .text
    .global _start
    _start:
    asm_main_after_prologue:
        /* write */
        mov $1, %rax    /* syscall number */
        mov $1, %rdi    /* stdout */
        mov $msg, %rsi  /* buffer */
        mov $len, %rdx  /* len */
        syscall
    
        /* exit */
        mov $60, %rax   /* syscall number */
        mov $0, %rdi    /* exit status */
        syscall
    msg:
        .ascii "hello\n"
    len = . - msg
    

    GitHub upstream.

Make system calls from C

Here's an example with register constraints: How to invoke a system call via syscall or sysenter in inline assembly?

aarch64

I've shown a minimal runnable userland example at: https://reverseengineering.stackexchange.com/questions/16917/arm64-syscalls-table/18834#18834 TODO grep kernel code here, should be easy.

How to set image in imageview in android?

if u want to set a bitmap object to image view here is simple two line`

Bitmap bitmap=BitmapFactory.decodeResource(getResources(),R.drawable.sample_drawable_image);
image.setImageBitmap(bitmap);

Creating a file only if it doesn't exist in Node.js

With async / await and Typescript I would do:

import * as fs from 'fs'

async function upsertFile(name: string) {
  try {
    // try to read file
    await fs.promises.readFile(name)
  } catch (error) {
    // create empty file, because it wasn't found
    await fs.promises.writeFile(name, '')
  }
}

Combine several images horizontally with Python

Here's my solution:

from PIL import Image


def join_images(*rows, bg_color=(0, 0, 0, 0), alignment=(0.5, 0.5)):
    rows = [
        [image.convert('RGBA') for image in row]
        for row
        in rows
    ]

    heights = [
        max(image.height for image in row)
        for row
        in rows
    ]

    widths = [
        max(image.width for image in column)
        for column
        in zip(*rows)
    ]

    tmp = Image.new(
        'RGBA',
        size=(sum(widths), sum(heights)),
        color=bg_color
    )

    for i, row in enumerate(rows):
        for j, image in enumerate(row):
            y = sum(heights[:i]) + int((heights[i] - image.height) * alignment[1])
            x = sum(widths[:j]) + int((widths[j] - image.width) * alignment[0])
            tmp.paste(image, (x, y))

    return tmp


def join_images_horizontally(*row, bg_color=(0, 0, 0), alignment=(0.5, 0.5)):
    return join_images(
        row,
        bg_color=bg_color,
        alignment=alignment
    )


def join_images_vertically(*column, bg_color=(0, 0, 0), alignment=(0.5, 0.5)):
    return join_images(
        *[[image] for image in column],
        bg_color=bg_color,
        alignment=alignment
    )

For these images:

images = [
    [Image.open('banana.png'), Image.open('apple.png')],
    [Image.open('lime.png'), Image.open('lemon.png')],
]

Results will look like:


join_images(
    *images,
    bg_color='green',
    alignment=(0.5, 0.5)
).show()

enter image description here


join_images(
    *images,
    bg_color='green',
    alignment=(0, 0)

).show()

enter image description here


join_images(
    *images,
    bg_color='green',
    alignment=(1, 1)
).show()

enter image description here

Angular2 change detection: ngOnChanges not firing for nested object

Here's a hack that just got me out of trouble with this one.

So a similar scenario to the OP - I've got a nested Angular component that needs data passed down to it, but the input points to an array, and as mentioned above, Angular doesn't see a change as it does not examine the contents of the array.

So to fix it I convert the array to a string for Angular to detect a change, and then in the nested component I split(',') the string back to an array and its happy days again.

how do I get a new line, after using float:left?

You need to "clear" the float after every 6 images. So with your current code, change the styles for containerdivNewLine to:

.containerdivNewLine { clear: both; float: left; display: block; position: relative; } 

MySQL - DATE_ADD month interval

BETWEEN ... AND

If expr is greater than or equal to min and expr is less than or equal to max, BETWEEN returns 1, otherwise it returns 0.

The important part here is EQUAL to max., which 1st of July is.

Purpose of installing Twitter Bootstrap through npm?

If you NPM those modules you can serve them using static redirect.

First install the packages:

npm install jquery
npm install bootstrap

Then on the server.js:

var express = require('express');
var app = express();

// prepare server
app.use('/api', api); // redirect API calls
app.use('/', express.static(__dirname + '/www')); // redirect root
app.use('/js', express.static(__dirname + '/node_modules/bootstrap/dist/js')); // redirect bootstrap JS
app.use('/js', express.static(__dirname + '/node_modules/jquery/dist')); // redirect JS jQuery
app.use('/css', express.static(__dirname + '/node_modules/bootstrap/dist/css')); // redirect CSS bootstrap

Then, finally, at the .html:

<link rel="stylesheet" href="/css/bootstrap.min.css">
<script src="/js/jquery.min.js"></script>
<script src="/js/bootstrap.min.js"></script>

I would not serve pages directly from the folder where your server.js file is (which is usually the same as node_modules) as proposed by timetowonder, that way people can access your server.js file.

Of course you can simply download and copy & paste on your folder, but with NPM you can simply update when needed... easier, I think.

Are there such things as variables within an Excel formula?

Not related to variables, your example will also be solved by MOD:

=Mod(VLOOKUP(A1, B:B, 1, 0);10)

What is Python buffer type for?

I think buffers are e.g. useful when interfacing python to native libraries. (Guido van Rossum explains buffer in this mailinglist post).

For example, numpy seems to use buffer for efficient data storage:

import numpy
a = numpy.ndarray(1000000)

the a.data is a:

<read-write buffer for 0x1d7b410, size 8000000, offset 0 at 0x1e353b0>

How do I join two SQLite tables in my Android application?

You need rawQuery method.

Example:

private final String MY_QUERY = "SELECT * FROM table_a a INNER JOIN table_b b ON a.id=b.other_id WHERE b.property_id=?";

db.rawQuery(MY_QUERY, new String[]{String.valueOf(propertyId)});

Use ? bindings instead of putting values into raw sql query.

Inserting data to table (mysqli insert)

In mysqli_query(first parameter should be connection,your sql statement) so

$connetion_name=mysqli_connect("localhost","root","","web_table") or die(mysqli_error());
mysqli_query($connection_name,'INSERT INTO web_formitem (ID, formID, caption, key, sortorder, type, enabled, mandatory, data) VALUES (105, 7, Tip izdelka (6), producttype_6, 42, 5, 1, 0, 0)');

but best practice is

$connetion_name=mysqli_connect("localhost","root","","web_table") or die(mysqli_error());
$sql_statement="INSERT INTO web_formitem (ID, formID, caption, key, sortorder, type, enabled, mandatory, data) VALUES (105, 7, Tip izdelka (6), producttype_6, 42, 5, 1, 0, 0)";
mysqli_query($connection_name,$sql_statement);

Can't create project on Netbeans 8.2

For anyone that wants to download jdk 8 without an oracle account: https://download.oracle.com/otn-pub/java/jdk/8u271-b09/61ae65e088624f5aaa0b1d2d801acb16/jdk-8u271-windows-x64.exe copy and paste the link. Jdk 15 didn't work for me so i tried using jdk 8 and it worked.

How do I add a margin between bootstrap columns without wrapping

The simple way to do this is doing a div within a div

_x000D_
_x000D_
<div class="col-sm-4" style="padding: 5px;border:2px solid red;">_x000D_
   <div class="server-action-menu" id="server_1">Server 1_x000D_
   </div>_x000D_
 </div>_x000D_
<div class="col-sm-4" style="padding: 5px;border:2px solid red;">_x000D_
   <div class="server-action-menu" id="server_1">Server 2_x000D_
   </div>_x000D_
 </div>_x000D_
<div class="col-sm-4" style="padding: 5px;border:2px solid red;">_x000D_
   <div class="server-action-menu" id="server_1">Server 3_x000D_
   </div>_x000D_
 </div>
_x000D_
_x000D_
_x000D_

Reverse for '*' with arguments '()' and keyword arguments '{}' not found

You need single quotes around the view name

{% url 'viewname' %}

instead of

{% url viewname %}

mysqldump Error 1045 Access denied despite correct passwords etc

Tried most of the above with no joy. Looking at my password, it had characters that might confuse a parser. I wrapped the password in quotes and the error was resolved. -p"a:@#$%^&+6>&FAEH"

Using 8.0

Change background color for selected ListBox item

<UserControl.Resources>
    <Style x:Key="myLBStyle" TargetType="{x:Type ListBoxItem}">
        <Style.Resources>
            <SolidColorBrush x:Key="{x:Static SystemColors.HighlightBrushKey}"
                             Color="Transparent"/>
        </Style.Resources>
    </Style>
</UserControl.Resources> 

and

<ListBox ItemsSource="{Binding Path=FirstNames}"
         ItemContainerStyle="{StaticResource myLBStyle}">  

You just override the style of the listboxitem (see the: TargetType is ListBoxItem)

How to recognize swipe in all 4 directions

For Swift 5 it's updated

//Add in ViewDidLoad
let gesture = UISwipeGestureRecognizer(target: self, action: #selector(ViewController.handleSwipe))
        gesture.direction = .right
        self.view.addGestureRecognizer(gesture)

//Add New Method
@objc func handleSwipe(sender: UISwipeGestureRecognizer) {
        print("swipe direction is",sender.direction)

    }

Replacing H1 text with a logo image: best method for SEO and accessibility?

You're missing the option:

<h1>
  <a href="http://stackoverflow.com">
    <img src="logo.png" alt="Stack Overflow" />
  </a>
</h1>

title in href and img to h1 is very, very important!

Disabled form fields not submitting data

add CSS or class to the input element which works in select and text tags like

style="pointer-events: none;background-color:#E9ECEF"

Converting list to *args when calling function

*args just means that the function takes a number of arguments, generally of the same type.

Check out this section in the Python tutorial for more info.

What is AndroidX?

AndroidX - Android Extension Library

From AndroidX documentation

We are rolling out a new package structure to make it clearer which packages are bundled with the Android operating system, and which are packaged with your app's APK. Going forward, the android.* package hierarchy will be reserved for Android packages that ship with the operating system. Other packages will be issued in the new androidx.* package hierarchy as part of the AndroidX library.

Need of AndroidX

AndroidX is a redesigned library to make package names more clear. So from now on android hierarchy will be for only android default classes, which comes with android operating system and other library/dependencies will be part of androidx (makes more sense). So from now on all the new development will be updated in androidx.

com.android.support.** : androidx.
com.android.support:appcompat-v7 : androidx.appcompat:appcompat com.android.support:recyclerview-v7 : androidx.recyclerview:recyclerview com.android.support:design : com.google.android.material:material

Complete Artifact mappings for AndroidX packages

AndroidX uses Semantic-version

Previously, support library used the SDK version but AndroidX uses the Semantic-version. It’s going to re-version from 28.0.0 ? 1.0.0.

How to migrate current project

In Android Studio 3.2 (September 2018), there is a direct option to migrate existing project to AndroidX. This refactor all packages automatically.

Before you migrate, it is strongly recommended to backup your project.

Existing project

  • Android Studio > Refactor Menu > Migrate to AndroidX...
  • It will analyze and will open Refractor window in bottom. Accept changes to be done.

image

New project

Put these flags in your gradle.properties

android.enableJetifier=true
android.useAndroidX=true

Check @Library mappings for equal AndroidX package.

Check @Official page of Migrate to AndroidX

What is Jetifier?

Bugs of migrating

  • If you build app, and find some errors after migrating, then you need to fix those minor errors. You will not get stuck there, because that can be easily fixed.
  • 3rd party libraries are not converted to AndroidX in directory, but they get converted at run time by Jetifier, so don't worry about compile time errors, your app will run perfectly.

Support 28.0.0 is last release?

From Android Support Revision 28.0.0

This will be the last feature release under the android.support packaging, and developers are encouraged to migrate to AndroidX 1.0.0

So go with AndroidX, because Android will update only androidx package from now.

Further Reading

https://developer.android.com/topic/libraries/support-library/androidx-overview

https://android-developers.googleblog.com/2018/05/hello-world-androidx.html

What is the purpose of Looper and how to use it?

Understanding Looper Threads

A java Thread a unit of execution which was designed to perform a task in its run() method & terminate after that: enter image description here

But in Android there are many use cases where we need to keep a Thread alive and wait for user inputs/events for eg. UI thread aka Main Thread.

Main thread in Android is a Java thread which is first started by JVM at the launch of an app and keeps on running till the user choose to close it or encounters unhandled exception.

When an application is launched, the system creates a thread of execution for the application, called "main." This thread is very important because it is in charge of dispatching events to the appropriate user interface widgets, including drawing events.

enter image description here

Now point to note here is although main thread is Java thread yet it keeps on listening to user events and draw 60 fps frames on screen and still it wont die after each cycle. how is it so?

The answer is Looper Class: Looper is a class which is used to keep a thread alive and manage a message queue to execute tasks on that thread.

Threads by default do not have a message loop associated with them but you can assign one by calling Looper.prepare() in the run method and then call the Looper.loop().

Purpose of Looper is to keep a Thread alive and wait for next cycle of input Message object to perform computation which otherwise will get destroyed after first cycle of execution.

If you want to dig deeper how Looper manage Message object queue then you can have a look at source code of Looperclass:

https://github.com/aosp-mirror/platform_frameworks_base/blob/master/core/java/android/os/Looper.java

Below is an example of how you can create a Looper Thread and communicate with Activity class using LocalBroadcast

class LooperThread : Thread() {

    // sendMessage success result on UI
    private fun sendServerResult(result: String) {
        val resultIntent = Intent(ServerService.ACTION)
        resultIntent.putExtra(ServerService.RESULT_CODE, Activity.RESULT_OK)
        resultIntent.putExtra(ServerService.RESULT_VALUE, result)
        LocalBroadcastManager.getInstance(AppController.getAppController()).sendBroadcast(resultIntent)
    }

    override fun run() {
        val looperIsNotPreparedInCurrentThread = Looper.myLooper() == null

        // Prepare Looper if not already prepared
        if (looperIsNotPreparedInCurrentThread) {
            Looper.prepare()
        }

        // Create a handler to handle messaged from Activity
        handler = Handler(Handler.Callback { message ->
            // Messages sent to Looper thread will be visible here
            Log.e(TAG, "Received Message" + message.data.toString())

            //message from Activity
            val result = message.data.getString(MainActivity.BUNDLE_KEY)

            // Send Result Back to activity
            sendServerResult(result)
            true
        })

        // Keep on looping till new messages arrive
        if (looperIsNotPreparedInCurrentThread) {
            Looper.loop()
        }
    }

    //Create and send a new  message to looper
    fun sendMessage(messageToSend: String) {
        //Create and post a new message to handler
        handler!!.sendMessage(createMessage(messageToSend))
    }


    // Bundle Data in message object
    private fun createMessage(messageToSend: String): Message {
        val message = Message()
        val bundle = Bundle()
        bundle.putString(MainActivity.BUNDLE_KEY, messageToSend)
        message.data = bundle
        return message
    }

    companion object {
        var handler: Handler? = null // in Android Handler should be static or leaks might occur
        private val TAG = javaClass.simpleName

    }
}

Usage:

 class MainActivity : AppCompatActivity() {

    private var looperThread: LooperThread? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        // start looper thread
        startLooperThread()

        // Send messages to Looper Thread
        sendMessage.setOnClickListener {

            // send random messages to looper thread
            val messageToSend = "" + Math.random()

            // post message
            looperThread!!.sendMessage(messageToSend)

        }   
    }

    override fun onResume() {
        super.onResume()

        //Register to Server Service callback
        val filterServer = IntentFilter(ServerService.ACTION)
        LocalBroadcastManager.getInstance(this).registerReceiver(serverReceiver, filterServer)

    }

    override fun onPause() {
        super.onPause()

        //Stop Server service callbacks
     LocalBroadcastManager.getInstance(this).unregisterReceiver(serverReceiver)
    }


    // Define the callback for what to do when data is received
    private val serverReceiver = object : BroadcastReceiver() {
        override fun onReceive(context: Context, intent: Intent) {
            val resultCode = intent.getIntExtra(ServerService.RESULT_CODE, Activity.RESULT_CANCELED)
            if (resultCode == Activity.RESULT_OK) {
                val resultValue = intent.getStringExtra(ServerService.RESULT_VALUE)
                Log.e(MainActivity.TAG, "Server result : $resultValue")

                serverOutput.text =
                        (serverOutput.text.toString()
                                + "\n"
                                + "Received : " + resultValue)

                serverScrollView.post( { serverScrollView.fullScroll(View.FOCUS_DOWN) })
            }
        }
    }

    private fun startLooperThread() {

        // create and start a new LooperThread
        looperThread = LooperThread()
        looperThread!!.name = "Main Looper Thread"
        looperThread!!.start()

    }

    companion object {
        val BUNDLE_KEY = "handlerMsgBundle"
        private val TAG = javaClass.simpleName
    }
}

Can we use Async task or Intent Services instead?

  • Async tasks are designed to perform a short operation in background and give progres & results on UI thread. Async tasks have limits like you cant create more than 128 Async tasks and ThreadPoolExecutor will allow only upto 5 Async tasks.

  • IntentServices are also designed to do background task for a little longer duration and you can use LocalBroadcast to communicate with Activity. But services get destroyed after task execution. If you want to keep it running for a long time than you need to do hecks like while(true){...}.

Other meaningful use cases for Looper Thread:

  • Used for 2 way socket communication where server keep on listening to Client socket and write back acknowledgment

  • Bitmap processing in background. Pass the image url to Looper thread and it will apply filter effects and store it in tempe rory location and then broadcast temp path of image.

Attach to a processes output for viewing

There are a few options here. One is to redirect the output of the command to a file, and then use 'tail' to view new lines that are added to that file in real time.

Another option is to launch your program inside of 'screen', which is a sort-of text-based Terminal application. Screen sessions can be attached and detached, but are nominally meant only to be used by the same user, so if you want to share them between users, it's a big pain in the ass.

How can I replace newlines using PowerShell?

In my understanding, Get-Content eliminates ALL newlines/carriage returns when it rolls your text file through the pipeline. To do multiline regexes, you have to re-combine your string array into one giant string. I do something like:

$text = [string]::Join("`n", (Get-Content test.txt))
[regex]::Replace($text, "t`n", "ting`na ", "Singleline")

Clarification: small files only folks! Please don't try this on your 40 GB log file :)

mysql -> insert into tbl (select from another table) and some default values

INSERT INTO def (field_1, field_2, field3) 
VALUES 
('$field_1', (SELECT id_user from user_table where name = 'jhon'), '$field3')

org.hibernate.MappingException: Unknown entity

You entity is not correctly annotated, you must use the @javax.persistence.Entity annotation. You can use the Hibernate extension @org.hibernate.annotations.Entity to go beyond what JPA has to offer but the Hibernate annotation is not a replacement, it's a complement.

So change your code into:

import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;

@Entity
public class Message { 
    ...  
}

References

Fastest way to tell if two files have the same contents in Unix/Linux?

To quickly and safely compare any two files:

if cmp --silent -- "$FILE1" "$FILE2"; then
  echo "files contents are identical"
else
  echo "files differ"
fi

It's readable, efficient, and works for any file names including "` $()

jQuery Refresh/Reload Page if Ajax Success after time

if(success == true)
{
  //For wait 5 seconds
  setTimeout(function() 
  {
    location.reload();  //Refresh page
  }, 5000);
}

CSS Image size, how to fill, but not stretch?

<div class="container">
     <img src="http://i.stack.imgur.com/2OrtT.jpg"/>
</div>

<style>
.container {
       width: 150px;
       height: 100px;
       overflow: hidden;
}
</style>

This view is not constrained vertically. At runtime it will jump to the left unless you add a vertical constraint

app:layout_constraintEnd_toEndOf="parent"
app:layout_constraintStart_toStartOf="parent"
app:layout_constraintTop_toTopOf="parent"

This help me a lot

What is a callback URL in relation to an API?

Another use case could be something like OAuth, it's may not be called by the API directly, instead the callback URL will be called by the browser after completing the authencation with the identity provider.

Normally after end user key in the username password, the identity service provider will trigger a browser redirect to your "callback" url with the temporary authroization code, e.g.

https://example.com/callback?code=AUTHORIZATION_CODE

Then your application could use this authorization code to request a access token with the identity provider which has a much longer lifetime.

How do I execute a string containing Python code in Python?

In the example a string is executed as code using the exec function.

import sys
import StringIO

# create file-like string to capture output
codeOut = StringIO.StringIO()
codeErr = StringIO.StringIO()

code = """
def f(x):
    x = x + 1
    return x

print 'This is my output.'
"""

# capture output and errors
sys.stdout = codeOut
sys.stderr = codeErr

exec code

# restore stdout and stderr
sys.stdout = sys.__stdout__
sys.stderr = sys.__stderr__

print f(4)

s = codeErr.getvalue()

print "error:\n%s\n" % s

s = codeOut.getvalue()

print "output:\n%s" % s

codeOut.close()
codeErr.close()

Scrollview can host only one direct child

Wrap all the children inside of another LinearLayout with wrap_content for both the width and the height as well as the vertical orientation.

Remove Unnamed columns in pandas dataframe

df = df.loc[:, ~df.columns.str.contains('^Unnamed')]

In [162]: df
Out[162]:
   colA  ColB  colC  colD  colE  colF  colG
0    44    45    26    26    40    26    46
1    47    16    38    47    48    22    37
2    19    28    36    18    40    18    46
3    50    14    12    33    12    44    23
4    39    47    16    42    33    48    38

if the first column in the CSV file has index values, then you can do this instead:

df = pd.read_csv('data.csv', index_col=0)

Create Table from JSON Data with angularjs and ng-repeat

Angular 2 or 4:

There's no more ng-repeat, it's *ngFor now in recent Angular versions!

<table style="padding: 20px; width: 60%;">
    <tr>
      <th  align="left">id</th>
      <th  align="left">status</th>
      <th  align="left">name</th>
    </tr>
    <tr *ngFor="let item of myJSONArray">
      <td>{{item.id}}</td>
      <td>{{item.status}}</td>
      <td>{{item.name}}</td>
    </tr>
</table>

Used this simple JSON:

[{"id":1,"status":"active","name":"A"},
{"id":2,"status":"live","name":"B"},
{"id":3,"status":"active","name":"C"},
{"id":6,"status":"deleted","name":"D"},
{"id":4,"status":"live","name":"E"},
{"id":5,"status":"active","name":"F"}]

List supported SSL/TLS versions for a specific OpenSSL build

Try the following command:

openssl ciphers

This should produce a list of all of the ciphers supported in your version of openssl.

To see just a particular set of ciphers (e.g. just sslv3 ciphers) try:

openssl ciphers -ssl3

See https://www.openssl.org/docs/apps/ciphers.html for more info.

BAT file to map to network drive without running as admin

This .vbs code creates a .bat file with the current mapped network drives. Then, just put the created file into the machine which you want to re-create the mappings and double-click it. It will try to create all mappings using the same drive letters (errors can occur if any letter is in use). This method also can be used as a backup of the current mappings. Save the code bellow as a .vbs file (e.g. Mappings.vbs) and double-click it.

' ********** My Code **********
Set wshShell = CreateObject( "WScript.Shell" )

' ********** Get ComputerName
strComputer = wshShell.ExpandEnvironmentStrings( "%COMPUTERNAME%" )

' ********** Get Domain 
sUserDomain = createobject("wscript.network").UserDomain

Set Connect = GetObject("winmgmts://"&strComputer)
Set WshNetwork = WScript.CreateObject("WScript.Network")
Set oDrives = WshNetwork.EnumNetworkDrives
Set oPrinters = WshNetwork.EnumPrinterConnections

' ********** Current Path
sCurrentPath = CreateObject("Scripting.FileSystemObject").GetParentFolderName(WScript.ScriptFullName)

' ********** Blank the report message
strMsg = ""

' ********** Set objects 
Set objWMIService = GetObject("winmgmts:" & "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set objWbem = GetObject("winmgmts:")
Set objRegistry = GetObject("winmgmts://" & strComputer & "/root/default:StdRegProv")

' ********** Get UserName
sUser = CreateObject("WScript.Network").UserName

' ********** Print user and computer
'strMsg = strMsg & "    User: " & sUser & VbCrLf
'strMsg = strMsg & "Computer: " & strComputer & VbCrLf & VbCrLf

strMsg = strMsg & "###  COPIED FROM " & strComputer & " ###" & VbCrLf& VbCrLf
strMsg = strMsg & "@echo off" & vbCrLf

For i = 0 to oDrives.Count - 1 Step 2
    strMsg = strMsg & "net use " & oDrives.Item(i) & " " & oDrives.Item(i+1) & " /user:" & sUserDomain & "\" & sUser & " /persistent:yes" & VbCrLf
Next
strMsg = strMsg & ":exit" & VbCrLf
strMsg = strMsg & "@pause" & VbCrLf

' ********** write the file to disk.
strDirectory = sCurrentPath 
Set objFSO = CreateObject("Scripting.FileSystemObject")
If objFSO.FolderExists(strDirectory) Then
    ' Procede
Else
    Set objFolder = objFSO.CreateFolder(strDirectory)
End if

' ********** Calculate date serial for filename **********
intMonth = month(now)
if intMonth < 10 then
    strThisMonth = "0" & intMonth
else
    strThisMonth = intMOnth
end if
intDay = Day(now)
if intDay < 10 then
    strThisDay = "0" & intDay
else
    strThisDay = intDay
end if
strFilenameDateSerial = year(now) & strThisMonth & strThisDay
    sFileName = strDirectory & "\" & strComputer & "_" & sUser & "_MappedDrives" & "_" & strFilenameDateSerial & ".bat"
    Set objFile = objFSO.CreateTextFile(sFileName,True) 
objFile.Write strMsg & vbCrLf

' ********** Ask to view file
strFinish = "End: A .bat was generated. " & VbCrLf & "Copy the generated file  (" & sFileName & ")  into the machine where you want to recreate the mappings and double-click it." & VbCrLf & VbCrLf 
MsgBox(strFinish)

How to go from Blob to ArrayBuffer

There is now (Chrome 76+ & FF 69+) a Blob.prototype.arrayBuffer() method which will return a Promise resolving with an ArrayBuffer representing the Blob's data.

_x000D_
_x000D_
(async () => {_x000D_
  const blob = new Blob(['hello']);_x000D_
  const buf = await blob.arrayBuffer();_x000D_
  console.log( buf.byteLength ); // 5_x000D_
})();
_x000D_
_x000D_
_x000D_

Display text on MouseOver for image in html

You can do like this also:

HTML:

<a><img src='https://encrypted-tbn2.google.com/images?q=tbn:ANd9GcQB3a3aouZcIPEF0di4r9uK4c0r9FlFnCasg_P8ISk8tZytippZRQ' onmouseover="somefunction();"></a>

In javascript:

function somefunction()
{
  //Do somethisg.
}

?

How do I get the XML SOAP request of an WCF Web service request?

There is an another way to see XML SOAP - custom MessageEncoder. The main difference from IClientMessageInspector is that it works on lower level, so it captures original byte content including any malformed xml.

In order to implement tracing using this approach you need to wrap a standard textMessageEncoding with custom message encoder as new binding element and apply that custom binding to endpoint in your config.

Also you can see as example how I did it in my project - wrapping textMessageEncoding, logging encoder, custom binding element and config.

Activity restart on rotation Android

One of the best component of android architechure introduce by google will fulfill your all the requirement that is ViewModel.

That is designed to store and manage UI related data in lifecycle way plus that will allow data to survive as screen rotates

class MyViewModel : ViewModel() {

Please refer this:https://developer.android.com/topic/libraries/architecture/viewmodel

How to redirect to a different domain using NGINX?

Why use the rewrite module if you can do return? Technically speaking, return is part of the rewrite module as you can read here but this snippet is easier to read imho.

server {
    server_name  .domain.com;

    return 302 $scheme://forwarded-domain.com;
}

You can also give it a 301 redirect.

Check whether a string matches a regex in JS

_x000D_
_x000D_
const regExpStr = "^([a-z0-9]{5,})$"
const result = new RegExp(regExpStr, 'g').test("Your string") // here I have used 'g' which means global search
console.log(result) // true if it matched, false if it doesn't
_x000D_
_x000D_
_x000D_

Eclipse Build Path Nesting Errors

I wanted to throw in a non-mavenish answer to this thread.

Due to version control and strict directory structure reasons, I was unable to follow Acheron's answer (the best answer) of doing something similar to removing src/ and adding src/main/java and src/test/java to the build path.

I had actually been off-and-on battling this nested build path issue for a couple weeks. The answer to the problem is hinted in the error message:

To enable the nesting exclude 'main/' from 'final/src'

Fix

In your build path, you need to edit your Inclusion and Exclusion Patterns by clicking on Excluded: (None) and then Edit...:

  1. Go to the navigator and press right click on the project
  2. Build Path
  3. Configure Build Path
  4. Source (tab)

Exclusion Patterns

There you can add main/webapp/WEB-INF/classes as an Exclusion Pattern. Then it should allow you to add main/webapp/WEB-INF/classes to the build path as a separate source folder.

Get DOS path instead of Windows path

use this link, it will automatically convert any path you give to any format https://pathconverter-pp.azurewebsites.net

Return back to MainActivity from another activity

Use this code on button click in activity and When return back to another activity just finish previous activity by setting flag in intent then put only one Activity in the Stack and destroy the previous one.

  Intent i=new Intent("this","YourClassName.Class");
  i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
  startActivity(i);

Base64 encoding and decoding in client-side Javascript

I have tried the Javascript routines at phpjs.org and they have worked well.

I first tried the routines suggested in the chosen answer by Ranhiru Cooray - http://ntt.cc/2008/01/19/base64-encoder-decoder-with-javascript.html

I found that they did not work in all circumstances. I wrote up a test case where these routines fail and posted them to GitHub at:

https://github.com/scottcarter/base64_javascript_test_data.git

I also posted a comment to the blog post at ntt.cc to alert the author (awaiting moderation - the article is old so not sure if comment will get posted).

Tool to convert java to c# code

For your reference:

Note: I had no experience on them.

Cannot connect to Database server (mysql workbench)

It looks like there are a lot of causes of this error.

My Cause / Solution

In my case, the cause was that my server was configured to only accept connections from localhost. I fixed it by following this article: How Do I Enable Remote Access To MySQL Database Server?. My my.cnf file had no skip-networking line, so I just changed the line

bind-address = 127.0.0.1

to

bind-address = 0.0.0.0

This allows connections from any IP, not just 127.0.0.1.

Then, I created a MySql user that could connect from my client machine by running the following terminal commands:

# mysql -u root -p
mysql> CREATE USER 'username'@'1.2.3.4' IDENTIFIED BY 'password';
    -> GRANT ALL PRIVILEGES ON *.* TO 'username'@'1.2.3.4' WITH GRANT OPTION;
    -> \q

where 1.2.3.4 is the IP of the client you are trying to connect from. If you really have trouble, you can use '%' instead of '1.2.3.4' to allow the user to connect from any IP.

Other Causes

For a fairly extensive list, see Causes of Access-Denied Errors.

Now() function with time trim

Paste this function in your Module and use it as like formula

Public Function format_date(t As String)
    format_date = Format(t, "YYYY-MM-DD")
End Function

for example in Cell A1 apply this formula

=format_date(now())

it will return in YYYY-MM-DD format. Change any format (year month date) as your wish.

jQuery: get data attribute

Change IDs and data attributes as you wish!

  <select id="selectVehicle">
       <option value="1" data-year="2011">Mazda</option>
       <option value="2" data-year="2015">Honda</option>
       <option value="3" data-year="2008">Mercedes</option>
       <option value="4" data-year="2005">Toyota</option>
  </select>

$("#selectVehicle").change(function () {
     alert($(this).find(':selected').data("year"));
});

Here is the working example: https://jsfiddle.net/ed5axgvk/1/

Regex to remove letters, symbols except numbers

If you want to keep only numbers then use /[^0-9]+/ instead of /[^a-zA-Z]+/

"Press Any Key to Continue" function in C

You don't say what system you're using, but as you already have some answers that may or may not work for Windows, I'll answer for POSIX systems.

In POSIX, keyboard input comes through something called a terminal interface, which by default buffers lines of input until Return/Enter is hit, so as to deal properly with backspace. You can change that with the tcsetattr call:

#include <termios.h>

struct termios info;
tcgetattr(0, &info);          /* get current terminal attirbutes; 0 is the file descriptor for stdin */
info.c_lflag &= ~ICANON;      /* disable canonical mode */
info.c_cc[VMIN] = 1;          /* wait until at least one keystroke available */
info.c_cc[VTIME] = 0;         /* no timeout */
tcsetattr(0, TCSANOW, &info); /* set immediately */

Now when you read from stdin (with getchar(), or any other way), it will return characters immediately, without waiting for a Return/Enter. In addition, backspace will no longer 'work' -- instead of erasing the last character, you'll read an actual backspace character in the input.

Also, you'll want to make sure to restore canonical mode before your program exits, or the non-canonical handling may cause odd effects with your shell or whoever invoked your program.

Null pointer Exception on .setOnClickListener

Submit is null because it is not part of activity_main.xml

When you call findViewById inside an Activity, it is going to look for a View inside your Activity's layout.

try this instead :

Submit = (Button)loginDialog.findViewById(R.id.Submit);

Another thing : you use

android:layout_below="@+id/LoginTitle"

but what you want is probably

android:layout_below="@id/LoginTitle"

See this question about the difference between @id and @+id.

Adding a column to a data.frame

You can add a column to your data using various techniques. The quotes below come from the "Details" section of the relevant help text, [[.data.frame.

Data frames can be indexed in several modes. When [ and [[ are used with a single vector index (x[i] or x[[i]]), they index the data frame as if it were a list.

my.dataframe["new.col"] <- a.vector
my.dataframe[["new.col"]] <- a.vector

The data.frame method for $, treats x as a list

my.dataframe$new.col <- a.vector

When [ and [[ are used with two indices (x[i, j] and x[[i, j]]) they act like indexing a matrix

my.dataframe[ , "new.col"] <- a.vector

Since the method for data.frame assumes that if you don't specify if you're working with columns or rows, it will assume you mean columns.


For your example, this should work:

# make some fake data
your.df <- data.frame(no = c(1:4, 1:7, 1:5), h_freq = runif(16), h_freqsq = runif(16))

# find where one appears and 
from <- which(your.df$no == 1)
to <- c((from-1)[-1], nrow(your.df)) # up to which point the sequence runs

# generate a sequence (len) and based on its length, repeat a consecutive number len times
get.seq <- mapply(from, to, 1:length(from), FUN = function(x, y, z) {
            len <- length(seq(from = x[1], to = y[1]))
            return(rep(z, times = len))
         })

# when we unlist, we get a vector
your.df$group <- unlist(get.seq)
# and append it to your original data.frame. since this is
# designating a group, it makes sense to make it a factor
your.df$group <- as.factor(your.df$group)


   no     h_freq   h_freqsq group
1   1 0.40998238 0.06463876     1
2   2 0.98086928 0.33093795     1
3   3 0.28908651 0.74077119     1
4   4 0.10476768 0.56784786     1
5   1 0.75478995 0.60479945     2
6   2 0.26974011 0.95231761     2
7   3 0.53676266 0.74370154     2
8   4 0.99784066 0.37499294     2
9   5 0.89771767 0.83467805     2
10  6 0.05363139 0.32066178     2
11  7 0.71741529 0.84572717     2
12  1 0.10654430 0.32917711     3
13  2 0.41971959 0.87155514     3
14  3 0.32432646 0.65789294     3
15  4 0.77896780 0.27599187     3
16  5 0.06100008 0.55399326     3

c# dictionary one key many values

A .NET dictionary does only have a 1-to-1 relationship for keys and values. But that doesn't mean that a value can't be another array/list/dictionary.

I can't think of a reason to have a 1 to many relationship in a dictionary, but obviously there is one.

If you have different types of data that you want to store to a key, then that sounds like the ideal time to create your own class. Then you have a 1 to 1, but you have the value class storing more that 1 piece of data.

Find and replace words/lines in a file

public static void replaceFileString(String old, String new) throws IOException {
    String fileName = Settings.getValue("fileDirectory");
    FileInputStream fis = new FileInputStream(fileName);
    String content = IOUtils.toString(fis, Charset.defaultCharset());
    content = content.replaceAll(old, new);
    FileOutputStream fos = new FileOutputStream(fileName);
    IOUtils.write(content, new FileOutputStream(fileName), Charset.defaultCharset());
    fis.close();
    fos.close();
}

above is my implementation of Meriton's example that works for me. The fileName is the directory (ie. D:\utilities\settings.txt). I'm not sure what character set should be used, but I ran this code on a Windows XP machine just now and it did the trick without doing that temporary file creation and renaming stuff.

csv.Error: iterator should return strings, not bytes

Your problem is you have the b in the open flag. The flag rt (read, text) is the default, so, using the context manager, simply do this:

with open('sample.csv') as ifile:
    read = csv.reader(ifile) 
    for row in read:
        print (row)  

The context manager means you don't need generic error handling (without which you may get stuck with the file open, especially in an interpreter), because it will automatically close the file on an error, or on exiting the context.

The above is the same as:

with open('sample.csv', 'r') as ifile:
    ...

or

with open('sample.csv', 'rt') as ifile:
    ...

casting Object array to Integer array error

You can't cast an Object array to an Integer array. You have to loop through all elements of a and cast each one individually.

Object[] a = new Object[1];
Integer b=1;
a[0]=b;
Integer[] c = new Integer[a.length];
for(int i = 0; i < a.length; i++)
{
    c[i] = (Integer) a[i];
}

Edit: I believe the rationale behind this restriction is that when casting, the JVM wants to ensure type-safety at runtime. Since an array of Objects can be anything besides Integers, the JVM would have to do what the above code is doing anyway (look at each element individually). The language designers decided they didn't want the JVM to do that (I'm not sure why, but I'm sure it's a good reason).

However, you can cast a subtype array to a supertype array (e.g. Integer[] to Object[])!

How to get file creation date/time in Bash/Debian?

ls -i menus.xml

94490 menus.xml Here the number 94490 represents inode

Then do a:

df -h

Filesystem            Size  Used Avail Use% Mounted on
/dev/mapper/vg-root   4.0G  3.4G  408M  90% /
tmpfs                 1.9G     0  1.9G   0% /dev/shm
/dev/sda1             124M   27M   92M  23% /boot
/dev/mapper/vg-var    7.9G  1.1G  6.5G  15% /var

To find the mounting point of the root "/" filesystem, because the file menus.xml is on '/' that is '/dev/mapper/vg-root'

debugfs -R 'stat <94490>' /dev/mapper/vg-root

The output may be like the one below:

debugfs -R 'stat <94490>' /dev/mapper/vg-root

debugfs 1.41.12 (17-May-2010)
Inode: 94490   Type: regular    Mode:  0644   Flags: 0x0
Generation: 2826123170    Version: 0x00000000
User:     0   Group:     0   Size: 4441
File ACL: 0    Directory ACL: 0
Links: 1   Blockcount: 16
Fragment:  Address: 0    Number: 0    Size: 0
ctime: 0x5266e438 -- Wed Oct 23 09:46:48 2013
atime: 0x5266e47b -- Wed Oct 23 09:47:55 2013
mtime: 0x5266e438 -- Wed Oct 23 09:46:48 2013
Size of extra inode fields: 4
Extended attributes stored in inode body: 
  selinux = "unconfined_u:object_r:usr_t:s0\000" (31)
BLOCKS:
(0-1):375818-375819
TOTAL: 2

Where you can see the creation time:

ctime: 0x5266e438 -- Wed Oct 23 09:46:48 2013

In PHP, how do you change the key of an array element?

The answer from KernelM is nice, but in order to avoid the issue raised by Greg in the comment (conflicting keys), using a new array would be safer

$newarr[$newkey] = $oldarr[$oldkey];
$oldarr=$newarr;
unset($newarr);

How to refactor Node.js code that uses fs.readFileSync() into using fs.readFile()?

This variant is better because you could not know whether file exists or not. You should send correct header when you know for certain that you can read contents of your file. Also, if you have branches of code that does not finish with '.end()', browser will wait until it get them. In other words, your browser will wait a long time.

var fs = require("fs");
var filename = "./index.html";

function start(resp) {

    fs.readFile(filename, "utf8", function(err, data) {
        if (err) {
            // may be filename does not exists?
            resp.writeHead(404, {
                'Content-Type' : 'text/html'
            });
            // log this error into browser
            resp.write(err.toString());
            resp.end();
        } else {

            resp.writeHead(200, {
                "Content-Type": "text/html"
            });      
            resp.write(data.toString());
            resp.end();
        }
    });
}

Use custom build output folder when using create-react-app

I had the scenario like want to rename the folder and change the build output location, and used below code in the package.json with the latest version

"build": "react-scripts build && mv build ../my_bundles"

jQuery AJAX Call to PHP Script with JSON Return

Use parseJSON jquery method to covert string into object

var objData = jQuery.parseJSON(data);

Now you can write code

$('#result').html(objData .status +':' + objData .message);

Images can't contain alpha channels or transparencies

You must remove alpha channels when uploading a photo to iTunes Connect.

You can do this by Preview, Photos App (old iPhoto), Pixelmator, Adobe Photoshop and GIMP.

Preview

  1. Open the photo in Preview (if the photo is in your photo album in Photos app (the old iPhoto), then simply drag it from the album to desktop. Then control-click (right-click when mouse) the duplicated photo and select Preview.app under Open With menu).

  2. Select Export… under File menu, and after selecting the destination, uncheck Alpha at the bottom, and click Export.

    File ==> Export...

    Alpha

Pixelmator

  1. Open the image in Pixelmator, without creating a new Pixelmator file. Just drag the photo to the Pixelmator window.

  2. From Share menu, click Export for Web…

    PM

  3. In the top bar, deselect Transparency.

  4. Click Next and then save the new file somewhere.

Finally, upload the new photo to iTunes Connect.

GIMP

  1. Open the photo in GIMP.

  2. Open the Layer menu.

  3. Under Transparency, click Remove Alpha Channel.

  4. Save the photo.

Adobe Photoshop

  1. Open the photo in Adobe Photoshop.

  2. Under Layer menu, click Layer Mask and then From Transparency.

  3. Delete the layer mask by right-clicking on the mask in the Layer panel and selecting Delete Layer Mask.

How to prevent a browser from storing passwords

One way would be to generate random input names and work with them.

This way, browsers will be presented with the new form each time and won't be able to pre-populate the input fields.

If you provide us with some sample code (do you have a JavaScript single-page application (SPA) app or some server side rendering) I would be happy to help you in the implementation.

Why are Python lambdas useful?

Lambda function it's a non-bureaucratic way to create a function.

That's it. For example, let's supose you have your main function and need to square values. Let's see the traditional way and the lambda way to do this:

Traditional way:

def main():
...
...
y = square(some_number)
...
return something

def square(x):
    return x**2

The lambda way:

def main():
...
square = lambda x: x**2
y = square(some_number)
return something

See the difference?

Lambda functions go very well with lists, like lists comprehensions or map. In fact, list comprehension it's a "pythonic" way to express yourself using lambda. Ex:

>>>a = [1,2,3,4]
>>>[x**2 for x in a]
[1,4,9,16]

Let's see what each elements of the syntax means:

[] : "Give me a list"

x**2 : "using this new-born function"

for x in a: "into each element in a"

That's convenient uh? Creating functions like this. Let's rewrite it using lambda:

>>> square = lambda x: x**2
>>> [square(s) for x in a]
[1,4,9,16]

Now let's use map, which is the same thing, but more language-neutral. Maps takes 2 arguments:

(i) one function

(ii) an iterable

And gives you a list where each element it's the function applied to each element of the iterable.

So, using map we would have:

>>> a = [1,2,3,4]
>>> squared_list = map(lambda x: x**2, a)

If you master lambdas and mapping, you will have a great power to manipulate data and in a concise way. Lambda functions are neither obscure nor take away code clarity. Don't confuse something hard with something new. Once you start using them, you will find it very clear.

Jenkins: Cannot define variable in pipeline stage

The Declarative model for Jenkins Pipelines has a restricted subset of syntax that it allows in the stage blocks - see the syntax guide for more info. You can bypass that restriction by wrapping your steps in a script { ... } block, but as a result, you'll lose validation of syntax, parameters, etc within the script block.

Reading a plain text file in Java

You can use readAllLines and the join method to get whole file content in one line:

String str = String.join("\n",Files.readAllLines(Paths.get("e:\\text.txt")));

It uses UTF-8 encoding by default, which reads ASCII data correctly.

Also you can use readAllBytes:

String str = new String(Files.readAllBytes(Paths.get("e:\\text.txt")), StandardCharsets.UTF_8);

I think readAllBytes is faster and more precise, because it does not replace new line with \n and also new line may be \r\n. It is depending on your needs which one is suitable.

Preferred way of getting the selected item of a JComboBox

If you have only put (non-null) String references in the JComboBox, then either way is fine.

However, the first solution would also allow for future modifications in which you insert Integers, Doubless, LinkedLists etc. as items in the combo box.

To be robust against null values (still without casting) you may consider a third option:

String x = String.valueOf(JComboBox.getSelectedItem());

C++ correct way to return pointer to array from function

Your code (which looks ok) doesn't return a pointer to an array. It returns a pointer to the first element of an array.

In fact that's usually what you want to do. Most manipulation of arrays are done via pointers to individual elements, not via pointers to the array as a whole.

You can define a pointer to an array, for example this:

double (*p)[42];

defines p as a pointer to a 42-element array of doubles. A big problem with that is that you have to specify the number of elements in the array as part of the type -- and that number has to be a compile-time constant. Most programs that deal with arrays need to deal with arrays of varying sizes; a given array's size won't vary after it's been created, but its initial size isn't necessarily known at compile time, and different array objects can have different sizes.

A pointer to the first element of an array lets you use either pointer arithmetic or the indexing operator [] to traverse the elements of the array. But the pointer doesn't tell you how many elements the array has; you generally have to keep track of that yourself.

If a function needs to create an array and return a pointer to its first element, you have to manage the storage for that array yourself, in one of several ways. You can have the caller pass in a pointer to (the first element of) an array object, probably along with another argument specifying its size -- which means the caller has to know how big the array needs to be. Or the function can return a pointer to (the first element of) a static array defined inside the function -- which means the size of the array is fixed, and the same array will be clobbered by a second call to the function. Or the function can allocate the array on the heap -- which makes the caller responsible for deallocating it later.

Everything I've written so far is common to C and C++, and in fact it's much more in the style of C than C++. Section 6 of the comp.lang.c FAQ discusses the behavior of arrays and pointers in C.

But if you're writing in C++, you're probably better off using C++ idioms. For example, the C++ standard library provides a number of headers defining container classes such as <vector> and <array>, which will take care of most of this stuff for you. Unless you have a particular reason to use raw arrays and pointers, you're probably better off just using C++ containers instead.

EDIT : I think you edited your question as I was typing this answer. The new code at the end of your question is, as you observer, no good; it returns a pointer to an object that ceases to exist as soon as the function returns. I think I've covered the alternatives.

Postman: How to make multiple requests at the same time

I guess there's no such feature in postman as to run concurrent tests.

If i were you i would consider Apache jMeter which is used exactly for such scenarios.

Regarding Postman, the only thing that could more or less meet your needs is - Postman Runner. enter image description here There you can specify the details:

  • number of iterations,
  • upload csv file with data for different test runs, etc.

The runs won't be concurrent, only consecutive.

Hope that helps. But do consider jMeter (you'll love it).

jquery click event not firing?

I was wasting my time on this for hours. Fortunately, I found the solution. If you are using bootstrap admin templates (AdminLTE), this problem may show up. Thing is we have to use adminLTE framework plugins.

example: ifChecked event:

$('input').on('ifChecked', function(event){
   alert(event.type + ' callback');
});

For more information click here.

Hope it helps you too.

MySQL SELECT query string matching

Incorrect:

SELECT * FROM customers WHERE name LIKE '%Bob Smith%';

Instead:

select count(*)
from rearp.customers c
where c.name  LIKE '%Bob smith.8%';

select count will just query (totals)

C will link the db.table to the names row you need this to index

LIKE should be obvs

8 will call all references in DB 8 or less (not really needed but i like neatness)

How can I pass a reference to a function, with parameters?

What you are after is called partial function application.

Don't be fooled by those that don't understand the subtle difference between that and currying, they are different.

Partial function application can be used to implement, but is not currying. Here is a quote from a blog post on the difference:

Where partial application takes a function and from it builds a function which takes fewer arguments, currying builds functions which take multiple arguments by composition of functions which each take a single argument.

This has already been answered, see this question for your answer: How can I pre-set arguments in JavaScript function call?

Example:

var fr = partial(f, 1, 2, 3);

// now, when you invoke fr() it will invoke f(1,2,3)
fr();

Again, see that question for the details.

How to find Max Date in List<Object>?

Comparator<User> cmp = new Comparator<User>() {
    @Override
    public int compare(User user1, User user2) {
        return user1.date.compareTo(user2.date);
    }
};

Collections.max(list, cmp);

Question mark and colon in JavaScript

?: is a short-hand condition for else {} and if(){} problems. So your code is interchangeable to this:

if(max != 0){
       hsb.s = 225 * delta / max
}
else {
       hsb.s = 0
}

MDN - Conditional (Ternary) Operator

How to create a regex for accepting only alphanumeric characters?

[a-zA-Z0-9] will only match ASCII characters, it won't match

String target = new String("A" + "\u00ea" + "\u00f1" +
                             "\u00fc" + "C");

If you also want to match unicode characters:

String pat = "^[\\p{L}0-9]*$";

How to execute a .sql script from bash

If you want to run a script to a database:

mysql -u user -p data_base_name_here < db.sql

When do I need to use Begin / End Blocks and the Go keyword in SQL Server?

You need BEGIN ... END to create a block spanning more than one statement. So, if you wanted to do 2 things in one 'leg' of an IF statement, or if you wanted to do more than one thing in the body of a WHILE loop, you'd need to bracket those statements with BEGIN...END.

The GO keyword is not part of SQL. It's only used by Query Analyzer to divide scripts into "batches" that are executed independently.

What exactly is an instance in Java?

basically object and instance are the two words used interchangeably. A class is template for an object and an object is an instance of a class.

CSS Auto hide elements after 5 seconds

Of course you can, just use setTimeout to change a class or something to trigger the transition.

HTML:

<p id="aap">OHAI!</p>

CSS:

p {
    opacity:1;
    transition:opacity 500ms;
}
p.waa {
    opacity:0;
}

JS to run on load or DOMContentReady:

setTimeout(function(){
    document.getElementById('aap').className = 'waa';
}, 5000);

Example fiddle here.

How to simulate a real mouse click using java?

Some applications may detect click source at low OS level. If you really need that kind of hack, you may just run target app in virtual machine's window, and run cliker in host OS, it can help.

How can you print multiple variables inside a string using printf?

Change the line where you print the output to:

printf("\nmaximum of %d and %d is = %d",a,b,c);

See the docs here

Have a variable in images path in Sass?

Have you tried the Interpolation syntax?

background: url(#{$get-path-to-assets}/site/background.jpg) repeat-x fixed 0 0;

The requested resource does not support HTTP method 'GET'

Resolved this issue by using http(s) when accessing the endpoint. The route I was accessing was not available over http. So I would say verify the protocols for which the route is available.

Select query with date condition

hey guys i think what you are looking for is this one using select command. With this you can specify a RANGE GREATER THAN(>) OR LESSER THAN(<) IN MySQL WITH THIS:::::

select* from <**TABLE NAME**> where year(**COLUMN NAME**) > **DATE** OR YEAR(COLUMN NAME )< **DATE**;

FOR EXAMPLE:

select name, BIRTH from pet1 where year(birth)> 1996 OR YEAR(BIRTH)< 1989;
+----------+------------+
| name     | BIRTH      |
+----------+------------+
| bowser   | 1979-09-11 |
| chirpy   | 1998-09-11 |
| whistler | 1999-09-09 |
+----------+------------+

FOR SIMPLE RANGE LIKE USE ONLY GREATER THAN / LESSER THAN

mysql> select COLUMN NAME from <TABLE NAME> where year(COLUMN NAME)> 1996;

FOR EXAMPLE mysql>

select name from pet1 where year(birth)> 1996 OR YEAR(BIRTH)< 1989;
+----------+
| name     |
+----------+
| bowser   |
| chirpy   |
| whistler |
+----------+
3 rows in set (0.00 sec)

how to read a long multiline string line by line in python

This answer fails in a couple of edge cases (see comments). The accepted solution above will handle these. str.splitlines() is the way to go. I will leave this answer nevertheless as reference.

Old (incorrect) answer:

s =  \
"""line1
line2
line3
"""

lines = s.split('\n')
print(lines)
for line in lines:
    print(line)

How to resolve Nodejs: Error: ENOENT: no such file or directory

I solved this error by simply creating a blank file at that location for which I got the error. If you are getting the error for a directory, You can try by creating empty directory also. All the best.

Invoking JavaScript code in an iframe from the parent page

The IFRAME should be in the frames[] collection. Use something like

frames['iframeid'].method();

How to make a DIV always float on the screen in top right corner?

Use position: fixed, and anchor it to the top and right sides of the page:

#fixed-div {
    position: fixed;
    top: 1em;
    right: 1em;
}

IE6 does not support position: fixed, however. If you need this functionality in IE6, this purely-CSS solution seems to do the trick. You'll need a wrapper <div> to contain some of the styles for it to work, as seen in the stylesheet.

Transpose list of lists

How about

map(list, zip(*l))
--> [[1, 4, 7], [2, 5, 8], [3, 6, 9]]

For python 3.x users can use

list(map(list, zip(*l))) # short circuits at shortest nested list if table is jagged
list(map(list, itertools.zip_longest(*l, fillvalue=None))) # discards no data if jagged and fills short nested lists with None

Explanation:

There are two things we need to know to understand what's going on:

  1. The signature of zip: zip(*iterables) This means zip expects an arbitrary number of arguments each of which must be iterable. E.g. zip([1, 2], [3, 4], [5, 6]).
  2. Unpacked argument lists: Given a sequence of arguments args, f(*args) will call f such that each element in args is a separate positional argument of f.
  3. itertools.zip_longest does not discard any data if the number of elements of the nested lists are not the same (homogenous), and instead fills in the shorter nested lists then zips them up.

Coming back to the input from the question l = [[1, 2, 3], [4, 5, 6], [7, 8, 9]], zip(*l) would be equivalent to zip([1, 2, 3], [4, 5, 6], [7, 8, 9]). The rest is just making sure the result is a list of lists instead of a list of tuples.

Logging request/response messages when using HttpClient

See http://mikehadlow.blogspot.com/2012/07/tracing-systemnet-to-debug-http-clients.html

To configure a System.Net listener to output to both the console and a log file, add the following to your assembly configuration file:

<system.diagnostics>
  <trace autoflush="true" />
  <sources>
    <source name="System.Net">
      <listeners>
        <add name="MyTraceFile"/>
        <add name="MyConsole"/>
      </listeners>
    </source>
  </sources>
  <sharedListeners>
    <add
      name="MyTraceFile"
      type="System.Diagnostics.TextWriterTraceListener"
      initializeData="System.Net.trace.log" />
    <add name="MyConsole" type="System.Diagnostics.ConsoleTraceListener" />
  </sharedListeners>
  <switches>
    <add name="System.Net" value="Verbose" />
  </switches>
</system.diagnostics>

Fatal error: Out of memory, but I do have plenty of memory (PHP)

Try to run php over fcgid, this may help:

These are the classic errors you will see when running PHP as an Apache module. We struggled with these errors for months. Switching to using PHP via mod_fcgid (as James recommends) will fix all of these problems. Be sure you have the latest Visual C++ Redistributable package installed:

http://support.microsoft.com/kb/2019667

Also, I recommend switching to the 64-bit version of MySQL. No real reason to run the 32-bit version anymore.

Source: Apache 2.4.6.0 crash due to a problem in php5ts.dll 5.5.1.0

Static nested class in Java, why?

One of the reasons for static vs. normal have to do with classloading. You cannot instantiate an inner class in the constructor of it's parent.

PS: I've always understood 'nested' and 'inner' to be interchangeable. There may be subtle nuances in the terms but most Java developers would understand either.

PyLint "Unable to import" error - how to set PYTHONPATH?

just add this code in .vscode/settings.json file

,"python.linting.pylintPath": "venv/bin/pylint"

This will notify the location of pylint(which is an error checker for python)

Install sbt on ubuntu

It seems like you installed a zip version of sbt, which is fine. But I suggest you install the native debian package if you are on Ubuntu. That is how I managed to install it on my Ubuntu 12.04. Check it out here: http://www.scala-sbt.org/release/docs/Installing-sbt-on-Linux.html Or simply directly download it from here.

Fastest way to ping a network range and return responsive hosts?

This script runs on Git Bash (MINGW64) on Windows and return a messages depending of the ping result.

#!/bin/bash
#$1 should be something like "19.62.55"

if [ -z "$1" ]
  then
    echo "No identify of the network supplied, i.e. 19.62.55"
else
    ipAddress=$1

    for i in {1..256} ;do 
    (
        {
        ping -w 5 $ipAddress.$i ; 
        result=$(echo $?);
        } &> /dev/null


        if [ $result = 0 ]; then
            echo Successful Ping From : $ipAddress.$i
        else
            echo Failed Ping From : $ipAddress.$i
        fi &);
    done

fi

Cannot set some HTTP headers when using System.Net.WebRequest

If you need the short and technical answer go right to the last section of the answer.

If you want to know better, read it all, and i hope you'll enjoy...


I countered this problem too today, and what i discovered today is that:

  1. the above answers are true, as:

    1.1 it's telling you that the header you are trying to add already exist and you should then modify its value using the appropriate property (the indexer, for instance), instead of trying to add it again.

    1.2 Anytime you're changing the headers of an HttpWebRequest, you need to use the appropriate properties on the object itself, if they exist.

Thanks FOR and Jvenema for the leading guidelines...

  1. But, What i found out, and that was the missing piece in the puzzle is that:

    2.1 The WebHeaderCollection class is generally accessed through WebRequest.Headers or WebResponse.Headers. Some common headers are considered restricted and are either exposed directly by the API (such as Content-Type) or protected by the system and cannot be changed.

The restricted headers are:

  • Accept
  • Connection
  • Content-Length
  • Content-Type
  • Date
  • Expect
  • Host
  • If-Modified-Since
  • Range
  • Referer
  • Transfer-Encoding
  • User-Agent
  • Proxy-Connection

So, next time you are facing this exception and don't know how to solve this, remember that there are some restricted headers, and the solution is to modify their values using the appropriate property explicitly from the WebRequest/HttpWebRequest class.


Edit: (useful, from comments, comment by user Kaido)

Solution is to check if the header exists already or is restricted (WebHeaderCollection.IsRestricted(key)) before calling add

Why is the gets function so dangerous that it should not be used?

Why is gets() dangerous

The first internet worm (the Morris Internet Worm) escaped about 30 years ago (1988-11-02), and it used gets() and a buffer overflow as one of its methods of propagating from system to system. The basic problem is that the function doesn't know how big the buffer is, so it continues reading until it finds a newline or encounters EOF, and may overflow the bounds of the buffer it was given.

You should forget you ever heard that gets() existed.

The C11 standard ISO/IEC 9899:2011 eliminated gets() as a standard function, which is A Good Thingβ„’ (it was formally marked as 'obsolescent' and 'deprecated' in ISO/IEC 9899:1999/Cor.3:2007 β€” Technical Corrigendum 3 for C99, and then removed in C11). Sadly, it will remain in libraries for many years (meaning 'decades') for reasons of backwards compatibility. If it were up to me, the implementation of gets() would become:

char *gets(char *buffer)
{
    assert(buffer != 0);
    abort();
    return 0;
}

Given that your code will crash anyway, sooner or later, it is better to head the trouble off sooner rather than later. I'd be prepared to add an error message:

fputs("obsolete and dangerous function gets() called\n", stderr);

Modern versions of the Linux compilation system generates warnings if you link gets() β€” and also for some other functions that also have security problems (mktemp(), …).

Alternatives to gets()

fgets()

As everyone else said, the canonical alternative to gets() is fgets() specifying stdin as the file stream.

char buffer[BUFSIZ];

while (fgets(buffer, sizeof(buffer), stdin) != 0)
{
    ...process line of data...
}

What no-one else yet mentioned is that gets() does not include the newline but fgets() does. So, you might need to use a wrapper around fgets() that deletes the newline:

char *fgets_wrapper(char *buffer, size_t buflen, FILE *fp)
{
    if (fgets(buffer, buflen, fp) != 0)
    {
        size_t len = strlen(buffer);
        if (len > 0 && buffer[len-1] == '\n')
            buffer[len-1] = '\0';
        return buffer;
    }
    return 0;
}

Or, better:

char *fgets_wrapper(char *buffer, size_t buflen, FILE *fp)
{
    if (fgets(buffer, buflen, fp) != 0)
    {
        buffer[strcspn(buffer, "\n")] = '\0';
        return buffer;
    }
    return 0;
}

Also, as caf points out in a comment and paxdiablo shows in his answer, with fgets() you might have data left over on a line. My wrapper code leaves that data to be read next time; you can readily modify it to gobble the rest of the line of data if you prefer:

        if (len > 0 && buffer[len-1] == '\n')
            buffer[len-1] = '\0';
        else
        {
             int ch;
             while ((ch = getc(fp)) != EOF && ch != '\n')
                 ;
        }

The residual problem is how to report the three different result states β€” EOF or error, line read and not truncated, and partial line read but data was truncated.

This problem doesn't arise with gets() because it doesn't know where your buffer ends and merrily tramples beyond the end, wreaking havoc on your beautifully tended memory layout, often messing up the return stack (a Stack Overflow) if the buffer is allocated on the stack, or trampling over the control information if the buffer is dynamically allocated, or copying data over other precious global (or module) variables if the buffer is statically allocated. None of these is a good idea β€” they epitomize the phrase 'undefined behaviour`.


There is also the TR 24731-1 (Technical Report from the C Standard Committee) which provides safer alternatives to a variety of functions, including gets():

Β§6.5.4.1 The gets_s function

Synopsis

#define __STDC_WANT_LIB_EXT1__ 1
#include <stdio.h>
char *gets_s(char *s, rsize_t n);

Runtime-constraints

s shall not be a null pointer. n shall neither be equal to zero nor be greater than RSIZE_MAX. A new-line character, end-of-file, or read error shall occur within reading n-1 characters from stdin.25)

3 If there is a runtime-constraint violation, s[0] is set to the null character, and characters are read and discarded from stdin until a new-line character is read, or end-of-file or a read error occurs.

Description

4 The gets_s function reads at most one less than the number of characters specified by n from the stream pointed to by stdin, into the array pointed to by s. No additional characters are read after a new-line character (which is discarded) or after end-of-file. The discarded new-line character does not count towards number of characters read. A null character is written immediately after the last character read into the array.

5 If end-of-file is encountered and no characters have been read into the array, or if a read error occurs during the operation, then s[0] is set to the null character, and the other elements of s take unspecified values.

Recommended practice

6 The fgets function allows properly-written programs to safely process input lines too long to store in the result array. In general this requires that callers of fgets pay attention to the presence or absence of a new-line character in the result array. Consider using fgets (along with any needed processing based on new-line characters) instead of gets_s.

25) The gets_s function, unlike gets, makes it a runtime-constraint violation for a line of input to overflow the buffer to store it. Unlike fgets, gets_s maintains a one-to-one relationship between input lines and successful calls to gets_s. Programs that use gets expect such a relationship.

The Microsoft Visual Studio compilers implement an approximation to the TR 24731-1 standard, but there are differences between the signatures implemented by Microsoft and those in the TR.

The C11 standard, ISO/IEC 9899-2011, includes TR24731 in Annex K as an optional part of the library. Unfortunately, it is seldom implemented on Unix-like systems.


getline() β€” POSIX

POSIX 2008 also provides a safe alternative to gets() called getline(). It allocates space for the line dynamically, so you end up needing to free it. It removes the limitation on line length, therefore. It also returns the length of the data that was read, or -1 (and not EOF!), which means that null bytes in the input can be handled reliably. There is also a 'choose your own single-character delimiter' variation called getdelim(); this can be useful if you are dealing with the output from find -print0 where the ends of the file names are marked with an ASCII NUL '\0' character, for example.

How do I remove all HTML tags from a string without knowing which tags are in it?

You can use a simple regex like this:

public static string StripHTML(string input)
{
   return Regex.Replace(input, "<.*?>", String.Empty);
}

Be aware that this solution has its own flaw. See Remove HTML tags in String for more information (especially the comments of @mehaase)

Another solution would be to use the HTML Agility Pack.
You can find an example using the library here: HTML agility pack - removing unwanted tags without removing content?

Android Closing Activity Programmatically

What about the Activity.finish() method (quoting) :

Call this when your activity is done and should be closed.

What are the benefits of learning Vim?

To learn vi(m) fast one must first understand the whole design. Vim has a great set of cursor-movement commands, check a few (X is a character, # a digit):

j k enter arrows 0 $ w W b B ctrolD crtolU ctrolE ctrolY H M L fX FX tX TX , ; % gg G n N mX 'X ''

and many more it would be boring to enumerate. Many of these support a count before the command, like 4j to move 4 lines up.

Now, back to the design, you type a command like d for delete followed by a cursor movement and the command applies to the piece of text from the cursor position till the movement end. For example H moves to the top of the screen, dH deletes to the top of the screen and cH changes (replaces) to the top of the screen.

This design is quite powerful. It also reduces, or organizes, what you need to learn. Definitively the first step is to learn a few cursor movement commands. Say,8 or 10 at first. Then you are almost done.

Action bar navigation modes are deprecated in Android L

FragmentTabHost is also an option.

This code is from Android developer's site:

/**
 * This demonstrates how you can implement switching between the tabs of a
 * TabHost through fragments, using FragmentTabHost.
 */
public class FragmentTabs extends FragmentActivity {
    private FragmentTabHost mTabHost;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.fragment_tabs);
    mTabHost = (FragmentTabHost)findViewById(android.R.id.tabhost);
    mTabHost.setup(this, getSupportFragmentManager(), R.id.realtabcontent);

    mTabHost.addTab(mTabHost.newTabSpec("simple").setIndicator("Simple"),
            FragmentStackSupport.CountingFragment.class, null);
    mTabHost.addTab(mTabHost.newTabSpec("contacts").setIndicator("Contacts"),
            LoaderCursorSupport.CursorLoaderListFragment.class, null);
    mTabHost.addTab(mTabHost.newTabSpec("custom").setIndicator("Custom"),
            LoaderCustomSupport.AppListFragment.class, null);
    mTabHost.addTab(mTabHost.newTabSpec("throttle").setIndicator("Throttle"),
            LoaderThrottleSupport.ThrottledLoaderListFragment.class, null);
    }
}

How to set True as default value for BooleanField on Django?

I found the cleanest way of doing it is this.

Tested on Django 3.1.5

class MyForm(forms.Form):
    my_boolean = forms.BooleanField(required=False, initial=True)

I found the answer here

How do you get the cursor position in a textarea?

Here's a cross browser function I have in my standard library:

function getCursorPos(input) {
    if ("selectionStart" in input && document.activeElement == input) {
        return {
            start: input.selectionStart,
            end: input.selectionEnd
        };
    }
    else if (input.createTextRange) {
        var sel = document.selection.createRange();
        if (sel.parentElement() === input) {
            var rng = input.createTextRange();
            rng.moveToBookmark(sel.getBookmark());
            for (var len = 0;
                     rng.compareEndPoints("EndToStart", rng) > 0;
                     rng.moveEnd("character", -1)) {
                len++;
            }
            rng.setEndPoint("StartToStart", input.createTextRange());
            for (var pos = { start: 0, end: len };
                     rng.compareEndPoints("EndToStart", rng) > 0;
                     rng.moveEnd("character", -1)) {
                pos.start++;
                pos.end++;
            }
            return pos;
        }
    }
    return -1;
}

Use it in your code like this:

var cursorPosition = getCursorPos($('#myTextarea')[0])

Here's its complementary function:

function setCursorPos(input, start, end) {
    if (arguments.length < 3) end = start;
    if ("selectionStart" in input) {
        setTimeout(function() {
            input.selectionStart = start;
            input.selectionEnd = end;
        }, 1);
    }
    else if (input.createTextRange) {
        var rng = input.createTextRange();
        rng.moveStart("character", start);
        rng.collapse();
        rng.moveEnd("character", end - start);
        rng.select();
    }
}

http://jsfiddle.net/gilly3/6SUN8/

How do I create a self-signed certificate for code signing on Windows?

Updated Answer

If you are using the following Windows versions or later: Windows Server 2012, Windows Server 2012 R2, or Windows 8.1 then MakeCert is now deprecated, and Microsoft recommends using the PowerShell Cmdlet New-SelfSignedCertificate.

If you're using an older version such as Windows 7, you'll need to stick with MakeCert or another solution. Some people suggest the Public Key Infrastructure Powershell (PSPKI) Module.

Original Answer

While you can create a self-signed code-signing certificate (SPC - Software Publisher Certificate) in one go, I prefer to do the following:

Creating a self-signed certificate authority (CA)

makecert -r -pe -n "CN=My CA" -ss CA -sr CurrentUser ^
         -a sha256 -cy authority -sky signature -sv MyCA.pvk MyCA.cer

(^ = allow batch command-line to wrap line)

This creates a self-signed (-r) certificate, with an exportable private key (-pe). It's named "My CA", and should be put in the CA store for the current user. We're using the SHA-256 algorithm. The key is meant for signing (-sky).

The private key should be stored in the MyCA.pvk file, and the certificate in the MyCA.cer file.

Importing the CA certificate

Because there's no point in having a CA certificate if you don't trust it, you'll need to import it into the Windows certificate store. You can use the Certificates MMC snapin, but from the command line:

certutil -user -addstore Root MyCA.cer

Creating a code-signing certificate (SPC)

makecert -pe -n "CN=My SPC" -a sha256 -cy end ^
         -sky signature ^
         -ic MyCA.cer -iv MyCA.pvk ^
         -sv MySPC.pvk MySPC.cer

It is pretty much the same as above, but we're providing an issuer key and certificate (the -ic and -iv switches).

We'll also want to convert the certificate and key into a PFX file:

pvk2pfx -pvk MySPC.pvk -spc MySPC.cer -pfx MySPC.pfx

If you want to protect the PFX file, add the -po switch, otherwise PVK2PFX creates a PFX file with no passphrase.

Using the certificate for signing code

signtool sign /v /f MySPC.pfx ^
              /t http://timestamp.url MyExecutable.exe

(See why timestamps may matter)

If you import the PFX file into the certificate store (you can use PVKIMPRT or the MMC snapin), you can sign code as follows:

signtool sign /v /n "Me" /s SPC ^
              /t http://timestamp.url MyExecutable.exe

Some possible timestamp URLs for signtool /t are:

  • http://timestamp.verisign.com/scripts/timstamp.dll
  • http://timestamp.globalsign.com/scripts/timstamp.dll
  • http://timestamp.comodoca.com/authenticode

Full Microsoft documentation

Downloads

For those who are not .NET developers, you will need a copy of the Windows SDK and .NET framework. A current link is available here: SDK & .NET (which installs makecert in C:\Program Files\Microsoft SDKs\Windows\v7.1). Your mileage may vary.

MakeCert is available from the Visual Studio Command Prompt. Visual Studio 2015 does have it, and it can be launched from the Start Menu in Windows 7 under "Developer Command Prompt for VS 2015" or "VS2015 x64 Native Tools Command Prompt" (probably all of them in the same folder).

Accessing a class' member variables in Python?

If you have an instance function (i.e. one that gets passed self) you can use self to get a reference to the class using self.__class__

For example in the code below tornado creates an instance to handle get requests, but we can get hold of the get_handler class and use it to hold a riak client so we do not need to create one for every request.

import tornado.web
import riak

class get_handler(tornado.web.requestHandler):
    riak_client = None

    def post(self):
        cls = self.__class__
        if cls.riak_client is None:
            cls.riak_client = riak.RiakClient(pb_port=8087, protocol='pbc')
        # Additional code to send response to the request ...
    

How to use a DataAdapter with stored procedure and parameter

SqlConnection con = new SqlConnection(@"Some Connection String");//connection object
SqlDataAdapter da = new SqlDataAdapter("ParaEmp_Select",con);//SqlDataAdapter class object
da.SelectCommand.CommandType = CommandType.StoredProcedure; //command sype
da.SelectCommand.Parameters.Add("@Contactid", SqlDbType.Int).Value = 123; //pass perametter
DataTable dt = new DataTable();  //dataset class object
da.Fill(dt); //call the stored producer

set height of imageview as matchparent programmatically

For Kotlin Users

val params = mImageView?.layoutParams as FrameLayout.LayoutParams
params.width = FrameLayout.LayoutParams.MATCH_PARENT
params.height = FrameLayout.LayoutParams.MATCH_PARENT
mImageView?.layoutParams = params

Here I used FrameLayout.LayoutParams since my views( ImageView) parent is FrameLayout

How do I Search/Find and Replace in a standard string?

// Replace all occurrences of searchStr in str with replacer
// Each match is replaced only once to prevent an infinite loop
// The algorithm iterates once over the input and only concatenates 
// to the output, so it should be reasonably efficient
std::string replace(const std::string& str, const std::string& searchStr, 
    const std::string& replacer)
{
    // Prevent an infinite loop if the input is empty
    if (searchStr == "") {
        return str;
    }

    std::string result = "";
    size_t pos = 0;
    size_t pos2 = str.find(searchStr, pos);

    while (pos2 != std::string::npos) {
        result += str.substr(pos, pos2-pos) + replacer;
        pos = pos2 + searchStr.length();
        pos2 = str.find(searchStr, pos);
    }

    result += str.substr(pos, str.length()-pos);
    return result;
}

Javascript - How to extract filename from a file input control

Neither of the highly upvoted answers actually provide "just the file name without extension" and the other solutions are way too much code for such a simple job.

I think this should be a one-liner to any JavaScript programmer. It's a very simple regular expression:

function basename(prevname) {
    return prevname.replace(/^(.*[/\\])?/, '').replace(/(\.[^.]*)$/, '');
}

First, strip anything up to the last slash, if present.

Then, strip anything after the last period, if present.

It's simple, it's robust, it implements exactly what's asked for. Am I missing something?

How do you select the entire excel sheet with Range using VBA?

I believe you want to find the current region of A1 and surrounding cells - not necessarily all cells on the sheet. If so - simply use... Range("A1").CurrentRegion

Apache giving 403 forbidden errors

Check that :

  • Apache can physically access the file (the user that run apache, probably www-data or apache, can access the file in the filesystem)
  • Apache can list the content of the folder (read permission)
  • Apache has a "Allow" directive for that folder. There should be one for /var/www/, you can check default vhost for example.

Additionally, you can look at the error.log file (usually located at /var/log/apache2/error.log) which will describe why you get the 403 error exactly.

Finally, you may want to restart apache, just to be sure all that configuration is applied. This can be generally done with /etc/init.d/apache2 restart. On some system, the script will be called httpd. Just figure out.

composer laravel create project

make sure that your composer is up to date. write in the cmd

composer create-project –-prefer-dist laravel/laravel NameOfProject "Version" 

How can I populate a select dropdown list from a JSON feed with AngularJS?

In my Angular Bootstrap dropdowns I initialize the JSON Array (vm.zoneDropdown) with ng-init (you can also have ng-init inside the directive template) and I pass the Array in a custom src attribute

<custom-dropdown control-id="zone" label="Zona" model="vm.form.zone" src="vm.zoneDropdown"
                         ng-init="vm.getZoneDropdownSrc()" is-required="true" form="farmaciaForm" css-class="custom-dropdown col-md-3"></custom-dropdown>

Inside the controller:

vm.zoneDropdown = [];
vm.getZoneDropdownSrc = function () {
    vm.zoneDropdown = $customService.getZone();
}

And inside the customDropdown directive template(note that this is only one part of the bootstrap dropdown):

<ul class="uib-dropdown-menu" role="menu" aria-labelledby="btn-append-to-body">
    <li role="menuitem" ng-repeat="dropdownItem in vm.src" ng-click="vm.setValue(dropdownItem)">
        <a ng-click="vm.preventDefault($event)" href="##">{{dropdownItem.text}}</a>
    </li>
</ul>

How do I see what character set a MySQL database / table / column is?

For databases:

USE your_database_name;
show variables like "character_set_database";
-- or:
-- show variables like "collation_database";

Cf. this page. And check out the MySQL manual

How do I remove whitespace from the end of a string in Python?

You can use strip() or split() to control the spaces values as in the following:

words = "   first  second   "

# Remove end spaces
def remove_end_spaces(string):
    return "".join(string.rstrip())


# Remove the first and end spaces
def remove_first_end_spaces(string):
    return "".join(string.rstrip().lstrip())


# Remove all spaces
def remove_all_spaces(string):
    return "".join(string.split())


# Show results
print(words)
print(remove_end_spaces(words))
print(remove_first_end_spaces(words))
print(remove_all_spaces(words))

How do I remove the top margin in a web page?

For opera just add this in header

<link rel='stylesheet' media='handheld' href='body.css' />

This makes opera use most of your customised css.

Cannot attach the file *.mdf as database

You already have an old copy of that database installed in Server Explorer. So its a simple naming collision in the Server Object Explorer / SQL server. You likely created the same database Catalog Name already before you decided to move it to the Apps_Data folder. So that Database name already exists and just needs to be deleted.

Just go into Visual Studio > View > SQL Server Object Explorer and delete the old database name and its connection. Retry your app again and it should install the .mdf file in App_Data and create the same exact database again in the Server Explorer.

regular expression to match exactly 5 digits

This should work:

<script type="text/javascript">
var testing='this is d23553 test 32533\n31203 not 333';
var r = new RegExp(/(?:^|[^\d])(\d{5})(?:$|[^\d])/mg);
var matches = [];
while ((match = r.exec(testing))) matches.push(match[1]);
alert('Found: '+matches.join(', '));
</script>

'float' vs. 'double' precision

It's usually based on significant figures of both the exponent and significand in base 2, not base 10. From what I can tell in the C99 standard, however, there is no specified precision for floats and doubles (other than the fact that 1 and 1 + 1E-5 / 1 + 1E-7 are distinguishable [float and double repsectively]). However, the number of significant figures is left to the implementer (as well as which base they use internally, so in other words, an implementation could decide to make it based on 18 digits of precision in base 3). [1]

If you need to know these values, the constants FLT_RADIX and FLT_MANT_DIG (and DBL_MANT_DIG / LDBL_MANT_DIG) are defined in float.h.

The reason it's called a double is because the number of bytes used to store it is double the number of a float (but this includes both the exponent and significand). The IEEE 754 standard (used by most compilers) allocate relatively more bits for the significand than the exponent (23 to 9 for float vs. 52 to 12 for double), which is why the precision is more than doubled.

1: Section 5.2.4.2.2 ( http://www.open-std.org/jtc1/sc22/wg14/www/docs/n1256.pdf )

What is the maximum possible length of a .NET string?

The max length of a string on my machine is 1,073,741,791.

You see, Strings aren't limited by integer as is commonly believed.

Memory restrictions aside, Strings cannot have more than 230 (1,073,741,824) characters, since a 2GB limit is imposed by the Microsoft CLR (Common Language Runtime). 33 more than my computer allowed.

Now, here's something you're welcome to try yourself.

Create a new C# console app in Visual Studio and then copy/paste the main method here:

static void Main(string[] args)
{
    Console.WriteLine("String test, by Nicholas John Joseph Taylor");

    Console.WriteLine("\nTheoretically, C# should support a string of int.MaxValue, but we run out of memory before then.");

    Console.WriteLine("\nThis is a quickish test to narrow down results to find the max supported length of a string.");

    Console.WriteLine("\nThe test starts ...now:\n");

    int Length = 0;

    string s = "";

    int Increment = 1000000000; // We know that s string with the length of 1000000000 causes an out of memory exception.

    LoopPoint:

    // Make a string appendage the length of the value of Increment

    StringBuilder StringAppendage = new StringBuilder();

    for (int CharacterPosition = 0; CharacterPosition < Increment; CharacterPosition++)
    {
        StringAppendage.Append("0");

    }

    // Repeatedly append string appendage until an out of memory exception is thrown.

    try
    {
        if (Increment > 0)
            while (Length < int.MaxValue)
            {
                Length += Increment;

                s += StringAppendage.ToString(); // Append string appendage the length of the value of Increment

                Console.WriteLine("s.Length = " + s.Length + " at " + DateTime.Now.ToString("dd/MM/yyyy HH:mm"));

            }

    }
    catch (OutOfMemoryException ex) // Note: Any other exception will crash the program.
    {
        Console.WriteLine("\n" + ex.Message + " at " + DateTime.Now.ToString("dd/MM/yyyy HH:mm") + ".");

        Length -= Increment;

        Increment /= 10;

        Console.WriteLine("After decimation, the value of Increment is " + Increment + ".");

    }
    catch (Exception ex2)
    {
        Console.WriteLine("\n" + ex2.Message + " at " + DateTime.Now.ToString("dd/MM/yyyy HH:mm") + ".");

        Console.WriteLine("Press a key to continue...");

        Console.ReadKey();

    }

    if (Increment > 0)
    {
        goto LoopPoint;

    }

    Console.WriteLine("Test complete.");

    Console.WriteLine("\nThe max length of a string is " + s.Length + ".");

    Console.WriteLine("\nPress any key to continue.");

    Console.ReadKey();

}

My results were as follows:

String test, by Nicholas John Joseph Taylor

Theoretically, C# should support a string of int.MaxValue, but we run out of memory before then.

This is a quickish test to narrow down results to find the max supported length of a string.

The test starts ...now:

s.Length = 1000000000 at 08/05/2019 12:06

Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:06. After decimation, the value of Increment is 100000000.

Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:06. After decimation, the value of Increment is 10000000. s.Length = 1010000000 at 08/05/2019 12:06 s.Length = 1020000000 at 08/05/2019 12:06 s.Length = 1030000000 at 08/05/2019 12:06 s.Length = 1040000000 at 08/05/2019 12:06 s.Length = 1050000000 at 08/05/2019 12:06 s.Length = 1060000000 at 08/05/2019 12:06 s.Length = 1070000000 at 08/05/2019 12:06

Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:06. After decimation, the value of Increment is 1000000. s.Length = 1071000000 at 08/05/2019 12:06 s.Length = 1072000000 at 08/05/2019 12:06 s.Length = 1073000000 at 08/05/2019 12:06

Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:06. After decimation, the value of Increment is 100000. s.Length = 1073100000 at 08/05/2019 12:06 s.Length = 1073200000 at 08/05/2019 12:06 s.Length = 1073300000 at 08/05/2019 12:06 s.Length = 1073400000 at 08/05/2019 12:06 s.Length = 1073500000 at 08/05/2019 12:06 s.Length = 1073600000 at 08/05/2019 12:06 s.Length = 1073700000 at 08/05/2019 12:06

Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:06. After decimation, the value of Increment is 10000. s.Length = 1073710000 at 08/05/2019 12:06 s.Length = 1073720000 at 08/05/2019 12:06 s.Length = 1073730000 at 08/05/2019 12:06 s.Length = 1073740000 at 08/05/2019 12:06

Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:06. After decimation, the value of Increment is 1000. s.Length = 1073741000 at 08/05/2019 12:06

Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:06. After decimation, the value of Increment is 100. s.Length = 1073741100 at 08/05/2019 12:06 s.Length = 1073741200 at 08/05/2019 12:06 s.Length = 1073741300 at 08/05/2019 12:07 s.Length = 1073741400 at 08/05/2019 12:07 s.Length = 1073741500 at 08/05/2019 12:07 s.Length = 1073741600 at 08/05/2019 12:07 s.Length = 1073741700 at 08/05/2019 12:07

Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:07. After decimation, the value of Increment is 10. s.Length = 1073741710 at 08/05/2019 12:07 s.Length = 1073741720 at 08/05/2019 12:07 s.Length = 1073741730 at 08/05/2019 12:07 s.Length = 1073741740 at 08/05/2019 12:07 s.Length = 1073741750 at 08/05/2019 12:07 s.Length = 1073741760 at 08/05/2019 12:07 s.Length = 1073741770 at 08/05/2019 12:07 s.Length = 1073741780 at 08/05/2019 12:07 s.Length = 1073741790 at 08/05/2019 12:07

Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:07. After decimation, the value of Increment is 1. s.Length = 1073741791 at 08/05/2019 12:07

Exception of type 'System.OutOfMemoryException' was thrown. at 08/05/2019 12:07. After decimation, the value of Increment is 0. Test complete.

The max length of a string is 1073741791.

Press any key to continue.

The max length of a string on my machine is 1073741791.

I'd appreciate it very much if people could post their results as a comment below.

It will be interesting to learn if people get the same or different results.

error C2065: 'cout' : undeclared identifier

If the only file you include is iostream and it still says undefined, then maybe iostream doesn't contain what it's supposed to. Is it possible that you have an empty file coincidentally named "iostream" in your project?

DIV height set as percentage of screen?

This is the solution ,

Add the html also to 100%

html,body {

   height: 100%;
   width: 100%;

}

Printing an array in C++?

Besides the for-loop based solutions, you can also use an ostream_iterator<>. Here's an example that leverages the sample code in the (now retired) SGI STL reference:

#include <iostream>
#include <iterator>
#include <algorithm>

int main()
{
  short foo[] = { 1, 3, 5, 7 };

  using namespace std;
  copy(foo,
       foo + sizeof(foo) / sizeof(foo[0]),
       ostream_iterator<short>(cout, "\n"));
}

This generates the following:

 ./a.out 
1
3
5
7

However, this may be overkill for your needs. A straight for-loop is probably all that you need, although litb's template sugar is quite nice, too.

Edit: Forgot the "printing in reverse" requirement. Here's one way to do it:

#include <iostream>
#include <iterator>
#include <algorithm>

int main()
{
  short foo[] = { 1, 3, 5, 7 };

  using namespace std;

  reverse_iterator<short *> begin(foo + sizeof(foo) / sizeof(foo[0]));
  reverse_iterator<short *> end(foo);

  copy(begin,
       end,
       ostream_iterator<short>(cout, "\n"));
}

and the output:

$ ./a.out 
7
5
3
1

Edit: C++14 update that simplifies the above code snippets using array iterator functions like std::begin() and std::rbegin():

#include <iostream>
#include <iterator>
#include <algorithm>

int main()
{
    short foo[] = { 1, 3, 5, 7 };

    // Generate array iterators using C++14 std::{r}begin()
    // and std::{r}end().

    // Forward
    std::copy(std::begin(foo),
              std::end(foo),
              std::ostream_iterator<short>(std::cout, "\n"));

    // Reverse
    std::copy(std::rbegin(foo),
              std::rend(foo),
              std::ostream_iterator<short>(std::cout, "\n"));
}

How to calculate cumulative normal distribution?

Taken from above:

from scipy.stats import norm
>>> norm.cdf(1.96)
0.9750021048517795
>>> norm.cdf(-1.96)
0.024997895148220435

For a two-tailed test:

Import numpy as np
z = 1.96
p_value = 2 * norm.cdf(-np.abs(z))
0.04999579029644087

Specify the from user when sending email using the mail command

None of the above worked for me. And it took me long to figure it out, hopefully this helps the next guy.

I'm using Ubuntu 12.04 LTS with mailutils v2.1.

I found this solutions somewhere on the net, don't know where, can't find it again:

-aFrom:[email protected]

Full Command used:

cat /root/Reports/ServerName-Report-$DATE.txt | mail -s "Server-Name-Report-$DATE" [email protected] -aFrom:[email protected]

Hiding a sheet in Excel 2007 (with a password) OR hide VBA code in Excel

No.

If the user is sophisticated or determined enough to:

  1. Open the Excel VBA editor
  2. Use the object browser to see the list of all sheets, including VERYHIDDEN ones
  3. Change the property of the sheet to VISIBLE or just HIDDEN

then they are probably sophisticated or determined enough to:

  1. Search the internet for "remove Excel 2007 project password"
  2. Apply the instructions they find.

So what's on this hidden sheet? Proprietary information like price formulas, or client names, or employee salaries? Putting that info in even an hidden tab probably isn't the greatest idea to begin with.

Is it possible to modify a string of char in C?

No, you cannot modify it, as the string can be stored in read-only memory. If you want to modify it, you can use an array instead e.g.

char a[] = "This is a string";

Or alternately, you could allocate memory using malloc e.g.

char *a = malloc(100);
strcpy(a, "This is a string");
free(a); // deallocate memory once you've done

Regular expression to match balanced parentheses

It is actually possible to do it using .NET regular expressions, but it is not trivial, so read carefully.

You can read a nice article here. You also may need to read up on .NET regular expressions. You can start reading here.

Angle brackets <> were used because they do not require escaping.

The regular expression looks like this:

<
[^<>]*
(
    (
        (?<Open><)
        [^<>]*
    )+
    (
        (?<Close-Open>>)
        [^<>]*
    )+
)*
(?(Open)(?!))
>

Android Studio - How to increase Allocated Heap Size

I looked at my Environment Variables and had a System Variable called _JAVA_OPTIONS with the value -Xms256m -Xmx512m, after changing this to -Xms256m -Xmx1024m the max heap size increased accordingly.

Different ways of adding to Dictionary

To insert the Value into the Dictionary

 Dictionary<string, string> dDS1 = new Dictionary<string, string>();//Declaration
 dDS1.Add("VEqpt", "aaaa");//adding key and value into the dictionary
 string Count = dDS1["VEqpt"];//assigning the value of dictionary key to Count variable
 dDS1["VEqpt"] = Count + "bbbb";//assigning the value to key

printing all contents of array in C#

this is the easiest way that you could print the String by using array!!!

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace arraypracticeforstring
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] arr = new string[3] { "Snehal", "Janki", "Thakkar" };

            foreach (string item in arr)
            {
                Console.WriteLine(item.ToString());
            }
            Console.ReadLine();
        }
    }
}

Change background colour for Visual Studio

The background color of the Visual Studio text editor in a Theme Editor is accessed by:

Text Editor ? Plain Text ? Background

enter image description here

how to check if item is selected from a comboBox in C#

You can try

if(combo1.Text == "")
{

}

Looping through GridView rows and Checking Checkbox Control

Loop like

foreach (GridViewRow row in grid.Rows)
{
   if (((CheckBox)row.FindControl("chkboxid")).Checked)
   {
    //read the label            
   }            
}

Plotting in a non-blocking way with Matplotlib

I figured out that the plt.pause(0.001) command is the only thing needed and nothing else.

plt.show() and plt.draw() are unnecessary and / or blocking in one way or the other. So here is a code that draws and updates a figure and keeps going. Essentially plt.pause(0.001) seems to be the closest equivalent to matlab's drawnow.

Unfortunately those plots will not be interactive (they freeze), except you insert an input() command, but then the code will stop.

The documentation of the plt.pause(interval) command states:

If there is an active figure, it will be updated and displayed before the pause...... This can be used for crude animation.

and this is pretty much exactly what we want. Try this code:

import numpy as np
from matplotlib import pyplot as plt

x = np.arange(0, 51)               # x coordinates  
         
for z in range(10, 50):

    y = np.power(x, z/10)          # y coordinates of plot for animation

    plt.cla()                      # delete previous plot
    plt.axis([-50, 50, 0, 10000])  # set axis limits, to avoid rescaling
    plt.plot(x, y)                 # generate new plot
    plt.pause(0.1)                 # pause 0.1 sec, to force a plot redraw

Adding an identity to an existing column

You cannot alter a column to be an IDENTITY column. What you'll need to do is create a new column which is defined as an IDENTITY from the get-go, then drop the old column, and rename the new one to the old name.

ALTER TABLE (yourTable) ADD NewColumn INT IDENTITY(1,1)

ALTER TABLE (yourTable) DROP COLUMN OldColumnName

EXEC sp_rename 'yourTable.NewColumn', 'OldColumnName', 'COLUMN'

Marc

How to get parameter on Angular2 route in Angular way?

As of Angular 6+, this is handled slightly differently than in previous versions. As @BeetleJuice mentions in the answer above, paramMap is new interface for getting route params, but the execution is a bit different in more recent versions of Angular. Assuming this is in a component:

private _entityId: number;

constructor(private _route: ActivatedRoute) {
    // ...
}

ngOnInit() {
    // For a static snapshot of the route...
    this._entityId = this._route.snapshot.paramMap.get('id');

    // For subscribing to the observable paramMap...
    this._route.paramMap.pipe(
        switchMap((params: ParamMap) => this._entityId = params.get('id'))
    );

    // Or as an alternative, with slightly different execution...
    this._route.paramMap.subscribe((params: ParamMap) =>  {
        this._entityId = params.get('id');
    });
}

I prefer to use both because then on direct page load I can get the ID param, and also if navigating between related entities the subscription will update properly.

Source in Angular Docs

Java equivalent to JavaScript's encodeURIComponent that produces identical output?

for me this worked:

import org.apache.http.client.utils.URIBuilder;

String encodedString = new URIBuilder()
  .setParameter("i", stringToEncode)
  .build()
  .getRawQuery() // output: i=encodedString
  .substring(2);

or with a different UriBuilder

import javax.ws.rs.core.UriBuilder;

String encodedString = UriBuilder.fromPath("")
  .queryParam("i", stringToEncode)
  .toString()   // output: ?i=encodedString
  .substring(3);

In my opinion using a standard library is a better idea rather than post processing manually. Also @Chris answer looked good, but it doesn't work for urls, like "http://a+b c.html"

How to use Session attributes in Spring-mvc

SessionAttribute annotation is the simplest and straight forward instead of getting session from request object and setting attribute. Any object can be added to the model in controller and it will stored in session if its name matches with the argument in @SessionAttributes annotation. In below eg, personObj will be available in session.

@Controller
@SessionAttributes("personObj")
public class PersonController {

    @RequestMapping(value="/person-form")
    public ModelAndView personPage() {
        return new ModelAndView("person-page", "person-entity", new Person());
    }

    @RequestMapping(value="/process-person")
    public ModelAndView processPerson(@ModelAttribute Person person) {
        ModelAndView modelAndView = new ModelAndView();
        modelAndView.setViewName("person-result-page");

        modelAndView.addObject("pers", person);
        modelAndView.addObject("personObj", person);

        return modelAndView;
    }

}

Postgresql tables exists, but getting "relation does not exist" when querying

In my case, the dump file I restored had these commands.

CREATE SCHEMA employees;
SET search_path = employees, pg_catalog;

I've commented those and restored again. The issue got resolved

Hibernate: How to set NULL query-parameter value with HQL?

I did not try this, but what happens when you use :status twice to check for NULL?

Query query = getSession().createQuery(
     "from CountryDTO c where ( c.status = :status OR ( c.status IS NULL AND :status IS NULL ) ) and c.type =:type"
)
.setParameter("status", status, Hibernate.STRING)
.setParameter("type", type, Hibernate.STRING);

How to execute an Oracle stored procedure via a database link

check http://www.tech-archive.net/Archive/VB/microsoft.public.vb.database.ado/2005-08/msg00056.html

one needs to use something like

cmd.CommandText = "BEGIN foo@v; END;" 

worked for me in vb.net, c#

isPrime Function for Python Language

Srsly guys... Why so many lines of code for a simple method like this? Here's my solution:

def isPrime(a):
    div = a - 1
    res = True
    while(div > 1):
        if a % div == 0:
            res = False
        div = div - 1
    return res

Setting the classpath in java using Eclipse IDE

Try this:

Project -> Properties -> Java Build Path -> Add Class Folder.

If it doesnt work, please be specific in what way your compilation fails, specifically post the error messages Eclipse returns, and i will know what to do about it.

How to convert timestamps to dates in Bash?

On later versions of common Linux distributions you can use:

date -d @1267619929

Why can I not switch branches?

I got this message when updating new files from remote and index got out of whack. Tried to fix the index, but resolving via Xcode 4.5, GitHub.app (103), and GitX.app (0.7.1) failed. So, I did this:

git commit -a -m "your commit message here"

which worked in bypassing the git index.

Two blog posts that helped me understand about Git and Xcode are:

  • Ray Wenderlich on Xcode 4.5 and
  • Oliver Steele from 2008

  • How to expand and compute log(a + b)?

    In general, one doesn't expand out log(a + b); you just deal with it as is. That said, there are occasionally circumstances where it makes sense to use the following identity:

    log(a + b) = log(a * (1 + b/a)) = log a + log(1 + b/a)
    

    (In fact, this identity is often used when implementing log in math libraries).

    Extract the first (or last) n characters of a string

    Make it simple and use R basic functions:

    # To get the LEFT part:
    > substr(a, 1, 4)
    [1] "left"
    > 
    # To get the MIDDLE part:
    > substr(a, 3, 7)
    [1] "ftrig"
    > 
    # To get the RIGHT part:
    > substr(a, 5, 10)
    [1] "right"
    

    The substr() function tells you where start and stop substr(x, start, stop)

    git diff between cloned and original remote repository

    This example might help someone:

    Note "origin" is my alias for remote "What is on Github"
    Note "mybranch" is my alias for my branch "what is local" that I'm syncing with github
    --your branch name is 'master' if you didn't create one. However, I'm using the different name mybranch to show where the branch name parameter is used.


    What exactly are my remote repos on github?

    $ git remote -v
    origin  https://github.com/flipmcf/Playground.git (fetch)
    origin  https://github.com/flipmcf/Playground.git (push)
    

    Add the "other github repository of the same code" - we call this a fork:

    $ git remote add someOtherRepo https://github.com/otherUser/Playground.git
    
    $git remote -v
    origin  https://github.com/flipmcf/Playground.git (fetch)
    origin  https://github.com/flipmcf/Playground.git (push)
    someOtherRepo https://github.com/otherUser/Playground.git (push)
    someOtherRepo https://github.com/otherUser/Playground.git (fetch)
    

    make sure our local repo is up to date:

    $ git fetch
    

    Change some stuff locally. let's say file ./foo/bar.py

    $ git status
    # On branch mybranch
    # Changes to be committed:
    #   (use "git reset HEAD <file>..." to unstage)
    #
    #   modified:   foo/bar.py
    

    Review my uncommitted changes

    $ git diff mybranch
    diff --git a/playground/foo/bar.py b/playground/foo/bar.py
    index b4fb1be..516323b 100655
    --- a/playground/foo/bar.py
    +++ b/playground/foo/bar.py
    @@ -1,27 +1,29 @@
    - This line is wrong
    + This line is fixed now - yea!
    + And I added this line too.
    

    Commit locally.

    $ git commit foo/bar.py -m"I changed stuff"
    [myfork 9f31ff7] I changed stuff
    1 files changed, 2 insertions(+), 1 deletions(-)
    

    Now, I'm different than my remote (on github)

    $ git status
    # On branch mybranch
    # Your branch is ahead of 'origin/mybranch' by 1 commit.
    #
    nothing to commit (working directory clean)
    

    Diff this with remote - your fork: (this is frequently done with git diff master origin)

    $ git diff mybranch origin
    diff --git a/playground/foo/bar.py b/playground/foo/bar.py
    index 516323b..b4fb1be 100655
    --- a/playground/foo/bar.py
    +++ b/playground/foo/bar.py
    @@ -1,27 +1,29 @@
    - This line is wrong
    + This line is fixed now - yea!
    + And I added this line too.
    

    (git push to apply these to remote)

    How does my remote branch differ from the remote master branch?

    $ git diff origin/mybranch origin/master
    

    How does my local stuff differ from the remote master branch?

    $ git diff origin/master
    

    How does my stuff differ from someone else's fork, master branch of the same repo?

    $git diff mybranch someOtherRepo/master
    

    AWS Lambda import module error in python

    Error was due to file name of the lambda function. While creating the lambda function it will ask for Lambda function handler. You have to name it as your Python_File_Name.Method_Name. In this scenario I named it as lambda.lambda_handler (lambda.py is the file name).

    Please find below the snapshot. enter image description here

    How can I run another application within a panel of my C# program?

    I know this is possible if the other application can attach itself to a win32 window handle. For example, we have a separate C# application that hosts a DirectX application inside one of its windows. I'm not familiar with the exact details of how this is implemented, but I think just passing the win32 Handle of your panel to the other application is enough for that application to attach its DirectX surface.

    MySQL: selecting rows where a column is null

    SELECT pid FROM planets WHERE userid is null;
    

    How to validate date with format "mm/dd/yyyy" in JavaScript?

    I think Niklas has the right answer to your problem. Besides that, I think the following date validation function is a little bit easier to read:

    // Validates that the input string is a valid date formatted as "mm/dd/yyyy"
    function isValidDate(dateString)
    {
        // First check for the pattern
        if(!/^\d{1,2}\/\d{1,2}\/\d{4}$/.test(dateString))
            return false;
    
        // Parse the date parts to integers
        var parts = dateString.split("/");
        var day = parseInt(parts[1], 10);
        var month = parseInt(parts[0], 10);
        var year = parseInt(parts[2], 10);
    
        // Check the ranges of month and year
        if(year < 1000 || year > 3000 || month == 0 || month > 12)
            return false;
    
        var monthLength = [ 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 ];
    
        // Adjust for leap years
        if(year % 400 == 0 || (year % 100 != 0 && year % 4 == 0))
            monthLength[1] = 29;
    
        // Check the range of the day
        return day > 0 && day <= monthLength[month - 1];
    };
    

    What does getActivity() mean?

    I to had a similar doubt what I got to know was getActivity() returns the Activity to which the fragment is associated.

    The getActivity() method is used generally in static fragment as the associated activity will not be static and non static member cannot be used in static member.

    I used <code>getActivity()</code> here to get non-static activity to which the the placeholder fragment is associated.

    How to iterate through range of Dates in Java?

    This will help you start 30 days back and loop through until today's date. you can easily change range of dates and direction.

    private void iterateThroughDates() throws Exception {
        Calendar start = Calendar.getInstance();
        start.add(Calendar.DATE, -30);
        Calendar end = Calendar.getInstance();
        for (Calendar date = start; date.before(end); date.add(Calendar.DATE, 1))
            {
            System.out.println(date.getTime());
            }
    }
    

    Tomcat request timeout

    Add tomcat in Eclipse

    In Eclipse, as tomcat server, double click "Tomcat v7.0 Server at Localhost", Change the properties as shown in time out settings 45 to whatever sec you like

    Java: Local variable mi defined in an enclosing scope must be final or effectively final

    Yes this is happening because you are accessing mi variable from within your anonymous inner class, what happens deep inside is that another copy of your variable is created and will be use inside the anonymous inner class, so for data consistency the compiler will try restrict you from changing the value of mi so that's why its telling you to set it to final.

    log4j: Log output of a specific class to a specific appender

    Here's an answer regarding the XML configuration, note that if you don't give the file appender a ConversionPattern it will create 0 byte file and not write anything:

    <?xml version="1.0" encoding="UTF-8" ?>
    <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
    
    <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
        <appender name="console" class="org.apache.log4j.ConsoleAppender">
            <param name="Target" value="System.out"/>
            <layout class="org.apache.log4j.PatternLayout">
                <param name="ConversionPattern" value="%-5p %c{1} - %m%n"/>
            </layout>
        </appender>
    
        <appender name="bdfile" class="org.apache.log4j.RollingFileAppender">
            <param name="append" value="false"/>
            <param name="maxFileSize" value="1GB"/>
            <param name="maxBackupIndex" value="2"/>
            <param name="file" value="/tmp/bd.log"/>
            <layout class="org.apache.log4j.PatternLayout">
                <param name="ConversionPattern" value="%-5p %c{1} - %m%n"/>
            </layout>
        </appender>
    
        <logger name="com.example.mypackage" additivity="false">
            <level value="debug"/>
            <appender-ref ref="bdfile"/>
        </logger>
    
        <root>
            <priority value="info"/>
            <appender-ref ref="bdfile"/>
            <appender-ref ref="console"/>
        </root>
    
    </log4j:configuration>
    

    How do I access ViewBag from JS

    You can achieve the solution, by doing this:

    JavaScript:

    var myValue = document.getElementById("@(ViewBag.CC)").value;
    

    or if you want to use jQuery, then:

    jQuery

    var myValue = $('#' + '@(ViewBag.CC)').val();
    

    Is null check needed before calling instanceof?

    No, a null check is not needed before using instanceof.

    The expression x instanceof SomeClass is false if x is null.

    From the Java Language Specification, section 15.20.2, "Type comparison operator instanceof":

    "At run time, the result of the instanceof operator is true if the value of the RelationalExpression is not null and the reference could be cast to the ReferenceType without raising a ClassCastException. Otherwise the result is false."

    So if the operand is null, the result is false.

    Convert a string to datetime in PowerShell

    You need to specify the format it already has, in order to parse it:

    $InvoiceDate = [datetime]::ParseExact($invoice, "dd-MMM-yy", $null)
    

    Now you can output it in the format you need:

    $InvoiceDate.ToString('yyyy-MM-dd')
    

    or

    '{0:yyyy-MM-dd}' -f $InvoiceDate
    

    Is there an operator to calculate percentage in Python?

    Very quickly and sortly-code implementation by using the lambda operator.

    In [17]: percent = lambda part, whole:float(whole) / 100 * float(part)
    In [18]: percent(5,400)
    Out[18]: 20.0
    In [19]: percent(5,435)
    Out[19]: 21.75
    

    Printing tuple with string formatting in Python

    You can try this one as well;

    tup = (1,2,3)
    print("this is a tuple {something}".format(something=tup))
    

    You can't use %something with (tup) just because of packing and unpacking concept with tuple.

    "pip install json" fails on Ubuntu

    While it's true that json is a built-in module, I also found that on an Ubuntu system with python-minimal installed, you DO have python but you can't do import json. And then I understand that you would try to install the module using pip!

    If you have python-minimal you'll get a version of python with less modules than when you'd typically compile python yourself, and one of the modules you'll be missing is the json module. The solution is to install an additional package, called libpython2.7-stdlib, to install all 'default' python libraries.

    sudo apt install libpython2.7-stdlib
    

    And then you can do import json in python and it would work!