Programs & Examples On #Hexdump

A hex dump is a hexadecimal view of data. Looking at a hex dump of data is commonly done as a part of debugging, or of reverse engineering. In a hex dump, each byte (8-bits) is represented as a two-digit hexadecimal number.

Transform hexadecimal information to binary using a Linux command

As @user786653 suggested, use the xxd(1) program:

xxd -r -p input.txt output.bin

Tracing XML request/responses with JAX-WS

The answers listed here which guide you to use SOAPHandler are fully correct. The benefit of that approach is that it will work with any JAX-WS implementation, as SOAPHandler is part of the JAX-WS specification. However, the problem with SOAPHandler is that it implicitly attempts to represent the whole XML message in memory. This can lead to huge memory usage. Various implementations of JAX-WS have added their own workarounds for this. If you work with large requests or large responses, then you need to look into one of the proprietary approaches.

Since you ask about "the one included in JDK 1.5 or better" I'll answer with respect to what is formally known as JAX-WS RI (aka Metro) which is what is included with the JDK.

JAX-WS RI has a specific solution for this which is very efficient in terms of memory usage.

See https://javaee.github.io/metro/doc/user-guide/ch02.html#efficient-handlers-in-jax-ws-ri. Unfortunately that link is now broken but you can find it on WayBack Machine. I'll give the highlights below:

The Metro folks back in 2007 introduced an additional handler type, MessageHandler<MessageHandlerContext>, which is proprietary to Metro. It is far more efficient than SOAPHandler<SOAPMessageContext> as it doesn't try to do in-memory DOM representation.

Here's the crucial text from the original blog article:

MessageHandler:

Utilizing the extensible Handler framework provided by JAX-WS Specification and the better Message abstraction in RI, we introduced a new handler called MessageHandler to extend your Web Service applications. MessageHandler is similar to SOAPHandler, except that implementations of it gets access to MessageHandlerContext (an extension of MessageContext). Through MessageHandlerContext one can access the Message and process it using the Message API. As I put in the title of the blog, this handler lets you work on Message, which provides efficient ways to access/process the message not just a DOM based message. The programming model of the handlers is same and the Message handlers can be mixed with standard Logical and SOAP handlers. I have added a sample in JAX-WS RI 2.1.3 showing the use of MessageHandler to log messages and here is a snippet from the sample:

public class LoggingHandler implements MessageHandler<MessageHandlerContext> {
    public boolean handleMessage(MessageHandlerContext mhc) {
        Message m = mhc.getMessage().copy();
        XMLStreamWriter writer = XMLStreamWriterFactory.create(System.out);
        try {
            m.writeTo(writer);
        } catch (XMLStreamException e) {
            e.printStackTrace();
            return false;
        }
        return true;
    }

    public boolean handleFault(MessageHandlerContext mhc) {
        ..... 
        return true;
    }

    public void close(MessageContext messageContext) {    }

    public Set getHeaders() {
        return null;
    }
}

(end quote from 2007 blog post)

Needless to say your custom Handler, LoggingHandler in the example, needs to be added to your Handler Chain to have any effect. This is the same as adding any other Handler, so you can look in the other answers on this page for how to do that.

You can find a full example in the Metro GitHub repo.

Pass a PHP variable value through an HTML form

EDIT: After your comments, I understand that you want to pass variable through your form.

You can do this using hidden field:

<input type='hidden' name='var' value='<?php echo "$var";?>'/> 

In PHP action File:

<?php 
   if(isset($_POST['var'])) $var=$_POST['var'];
?>

Or using sessions: In your first page:

 $_SESSION['var']=$var;

start_session(); should be placed at the beginning of your php page.

In PHP action File:

if(isset($_SESSION['var'])) $var=$_SESSION['var'];

First Answer:

You can also use $GLOBALS :

if (isset($_POST['save_exit']))
{

   echo $GLOBALS['var']; 

}

Check this documentation for more informations.

How can I add (simple) tracing in C#?

DotNetCoders has a starter article on it: http://www.dotnetcoders.com/web/Articles/ShowArticle.aspx?article=50. They talk about how to set up the switches in the configuration file and how to write the code, but it is pretty old (2002).

There's another article on CodeProject: A Treatise on Using Debug and Trace classes, including Exception Handling, but it's the same age.

CodeGuru has another article on custom TraceListeners: Implementing a Custom TraceListener

Understanding typedefs for function pointers in C

Consider the signal() function from the C standard:

extern void (*signal(int, void(*)(int)))(int);

Perfectly obscurely obvious - it's a function that takes two arguments, an integer and a pointer to a function that takes an integer as an argument and returns nothing, and it (signal()) returns a pointer to a function that takes an integer as an argument and returns nothing.

If you write:

typedef void (*SignalHandler)(int signum);

then you can instead declare signal() as:

extern  SignalHandler signal(int signum, SignalHandler handler);

This means the same thing, but is usually regarded as somewhat easier to read. It is clearer that the function takes an int and a SignalHandler and returns a SignalHandler.

It takes a bit of getting used to, though. The one thing you can't do, though is write a signal handler function using the SignalHandler typedef in the function definition.

I'm still of the old-school that prefers to invoke a function pointer as:

(*functionpointer)(arg1, arg2, ...);

Modern syntax uses just:

functionpointer(arg1, arg2, ...);

I can see why that works - I just prefer to know that I need to look for where the variable is initialized rather than for a function called functionpointer.


Sam commented:

I have seen this explanation before. And then, as is the case now, I think what I didn't get was the connection between the two statements:

    extern void (*signal(int, void()(int)))(int);  /*and*/

    typedef void (*SignalHandler)(int signum);
    extern SignalHandler signal(int signum, SignalHandler handler);

Or, what I want to ask is, what is the underlying concept that one can use to come up with the second version you have? What is the fundamental that connects "SignalHandler" and the first typedef? I think what needs to be explained here is what is typedef is actually doing here.

Let's try again. The first of these is lifted straight from the C standard - I retyped it, and checked that I had the parentheses right (not until I corrected it - it is a tough cookie to remember).

First of all, remember that typedef introduces an alias for a type. So, the alias is SignalHandler, and its type is:

a pointer to a function that takes an integer as an argument and returns nothing.

The 'returns nothing' part is spelled void; the argument that is an integer is (I trust) self-explanatory. The following notation is simply (or not) how C spells pointer to function taking arguments as specified and returning the given type:

type (*function)(argtypes);

After creating the signal handler type, I can use it to declare variables and so on. For example:

static void alarm_catcher(int signum)
{
    fprintf(stderr, "%s() called (%d)\n", __func__, signum);
}

static void signal_catcher(int signum)
{
    fprintf(stderr, "%s() called (%d) - exiting\n", __func__, signum);
    exit(1);
}

static struct Handlers
{
    int              signum;
    SignalHandler    handler;
} handler[] =
{
    { SIGALRM,   alarm_catcher  },
    { SIGINT,    signal_catcher },
    { SIGQUIT,   signal_catcher },
};

int main(void)
{
    size_t num_handlers = sizeof(handler) / sizeof(handler[0]);
    size_t i;

    for (i = 0; i < num_handlers; i++)
    {
        SignalHandler old_handler = signal(handler[i].signum, SIG_IGN);
        if (old_handler != SIG_IGN)
            old_handler = signal(handler[i].signum, handler[i].handler);
        assert(old_handler == SIG_IGN);
    }

    ...continue with ordinary processing...

    return(EXIT_SUCCESS);
}

Please note How to avoid using printf() in a signal handler?

So, what have we done here - apart from omit 4 standard headers that would be needed to make the code compile cleanly?

The first two functions are functions that take a single integer and return nothing. One of them actually doesn't return at all thanks to the exit(1); but the other does return after printing a message. Be aware that the C standard does not permit you to do very much inside a signal handler; POSIX is a bit more generous in what is allowed, but officially does not sanction calling fprintf(). I also print out the signal number that was received. In the alarm_handler() function, the value will always be SIGALRM as that is the only signal that it is a handler for, but signal_handler() might get SIGINT or SIGQUIT as the signal number because the same function is used for both.

Then I create an array of structures, where each element identifies a signal number and the handler to be installed for that signal. I've chosen to worry about 3 signals; I'd often worry about SIGHUP, SIGPIPE and SIGTERM too and about whether they are defined (#ifdef conditional compilation), but that just complicates things. I'd also probably use POSIX sigaction() instead of signal(), but that is another issue; let's stick with what we started with.

The main() function iterates over the list of handlers to be installed. For each handler, it first calls signal() to find out whether the process is currently ignoring the signal, and while doing so, installs SIG_IGN as the handler, which ensures that the signal stays ignored. If the signal was not previously being ignored, it then calls signal() again, this time to install the preferred signal handler. (The other value is presumably SIG_DFL, the default signal handler for the signal.) Because the first call to 'signal()' set the handler to SIG_IGN and signal() returns the previous error handler, the value of old after the if statement must be SIG_IGN - hence the assertion. (Well, it could be SIG_ERR if something went dramatically wrong - but then I'd learn about that from the assert firing.)

The program then does its stuff and exits normally.

Note that the name of a function can be regarded as a pointer to a function of the appropriate type. When you do not apply the function-call parentheses - as in the initializers, for example - the function name becomes a function pointer. This is also why it is reasonable to invoke functions via the pointertofunction(arg1, arg2) notation; when you see alarm_handler(1), you can consider that alarm_handler is a pointer to the function and therefore alarm_handler(1) is an invocation of a function via a function pointer.

So, thus far, I've shown that a SignalHandler variable is relatively straight-forward to use, as long as you have some of the right type of value to assign to it - which is what the two signal handler functions provide.

Now we get back to the question - how do the two declarations for signal() relate to each other.

Let's review the second declaration:

 extern SignalHandler signal(int signum, SignalHandler handler);

If we changed the function name and the type like this:

 extern double function(int num1, double num2);

you would have no problem interpreting this as a function that takes an int and a double as arguments and returns a double value (would you? maybe you'd better not 'fess up if that is problematic - but maybe you should be cautious about asking questions as hard as this one if it is a problem).

Now, instead of being a double, the signal() function takes a SignalHandler as its second argument, and it returns one as its result.

The mechanics by which that can also be treated as:

extern void (*signal(int signum, void(*handler)(int signum)))(int signum);

are tricky to explain - so I'll probably screw it up. This time I've given the parameters names - though the names aren't critical.

In general, in C, the declaration mechanism is such that if you write:

type var;

then when you write var it represents a value of the given type. For example:

int     i;            // i is an int
int    *ip;           // *ip is an int, so ip is a pointer to an integer
int     abs(int val); // abs(-1) is an int, so abs is a (pointer to a)
                      // function returning an int and taking an int argument

In the standard, typedef is treated as a storage class in the grammar, rather like static and extern are storage classes.

typedef void (*SignalHandler)(int signum);

means that when you see a variable of type SignalHandler (say alarm_handler) invoked as:

(*alarm_handler)(-1);

the result has type void - there is no result. And (*alarm_handler)(-1); is an invocation of alarm_handler() with argument -1.

So, if we declared:

extern SignalHandler alt_signal(void);

it means that:

(*alt_signal)();

represents a void value. And therefore:

extern void (*alt_signal(void))(int signum);

is equivalent. Now, signal() is more complex because it not only returns a SignalHandler, it also accepts both an int and a SignalHandler as arguments:

extern void (*signal(int signum, SignalHandler handler))(int signum);

extern void (*signal(int signum, void (*handler)(int signum)))(int signum);

If that still confuses you, I'm not sure how to help - it is still at some levels mysterious to me, but I've grown used to how it works and can therefore tell you that if you stick with it for another 25 years or so, it will become second nature to you (and maybe even a bit quicker if you are clever).

Oracle query to identify columns having special characters

They key is the backslash escape character will not work with the right square bracket inside of the character class square brackets (it is interpreted as a literal backslash inside the character class square brackets). Add the right square bracket with an OR at the end like this:

select EmpNo, SampleText
from test 
where NOT regexp_like(SampleText, '[ A-Za-z0-9.{}[]|]');

Check whether a string is not null and not empty

To check on if all the string attributes in an object is empty(Instead of using !=null on all the field names following java reflection api approach

private String name1;
private String name2;
private String name3;

public boolean isEmpty()  {

    for (Field field : this.getClass().getDeclaredFields()) {
        try {
            field.setAccessible(true);
            if (field.get(this) != null) {
                return false;
            }
        } catch (Exception e) {
            System.out.println("Exception occurred in processing");
        }
    }
    return true;
}

This method would return true if all the String field values are blank,It would return false if any one values is present in the String attributes

How can I uninstall Ruby on ubuntu?

On Lubuntu, I just tried apt-get purge ruby* and as well as removing ruby, it looks like this command tried to remove various things to do with GRUB, which is a bit worrying for next time I want to reboot my computer. I can't yet say if any damage has really been done.

How can I create tests in Android Studio?

I think this post by Rex St John is very useful for unit testing with android studio.


(source: rexstjohn.com)

Can I scale a div's height proportionally to its width using CSS?

If you want vertical sizing proportional to a width set in pixels on an enclosing div, I believe you need an extra element, like so:

#html

<div class="ptest">
    <div class="ptest-wrap">
        <div class="ptest-inner">
            Put content here
        </div>
    </div>
</div>

#css
.ptest {
  width: 200px;
  position: relative;
}

.ptest-wrap {
    padding-top: 60%;
}
.ptest-inner {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: #333;
}

Here's the 2 div solution that doesn't work. Note the 60% vertical padding is proportional to the window width, not the div.ptest width:

http://jsfiddle.net/d85FM/

Here's the example with the code above, which does work:

http://jsfiddle.net/mmq29/

python error: no module named pylab

I solved the same problem by installing "matplotlib".

Binding objects defined in code-behind

That's my way to bind to code behind (see property DataTemplateSelector)

public partial class MainWindow : Window
{
  public MainWindow()
  {
    this.DataTemplateSelector = new MyDataTemplateSelector();

    InitializeComponent();

    // ... more initializations ...
  }

  public DataTemplateSelector DataTemplateSelector { get; }

  // ... more code stuff ...
}

In XAML will referenced by RelativeSource via Ancestors up to containing Window, so I'm at my Window class and use the property via Path declaration:

<GridViewColumn Header="Value(s)"
                CellTemplateSelector="{Binding RelativeSource={RelativeSource FindAncestor, AncestorType={x:Type Window}}, Path=DataTemplateSelector}"/>

Setting of property DataTemplateSelector before call InitializeComponent depends on missing implementation of IPropertyChanged or use of implementation with DependencyProperty so no communication run on change of property DataTemplateSelector.

Android: Scale a Drawable or background image?

What Dweebo proposed works. But in my humble opinion it is unnecessary. A background drawable scales well by itself. The view should have fixed width and height, like in the following example:

 < RelativeLayout 
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@android:color/black">

    <LinearLayout
        android:layout_width="500dip"
        android:layout_height="450dip"
        android:layout_centerInParent="true"
        android:background="@drawable/my_drawable"
        android:orientation="vertical"
        android:padding="30dip"
        >
        ...
     </LinearLayout>
 < / RelativeLayout>

how to create virtual host on XAMPP

I see two errors:

<VirtualHost *:80> -> Fix to :8081, your POrt the server runs on
    ServerName comm-app.local
    DocumentRoot "C:/xampp/htdocs/CommunicationApp/public"
    SetEnv APPLICATION_ENV "development"
    <Directory "C:/xampp/htdocs/CommunicationApp/public" -> This is probably why it crashes, missing >
        DirectoryIndex index.php
        AllowOverride All
        Order allow,deny
        Allow from all
    </Directory>
 -> MIssing close container: </VirtualHost> 

Fixed version:

<VirtualHost *:8081>
    ServerName comm-app.local
    DocumentRoot "C:/xampp/htdocs/CommunicationApp/public"
    SetEnv APPLICATION_ENV "development"
    <Directory "C:/xampp/htdocs/CommunicationApp/public">
        DirectoryIndex index.php
        AllowOverride All
        Order allow,deny
        Allow from all
    </Directory>
</VirtualHost>

One thing to mention:

You can always try and run command:

service apache2 configtest

This will tell you when you got a malformed configuration and maybe even can tell you where the problem is.

Furthermore it helps avoid unavailability in a LIVE system:

service apache2 restart

will shutdown and then fail to start, this configtest you know beforehand "oops I did something wrong, I should fix this first" but the apache itself is still running with old configuration. :)

Laravel blade check empty foreach

Check the documentation for the best result:

@forelse($status->replies as $reply)
    <p>{{ $reply->body }}</p>
@empty
    <p>No replies</p>
@endforelse

Common HTTPclient and proxy

I had a similar problem with HttpClient version 4.

I couldn't connect to the server because of a SOCKS proxy error and I fixed it using the below configuration:

client.getParams().setParameter("socksProxyHost",proxyHost);
client.getParams().setParameter("socksProxyPort",proxyPort);

draw diagonal lines in div background with CSS

All other answers to this 3-year old question require CSS3 (or SVG). However, it can also be done with nothing but lame old CSS2:

_x000D_
_x000D_
.crossed {_x000D_
    position: relative;_x000D_
    width: 300px;_x000D_
    height: 300px;_x000D_
}_x000D_
_x000D_
.crossed:before {_x000D_
    content: '';_x000D_
    position: absolute;_x000D_
    left: 0;_x000D_
    right: 0;_x000D_
    top: 1px;_x000D_
    bottom: 1px;_x000D_
    border-width: 149px;_x000D_
    border-style: solid;_x000D_
    border-color: black white;_x000D_
}_x000D_
_x000D_
.crossed:after {_x000D_
    content: '';_x000D_
    position: absolute;_x000D_
    left: 1px;_x000D_
    right: 1px;_x000D_
    top: 0;_x000D_
    bottom: 0;_x000D_
    border-width: 149px;_x000D_
    border-style: solid;_x000D_
    border-color: white transparent;_x000D_
}
_x000D_
<div class='crossed'></div>
_x000D_
_x000D_
_x000D_

Explanation, as requested:

Rather than actually drawing diagonal lines, it occurred to me we can instead color the so-called negative space triangles adjacent to where we want to see these lines. The trick I came up with to accomplish this exploits the fact that multi-colored CSS borders are bevelled diagonally:

_x000D_
_x000D_
.borders {_x000D_
    width: 200px;_x000D_
    height: 100px;_x000D_
    background-color: black;_x000D_
    border-width: 40px;_x000D_
    border-style: solid;_x000D_
    border-color: red blue green yellow;_x000D_
}
_x000D_
<div class='borders'></div>
_x000D_
_x000D_
_x000D_

To make things fit the way we want, we choose an inner rectangle with dimensions 0 and LINE_THICKNESS pixels, and another one with those dimensions reversed:

_x000D_
_x000D_
.r1 { width: 10px;_x000D_
      height: 0;_x000D_
      border-width: 40px;_x000D_
      border-style: solid;_x000D_
      border-color: red blue;_x000D_
      margin-bottom: 10px; }_x000D_
.r2 { width: 0;_x000D_
      height: 10px;_x000D_
      border-width: 40px;_x000D_
      border-style: solid;_x000D_
      border-color: blue transparent; }
_x000D_
<div class='r1'></div><div class='r2'></div>
_x000D_
_x000D_
_x000D_

Finally, use the :before and :after pseudo-selectors and position relative/absolute as a neat way to insert the borders of both of the above rectangles on top of each other into your HTML element of choice, to produce a diagonal cross. Note that results probably look best with a thin LINE_THICKNESS value, such as 1px.

How do I assert equality on two classes without an equals method?

I know it's a bit old, but I hope it helps.

I run into the same problem that you, so, after investigation, I found few similar questions than this one, and, after finding the solution, I'm answering the same in those, since I thought it could to help others.

The most voted answer (not the one picked by the author) of this similar question, is the most suitable solution for you.

Basically, it consist on using the library called Unitils.

This is the use:

User user1 = new User(1, "John", "Doe");
User user2 = new User(1, "John", "Doe");
assertReflectionEquals(user1, user2);

Which will pass even if the class User doesn't implement equals(). You can see more examples and a really cool assert called assertLenientEquals in their tutorial.

Timing Delays in VBA

I use this little function for VBA.

Public Function Pause(NumberOfSeconds As Variant)
    On Error GoTo Error_GoTo

    Dim PauseTime As Variant
    Dim Start As Variant
    Dim Elapsed As Variant

    PauseTime = NumberOfSeconds
    Start = Timer
    Elapsed = 0
    Do While Timer < Start + PauseTime
        Elapsed = Elapsed + 1
        If Timer = 0 Then
            ' Crossing midnight
            PauseTime = PauseTime - Elapsed
            Start = 0
            Elapsed = 0
        End If
        DoEvents
    Loop

Exit_GoTo:
    On Error GoTo 0
    Exit Function
Error_GoTo:
    Debug.Print Err.Number, Err.Description, Erl
    GoTo Exit_GoTo
End Function

How to convert Observable<any> to array[]

You will need to subscribe to your observables:

this.CountryService.GetCountries()
    .subscribe(countries => {
        this.myGridOptions.rowData = countries as CountryData[]
    })

And, in your html, wherever needed, you can pass the async pipe to it.

Count the number of occurrences of each letter in string

//c code for count the occurence of each character in a string.

void main()
   {
   int i,j; int c[26],count=0; char a[]="shahid";
   clrscr();
   for(i=0;i<26;i++)
    {
        count=0;
          for(j=0;j<strlen(a);j++)
                {
                 if(a[j]==97+i)
                    {
                     count++;
                         }
                           }
                  c[i]=count;
               }
              for(i=0;i<26;i++)
               {
              j=97+i;
          if(c[i]!=0) {  printf("%c of %d times\n",j,c[i]);
                 }
              }
           getch();
           }

Java program to get the current date without timestamp

You could always use apache commons' DateUtils class. It has the static method isSameDay() which "Checks if two date objects are on the same day ignoring time."

static boolean isSameDay(Date date1, Date date2) 

Magento addFieldToFilter: Two fields, match as OR, not AND

public function testAction()
{
        $filter_a = array('like'=>'a%');
        $filter_b = array('like'=>'b%');
        echo(
        (string) 
        Mage::getModel('catalog/product')
        ->getCollection()
        ->addFieldToFilter('sku',array($filter_a,$filter_b))
        ->getSelect()
        );
}

Result:

WHERE (((e.sku like 'a%') or (e.sku like 'b%')))

Source: http://alanstorm.com/magento_collections

AFNetworking Post Request

It's first worth adding (as this answer is still popular 6 years after I initially wrote it...) that the first thing you should consider is whether you should even use AFNetworking. NSURLSession was added in iOS 7 and means you don't need to use AFNetworking in many cases - and one less third party library is always a good thing.

For AFNetworking 3.0:

AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
NSDictionary *params = @{@"user[height]": height,
                         @"user[weight]": weight};
[manager POST:@"https://example.com/myobject" parameters:params progress:nil success:^(NSURLSessionTask *task, id responseObject) {
    NSLog(@"JSON: %@", responseObject);
} failure:^(NSURLSessionTask *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

For AFNetworking 2.0 (and also using the new NSDictionary syntax):

AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
NSDictionary *params = @{@"user[height]": height,
                         @"user[weight]": weight};
[manager POST:@"https://example.com/myobject" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSLog(@"JSON: %@", responseObject);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"Error: %@", error);
}];

If you are stuck using AFNetworking 1.0, you need to do it this way:

NSURL *url = [NSURL URLWithString:@"https://example.com/"];
AFHTTPClient *httpClient = [[AFHTTPClient alloc] initWithBaseURL:url];

NSDictionary *params = [NSDictionary dictionaryWithObjectsAndKeys:
                        height, @"user[height]",
                        weight, @"user[weight]",
                        nil];
[httpClient postPath:@"/myobject" parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
    NSString *responseStr = [[NSString alloc] initWithData:responseObject encoding:NSUTF8StringEncoding];
    NSLog(@"Request Successful, response '%@'", responseStr);
} failure:^(AFHTTPRequestOperation *operation, NSError *error) {
    NSLog(@"[HTTPClient Error]: %@", error.localizedDescription);
}];

What's the difference between xsd:include and xsd:import?

Use xsd:include to bring in an XSD from the same or no namespace.

Use xsd:import to bring in an XSD from a different namespace.

How do I know which version of Javascript I'm using?

Wikipedia (or rather, the community on Wikipedia) keeps a pretty good up-to-date list here.

  • Most browsers are on 1.5 (though they have features of later versions)
  • Mozilla progresses with every dot release (they maintain the standard so that's not surprising)
  • Firefox 4 is on JavaScript 1.8.5
  • The other big off-the-beaten-path one is IE9 - it implements ECMAScript 5, but doesn't implement all the features of JavaScript 1.8.5 (not sure what they're calling this version of JScript, engine codenamed Chakra, yet).

Find child element in AngularJS directive

jQlite (angular's "jQuery" port) doesn't support lookup by classes.

One solution would be to include jQuery in your app.

Another is using QuerySelector or QuerySelectorAll:

link: function(scope, element, attrs) {
   console.log(element[0].querySelector('.list-scrollable'))
}

We use the first item in the element array, which is the HTML element. element.eq(0) would yield the same.

FIDDLE

jQuery: Adding two attributes via the .attr(); method

Something like this:

$(myObj).attr({"data-test-1": num1, "data-test-2": num2});

git rebase merge conflict

Rebasing can be a real headache. You have to resolve the merge conflicts and continue rebasing. For example you can use the merge tool (which differs depending on your settings)

git mergetool

Then add your changes and go on

git rebase --continue

Good luck

Curly braces in string in PHP

Example:

$number = 4;
print "You have the {$number}th edition book";
//output: "You have the 4th edition book";

Without curly braces PHP would try to find a variable named $numberth, that doesn't exist!

What's the difference between subprocess Popen and call (how can I use them)?

There are two ways to do the redirect. Both apply to either subprocess.Popen or subprocess.call.

  1. Set the keyword argument shell = True or executable = /path/to/the/shell and specify the command just as you have it there.

  2. Since you're just redirecting the output to a file, set the keyword argument

    stdout = an_open_writeable_file_object
    

    where the object points to the output file.

subprocess.Popen is more general than subprocess.call.

Popen doesn't block, allowing you to interact with the process while it's running, or continue with other things in your Python program. The call to Popen returns a Popen object.

call does block. While it supports all the same arguments as the Popen constructor, so you can still set the process' output, environmental variables, etc., your script waits for the program to complete, and call returns a code representing the process' exit status.

returncode = call(*args, **kwargs) 

is basically the same as calling

returncode = Popen(*args, **kwargs).wait()

call is just a convenience function. It's implementation in CPython is in subprocess.py:

def call(*popenargs, timeout=None, **kwargs):
    """Run command with arguments.  Wait for command to complete or
    timeout, then return the returncode attribute.

    The arguments are the same as for the Popen constructor.  Example:

    retcode = call(["ls", "-l"])
    """
    with Popen(*popenargs, **kwargs) as p:
        try:
            return p.wait(timeout=timeout)
        except:
            p.kill()
            p.wait()
            raise

As you can see, it's a thin wrapper around Popen.

Angularjs dynamic ng-pattern validation

_x000D_
_x000D_
 <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.6/angular.js"></script>
_x000D_
<input type="number" require ng-pattern="/^\d{0,9}(\.\d{1,9})?$/"><input type="submit">
_x000D_
_x000D_
_x000D_

How to add an event after close the modal window?

Few answers that may be useful, especially if you have dynamic content.

$('#dialogueForm').live("dialogclose", function(){
   //your code to run on dialog close
});

Or, when opening the modal, have a callback.

$( "#dialogueForm" ).dialog({
              autoOpen: false,
              height: "auto",
              width: "auto",
              modal: true,
                my: "center",
                at: "center",
                of: window,
              close : function(){
                  // functionality goes here
              }  
              });

Fastest JSON reader/writer for C++

https://github.com/quartzjer/js0n

Ugliest interface possible, but does what you ask. Zero allocations.

http://zserge.com/jsmn.html Another zero-allocation approach.

The solutions posted above all do dynamic memory allocation, hence will be inevitably end up slower at some point, depending on the data structure - and will be dangerous to include in a heap constrained environment like an embedded system.

Benchmarks of vjson, rapidjson and sajson here : http://chadaustin.me/2013/01/json-parser-benchmarking/ if you are interested in that sort of thing.

And to answer your "writer" part of the question i doubt that you could beat an efficient

printf("{%s:%s}",name,value)

implementation with any library - assuming your printf/sprintf implementation itself is lightweight of course.

EDIT: actually let me take that back, RapidJson allows on-stack allocation only through its MemoryPoolAllocator and actually makes this a default for its GenericReader. I havent done the comparison but i would expect it to be more robust than anything else listed here. It also doesnt have any dependencies, and it doesnt throw exceptions which probably makes it ultimately suitable for embedded. Fully header based lib so, easy to include anywhere.

Using Laravel Homestead: 'no input file specified'

Same issue for me.

Neither vagrant provision or homestead up --provision worked for me, but the below did - probably as homestead was already running when I modified the yml file

vagrant reload --provision

In Python, how do I read the exif data for an image?

import sys
import PIL
import PIL.Image as PILimage
from PIL import ImageDraw, ImageFont, ImageEnhance
from PIL.ExifTags import TAGS, GPSTAGS



class Worker(object):
    def __init__(self, img):
        self.img = img
        self.exif_data = self.get_exif_data()
        self.lat = self.get_lat()
        self.lon = self.get_lon()
        self.date =self.get_date_time()
        super(Worker, self).__init__()

    @staticmethod
    def get_if_exist(data, key):
        if key in data:
            return data[key]
        return None

    @staticmethod
    def convert_to_degress(value):
        """Helper function to convert the GPS coordinates
        stored in the EXIF to degress in float format"""
        d0 = value[0][0]
        d1 = value[0][1]
        d = float(d0) / float(d1)
        m0 = value[1][0]
        m1 = value[1][1]
        m = float(m0) / float(m1)

        s0 = value[2][0]
        s1 = value[2][1]
        s = float(s0) / float(s1)

        return d + (m / 60.0) + (s / 3600.0)

    def get_exif_data(self):
        """Returns a dictionary from the exif data of an PIL Image item. Also
        converts the GPS Tags"""
        exif_data = {}
        info = self.img._getexif()
        if info:
            for tag, value in info.items():
                decoded = TAGS.get(tag, tag)
                if decoded == "GPSInfo":
                    gps_data = {}
                    for t in value:
                        sub_decoded = GPSTAGS.get(t, t)
                        gps_data[sub_decoded] = value[t]

                    exif_data[decoded] = gps_data
                else:
                    exif_data[decoded] = value
        return exif_data

    def get_lat(self):
        """Returns the latitude and longitude, if available, from the 
        provided exif_data (obtained through get_exif_data above)"""
        # print(exif_data)
        if 'GPSInfo' in self.exif_data:
            gps_info = self.exif_data["GPSInfo"]
            gps_latitude = self.get_if_exist(gps_info, "GPSLatitude")
            gps_latitude_ref = self.get_if_exist(gps_info, 'GPSLatitudeRef')
            if gps_latitude and gps_latitude_ref:
                lat = self.convert_to_degress(gps_latitude)
                if gps_latitude_ref != "N":
                    lat = 0 - lat
                lat = str(f"{lat:.{5}f}")
                return lat
        else:
            return None

    def get_lon(self):
        """Returns the latitude and longitude, if available, from the 
        provided exif_data (obtained through get_exif_data above)"""
        # print(exif_data)
        if 'GPSInfo' in self.exif_data:
            gps_info = self.exif_data["GPSInfo"]
            gps_longitude = self.get_if_exist(gps_info, 'GPSLongitude')
            gps_longitude_ref = self.get_if_exist(gps_info, 'GPSLongitudeRef')
            if gps_longitude and gps_longitude_ref:
                lon = self.convert_to_degress(gps_longitude)
                if gps_longitude_ref != "E":
                    lon = 0 - lon
                lon = str(f"{lon:.{5}f}")
                return lon
        else:
            return None

    def get_date_time(self):
        if 'DateTime' in self.exif_data:
            date_and_time = self.exif_data['DateTime']
            return date_and_time 

if __name__ == '__main__':
    try:
        img = PILimage.open(sys.argv[1])
        image = Worker(img)
        lat = image.lat
        lon = image.lon
        date = image.date
        print(date, lat, lon)

    except Exception as e:
        print(e)

How do I import a .dmp file into Oracle?

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

Follow the Steps:

Open run SQl Command Line

Step 1: Login as system user

       SQL> connect system/tiger

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

Step 3 : SQL> grant dba to UserName ;

Step 4 : SQL> GRANT UNLIMITED TABLESPACE TO UserName;

Step 5:

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

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

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

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

Done....

I hope you Find Right solution here.

Thanks.

Add Favicon with React and Webpack

Here is how I did.

public/index.html

I have added the generated favicon links.

...
<link rel="icon" type="image/png" sizes="32x32" href="%PUBLIC_URL%/path/to/favicon-32x32.png" />
<link rel="icon" type="image/png" sizes="16x16" href="%PUBLIC_URL%/path/to/favicon-16x16.png" />
<link rel="shortcut icon" href="%PUBLIC_URL%/path/to/favicon.ico" type="image/png/ico" />

webpack.config.js

new HTMLWebpackPlugin({
   template: '/path/to/index.html',
   favicon: '/path/to/favicon.ico',
})

Note

I use historyApiFallback in dev mode, but I didn't need to have any extra setup to get the favicon work nor on the server side.

How should you diagnose the error SEHException - External component has thrown an exception

The component makers say that this has been fixed in the latest version of their component which we are using in-house, but this has been given to the customer yet.

Ask the component maker how to test whether the problem that the customer is getting is the problem which they say they've fixed in their latest version, without/before deploying their latest version to the customer.

Android ADB doesn't see device

On windows, you will need to install drivers for the device for adb to recognize it. To see if the drivers are installed, check the device manager. If there is any "unrecognized device" in the device manager, the drivers are not installed. You can usually get the adb drivers from the manufacturers.

How to convert an integer (time) to HH:MM:SS::00 in SQL Server 2008?

This will work:

DECLARE @MS INT = 235216
select cast(dateadd(ms, @MS, '00:00:00') AS TIME(3))

(where ms is just a number of seconds not a timeformat)

Usage of @see in JavaDoc?

The @see tag is a bit different than the @link tag,
limited in some ways and more flexible in others:

different JavaDoc link types Different JavaDoc link types

  1. Displays the member name for better learning, and is refactorable; the name will update when renaming by refactor
  2. Refactorable and customizable; your text is displayed instead of the member name
  3. Displays name, refactorable
  4. Refactorable, customizable
  5. A rather mediocre combination that is:
  • Refactorable, customizable, and stays in the See Also section
  • Displays nicely in the Eclipse hover
  • Displays the link tag and its formatting when generated
  • When using multiple @see items, commas in the description make the output confusing
  1. Completely illegal; causes unexpected content and illegal character errors in the generator

See the results below:

JavaDoc generation results with different link types JavaDoc generation results with different link types

Best regards.

Spring Boot - Loading Initial Data

You can simply create a import.sql file in src/main/resources and Hibernate will execute it when the schema is created.

Understanding the Gemfile.lock file

It looks to me like PATH lists the first-generation dependencies directly from your gemspec, whereas GEM lists second-generation dependencies (i.e. what your dependencies depend on) and those from your Gemfile. PATH::remote is . because it relied on a local gemspec in the current directory to find out what belongs in PATH::spec, whereas GEM::remote is rubygems.org, since that's where it had to go to find out what belongs in GEM::spec.

In a Rails plugin, you'll see a PATH section, but not in a Rails app. Since the app doesn't have a gemspec file, there would be nothing to put in PATH.

As for DEPENDENCIES, gembundler.com states:

Runtime dependencies in your gemspec are treated like base dependencies, 
and development dependencies are added by default to the group, :development

The Gemfile generated by rails plugin new my_plugin says something similar:

# Bundler will treat runtime dependencies like base dependencies, and
# development dependencies will be added by default to the :development group.

What this means is that the difference between

s.add_development_dependency "july" # (1)

and

s.add_dependency "july" # (2)

is that (1) will only include "july" in Gemfile.lock (and therefore in the application) in a development environment. So when you run bundle install, you'll see "july" not only under PATH but also under DEPENDENCIES, but only in development. In production, it won't be there at all. However, when you use (2), you'll see "july" only in PATH, not in DEPENDENCIES, but it will show up when you bundle install from a production environment (i.e. in some other gem that includes yours as a dependency), not only development.

These are just my observations and I can't fully explain why any of this is the way it is but I welcome further comments.

What is the correct way to check for string equality in JavaScript?

always Until you fully understand the differences and implications of using the == and === operators, use the === operator since it will save you from obscure (non-obvious) bugs and WTFs. The "regular" == operator can have very unexpected results due to the type-coercion internally, so using === is always the recommended approach.

For insight into this, and other "good vs. bad" parts of Javascript read up on Mr. Douglas Crockford and his work. There's a great Google Tech Talk where he summarizes lots of good info: http://www.youtube.com/watch?v=hQVTIJBZook


Update:

The You Don't Know JS series by Kyle Simpson is excellent (and free to read online). The series goes into the commonly misunderstood areas of the language and explains the "bad parts" that Crockford suggests you avoid. By understanding them you can make proper use of them and avoid the pitfalls.

The "Up & Going" book includes a section on Equality, with this specific summary of when to use the loose (==) vs strict (===) operators:

To boil down a whole lot of details to a few simple takeaways, and help you know whether to use == or === in various situations, here are my simple rules:

  • If either value (aka side) in a comparison could be the true or false value, avoid == and use ===.
  • If either value in a comparison could be of these specific values (0, "", or [] -- empty array), avoid == and use ===.
  • In all other cases, you're safe to use ==. Not only is it safe, but in many cases it simplifies your code in a way that improves readability.

I still recommend Crockford's talk for developers who don't want to invest the time to really understand Javascript—it's good advice for a developer who only occasionally works in Javascript.

ORA-00932: inconsistent datatypes: expected - got CLOB

Take a substr of the CLOB and then convert it to a char:

UPDATE IMS_TEST 
  SET TEST_Category           = 'just testing' 
WHERE to_char(substr(TEST_SCRIPT, 1, 9))    = 'something'
  AND ID                      = '10000239';

Unable instantiate android.gms.maps.MapFragment

I've this issue i just update Google Play services and make sure that you are adding the google-play-service-lib project as dependency, it's working now without any code change but i still getting "The Google Play services resources were not found. Check your project configuration to ensure that the resources are included." but this only happens when you have setMyLocationEnabled(true), anyone knows why?

SQL query to check if a name begins and ends with a vowel

In MSSQL, this could be the way:

select distinct city from station 
where
right(city,1) in ('a', 'e', 'i', 'o','u') and left(city,1) in ('a', 'e', 'i', 'o','u') 

How do I write out a text file in C# with a code page other than UTF-8?

using System.IO;
using System.Text;

using (StreamWriter sw = new StreamWriter(File.Open(myfilename, FileMode.Create), Encoding.WhateverYouWant))
{    
    sw.WriteLine("my text...");     
}

An alternate way of getting your encoding:

using System.IO;
using System.Text;

using (var sw  = new StreamWriter(File.Open(@"c:\myfile.txt", FileMode.CreateNew), Encoding.GetEncoding("iso-8859-1"))) {
    sw.WriteLine("my text...");             
}

Check out the docs for the StreamWriter constructor.

How can I get name of element with jQuery?

var name = $('#myElement').attr('name');

Outputting data from unit test in Python

Another option - start a debugger where the test fails.

Try running your tests with Testoob (it will run your unittest suite without changes), and you can use the '--debug' command line switch to open a debugger when a test fails.

Here's a terminal session on windows:

C:\work> testoob tests.py --debug
F
Debugging for failure in test: test_foo (tests.MyTests.test_foo)
> c:\python25\lib\unittest.py(334)failUnlessEqual()
-> (msg or '%r != %r' % (first, second))
(Pdb) up
> c:\work\tests.py(6)test_foo()
-> self.assertEqual(x, y)
(Pdb) l
  1     from unittest import TestCase
  2     class MyTests(TestCase):
  3       def test_foo(self):
  4         x = 1
  5         y = 2
  6  ->     self.assertEqual(x, y)
[EOF]
(Pdb)

How to cancel/abort jQuery AJAX request?

You should also check for readyState 0. Because when you use xhr.abort() this function set readyState to 0 in this object, and your if check will be always true - readyState !=4

$(document).ready(
    var xhr;

    var fn = function(){
        if(xhr && xhr.readyState != 4 && xhr.readyState != 0){
            xhr.abort();
        }
        xhr = $.ajax({
            url: 'ajax/progress.ftl',
            success: function(data) {
                //do something
            }
        });
    };

    var interval = setInterval(fn, 500);
); 

How do I get the find command to print out the file size with the file name?

a simple solution is to use the -ls option in find:

find . -name \*.ear -ls

That gives you each entry in the normal "ls -l" format. Or, to get the specific output you seem to be looking for, this:

find . -name \*.ear -printf "%p\t%k KB\n"

Which will give you the filename followed by the size in KB.

Spring MVC - How to get all request params in a map in Spring controller?

Use org.springframework.web.context.request.WebRequest as a parameter in your controller method, it provides the method getParameterMap(), the advantage is that you do not tight your application to the Servlet API, the WebRequest is a example of JavaEE pattern Context Object.

How to setup virtual environment for Python in VS Code?

P.S:

  • I have been using vs code for a while now and found an another way to show virtual environments in vs code.

  • Go to the parent folder in which venv is there through command prompt.

  • Type code . and Enter. [Working on both windows and linux for me.]

  • That should also show the virtual environments present in that folder.

Original Answer

I almost run into same problem everytime I am working on VS-Code using venv. I follow below steps, hope it helps:

  1. Go to File > preferences > Settings.

  2. Click on Workspace settings.

  3. Under Files:Association, in the JSON: Schemas section, you will find Edit in settings.json , click on that.

  4. Update "python.pythonPath": "Your_venv_path/bin/python" under workspace settings. (For Windows): Update "python.pythonPath": "Your_venv_path/Scripts/python.exe" under workspace settings.

  5. Restart VSCode incase if it still doesn't show your venv.

Get string between two strings in a string

  private string gettxtbettwen(string txt, string first, string last)
    {

        StringBuilder sb = new StringBuilder(txt);
        int pos1 = txt.IndexOf(first)  + first.Length;
        int len = (txt.Length ) - pos1;

        string reminder = txt.Substring(pos1, len);


        int pos2 = reminder.IndexOf(last) - last.Length +1;


       



        return reminder.Substring(0, pos2); 



    }

Algorithm for solving Sudoku

I know I'm late, but this is my version:

from time import perf_counter

board = [
    [8, 0, 0, 0, 0, 0, 0, 0, 0],
    [0, 0, 3, 6, 0, 0, 0, 0, 0],
    [0, 7, 0, 0, 9, 0, 2, 0, 0],
    [0, 5, 0, 0, 0, 7, 0, 0, 0],
    [0, 0, 0, 0, 4, 5, 7, 0, 0],
    [0, 0, 0, 1, 0, 0, 0, 3, 0],
    [0, 0, 1, 0, 0, 0, 0, 6, 8],
    [0, 0, 8, 5, 0, 0, 0, 1, 0],
    [0, 9, 0, 0, 0, 0, 4, 0, 0]
]


def solve(bo):
    find = find_empty(bo)
    if not find:  # if find is None or False
        return True
    else:
        row, col = find

    for num in range(1, 10):
        if valid(bo, num, (row, col)):
            bo[row][col] = num

            if solve(bo):
                return True

            bo[row][col] = 0

    return False


def valid(bo, num, pos):

    # Check row
    for i in range(len(bo[0])):
        if bo[pos[0]][i] == num and pos[1] != i:
            return False

    # Check column
    for i in range(len(bo)):
        if bo[i][pos[1]] == num and pos[0] != i:
            return False

    # Check box
    box_x = pos[1] // 3
    box_y = pos[0] // 3

    for i in range(box_y*3, box_y*3 + 3):
        for j in range(box_x*3, box_x*3 + 3):
            if bo[i][j] == num and (i, j) != pos:
                return False

    return True


def print_board(bo):
    for i in range(len(bo)):
        if i % 3 == 0:
            if i == 0:
                print(" ?-------------------------?")
            else:
                print(" ?-------------------------?")

        for j in range(len(bo[0])):
            if j % 3 == 0:
                print(" ? ", end=" ")

            if j == 8:
                print(bo[i][j], " ?")
            else:
                print(bo[i][j], end=" ")

    print(" ?-------------------------?")


def find_empty(bo):
    for i in range(len(bo)):
        for j in range(len(bo[0])):
            if bo[i][j] == 0:
                return i, j  # row, column

    return None

print('\n--------------------------------------\n')

print('× Unsolved Suduku :-')
print_board(board)

print('\n--------------------------------------\n')

t1 = perf_counter()
solve(board)
t2 = perf_counter()
print('× Solved Suduku :-')
print_board(board)

print('\n--------------------------------------\n')

print(f' TIME TAKEN = {round(t2-t1,3)} SECONDS')

print('\n--------------------------------------\n')

It uses backtracking. But is not coded by me, it's Tech With Tim's. That list contains the world hardest sudoku, and by implementing the timing function, the time is:

===========================
[Finished in 2.838 seconds]
===========================

But with a simple sudoku puzzle like:

board = [
    [7, 8, 0, 4, 0, 0, 1, 2, 0],
    [6, 0, 0, 0, 7, 5, 0, 0, 9],
    [0, 0, 0, 6, 0, 1, 0, 7, 8],
    [0, 0, 7, 0, 4, 0, 2, 6, 0],
    [0, 0, 1, 0, 5, 0, 9, 3, 0],
    [9, 0, 4, 0, 6, 0, 0, 0, 5],
    [0, 7, 0, 3, 0, 0, 0, 1, 2],
    [1, 2, 0, 0, 0, 7, 4, 0, 0],
    [0, 4, 9, 2, 0, 6, 0, 0, 7]
]

The result is :

===========================
[Finished in 0.011 seconds]
===========================

Pretty fast I can say.

Python conversion from binary string to hexadecimal

>>> import string
>>> s="0000 0100 1000 1101"
>>> ''.join([ "%x"%string.atoi(bin,2) for bin in s.split() ]  )
'048d'
>>>

or

>>> s="0000 0100 1000 1101"
>>> hex(string.atoi(s.replace(" ",""),2))
'0x48d'

Oracle query execution time

One can issue the SQL*Plus command SET TIMING ON to get wall-clock times, but one can't take, for example, fetch time out of that trivially.

The AUTOTRACE setting, when used as SET AUTOTRACE TRACEONLY will suppress output, but still perform all of the work to satisfy the query and send the results back to SQL*Plus, which will suppress it.

Lastly, one can trace the SQL*Plus session, and manually calculate the time spent waiting on events which are client waits, such as "SQL*Net message to client", "SQL*Net message from client".

How can I remove all text after a character in bash?

trim off everything after the last instance of ":"

cat fileListingPathsAndFiles.txt | grep -o '^.*:'

and if you wanted to drop that last ":"

cat file.txt | grep -o '^.*:' | sed 's/:$//'

@kp123: you'd want to replace : with / (where the sed colon should be \/)

How can I force users to access my page over HTTPS instead of HTTP?

The PHP way:

$is_https=false;
if (isset($_SERVER['HTTPS'])) $is_https=$_SERVER['HTTPS'];
if ($is_https !== "on")
{
    header("Location: https://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']);
    exit(1);
}

The Apache mod_rewrite way:

RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Is Java a Compiled or an Interpreted programming language ?

Java is a compiled programming language, but rather than compile straight to executable machine code, it compiles to an intermediate binary form called JVM byte code. The byte code is then compiled and/or interpreted to run the program.

Setting button text via javascript

Use textContent instead of value to set the button text.

Typically the value attribute is used to associate a value with the button when it's submitted as form data.

Note that while it's possible to set the button text with innerHTML, using textContext should be preferred because it's more performant and it can prevent cross-site scripting attacks as its value is not parsed as HTML.

JS:

var b = document.createElement('button');
b.setAttribute('content', 'test content');
b.setAttribute('class', 'btn');  
b.textContent = 'test value';

var wrapper = document.getElementById("divWrapper");
wrapper.appendChild(b);

Produces this in the DOM:

<div id="divWrapper">
    <button content="test content" class="btn">test value</button>
</div>

Demo: https://jsfiddle.net/13ucp6ob/

How to do a subquery in LINQ?

You could do something like this for your case - (syntax may be a bit off). Also look at this link

subQuery = (from crtu in CompanyRolesToUsers where crtu.RoleId==2 || crtu.RoleId==3 select crtu.UserId).ToArrayList();

finalQuery = from u in Users where u.LastName.Contains('fra')  && subQuery.Contains(u.Id) select u;

How to disable all <input > inside a form with jQuery?

With this one line you can disable any input field in a form

$('form *').prop('disabled', true);

Angular CLI Error: The serve command requires to be run in an Angular project, but a project definition could not be found

I had the same issue with Angular7 because we need to go the root folder before run your application. Go to the root folder of your app and run the command. It works perfectly for me.

FPDF error: Some data has already been output, can't send PDF

For fpdf to work properly, there cannot be any output at all beside what fpdf generates. For example, this will work:

<?php
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>

While this will not (note the leading space before the opening <? tag)

 <?php
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>

Also, this will not work either (the echo will break it):

<?php
echo "About to create pdf";
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>

I'm not sure about the drupal side of things, but I know that absolutely zero non-fpdf output is a requirement for fpdf to work.


add ob_start (); at the top and at the end add ob_end_flush();

<?php
    ob_start();
    require('fpdf.php');
    $pdf = new FPDF();
    $pdf->AddPage();
    $pdf->SetFont('Arial','B',16);
    $pdf->Cell(40,10,'Hello World!');
    $pdf->Output();
    ob_end_flush(); 
?>

give me an error as below:
FPDF error: Some data has already been output, can't send PDF

to over come this error: go to fpdf.php in that,goto line number 996

function Output($name='', $dest='')

after that make changes like this:

function Output($name='', $dest='') {   
    ob_clean();     //Output PDF to so

Hi do you have a session header on the top of your page. or any includes If you have then try to add this codes on top pf your page it should works fine.

<?

while (ob_get_level())
ob_end_clean();
header("Content-Encoding: None", true);

?>

cheers :-)


In my case i had set:

ini_set('display_errors', 'on');
error_reporting(E_ALL | E_STRICT);

When i made the request to generate the report, some warnings were displayed in the browser (like the usage of deprecated functions).
Turning off the display_errors option, the report was generated successfully.

Is there a way to collapse all code blocks in Eclipse?

Just to sum up:

  1. anycode:
    • ctrl + shift + NUMPAD_divide = collapse all
    • NUMPAD_multiply = exand all
  2. pydev:
    • -ctrl + 0 = collapse all
    • -ctrl + 9 = exand all

href="file://" doesn't work

%20 is the space between AmberCRO SOP.

Try -

href="http://file:///K:/AmberCRO SOP/2011-07-05/SOP-SOP-3.0.pdf"

Or rename the folder as AmberCRO-SOP and write it as -

href="http://file:///K:/AmberCRO-SOP/2011-07-05/SOP-SOP-3.0.pdf"

How to add icons to React Native app

You can import react-native-elements and use the font-awesome icons to your react native app

Install

npm install --save react-native-elements

then import that where you want to use icons

import { Icon } from 'react-native-elements'

Use it like

render() {
   return(
    <Icon
      reverse
      name='ios-american-football'
      type='ionicon'
      color='#517fa4'
    />
 );
}

Android "gps requires ACCESS_FINE_LOCATION" error, even though my manifest file contains this

My simple solution is this

if (ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) ==
        PackageManager.PERMISSION_GRANTED &&
        ContextCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) ==
        PackageManager.PERMISSION_GRANTED) {
    googleMap.setMyLocationEnabled(true);
    googleMap.getUiSettings().setMyLocationButtonEnabled(true);
} else {
    Toast.makeText(this, R.string.error_permission_map, Toast.LENGTH_LONG).show();
}

or you can open permission dialog in else like this

} else {
   ActivityCompat.requestPermissions(this, new String[] {
      Manifest.permission.ACCESS_FINE_LOCATION, 
      Manifest.permission.ACCESS_COARSE_LOCATION }, 
      TAG_CODE_PERMISSION_LOCATION);
}

How do I do an initial push to a remote repository with Git?

You have to add at least one file to the repository before committing, e.g. .gitignore.

Scroll Position of div with "overflow: auto"

You need to use the scrollTop property.

document.getElementById('box').scrollTop

HTML email in outlook table width issue - content is wider than the specified table width

I guess problem is in width attributes in table and td remove 'px' for example

<table border="0" cellpadding="0" cellspacing="0" width="580px" style="background-color: #0290ba;">

Should be

<table border="0" cellpadding="0" cellspacing="0" width="580" style="background-color: #0290ba;">

Why do I have to "git push --set-upstream origin <branch>"?

My understanding is that "-u" or "--set-upstream" allows you to specify the upstream (remote) repository for the branch you're on, so that next time you run "git push", you don't even have to specify the remote repository.

Push and set upstream (remote) repository as origin:

$ git push -u origin

Next time you push, you don't have to specify the remote repository:

$ git push

Text Progress Bar in the Console

Here's my Python 3 solution:

import time
for i in range(100):
    time.sleep(1)
    s = "{}% Complete".format(i)
    print(s,end=len(s) * '\b')

'\b' is a backslash, for each character in your string. This does not work within the Windows cmd window.

How to launch Windows Scheduler by command-line?

I'm using Windows 2003 on the server. I'm in action with "SCHTASKS.EXE"

    SCHTASKS /parameter [arguments]

    Description:
        Enables an administrator to create, delete, query, change, run and
        end scheduled tasks on a local or remote system. Replaces AT.exe.

    Parameter List:
        /Create         Creates a new scheduled task.

        /Delete         Deletes the scheduled task(s).

        /Query          Displays all scheduled tasks.

        /Change         Changes the properties of scheduled task.

        /Run            Runs the scheduled task immediately.

        /End            Stops the currently running scheduled task.

        /?              Displays this help message.

    Examples:
        SCHTASKS
        SCHTASKS /?
        SCHTASKS /Run /?
        SCHTASKS /End /?
        SCHTASKS /Create /?
        SCHTASKS /Delete /?
        SCHTASKS /Query  /?
        SCHTASKS /Change /?

    +-------------------------------------+
    ¦ Executed Wed 02/29/2012 10:48:36.65 ¦
    +-------------------------------------+

It's quite interesting and makes me feel so powerful. :)

Inserting a string into a list without getting split into characters

Don't use list as a variable name. It's a built in that you are masking.

To insert, use the insert function of lists.

l = ['hello','world']
l.insert(0, 'foo')
print l
['foo', 'hello', 'world']

Differences between fork and exec

The prime example to understand the fork() and exec() concept is the shell,the command interpreter program that users typically executes after logging into the system.The shell interprets the first word of command line as a command name

For many commands,the shell forks and the child process execs the command associated with the name treating the remaining words on the command line as parameters to the command.

The shell allows three types of commands. First, a command can be an executable file that contains object code produced by compilation of source code (a C program for example). Second, a command can be an executable file that contains a sequence of shell command lines. Finally, a command can be an internal shell command.(instead of an executable file ex->cd,ls etc.)

What characters can be used for up/down triangle (arrow without stem) for display in HTML?

"Not ASCII (neither's ?/?)" needs qualification.

While these characters are not defined in the American Standard Code for Information Interchange as glyphs, their codes WERE commonly used to give a graphical presentation for ASCII codes 24 and 25 (hex 18 and 19, CANcel and EM:End of Medium). Code page 437 (called Extended ASCII by IBM, includes the numeric codes 128 to 255) defined the use of these glyphs as ASCII codes and the ubiquity of these conventions permeated the industry as seen by their deployment as standards by leading companies such as HP, particularly for printers, and IBM, particularly for microcomputers starting with the original PC.

Just as the use of the ASCII codes for CAN and EM was relatively obsolete at the time, justifying their use as glyphs, so has the passage of time made the use of the codes as glyphs obsolete by the current use of UNICODE conventions.


It should be emphasized that the extensions to ASCII made by IBM in Extended ASCII, included not only a larger numeric set for numeric codes 128 to 255, but also extended the use of some numeric control codes, in the ASCII range 0 to 32, from just media transmission control protocols to include glyphs. It is often assumed, incorrectly, that the first 0 to 128 were not "extended" and that IBM was using the glyphs of conventional ASCII for this range. This error is also perpetrated in one of the previous references. This error became so pervasive that it colloquially redefined ASCII subliminally.

$this->session->set_flashdata() and then $this->session->flashdata() doesn't work in codeigniter

Well, the documentation does actually state that

CodeIgniter supports "flashdata", or session data that will only be available for the next server request, and are then automatically cleared.

as the very first thing, which obviusly means that you need to do a new server request. A redirect, a refresh, a link or some other mean to send the user to the next request.

Why use flashdata if you are using it in the same request, anyway? You'd might as well not use flashdata or use a regular session.

How to get the current URL within a Django template?

You can fetch the URL in your template like this:

<p>URL of this page: {{ request.get_full_path }}</p>

or by

{{ request.path }} if you don't need the extra parameters.

Some precisions and corrections should be brought to hypete's and Igancio's answers, I'll just summarize the whole idea here, for future reference.

If you need the request variable in the template, you must add the 'django.core.context_processors.request' to the TEMPLATE_CONTEXT_PROCESSORS settings, it's not by default (Django 1.4).

You must also not forget the other context processors used by your applications. So, to add the request to the other default processors, you could add this in your settings, to avoid hard-coding the default processor list (that may very well change in later versions):

from django.conf.global_settings import TEMPLATE_CONTEXT_PROCESSORS as TCP

TEMPLATE_CONTEXT_PROCESSORS = TCP + (
    'django.core.context_processors.request',
)

Then, provided you send the request contents in your response, for example as this:

from django.shortcuts import render_to_response
from django.template import RequestContext

def index(request):
    return render_to_response(
        'user/profile.html',
        { 'title': 'User profile' },
        context_instance=RequestContext(request)
    )

SELECT list is not in GROUP BY clause and contains nonaggregated column .... incompatible with sql_mode=only_full_group_by

Search for "SQL mode" if you are using PhpMyAdmin and take off the value: ONLY_FULL_GROUP_BY, just did and it okay.

Compilation error - missing zlib.h

You have installed the library in a non-standard location ($HOME/zlib/). That means the compiler will not know where your header files are and you need to tell the compiler that.

You can add a path to the list that the compiler uses to search for header files by using the -I (upper-case i) option.

Also note that the LD_LIBRARY_PATH is for the run-time linker and loader, and is searched for dynamic libraries when attempting to run an application. To add a path for the build-time linker use the -L option.

All-together the command line should look like

$ c++ -I$HOME/zlib/include some_file.cpp -L$HOME/zlib/lib -lz

How do I use regular expressions in bash scripts?

You need spaces around the operator =~

i="test"
if [[ $i =~ "200[78]" ]];
then
  echo "OK"
else
  echo "not OK"
fi

Creating a simple configuration file and parser in C++

As others have pointed out, it will probably be less work to make use of an existing configuration-file parser library rather than re-invent the wheel.

For example, if you decide to use the Config4Cpp library (which I maintain), then your configuration file syntax will be slightly different (put double quotes around values and terminate assignment statements with a semicolon) as shown in the example below:

# File: someFile.cfg
url = "http://mysite.com";
file = "main.exe";
true_false = "true";

The following program parses the above configuration file, copies the desired values into variables and prints them:

#include <config4cpp/Configuration.h>
#include <iostream>
using namespace config4cpp;
using namespace std;

int main(int argc, char ** argv)
{
    Configuration *  cfg = Configuration::create();
    const char *     scope = "";
    const char *     configFile = "someFile.cfg";
    const char *     url;
    const char *     file;
    bool             true_false;

    try {
        cfg->parse(configFile);
        url        = cfg->lookupString(scope, "url");
        file       = cfg->lookupString(scope, "file");
        true_false = cfg->lookupBoolean(scope, "true_false");
    } catch(const ConfigurationException & ex) {
        cerr << ex.c_str() << endl;
        cfg->destroy();
        return 1;
    }
    cout << "url=" << url << "; file=" << file
         << "; true_false=" << true_false
         << endl;
    cfg->destroy();
    return 0;
}

The Config4Cpp website provides comprehensive documentation, but reading just Chapters 2 and 3 of the "Getting Started Guide" should be more than sufficient for your needs.

Inheriting from a template class in c++

Rectangle will have to be a template, otherwise it is just one type. It cannot be a non-template whilst its base magically is. (Its base may be a template instantiation, though you seem to want to maintain the base's functionality as a template.)

Count number of rows per group and add result to original data frame

Using sqldf package:

library(sqldf)

sqldf("select a.*, b.cnt
       from df a,
           (select name, type, count(1) as cnt
            from df
            group by name, type) b
      where a.name = b.name and
            a.type = b.type")

#    name  type num cnt
# 1 black chair   4   2
# 2 black chair   5   2
# 3 black  sofa  12   1
# 4   red  sofa   4   1
# 5   red plate   3   1

Find all elements on a page whose element ID contains a certain text using jQuery

$('*[id*=mytext]:visible').each(function() {
    $(this).doStuff();
});

Note the asterisk '*' at the beginning of the selector matches all elements.

See the Attribute Contains Selectors, as well as the :visible and :hidden selectors.

Update an outdated branch against master in a Git repo

Update the master branch, which you need to do regardless.

Then, one of:

  1. Rebase the old branch against the master branch. Solve the merge conflicts during rebase, and the result will be an up-to-date branch that merges cleanly against master.

  2. Merge your branch into master, and resolve the merge conflicts.

  3. Merge master into your branch, and resolve the merge conflicts. Then, merging from your branch into master should be clean.

None of these is better than the other, they just have different trade-off patterns.

I would use the rebase approach, which gives cleaner overall results to later readers, in my opinion, but that is nothing aside from personal taste.

To rebase and keep the branch you would:

git checkout <branch> && git rebase <target>

In your case, check out the old branch, then

git rebase master 

to get it rebuilt against master.

How should I unit test multithreaded code?

You may use EasyMock.makeThreadSafe to make testing instance threadsafe

How to do SVN Update on my project using the command line

I think I got it. It's:

"SVN Client Path"  /command:update / path:"My folder path"

Init array of structs in Go

You can have it this way:

It is important to mind the commas after each struct item or set of items.

earnings := []LineItemsType{

        LineItemsType{

            TypeName: "Earnings",

            Totals: 0.0,

            HasTotal: true,

            items: []LineItems{

                LineItems{

                    name: "Basic Pay",

                    amount: 100.0,
                },

                LineItems{

                    name: "Commuter Allowance",

                    amount: 100.0,
                },
            },
        },
        LineItemsType{

            TypeName: "Earnings",

            Totals: 0.0,

            HasTotal: true,

            items: []LineItems{

                LineItems{

                    name: "Basic Pay",

                    amount: 100.0,
                },

                LineItems{

                    name: "Commuter Allowance",

                    amount: 100.0,
                },
            },
        },
    }

How do I get the height of a div's full content with jQuery?

You can get it with .outerHeight().

Sometimes, it will return 0. For the best results, you can call it in your div's ready event.

To be safe, you should not set the height of the div to x. You can keep its height auto to get content populated properly with the correct height.

$('#x').ready( function(){
// alerts the height in pixels
alert($('#x').outerHeight());
})

You can find a detailed post here.

Returning multiple values from a C++ function

Use a struct or a class for the return value. Using std::pair may work for now, but

  1. it's inflexible if you decide later you want more info returned;
  2. it's not very clear from the function's declaration in the header what is being returned and in what order.

Returning a structure with self-documenting member variable names will likely be less bug-prone for anyone using your function. Putting my coworker hat on for a moment, your divide_result structure is easy for me, a potential user of your function, to immediately understand after 2 seconds. Messing around with ouput parameters or mysterious pairs and tuples would take more time to read through and may be used incorrectly. And most likely even after using the function a few times I still won't remember the correct order of the arguments.

Confused about UPDLOCK, HOLDLOCK

UPDLOCK is used when you want to lock a row or rows during a select statement for a future update statement. The future update might be the very next statement in the transaction.

Other sessions can still see the data. They just cannot obtain locks that are incompatiable with the UPDLOCK and/or HOLDLOCK.

You use UPDLOCK when you wan to keep other sessions from changing the rows you have locked. It restricts their ability to update or delete locked rows.

You use HOLDLOCK when you want to keep other sessions from changing any of the data you are looking at. It restricts their ability to insert, update, or delete the rows you have locked. This allows you to run the query again and see the same results.

WPF chart controls

DynamicDataDisplay is brilliant, zoom and pan built in and its free on CodePlex.

Set default heap size in Windows

Try setting a Windows System Environment variable called _JAVA_OPTIONS with the heap size you want. Java should be able to find it and act accordingly.

SQLRecoverableException: I/O Exception: Connection reset

We experienced these errors intermittently after upgraded from 11g to 12c and our java was on 1.6.

The fix for us was to upgrade java and jdbc from 6 to 7

export JAVA_HOME='/usr/java1.7'

export CLASSPATH=/u01/app/oracle/product/12.1.0/dbhome_1/jdbc/libojdbc7.jar:$CLASSPATH 

Several days later, still intermittent connection resets.

We ended up removing all the java 7 above. Java 6 was fine. The problem was fixed by adding this to our user bash_profile.

Our groovy scripts that were experiencing the error were using /dev/random on our batch VM server. Below forced java and groovy to use /dev/urandom.

export JAVA_OPTS=" $JAVA_OPTS -Djava.security.egd=file:///dev/urandom "

Convert Difference between 2 times into Milliseconds?

To answer the title-question:

DateTime d1 = ...;
DateTime d2 = ...;
TimeSpan diff = d2 - d1;

int millisceonds = (int) diff.TotalMilliseconds;

You can use this to set a Timer:

timer1.interval = millisceonds;
timer1.Enabled = true;

Don't forget to disable the timer when handling the tick.

But if you want an event at 12:03, just substitute DateTime.Now for d1.

But it is not clear what the exact function of textBox1 and textBox2 are.

Text vertical alignment in WPF TextBlock

A Textblock itself can't do vertical alignment

The best way to do this that I've found is to put the textblock inside a border, so the border does the alignment for you.

<Border BorderBrush="{x:Null}" Height="50">
    <TextBlock TextWrapping="Wrap" Text="Some Text" VerticalAlignment="Center"/>
</Border>

Note: This is functionally equivalent to using a grid, it just depends how you want the controls to fit in with the rest of your layout as to which one is more suitable

positional argument follows keyword argument

The grammar of the language specifies that positional arguments appear before keyword or starred arguments in calls:

argument_list        ::=  positional_arguments ["," starred_and_keywords]
                            ["," keywords_arguments]
                          | starred_and_keywords ["," keywords_arguments]
                          | keywords_arguments

Specifically, a keyword argument looks like this: tag='insider trading!' while a positional argument looks like this: ..., exchange, .... The problem lies in that you appear to have copy/pasted the parameter list, and left some of the default values in place, which makes them look like keyword arguments rather than positional ones. This is fine, except that you then go back to using positional arguments, which is a syntax error.

Also, when an argument has a default value, such as price=None, that means you don't have to provide it. If you don't provide it, it will use the default value instead.

To resolve this error, convert your later positional arguments into keyword arguments, or, if they have default values and you don't need to use them, simply don't specify them at all:

order_id = kite.order_place(self, exchange, tradingsymbol,
    transaction_type, quantity)

# Fully positional:
order_id = kite.order_place(self, exchange, tradingsymbol, transaction_type, quantity, price, product, order_type, validity, disclosed_quantity, trigger_price, squareoff_value, stoploss_value, trailing_stoploss, variety, tag)

# Some positional, some keyword (all keywords at end):

order_id = kite.order_place(self, exchange, tradingsymbol,
    transaction_type, quantity, tag='insider trading!')

Multiple inputs with same name through POST in php

For anyone else finding this - its worth noting that you can set the key value in the input name. Thanks to the answer in POSTing Form Fields with same Name Attribute you also can interplay strings or integers without quoting.

The answers assume that you don't mind the key value coming back for PHP however you can set name=[yourval] (string or int) which then allows you to refer to an existing record.

Docker container will automatically stop after "docker run -d"

Argument order matters

Jersey Beans answer (all 3 examples) worked for me. After quite a bit of trial and error I realized that the order of the arguments matter.

Keeps the container running in the background: docker run -t -d <image-name>

Keeps the container running in the foreground: docker run <image-name> -t -d

It wasn't obvious to me coming from a Powershell background.

Auto number column in SharePoint list

You can't add a new unique auto-generated ID to a SharePoint list, but there already is one there! If you edit the "All Items" view you will see a list of columns that do not have the display option checked.

There are quite a few of these columns that exist but that are never displayed, like "Created By" and "Created". These fields are used within SharePoint, but they are not displayed by default so as not to clutter up the display. You can't edit these fields, but you can display them to the user. if you check the "Display" box beside the ID field you will get a unique and auto-generated ID field displayed in your list.

Check out: Unique ID in SharePoint list

Laravel - display a PDF file in storage without forcing download?

Laravel 5.6.*

$name = 'file.jpg';

store on image or pdf

$file->storeAs('public/', $name );

download image or pdf

return response()->download($name);

view image or pdf

return response()->file($name);

Error: Microsoft Visual C++ 10.0 is required (Unable to find vcvarsall.bat) when running Python script

Tried to install lxml, grab and other extensions, which requires VS 10.0+ and get the same issue. I find own way to solve this problem(Windows 10 x64, Python 3.4+):

  1. Install Visual C++ 2010 Express (download). (Do not install Microsoft Visual Studio 2010 Service Pack 1 )

  2. Remove all the Microsoft Visual C++ 2010 Redistributable packages from Control Panel\Programs and Features. If you don't do those then the install is going to fail with an obscure "Fatal error during installation" error.

  3. Install offline version of Windows SDK for Visual Studio 2010 (v7.1) (download). This is required for 64bit extensions. Windows has builtin mounting for ISOs. Just mount the ISO and run Setup\SDKSetup.exe instead of setup.exe.

  4. Create a vcvars64.bat file in C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\amd64 that contains:

    CALL "C:\Program Files\Microsoft SDKs\Windows\v7.1\Bin\SetEnv.cmd" /x64

  5. Find extension on this site, then put them into the python folder, and install .whl extension with pip:

    python -m pip install extensionname.whl

  6. Enjoy

Parse date string and change format

@codeling and @user1767754 : The following two lines will work. I saw no one posted the complete solution for the example problem that was asked. Hopefully this is enough explanation.

import datetime

x = datetime.datetime.strptime("Mon Feb 15 2010", "%a %b %d %Y").strftime("%d/%m/%Y")
print(x)

Output:

15/02/2010

difference between System.out.println() and System.err.println()

System.out is "standard output" (stdout) and System.err is "error output" (stderr). Along with System.in (stdin), these are the three standard I/O streams in the Unix model. Most modern programming environments (C, Perl, etc.) support this model.

The standard output stream is used to print output from "normal operations" of the program, while the error stream is for "error messages". These need to be separate -- though in most cases they appear on the same console.

Suppose you have a simple program where you enter a phone number and it prints out the person who has that number. If you enter an invalid number, the program should inform you of that error, but it shouldn't do that as the answer: If you enter "999-ABC-4567" and the program prints an error message "Not a valid number", that doesn't mean there is a person named "Not a valid number" whose number is 999-ABC-4567. So it prints out nothing to the standard output, and the message "Not a valid number" is printed to the error output.

You can set up the execution environment to distinguish between the two streams, for example, make the standard output print to the screen and error output print to a file.

Import regular CSS file in SCSS file?

You can use a third-party importer to customise @import semantics.

node-sass-import-once, which works with node-sass (for Node.js) can inline import CSS files.

Example of direct usage:

var sass = require('node-sass');,
    importOnce = require('node-sass-import-once');

sass.render({
  file: "input.scss",
  importer: importOnce,
  importOnce: {
    css: true,
  }
});

Example grunt-sass config:

var importOnce = require("node-sass-import-once");
grunt.loadNpmTasks("grunt-sass");

grunt.initConfig({
  sass: {
    options: {
      sourceMap: true,
      importer: importOnce
    },
    dev: {
      files: {
        "dist/style.css": "scss/**/*.scss"
      }
    }
  });

Note that node-sass-import-once cannot currently import Sass partials without an explicit leading underscore. For example with the file partials/_partial.scss:

  • @import partials/_partial.scss succeeds
  • @import * partials/partial.scss fails

In general, be aware that a custom importer could change any import semantics. Read the docs before you start using it.

How to delete a column from a table in MySQL

You can use

alter table <tblname> drop column <colname>

MySQL: Large VARCHAR vs. TEXT?

  • TEXT and BLOB may by stored off the table with the table just having a pointer to the location of the actual storage. Where it is stored depends on lots of things like data size, columns size, row_format, and MySQL version.

  • VARCHAR is stored inline with the table. VARCHAR is faster when the size is reasonable, the tradeoff of which would be faster depends upon your data and your hardware, you'd want to benchmark a real-world scenario with your data.

python: after installing anaconda, how to import pandas

You should first create a new environment in conda. From the terminal, type:

$ conda create --name my_env pandas ipython

Python will be installed automatically as part of this installation. After selecting [y] to confirm, you now need to activate this environment:

$ source activate my_env

On Windows I believe it is just:

$ activate my_env

Now, confirm installed packages:

$ conda list

Finally, start python and run your session.

$ ipython

How to trim a string in SQL Server before 2017?

I assume this is a one-off data scrubbing exercise. Once done, ensure you add database constraints to prevent bad data in the future e.g.

ALTER TABLE Customer ADD
   CONSTRAINT customer_names__whitespace
      CHECK (
             Names NOT LIKE ' %'
             AND Names NOT LIKE '% '
             AND Names NOT LIKE '%  %'
            );

Also consider disallowing other characters (tab, carriage return, line feed, etc) that may cause problems.

It may also be a good time to split those Names into family_name, first_name, etc :)

Can we write our own iterator in Java?

The best reusable option is to implement the interface Iterable and override the method iterator().

Here's an example of a an ArrayList like class implementing the interface, in which you override the method Iterator().

import java.util.Iterator;

public class SOList<Type> implements Iterable<Type> {

    private Type[] arrayList;
    private int currentSize;

    public SOList(Type[] newArray) {
        this.arrayList = newArray;
        this.currentSize = arrayList.length;
    }

    @Override
    public Iterator<Type> iterator() {
        Iterator<Type> it = new Iterator<Type>() {

            private int currentIndex = 0;

            @Override
            public boolean hasNext() {
                return currentIndex < currentSize && arrayList[currentIndex] != null;
            }

            @Override
            public Type next() {
                return arrayList[currentIndex++];
            }

            @Override
            public void remove() {
                throw new UnsupportedOperationException();
            }
        };
        return it;
    }
}

This class implements the Iterable interface using Generics. Considering you have elements to the array, you will be able to get an instance of an Iterator, which is the needed instance used by the "foreach" loop, for instance.

You can just create an anonymous instance of the iterator without creating extending Iterator and take advantage of the value of currentSize to verify up to where you can navigate over the array (let's say you created an array with capacity of 10, but you have only 2 elements at 0 and 1). The instance will have its owner counter of where it is and all you need to do is to play with hasNext(), which verifies if the current value is not null, and the next(), which will return the instance of your currentIndex. Below is an example of using this API...

public static void main(String[] args) {
    // create an array of type Integer
    Integer[] numbers = new Integer[]{1, 2, 3, 4, 5};

    // create your list and hold the values.
    SOList<Integer> stackOverflowList = new SOList<Integer>(numbers);

    // Since our class SOList is an instance of Iterable, then we can use it on a foreach loop
    for(Integer num : stackOverflowList) {
        System.out.print(num);
    }

    // creating an array of Strings
    String[] languages = new String[]{"C", "C++", "Java", "Python", "Scala"};

    // create your list and hold the values using the same list implementation.
    SOList<String> languagesList = new SOList<String>(languages);

    System.out.println("");
    // Since our class SOList is an instance of Iterable, then we can use it on a foreach loop
    for(String lang : languagesList) {
        System.out.println(lang);
    }
}
// will print "12345
//C
//C++
//Java
//Python
//Scala

If you want, you can iterate over it as well using the Iterator instance:

// navigating the iterator
while (allNumbers.hasNext()) {
    Integer value = allNumbers.next();
    if (allNumbers.hasNext()) {
        System.out.print(value + ", ");
    } else {
        System.out.print(value);
    }
} 
// will print 1, 2, 3, 4, 5

The foreach documentation is located at http://download.oracle.com/javase/1,5.0/docs/guide/language/foreach.html. You can take a look at a more complete implementation at my personal practice google code.

Now, to get the effects of what you need I think you need to plug a concept of a filter in the Iterator... Since the iterator depends on the next values, it would be hard to return true on hasNext(), and then filter the next() implementation with a value that does not start with a char "a" for instance. I think you need to play around with a secondary Interator based on a filtered list with the values with the given filter.

How to remove item from array by value?

You can create your own method, passing throught the array and the value you want removed:

function removeItem(arr, item){
 return arr.filter(f => f !== item)
}

Then you can call this with:

ary = removeItem(ary, 'seven');

taking input of a string word by word

Put the line in a stringstream and extract word by word back:

#include <iostream>
#include <sstream>
using namespace std;

int main()
{
    string t;
    getline(cin,t);

    istringstream iss(t);
    string word;
    while(iss >> word) {
        /* do stuff with word */
    }
}

Of course, you can just skip the getline part and read word by word from cin directly.

And here you can read why is using namespace std considered bad practice.

How to show multiline text in a table cell

If you have a string variable with \n in it, that you want to put inside td, you can try

<td>
    {value
        .split('\n')
        .map((s, index) => (
            <React.Fragment key={index}>
                {s}
                <br />
            </React.Fragment>
        ))}
</td>

How to download file in swift?

After trying a few of the above suggestions without success (Swift versions...) I ended up using the official documentation: https://developer.apple.com/documentation/foundation/url_loading_system/downloading_files_from_websites

let downloadTask = URLSession.shared.downloadTask(with: url) {
    urlOrNil, responseOrNil, errorOrNil in
    // check for and handle errors:
    // * errorOrNil should be nil
    // * responseOrNil should be an HTTPURLResponse with statusCode in 200..<299
    
    guard let fileURL = urlOrNil else { return }
    do {
        let documentsURL = try
            FileManager.default.url(for: .documentDirectory,
                                    in: .userDomainMask,
                                    appropriateFor: nil,
                                    create: false)
        let savedURL = documentsURL.appendingPathComponent(fileURL.lastPathComponent)
        try FileManager.default.moveItem(at: fileURL, to: savedURL)
    } catch {
        print ("file error: \(error)")
    }
}
downloadTask.resume()

MySQL SELECT DISTINCT multiple columns

Another simple way to do it is with concat()

SELECT DISTINCT(CONCAT(a,b)) AS cc FROM my_table GROUP BY (cc);

Webpack - webpack-dev-server: command not found

I had the same issue but the below steps helped me to get out of it.

  1. Installing the 'webpack-dev-server' locally (In the project directory as it was not picking from the global installation)

    npm install --save webpack-dev-server

Can verify whether 'webpack-dev-server' folder exists inside node_modules.

  1. Running using npx for running directly

npx webpack-dev-server --mode development --config ./webpack.dev.js

npm run start also works fine where your entry in package.json scripts should be like the above like without npx.

Convert row to column header for Pandas DataFrame,

To rename the header without reassign df:

df.rename(columns=df.iloc[0], inplace = True)

To drop the row without reassign df:

df.drop(df.index[0], inplace = True)

Convert javascript object or array to json for ajax data

I'm not entirely sure but I think you are probably surprised at how arrays are serialized in JSON. Let's isolate the problem. Consider following code:

var display = Array();
display[0] = "none";
display[1] = "block";
display[2] = "none";

console.log( JSON.stringify(display) );

This will print:

["none","block","none"]

This is how JSON actually serializes array. However what you want to see is something like:

{"0":"none","1":"block","2":"none"}

To get this format you want to serialize object, not array. So let's rewrite above code like this:

var display2 = {};
display2["0"] = "none";
display2["1"] = "block";
display2["2"] = "none";

console.log( JSON.stringify(display2) );

This will print in the format you want.

You can play around with this here: http://jsbin.com/oDuhINAG/1/edit?js,console

What happens to a declared, uninitialized variable in C? Does it have a value?

0 if static or global, indeterminate if storage class is auto

C has always been very specific about the initial values of objects. If global or static, they will be zeroed. If auto, the value is indeterminate.

This was the case in pre-C89 compilers and was so specified by K&R and in DMR's original C report.

This was the case in C89, see section 6.5.7 Initialization.

If an object that has automatic storage duration is not initialized explicitely, its value is indeterminate. If an object that has static storage duration is not initialized explicitely, it is initialized implicitely as if every member that has arithmetic type were assigned 0 and every member that has pointer type were assigned a null pointer constant.

This was the case in C99, see section 6.7.8 Initialization.

If an object that has automatic storage duration is not initialized explicitly, its value is indeterminate. If an object that has static storage duration is not initialized explicitly, then:
— if it has pointer type, it is initialized to a null pointer;
— if it has arithmetic type, it is initialized to (positive or unsigned) zero;
— if it is an aggregate, every member is initialized (recursively) according to these rules;
— if it is a union, the first named member is initialized (recursively) according to these rules.

As to what exactly indeterminate means, I'm not sure for C89, C99 says:

3.17.2
indeterminate value

either an unspecified value or a trap representation

But regardless of what standards say, in real life, each stack page actually does start off as zero, but when your program looks at any auto storage class values, it sees whatever was left behind by your own program when it last used those stack addresses. If you allocate a lot of auto arrays you will see them eventually start neatly with zeroes.

You might wonder, why is it this way? A different SO answer deals with that question, see: https://stackoverflow.com/a/2091505/140740

How can I strip first X characters from string using sed?

Well, there have been solutions here with sed, awk, cut and using bash syntax. I just want to throw in another POSIX conform variant:

$ echo "pid: 1234" | tail -c +6
1234

-c tells tail at which byte offset to start, counting from the end of the input data, yet if the the number starts with a + sign, it is from the beginning of the input data to the end.

Pandas group-by and sum

Use GroupBy.sum:

df.groupby(['Fruit','Name']).sum()

Out[31]: 
               Number
Fruit   Name         
Apples  Bob        16
        Mike        9
        Steve      10
Grapes  Bob        35
        Tom        87
        Tony       15
Oranges Bob        67
        Mike       57
        Tom        15
        Tony        1

How to import existing Android project into Eclipse?

Same problem happened to me as well and the .project file was not there in the project. I copied a .project file from an existing android project and replace the project name with the name of the project I am trying to import. Then using File -> Import -> Existing projects into workspace I was able to import the project.

Git - How to close commit editor?

Not sure the key combination that gets you there to the > prompt but it is not a bash prompt that I know. I usually get it by accident. Ctrl+C (or D) gets me back to the $ prompt.

How do I use CMake?

Regarding CMake 3.13.3, platform Windows, and IDE Visual Studio 2017, I suggest this guide. In brief I suggest:
1. Download cmake > unzip it > execute it.
2. As example download GLFW > unzip it > create inside folder Build.
3. In cmake Browse "Source" > Browse "Build" > Configure and Generate.
4. In Visual Studio 2017 Build your Solution.
5. Get the binaries.
Regards.

How to use executables from a package installed locally in node_modules?

UPDATE: As Seyeong Jeong points out in their answer below, since npm 5.2.0 you can use npx [command], which is more convenient.

OLD ANSWER for versions before 5.2.0:

The problem with putting

./node_modules/.bin

into your PATH is that it only works when your current working directory is the root of your project directory structure (i.e. the location of node_modules)

Independent of what your working directory is, you can get the path of locally installed binaries with

npm bin

To execute a locally installed coffee binary independent of where you are in the project directory hierarchy you can use this bash construct

PATH=$(npm bin):$PATH coffee

I aliased this to npm-exec

alias npm-exec='PATH=$(npm bin):$PATH'

So, now I can

npm-exec coffee

to run the correct copy of coffee no matter of where I am

$ pwd
/Users/regular/project1

$ npm-exec which coffee
/Users/regular/project1/node_modules/.bin/coffee

$ cd lib/
$ npm-exec which coffee
/Users/regular/project1/node_modules/.bin/coffee

$ cd ~/project2
$ npm-exec which coffee
/Users/regular/project2/node_modules/.bin/coffee

Java output formatting for Strings

For decimal values you can use DecimalFormat

import java.text.*;

public class DecimalFormatDemo {

   static public void customFormat(String pattern, double value ) {
      DecimalFormat myFormatter = new DecimalFormat(pattern);
      String output = myFormatter.format(value);
      System.out.println(value + "  " + pattern + "  " + output);
   }

   static public void main(String[] args) {

      customFormat("###,###.###", 123456.789);
      customFormat("###.##", 123456.789);
      customFormat("000000.000", 123.78);
      customFormat("$###,###.###", 12345.67);  
   }
}

and output will be:

123456.789  ###,###.###   123,456.789
123456.789  ###.##        123456.79
123.78      000000.000    000123.780
12345.67    $###,###.###  $12,345.67

For more details look here:

http://docs.oracle.com/javase/tutorial/java/data/numberformat.html

How to convert a unix timestamp (seconds since epoch) to Ruby DateTime?

DateTime.strptime can handle seconds since epoch. The number must be converted to a string:

require 'date'
DateTime.strptime("1318996912",'%s')

Generating a SHA-256 hash from the Linux command line

I believe that echo outputs a trailing newline. Try using -n as a parameter to echo to skip the newline.

How to align LinearLayout at the center of its parent?

This worked for me.. adding empty view ..

<LinearLayout
       android:layout_width="match_parent"
        android:layout_height="wrap_content"
       android:layout_gravity="center_horizontal"
        android:orientation="horizontal"
         >
<View
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_weight="1"
            />  
     <com.google.android.gms.ads.AdView

         android:id="@+id/adView"
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"

         android:layout_gravity="center_horizontal"
         ads:adSize="BANNER"
         ads:adUnitId="@string/banner_ad_unit_id" >

    </com.google.android.gms.ads.AdView>
    <View
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_weight="1"
            />  
    </LinearLayout>

Handling a Menu Item Click Event - Android

Replace Your onOptionsItemSelected as:

  @Override
          public boolean onOptionsItemSelected(MenuItem item) {
            switch (item.getItemId()) {
              case OK_MENU_ITEM:
                 startActivity(new Intent(DashboardActivity.this, SettingActivity.class));
                 break;

            // You can handle other cases Here.
              default: 
                 super.onOptionsItemSelected(item);
            }
          }

Here, I want to navigate from DashboardActivity to SettingActivity.

Reference to non-static member function must be called

The problem is that buttonClickedEvent is a member function and you need a pointer to member in order to invoke it.

Try this:

void (MyClass::*func)(int);
func = &MyClass::buttonClickedEvent;

And then when you invoke it, you need an object of type MyClass to do so, for example this:

(this->*func)(<argument>);

http://www.codeguru.com/cpp/cpp/article.php/c17401/C-Tutorial-PointertoMember-Function.htm

Get full URL and query string in Servlet for both HTTP and HTTPS requests

By design, getRequestURL() gives you the full URL, missing only the query string.

In HttpServletRequest, you can get individual parts of the URI using the methods below:

// Example: http://myhost:8080/people?lastname=Fox&age=30

String uri = request.getScheme() + "://" +   // "http" + "://
             request.getServerName() +       // "myhost"
             ":" +                           // ":"
             request.getServerPort() +       // "8080"
             request.getRequestURI() +       // "/people"
             "?" +                           // "?"
             request.getQueryString();       // "lastname=Fox&age=30"
  • .getScheme() will give you "https" if it was a https://domain request.
  • .getServerName() gives domain on http(s)://domain.
  • .getServerPort() will give you the port.

Use the snippet below:

String uri = request.getScheme() + "://" +
             request.getServerName() + 
             ("http".equals(request.getScheme()) && request.getServerPort() == 80 || "https".equals(request.getScheme()) && request.getServerPort() == 443 ? "" : ":" + request.getServerPort() ) +
             request.getRequestURI() +
            (request.getQueryString() != null ? "?" + request.getQueryString() : "");

This snippet above will get the full URI, hiding the port if the default one was used, and not adding the "?" and the query string if the latter was not provided.


Proxied requests

Note, that if your request passes through a proxy, you need to look at the X-Forwarded-Proto header since the scheme might be altered:

request.getHeader("X-Forwarded-Proto")

Also, a common header is X-Forwarded-For, which show the original request IP instead of the proxys IP.

request.getHeader("X-Forwarded-For")

If you are responsible for the configuration of the proxy/load balancer yourself, you need to ensure that these headers are set upon forwarding.

How can I select an element with multiple classes in jQuery?

your code $(".a, .b") will work for below multiple elements (at a same time)

<element class="a">
<element class="b">

if you want to select element having a and b both class like <element class="a b"> than use js without coma

$('.a.b')

How to exclude records with certain values in sql select

One way:

SELECT DISTINCT sc.StoreId
FROM StoreClients sc
WHERE NOT EXISTS(
    SELECT * FROM StoreClients sc2 
    WHERE sc2.StoreId = sc.StoreId AND sc2.ClientId = 5)

Remove border from IFrame

You can use style="border:0;" in your iframe code. That is the recommended way to remove border in HTML5.

Check out my html5 iframe generator tool to customize your iframe without editing code.

Replacing backslashes with forward slashes with str_replace() in php

You need to escape backslash with a \

  $str = str_replace ("\\", "/", $str);

How to drop a list of rows from Pandas dataframe?

In a comment to @theodros-zelleke's answer, @j-jones asked about what to do if the index is not unique. I had to deal with such a situation. What I did was to rename the duplicates in the index before I called drop(), a la:

dropped_indexes = <determine-indexes-to-drop>
df.index = rename_duplicates(df.index)
df.drop(df.index[dropped_indexes], inplace=True)

where rename_duplicates() is a function I defined that went through the elements of index and renamed the duplicates. I used the same renaming pattern as pd.read_csv() uses on columns, i.e., "%s.%d" % (name, count), where name is the name of the row and count is how many times it has occurred previously.

curl: (6) Could not resolve host: google.com; Name or service not known

Perhaps you have some very weird and restrictive SELinux rules in place?

If not, try strace -o /tmp/wtf -fF curl -v google.com and try to spot from /tmp/wtf output file what's going on.

What is the difference between map and flatMap and a good use case for each?

RDD.map returns all elements in single array

RDD.flatMap returns elements in Arrays of array

let's assume we have text in text.txt file as

Spark is an expressive framework
This text is to understand map and faltMap functions of Spark RDD

Using map

val text=sc.textFile("text.txt").map(_.split(" ")).collect

output:

text: **Array[Array[String]]** = Array(Array(Spark, is, an, expressive, framework), Array(This, text, is, to, understand, map, and, faltMap, functions, of, Spark, RDD))

Using flatMap

val text=sc.textFile("text.txt").flatMap(_.split(" ")).collect

output:

 text: **Array[String]** = Array(Spark, is, an, expressive, framework, This, text, is, to, understand, map, and, faltMap, functions, of, Spark, RDD)

How to connect Bitbucket to Jenkins properly

I had this problem and it turned out the issue was that I had named my repository with CamelCase. Bitbucket automatically changes the URL of your repository to be all lower case and that gets sent to Jenkins in the webhook. Jenkins then searches for projects with a matching repository. If you, like me, have CamelCase in your repository URL in your project configuration you will be able to check out code, but the pattern matching on the webhook request will fail.

Just change your repo URL to be all lower case instead of CamelCase and the pattern match should find your project.

How do you handle multiple submit buttons in ASP.NET MVC Framework?

This script allows to specify a data-form-action attribute which will work as the HTML5 formaction attribute in all browsers (in an unobtrusive way):

$(document).on('click', '[type="submit"][data-form-action]', function(event) {
    var $this = $(this),
    var formAction = $this.attr('data-form-action'),
    $form = $($this.closest('form'));
    $form.attr('action', formAction);             
});

The form containing the button will be posted to the URL specified in the data-form-action attribute:

<button type="submit" data-form-action="different/url">Submit</button>   

This requires jQuery 1.7. For previous versions you should use live() instead of on().

PDF to image using Java

jPDFImages is not free but a commercial library which converts PDF pages to images in JPEG, TIFF or PNG format. The output image size is customizable.

Netbeans - class does not have a main method

If you named your class with the keyword in Java, your program wouldn't be recognized that it had the main method.

How do I protect javascript files?

You can also set up a mime type for application/JavaScript to run as PHP, .NET, Java, or whatever language you're using. I've done this for dynamic CSS files in the past.

case statement in where clause - SQL Server

You don't need case in the where statement, just use parentheses and or:

Select * From Times
WHERE StartDate <= @Date AND EndDate >= @Date
AND (
    (@day = 'Monday' AND Monday = 1)
    OR (@day = 'Tuesday' AND Tuesday = 1)
    OR Wednesday = 1
)

Additionally, your syntax is wrong for a case. It doesn't append things to the string--it returns a single value. You'd want something like this, if you were actually going to use a case statement (which you shouldn't):

Select * From Times
WHERE (StartDate <= @Date) AND (EndDate >= @Date)
AND 1 = CASE WHEN @day = 'Monday' THEN Monday
             WHEN @day = 'Tuesday' THEN Tuesday
             ELSE Wednesday
        END 

And just for an extra umph, you can use the between operator for your date:

where @Date between StartDate and EndDate

Making your final query:

select
    * 
from 
    Times
where
    @Date between StartDate and EndDate
    and (
        (@day = 'Monday' and Monday = 1)
        or (@day = 'Tuesday' and Tuesday = 1)
        or Wednesday = 1
    )

Create table (structure) from existing table

SELECT * INTO newtable
from Oldtable

What is the difference between exit and return?

the return statement exits from the current function and exit() exits from the program

they are the same when used in main() function

also return is a statement while exit() is a function which requires stdlb.h header file

Reading a simple text file

Having a file in your assets folder requires you to use this piece of code in order to get files from the assets folder:

yourContext.getAssets().open("test.txt");

In this example, getAssets() returns an AssetManager instance and then you're free to use whatever method you want from the AssetManager API.

Repository access denied. access via a deployment key is read-only

First confusion on my side was about where exactly to set SSH Keys in BitBucket.

I am new to BitBucket and I was setting a Deployment Key which gives read-access only.

So make sure you are setting your rsa pub key in your BitBucket Account Settings.

Click your BitBucket avatar and select Bitbucket Settings(Manage account). There you'll be able to set SSH Keys.

I simply deleted the Deployment Key, I don't need any for now. And it worked

enter image description here

Gmail: 530 5.5.1 Authentication Required. Learn more at

You need turn on the POP mail and IMAP mail feature in setting of the email you are using to send mail. Good luck!

Call Stored Procedure within Create Trigger in SQL Server

I think you will have to loop over the "inserted" table, which contains all rows that were updated. You can use a WHERE loop, or a WITH statement if your primary key is a GUID. This is the simpler (for me) to write, so here is my example. We use this approach, so I know for a fact it works fine.

ALTER TRIGGER [dbo].[RA2Newsletter] ON [dbo].[Reiseagent]
    AFTER INSERT
AS
        -- This is your primary key.  I assume INT, but initialize
        -- to minimum value for the type you are using.
        DECLARE @rAgent_ID INT = 0

        -- Looping variable.
        DECLARE @i INT = 0

        -- Count of rows affected for looping over
        DECLARE @count INT

        -- These are your old variables.
        DECLARE @rAgent_Name NVARCHAR(50)
        DECLARE @rAgent_Email NVARCHAR(50)
        DECLARE @rAgent_IP NVARCHAR(50)
        DECLARE @hotelID INT
        DECLARE @retval INT

    BEGIN 
        SET NOCOUNT ON ;

        -- Get count of affected rows
        SELECT  @Count = Count(rAgent_ID)
        FROM    inserted

        -- Loop over rows affected
        WHILE @i < @count
            BEGIN
                -- Get the next rAgent_ID
                SELECT TOP 1
                        @rAgent_ID = rAgent_ID
                FROM    inserted
                WHERE   rAgent_ID > @rAgent_ID
                ORDER BY rAgent_ID ASC

                -- Populate values for the current row
                SELECT  @rAgent_Name = rAgent_Name,
                        @rAgent_Email = rAgent_Email,
                        @rAgent_IP = rAgent_IP,
                        @hotelID = hotelID
                FROM    Inserted
                WHERE   rAgent_ID = @rAgent_ID

                -- Run your stored procedure
                EXEC insert2Newsletter '', '', @rAgent_Name, @rAgent_Email,
                    @rAgent_IP, @hotelID, 'RA', @retval 

                -- Set up next iteration
                SET @i = @i + 1
            END
    END 
GO

I sure hope this helps you out. Cheers!

How do I get the collection of Model State Errors in ASP.NET MVC?

Got this from BrockAllen's answer that worked for me, it displays the keys that have errors:

    var errors =
    from item in ModelState
    where item.Value.Errors.Count > 0
    select item.Key;
    var keys = errors.ToArray();

Source: https://forums.asp.net/t/1805163.aspx?Get+the+Key+value+of+the+Model+error

php multidimensional array get values

This is the way to iterate on this array:

foreach($hotels as $row) {
       foreach($row['rooms'] as $k) {
             echo $k['boards']['board_id'];
             echo $k['boards']['price'];
       }
}

You want to iterate on the hotels and the rooms (the ones with numeric indexes), because those seem to be the "collections" in this case. The other arrays only hold and group properties.

How to detect a loop in a linked list?

You can make use of Floyd's cycle-finding algorithm, also known as tortoise and hare algorithm.

The idea is to have two references to the list and move them at different speeds. Move one forward by 1 node and the other by 2 nodes.

  • If the linked list has a loop they will definitely meet.
  • Else either of the two references(or their next) will become null.

Java function implementing the algorithm:

boolean hasLoop(Node first) {

    if(first == null) // list does not exist..so no loop either
        return false;

    Node slow, fast; // create two references.

    slow = fast = first; // make both refer to the start of the list

    while(true) {

        slow = slow.next;          // 1 hop

        if(fast.next != null)
            fast = fast.next.next; // 2 hops
        else
            return false;          // next node null => no loop

        if(slow == null || fast == null) // if either hits null..no loop
            return false;

        if(slow == fast) // if the two ever meet...we must have a loop
            return true;
    }
}

Add left/right horizontal padding to UILabel

Subclass UILabel and override drawTextInRect: like this:

- (void)drawTextInRect:(CGRect)rect 
{
    UIEdgeInsets insets = {0, 10, 0, 0};
    return [super drawTextInRect:UIEdgeInsetsInsetRect(rect, insets)];
}

Convert a number range to another range, maintaining ratio

Actually there are some cases that above answers would break. Such as wrongly input value, wrongly input range, negative input/output ranges.

def remap( x, oMin, oMax, nMin, nMax ):

    #range check
    if oMin == oMax:
        print "Warning: Zero input range"
        return None

    if nMin == nMax:
        print "Warning: Zero output range"
        return None

    #check reversed input range
    reverseInput = False
    oldMin = min( oMin, oMax )
    oldMax = max( oMin, oMax )
    if not oldMin == oMin:
        reverseInput = True

    #check reversed output range
    reverseOutput = False   
    newMin = min( nMin, nMax )
    newMax = max( nMin, nMax )
    if not newMin == nMin :
        reverseOutput = True

    portion = (x-oldMin)*(newMax-newMin)/(oldMax-oldMin)
    if reverseInput:
        portion = (oldMax-x)*(newMax-newMin)/(oldMax-oldMin)

    result = portion + newMin
    if reverseOutput:
        result = newMax - portion

    return result

#test cases
print remap( 25.0, 0.0, 100.0, 1.0, -1.0 ), "==", 0.5
print remap( 25.0, 100.0, -100.0, -1.0, 1.0 ), "==", -0.25
print remap( -125.0, -100.0, -200.0, 1.0, -1.0 ), "==", 0.5
print remap( -125.0, -200.0, -100.0, -1.0, 1.0 ), "==", 0.5
#even when value is out of bound
print remap( -20.0, 0.0, 100.0, 0.0, 1.0 ), "==", -0.2

Why does git revert complain about a missing -m option?

By default git revert refuses to revert a merge commit as what that actually means is ambiguous. I presume that your HEAD is in fact a merge commit.

If you want to revert the merge commit, you have to specify which parent of the merge you want to consider to be the main trunk, i.e. what you want to revert to.

Often this will be parent number one, for example if you were on master and did git merge unwanted and then decided to revert the merge of unwanted. The first parent would be your pre-merge master branch and the second parent would be the tip of unwanted.

In this case you could do:

git revert -m 1 HEAD

Why es6 react component works only with "export default"?

Exporting without default means it's a "named export". You can have multiple named exports in a single file. So if you do this,

class Template {}
class AnotherTemplate {}

export { Template, AnotherTemplate }

then you have to import these exports using their exact names. So to use these components in another file you'd have to do,

import {Template, AnotherTemplate} from './components/templates'

Alternatively if you export as the default export like this,

export default class Template {}

Then in another file you import the default export without using the {}, like this,

import Template from './components/templates'

There can only be one default export per file. In React it's a convention to export one component from a file, and to export it is as the default export.

You're free to rename the default export as you import it,

import TheTemplate from './components/templates'

And you can import default and named exports at the same time,

import Template,{AnotherTemplate} from './components/templates'

What is the difference between pull and clone in git?

Hmm, what's missing to see the remote branch "4.2" when I pull, as I do when I clone? Something's clearly not identical.

tmp$  mkdir some_repo

tmp$  cd some_repo

some_repo$  git init
Initialized empty Git repository in /tmp/some_repo/.git/

some_repo$  git pull https://github.ourplace.net/babelfish/some_repo.git
  :
From https://github.ourplace.net/babelfish/some_repo
 * branch            HEAD       -> FETCH_HEAD

some_repo$  git branch
* master

vs

tmp$  rm -rf some_repo

tmp$  git clone https://github.ourplace.net/babelfish/some_repo.git
Cloning into 'some_repo'...
  :
Checking connectivity... done.

tmp$  cd some_repo

some_repo$  git branch
* 4.2

JSON character encoding - is UTF-8 well-supported by browsers or should I use numeric escape sequences?

I had a similar problem with é char... I think the comment "it's possible that the text you're feeding it isn't UTF-8" is probably close to the mark here. I have a feeling the default collation in my instance was something else until I realized and changed to utf8... problem is the data was already there, so not sure if it converted the data or not when i changed it, displays fine in mysql workbench. End result is that php will not json encode the data, just returns false. Doesn't matter what browser you use as its the server causing my issue, php will not parse the data to utf8 if this char is present. Like i say not sure if it is due to converting the schema to utf8 after data was present or just a php bug. In this case use json_encode(utf8_encode($string));

Best way to access web camera in Java

I think the project you are looking for is: https://github.com/sarxos/webcam-capture (I'm the author)

There is an example working exactly as you've described - after it's run, the window appear where, after you press "Start" button, you can see live image from webcam device and save it to file after you click on "Snapshot" (source code available, please note that FPS counter in the corner can be disabled):

snapshot

The project is portable (WinXP, Win7, Win8, Linux, Mac, Raspberry Pi) and does not require any additional software to be installed on the PC.

API is really nice and easy to learn. Example how to capture single image and save it to PNG file:

Webcam webcam = Webcam.getDefault();
webcam.open();
ImageIO.write(webcam.getImage(), "PNG", new File("test.png"));

VueJS conditionally add an attribute for an element

In html use

<input :required="condition" />

And define in data property like

data () {
   return {
      condition: false
   }
}

Convert base64 string to image

  public Optional<String> InputStreamToBase64(Optional<InputStream> inputStream) throws IOException{
    if (inputStream.isPresent()) {
        ByteArrayOutputStream outpString base64Image = data.split(",")[1];
byte[] imageBytes = javax.xml.bind.DatatypeConverter.parseBase64Binary(base64Image);

Then you can do whatever you like with the bytes like:

BufferedImage img = ImageIO.read(new ByteArrayInputStream(imageBytes));ut = new ByteArrayOutputStream();
        FileCopyUtils.copy(inputStream.get(), output);
        //TODO retrieve content type from file, & replace png below with it
        return Optional.ofNullable("data:image/png;base64," + DatatypeConverter.printBase64Binary(output.toByteArray()));
    }

    return Optional.empty();

How to get a product's image in Magento?

// Let's load the category Model and grab the product collection of that category

$product_collection = Mage::getModel('catalog/category')->load($categoryId)->getProductCollection();

// Now let's loop through the product collection and print the ID of every product 
foreach($product_collection as $product) {
  // Get the product ID

$product_id = $product->getId();

  // Load the full product model based on the product ID

$full_product = Mage::getModel('catalog/product')->load($product_id);

  // Now that we loaded the full product model, let's access all of it's data

  // Let's get the Product Name

  $product_name = $full_product->getName();

  // Let's get the Product URL path

  $product_url = $full_product->getProductUrl();

  // Let's get the Product Image URL

  $product_image_url = $full_product->getImageUrl();

  // Let's print the product information we gathered and continue onto the next one

 echo $product_name;

  echo $product_image_url;


}

How to crop an image using C#?

Here's a simple example on cropping an image

public Image Crop(string img, int width, int height, int x, int y)
{
    try
    {
        Image image = Image.FromFile(img);
        Bitmap bmp = new Bitmap(width, height, PixelFormat.Format24bppRgb);
        bmp.SetResolution(80, 60);

        Graphics gfx = Graphics.FromImage(bmp);
        gfx.SmoothingMode = SmoothingMode.AntiAlias;
        gfx.InterpolationMode = InterpolationMode.HighQualityBicubic;
        gfx.PixelOffsetMode = PixelOffsetMode.HighQuality;
        gfx.DrawImage(image, new Rectangle(0, 0, width, height), x, y, width, height, GraphicsUnit.Pixel);
        // Dispose to free up resources
        image.Dispose();
        bmp.Dispose();
        gfx.Dispose();

        return bmp;
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
        return null;
    }            
}

Access cell value of datatable

foreach(DataRow row in dt.Rows)
{
    string value = row[3].ToString();
}

ERROR 1064 (42000): You have an error in your SQL syntax; Want to configure a password as root being the user

From the mysql documentation version: 8.0.18:

A superuser account 'root'@'localhost' is created. A password for the superuser is set and stored in the error log file. To reveal it, use the following command: shell> sudo grep 'temporary password' /var/log/mysqld.log Change the root password as soon as possible by logging in with the generated, temporary password and set a custom password for the superuser account:

shell> mysql -uroot -p
mysql> ALTER USER 'root'@'localhost' IDENTIFIED BY 'MyNewPass4!';

Using a different font with twitter bootstrap

First of all you have to include your font in your website (or your CSS, to be more specific) using an appropriate @font-face rule.
From here on there are multiple ways to proceed. One thing I would not do is to edit the bootstrap.css directly - since once you get a newer version your changes will be lost. You do however have the possibility to customize your bootstrap files (there's a customize page on their website). Just enter the name of your font with all the fallback names into the corresponding typography textbox. Of course you will have to do this whenever you get a new or updated version of your bootstrap files.
Another chance you have is to overwrite the bootstrap rules within a different stylesheet. If you do this you just have to use selectors that are as specific as (or more specific than) the bootstrap selectors.
Side note: If you care about browser support a single EOT version of your font might not be sufficient. See http://caniuse.com/eot for a support table.

How do browser cookie domains work?

Will www.example.com be able to set cookie for .com?

No, but example.com.fr may be able to set a cookie for example2.com.fr. Firefox protects against this by maintaining a list of TLDs: http://securitylabs.websense.com/content/Blogs/3108.aspx

Apparently Internet Explorer doesn't allow two-letter domains to set cookies, which I suppose explains why o2.ie simply redirects to o2online.ie. I'd often wondered that.

Replace specific text with a redacted version using Python

You can do it using named-entity recognition (NER). It's fairly simple and there are out-of-the-shelf tools out there to do it, such as spaCy.

NER is an NLP task where a neural network (or other method) is trained to detect certain entities, such as names, places, dates and organizations.

Example:

Sponge Bob went to South beach, he payed a ticket of $200!
I know, Michael is a good person, he goes to McDonalds, but donates to charity at St. Louis street.

Returns:

NER with spacy

Just be aware that this is not 100%!

Here are a little snippet for you to try out:

import spacy

phrases = ['Sponge Bob went to South beach, he payed a ticket of $200!', 'I know, Michael is a good person, he goes to McDonalds, but donates to charity at St. Louis street.']
nlp = spacy.load('en')
for phrase in phrases:
   doc = nlp(phrase)
   replaced = ""
   for token in doc:
      if token in doc.ents:
         replaced+="XXXX "
      else:
         replaced+=token.text+" "

Read more here: https://spacy.io/usage/linguistic-features#named-entities

You could, instead of replacing with XXXX, replace based on the entity type, like:

if ent.label_ == "PERSON":
   replaced += "<PERSON> "

Then:

import re, random

personames = ["Jack", "Mike", "Bob", "Dylan"]

phrase = re.replace("<PERSON>", random.choice(personames), phrase)

Validate phone number using javascript

_x000D_
_x000D_
function validatePhone(inputtxt) {_x000D_
  var phoneno = /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/;_x000D_
  return phoneno.test(inputtxt)_x000D_
}
_x000D_
_x000D_
_x000D_

Get the last inserted row ID (with SQL statement)

If your SQL Server table has a column of type INT IDENTITY (or BIGINT IDENTITY), then you can get the latest inserted value using:

INSERT INTO dbo.YourTable(columns....)
   VALUES(..........)

SELECT SCOPE_IDENTITY()

This works as long as you haven't inserted another row - it just returns the last IDENTITY value handed out in this scope here.

There are at least two more options - @@IDENTITY and IDENT_CURRENT - read more about how they works and in what way they're different (and might give you unexpected results) in this excellent blog post by Pinal Dave here.

Tried to Load Angular More Than Once

I had a similar issue, and for me the issue was due to some missing semicolons in the controller. The minification of the app was probably causing the code to execute incorrectly (most likely the resulting code was causing state mutations, which causes the view to render, and then the controller executes the code again, and so on recursively).

Python Flask, how to set content type

As simple as this

x = "some data you want to return"
return x, 200, {'Content-Type': 'text/css; charset=utf-8'}

Hope it helps

Update: Use this method because it will work with both python 2.x and python 3.x

and secondly it also eliminates multiple header problem.

from flask import Response
r = Response(response="TEST OK", status=200, mimetype="application/xml")
r.headers["Content-Type"] = "text/xml; charset=utf-8"
return r

How to clear Tkinter Canvas?

Every canvas item is an object that Tkinter keeps track of. If you are clearing the screen by just drawing a black rectangle, then you effectively have created a memory leak -- eventually your program will crash due to the millions of items that have been drawn.

To clear a canvas, use the delete method. Give it the special parameter "all" to delete all items on the canvas (the string "all"" is a special tag that represents all items on the canvas):

canvas.delete("all")

If you want to delete only certain items on the canvas (such as foreground objects, while leaving the background objects on the display) you can assign tags to each item. Then, instead of "all", you could supply the name of a tag.

If you're creating a game, you probably don't need to delete and recreate items. For example, if you have an object that is moving across the screen, you can use the move or coords method to move the item.

Calling JMX MBean method from a shell script

Take a look at JManage. It's able to execute MBean methods and get / set attributes from command line.

Best practice to call ConfigureAwait for all server-side code

Brief answer to your question: No. You shouldn't call ConfigureAwait(false) at the application level like that.

TL;DR version of the long answer: If you are writing a library where you don't know your consumer and don't need a synchronization context (which you shouldn't in a library I believe), you should always use ConfigureAwait(false). Otherwise, the consumers of your library may face deadlocks by consuming your asynchronous methods in a blocking fashion. This depends on the situation.

Here is a bit more detailed explanation on the importance of ConfigureAwait method (a quote from my blog post):

When you are awaiting on a method with await keyword, compiler generates bunch of code in behalf of you. One of the purposes of this action is to handle synchronization with the UI (or main) thread. The key component of this feature is the SynchronizationContext.Current which gets the synchronization context for the current thread. SynchronizationContext.Current is populated depending on the environment you are in. The GetAwaiter method of Task looks up for SynchronizationContext.Current. If current synchronization context is not null, the continuation that gets passed to that awaiter will get posted back to that synchronization context.

When consuming a method, which uses the new asynchronous language features, in a blocking fashion, you will end up with a deadlock if you have an available SynchronizationContext. When you are consuming such methods in a blocking fashion (waiting on the Task with Wait method or taking the result directly from the Result property of the Task), you will block the main thread at the same time. When eventually the Task completes inside that method in the threadpool, it is going to invoke the continuation to post back to the main thread because SynchronizationContext.Current is available and captured. But there is a problem here: the UI thread is blocked and you have a deadlock!

Also, here are two great articles for you which are exactly for your question:

Finally, there is a great short video from Lucian Wischik exactly on this topic: Async library methods should consider using Task.ConfigureAwait(false).

Hope this helps.

How can I refresh or reload the JFrame?

Try this code. I also faced the same problem, but some how I solved it.

public class KitchenUserInterface {

    private JFrame frame;
    private JPanel main_panel, northpanel , southpanel;
    private JLabel label;
    private JButton nextOrder;
    private JList list;

    private static KitchenUserInterface kitchenRunner ;

    public void setList(String[] order){
        kitchenRunner.frame.dispose();
        kitchenRunner.frame.setVisible(false);
        kitchenRunner= new KitchenUserInterface(order);

    }

    public KitchenUserInterface getInstance() {
        if(kitchenRunner == null) {
            synchronized(KitchenUserInterface.class) {
                if(kitchenRunner == null) {
                    kitchenRunner = new KitchenUserInterface();
                }
            }
        }


        return this.kitchenRunner;
    }

    private KitchenUserInterface() {


        frame = new JFrame("Lullaby's Kitchen");
        main_panel = new JPanel();
        main_panel.setLayout(new BorderLayout());
        frame.setContentPane(main_panel);



        northpanel = new JPanel();
        northpanel.setLayout(new FlowLayout());


        label = new JLabel("Kitchen");

        northpanel.add(label);


        main_panel.add(northpanel , BorderLayout.NORTH);


        frame.setSize(500 , 500 );
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }

    private KitchenUserInterface (String[] order){
        this();
        list = new JList<String>(order);
        main_panel.add(list , BorderLayout.CENTER);

        southpanel = new JPanel();
         southpanel.setLayout(new FlowLayout());

         nextOrder = new JButton("Next Order Set");
         nextOrder.addActionListener(new OrderUpListener(list));
         southpanel.add(nextOrder);
         main_panel.add(southpanel, BorderLayout.SOUTH);



    }

    public static void main(String[] args) {
        KitchenUserInterface dat = kitchenRunner.getInstance();
        try{

        Thread.sleep(1500);
        System.out.println("Ready");
        dat.setList(OrderArray.getInstance().getOrders());
        }
        catch(Exception event) {
            System.out.println("Error sleep");
            System.out.println(event);
        }


        }

}

Make column fixed position in bootstrap

iterating over Ihab's answer, just using position:fixed and bootstraps col-offset you don't need to be specific on the width.

<div class="row">
    <div class="col-lg-3" style="position:fixed">
        Fixed content
    </div>
    <div class="col-lg-9 col-lg-offset-3">
        Normal scrollable content
    </div>
</div>

Uninstall all installed gems, in OSX?

The only command helped me to cleanup all gems and ignores default gems, which can't be uninstalled

for x in `gem list --no-versions`; do gem uninstall $x -a -x -I; done

How to convert Java String to JSON Object

@Nishit, JSONObject does not natively understand how to parse through a StringBuilder; instead you appear to be using the JSONObject(java.lang.Object bean) constructor to create the JSONObject, however passing it a StringBuilder.

See this link for more information on that particular constructor.

http://www.json.org/javadoc/org/json/JSONObject.html#JSONObject%28java.lang.Object%29

When a constructor calls for a java.lang.Object class, more than likely it's really telling you that you're expected to create your own class (since all Classes ultimately extend java.lang.Object) and that it will interface with that class in a specific way, albeit normally it will call for an interface instead (hence the name) OR it can accept any class and interface with it "abstractly" such as calling .toString() on it. Bottom line, you typically can't just pass it any class and expect it to work.

At any rate, this particular constructor is explained as such:

Construct a JSONObject from an Object using bean getters. It reflects on all of the public methods of the object. For each of the methods with no parameters and a name starting with "get" or "is" followed by an uppercase letter, the method is invoked, and a key and the value returned from the getter method are put into the new JSONObject. The key is formed by removing the "get" or "is" prefix. If the second remaining character is not upper case, then the first character is converted to lower case. For example, if an object has a method named "getName", and if the result of calling object.getName() is "Larry Fine", then the JSONObject will contain "name": "Larry Fine".

So, what this means is that it's expecting you to create your own class that implements get or is methods (i.e.

public String getName() {...}

or

public boolean isValid() {...}

So, to solve your problem, if you really want that higher level of control and want to do some manipulation (e.g. modify some values, etc.) but still use StringBuilder to dynamically generate the code, you can create a class that extends the StringBuilder class so that you can use the append feature, but implement get/is methods to allow JSONObject to pull the data out of it, however this is likely not what you want/need and depending on the JSON, you might spend a lot of time and energy creating the private fields and get/is methods (or use an IDE to do it for you) or it might be all for naught if you don't necessarily know the breakdown of the JSON string.

So, you can very simply call toString() on the StringBuilder which will provide a String representation of the StringBuilder instance and passing that to the JSONObject constructor, such as below:

...
StringBuilder jsonString = new StringBuilder();
while((readAPIResponse = br.readLine()) != null){
    jsonString.append(readAPIResponse);
}
JSONObject jsonObj = new JSONObject(jsonString.toString());
...

What is the path that Django uses for locating and loading templates?

Smart solution in Django 2.0.3 for keeping templates in project directory (/root/templates/app_name):

settings.py

BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TEMP_DIR = os.path.join(BASE_DIR, 'templates')
...
TEMPLATES = [
{
    'BACKEND': 'django.template.backends.django.DjangoTemplates',
    'DIRS': [TEMP_DIR],
...

in views.py just add such template path:

app_name/html_name

Using helpers in model: how do I include helper dependencies?

Just change the first line as follows :

include ActionView::Helpers

that will make it works.

UPDATE: For Rails 3 use:

ActionController::Base.helpers.sanitize(str)

Credit goes to lornc's answer

sprintf like functionality in Python

Two approaches are to write to a string buffer or to write lines to a list and join them later. I think the StringIO approach is more pythonic, but didn't work before Python 2.6.

from io import StringIO

with StringIO() as s:
   print("Hello", file=s)
   print("Goodbye", file=s)
   # And later...
   with open('myfile', 'w') as f:
       f.write(s.getvalue())

You can also use these without a ContextMananger (s = StringIO()). Currently, I'm using a context manager class with a print function. This fragment might be useful to be able to insert debugging or odd paging requirements:

class Report:
    ... usual init/enter/exit
    def print(self, *args, **kwargs):
        with StringIO() as s:
            print(*args, **kwargs, file=s)
            out = s.getvalue()
        ... stuff with out

with Report() as r:
   r.print(f"This is {datetime.date.today()}!", 'Yikes!', end=':')

How to check if $? is not equal to zero in unix shell scripting?

Try this after execution of your script :

if [ $? -ne 0 ];
then
//statements//
fi

How do you set the document title in React?

React Portals can let you render to elements outside the root React node (such at <title>), as if they were actual React nodes. So now you can set the title cleanly and without any additional dependencies:

Here's an example:

import React, { Component } from 'react';
import ReactDOM from 'react-dom';

class Title extends Component {
    constructor(props) {
        super(props);
        this.titleEl = document.getElementsByTagName("title")[0];
    }

    render() {
        let fullTitle;
        if(this.props.pageTitle) {
            fullTitle = this.props.pageTitle + " - " + this.props.siteTitle;
        } else {
            fullTitle = this.props.siteTitle;
        }

        return ReactDOM.createPortal(
            fullTitle || "",
            this.titleEl
        );
    }
}
Title.defaultProps = {
    pageTitle: null,
    siteTitle: "Your Site Name Here",
};

export default Title;

Just put the component in the page and set pageTitle:

<Title pageTitle="Dashboard" />
<Title pageTitle={item.name} />

Relationship between hashCode and equals method in Java

According to the doc, the default implementation of hashCode will return some integer that differ for every object

As much as is reasonably practical, the hashCode method defined by class Object does return distinct integers for distinct objects. (This is typically implemented by converting the internal address of the object into an integer, but this implementation
technique is not required by the JavaTM programming language.)

However some time you want the hash code to be the same for different object that have the same meaning. For example

Student s1 = new Student("John", 18);
Student s2 = new Student("John", 18);
s1.hashCode() != s2.hashCode(); // With the default implementation of hashCode

This kind of problem will be occur if you use a hash data structure in the collection framework such as HashTable, HashSet. Especially with collection such as HashSet you will end up having duplicate element and violate the Set contract.

Escaping quotes and double quotes

Using the backtick (`) works fine for me if I put them in the following places:

$cmd="\\server\toto.exe -batch=B -param=`"sort1;parmtxt='Security ID=1234'`""

$cmd returns as:

\\server\toto.exe -batch=B -param="sort1;parmtxt='Security ID=1234'"

Is that what you were looking for?

The error PowerShell gave me referred to an unexpected token 'sort1', and that's how I determined where to put the backticks.

The @' ... '@ syntax is called a "here string" and will return exactly what is entered. You can also use them to populate variables in the following fashion:

$cmd=@'
"\\server\toto.exe -batch=B -param="sort1;parmtxt='Security ID=1234'""
'@

The opening and closing symbols must be on their own line as shown above.

What are these ^M's that keep showing up in my files in emacs?

In git-config, set core.autocrlf to true to make git automatically convert line endings correctly for your platform, e.g. run this command for a global setting:

git config --global core.autocrlf true

Dynamic function name in javascript?

This is BEST solution, better then new Function('return function name(){}')().

Eval is fastest solution:

enter image description here

var name = 'FuncName'
var func = eval("(function " + name + "(){})")

Why should the static field be accessed in a static way?

Because when you access a static field, you should do so on the class (or in this case the enum). As in

MyUnits.MILLISECONDS;

Not on an instance as in

m.MILLISECONDS;

Edit To address the question of why: In Java, when you declare something as static, you are saying that it is a member of the class, not the object (hence why there is only one). Therefore it doesn't make sense to access it on the object, because that particular data member is associated with the class.

Aborting a stash pop in Git

Try using if tracked file.

git rm <path to file>
git reset  <path to file>
git checkout <path to file>

How to set a radio button in Android

For radioButton use

radio1.setChecked(true);

It does not make sense to have just one RadioButton. If you have more of them you need to uncheck others through

radio2.setChecked(false); ...

If your setting is just on/off use CheckBox.

AWS CLI S3 A client error (403) occurred when calling the HeadObject operation: Forbidden

Permissions

You need the s3:GetObject permission for this operation. For more information, see Specifying Permissions in a Policy. If the object you request does not exist, the error Amazon S3 returns depends on whether you also have the s3:ListBucket permission.

If you have the s3:ListBucket permission on the bucket, Amazon S3 returns an HTTP status code 404 ("no such key") error.

If you don’t have the s3:ListBucket permission, Amazon S3 returns an HTTP status code 403 ("access denied") error.

The following operation is related to HeadObject:

GetObject

Source: https://docs.aws.amazon.com/AmazonS3/latest/API/API_HeadObject.html