Programs & Examples On #Ipod touch

The iPod Touch (stylized and marketed as iPod touch) is a multi-purpose pocket computer designed and marketed by Apple Inc.

What are the sizes used for the iOS application splash screen?

As of July 2013 (iOS 6), this is what we always use:

IPHONE SPLASH 
Default.png - 320 x 480
[email protected] - 640 x 960 
[email protected] - 640 x 1096 (with status bar)
[email protected] - 640 x 1136 (without status bar)

IPAD SPLASH 
iPadImage-Appname-Portrait.png * 768w x 1004h (with status bar)
[email protected] * 1536w x 2008h (with status bar)
iPadImage-Appname-Landscape.png ** 1024w x 748h (with status bar)
[email protected] ** 2048w x 1496h (with status bar)

iPadImage-Appname-Portrait.png * 768w x 1024h (without status bar)
[email protected] * 1536w x 2048h (without status bar)
iPadImage-Appname-Landscape.png ** 1024w x 768h (without status bar)
[email protected] ** 2048w x 1536h (without status bar)

ICON
Appname-29.png
[email protected]
Appname-50.png
[email protected]
Appname-57.png
[email protected]
Appname-72.png
[email protected]
iTunesArtwork (512px x 512px)
iTunesArtwork@2x (1024px x 1024px)

Determine device (iPhone, iPod Touch) with iOS

I'd like to add that to retrieve the front and enclosure color of the device there's a private API:

UIDevice *device = [UIDevice currentDevice];
SEL selector = NSSelectorFromString([device.systemVersion hasPrefix:@"7"] ? @"_deviceInfoForKey:" :  @"deviceInfoForKey:");
if ([device respondsToSelector:selector]) {
    NSLog(@"DeviceColor: %@ DeviceEnclosureColor: %@", [device performSelector:selector withObject:@"DeviceColor"], [device performSelector:selector withObject:@"DeviceEnclosureColor"]);
}

I've blogged about this and provide a sample app:

http://www.futuretap.com/blog/device-colors/

jQuery/Javascript function to clear all the fields of a form

Note: this answer is relevant to resetting form fields, not clearing fields - see update.

You can use JavaScript's native reset() method to reset the entire form to its default state.

Example provided by Ryan:

$('#myForm')[0].reset();

Note: This may not reset certain fields, such as type="hidden".

UPDATE

As noted by IlyaDoroshin the same thing can be accomplished using jQuery's trigger():

$('#myForm').trigger("reset");

UPDATE

If you need to do more than reset the form to its default state, you should review the answers to Resetting a multi-stage form with jQuery.

Making an iframe responsive

The code below will make the fixed width content of a non-responsive website within an iframe resize to the viewport width, only if its width is larger than the viewport width. For demo purposes the website is a single image 800 pixels wide. You can test by resizing your browser window or load the page in your phone:

<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
body, html {width: 100%; height: 100%; margin: 0; padding: 0}
iframe {width: 100%; transform-origin: left top;}
.imgbox{text-align:center;display:block;}
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.11.1.js"></script>   
<script>
jQuery(document).ready(function($){
    nsZoomZoom(); 
    $(window).resize(function(){ 
        nsZoomZoom();
    });
    function nsZoomZoom(){
        htmlWidth = $('html').innerWidth();
        iframeWidth = 800;
        if (htmlWidth > iframeWidth)
            scale = 1;
        else {
            scale = htmlWidth / (iframeWidth); 
        }
        $("iframe").css('transform', 'scale(' + scale + ')');
        $("iframe").css('width', '800');
    } 
}); 
</script>
</head>
<body>
<div class=imgbox>
    <iframe src="http://placekitten.com/g/800/600" scrolling=no width=800 height=600 frameborder=no></iframe>
</div>
</body>

How to count the NaN values in a column in pandas DataFrame

You can use value_counts method and print values of np.nan

s.value_counts(dropna = False)[np.nan]

Removing the password from a VBA project

My 2 cents on Excel 2016:

  1. open the xls file with Notepad++
  2. Search for DPB= and replace it with DPx=
  3. Save the file
  4. Open the file, open the VB Editor, open modules will not work (error 40230)
  5. Save the file as xlsm
  6. It works

How do you kill a Thread in Java?

In Java threads are not killed, but the stopping of a thread is done in a cooperative way. The thread is asked to terminate and the thread can then shutdown gracefully.

Often a volatile boolean field is used which the thread periodically checks and terminates when it is set to the corresponding value.

I would not use a boolean to check whether the thread should terminate. If you use volatile as a field modifier, this will work reliable, but if your code becomes more complex, for instead uses other blocking methods inside the while loop, it might happen, that your code will not terminate at all or at least takes longer as you might want.

Certain blocking library methods support interruption.

Every thread has already a boolean flag interrupted status and you should make use of it. It can be implemented like this:

public void run() {
   try {
      while (!interrupted()) {
         // ...
      }
   } catch (InterruptedException consumed)
      /* Allow thread to exit */
   }
}

public void cancel() { interrupt(); }

Source code adapted from Java Concurrency in Practice. Since the cancel() method is public you can let another thread invoke this method as you wanted.

How to initialize log4j properly?

As per Apache Log4j FAQ page:

Why do I see a warning about "No appenders found for logger" and "Please configure log4j properly"?

This occurs when the default configuration files log4j.properties and log4j.xml can not be found and the application performs no explicit configuration. log4j uses Thread.getContextClassLoader().getResource() to locate the default configuration files and does not directly check the file system. Knowing the appropriate location to place log4j.properties or log4j.xml requires understanding the search strategy of the class loader in use. log4j does not provide a default configuration since output to the console or to the file system may be prohibited in some environments.

Basically the warning No appenders could be found for logger means that you're using log4j logging system, but you haven't added any Appenders (such as FileAppender, ConsoleAppender, SocketAppender, SyslogAppender, etc.) into your configuration file or the configuration file is missing.

There are three ways to configure log4j: with a properties file (log4j.properties), with an XML file and through Java code (rootLogger.addAppender(new NullAppender());).

log4j.properties

If you've property file present (e.g. when installing Solr), you need to place this file within your classpath directory.

classpath

Here are some command suggestions in Linux how to determine your classpath value:

$ echo $CLASSPATH
$ ps wuax | grep -i classpath
$ grep -Ri classpath /etc/tomcat? /var/lib/tomcat?/conf /usr/share/tomcat?

or from Java: System.getProperty("java.class.path").

Log4j XML

Below is a basic XML configuration file for log4j in XML format:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
  <appender name="console" class="org.apache.log4j.ConsoleAppender"> 
    <param name="Target" value="System.out"/> 
    <layout class="org.apache.log4j.PatternLayout"> 
      <param name="ConversionPattern" value="%-5p %c{1} - %m%n"/> 
    </layout> 
  </appender> 

  <root> 
    <priority value ="debug" /> 
    <appender-ref ref="console" /> 
  </root>
  
</log4j:configuration>

Tomcat

If you're using Tomcat, you may place your log4j.properties into: /usr/share/tomcat?/lib/ or /var/lib/tomcat?/webapps/*/WEB-INF/lib/ folder.

Solr

For the reference, Solr default log4j.properties file looks like:

#  Logging level
solr.log=logs/
log4j.rootLogger=INFO, file, CONSOLE

log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender

log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%-4r [%t] %-5p %c %x \u2013 %m%n

#- size rotation with log cleanup.
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.MaxFileSize=4MB
log4j.appender.file.MaxBackupIndex=9

#- File to log to and log format
log4j.appender.file.File=${solr.log}/solr.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%-5p - %d{yyyy-MM-dd HH:mm:ss.SSS}; %C; %m\n

log4j.logger.org.apache.zookeeper=WARN
log4j.logger.org.apache.hadoop=WARN

# set to INFO to enable infostream log messages
log4j.logger.org.apache.solr.update.LoggingInfoStream=OFF

Why can't log4j find my properties file in a J2EE or WAR application?

The short answer: the log4j classes and the properties file are not within the scope of the same classloader.

Log4j only uses the default Class.forName() mechanism for loading classes. Resources are handled similarly. See the documentation for java.lang.ClassLoader for more details.

So, if you're having problems, try loading the class or resource yourself. If you can't find it, neither will log4j. ;)


See also:

Visual Studio - How to change a project's folder name and solution name without breaking the solution

I found that these instructions were not enough. I also had to search through the code files for models, controllers, and views as well as the AppStart files to change the namespace.

Since I was copying my project not just renaming it, I also had to go into the applicationhost.config for IIS express and recreate the bindings using different port numbers and change the physical directory as well.

How to create a custom exception type in Java?

You have to define your exception elsewhere as a new class

public class YourCustomException extends Exception{

//Required inherited methods here
}

Then you can throw and catch YourCustomException as much as you'd like.

Javascript date.getYear() returns 111 in 2011?

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date/getYear

getYear is no longer used and has been replaced by the getFullYear method.

The getYear method returns the year minus 1900; thus:

  • For years greater than or equal to 2000, the value returned by getYear is 100 or greater. For example, if the year is 2026, getYear returns 126.
  • For years between and including 1900 and 1999, the value returned by getYear is between 0 and 99. For example, if the year is 1976, getYear returns 76.
  • For years less than 1900, the value returned by getYear is less than 0. For example, if the year is 1800, getYear returns -100.
  • To take into account years before and after 2000, you should use getFullYear instead of getYear so that the year is specified in full.

Error: invalid operands of types ‘const char [35]’ and ‘const char [2]’ to binary ‘operator+’

In line 2, there's a std::string involved (name). There are operations defined for char[] + std::string, std::string + char[], etc. "Hello " + name gives a std::string, which is added to " you are ", giving another string, etc.

In line 3, you're saying

char[] + char[] + char[]

and you can't just add arrays to each other.

Connection attempt failed with "ECONNREFUSED - Connection refused by server"

Use port number 22 (for sftp) instead of 21 (normal ftp). Solved this problem for me.

ESLint Parsing error: Unexpected token

In my case (im using Firebase Cloud Functions) i opened .eslintrc.json and changed:

"parserOptions": {
  // Required for certain syntax usages
  "ecmaVersion": 2017
},

to:

"parserOptions": {
  // Required for certain syntax usages
  "ecmaVersion": 2020
},

Explaining Python's '__enter__' and '__exit__'

I found it strangely difficult to locate the python docs for __enter__ and __exit__ methods by Googling, so to help others here is the link:

https://docs.python.org/2/reference/datamodel.html#with-statement-context-managers
https://docs.python.org/3/reference/datamodel.html#with-statement-context-managers
(detail is the same for both versions)

object.__enter__(self)
Enter the runtime context related to this object. The with statement will bind this method’s return value to the target(s) specified in the as clause of the statement, if any.

object.__exit__(self, exc_type, exc_value, traceback)
Exit the runtime context related to this object. The parameters describe the exception that caused the context to be exited. If the context was exited without an exception, all three arguments will be None.

If an exception is supplied, and the method wishes to suppress the exception (i.e., prevent it from being propagated), it should return a true value. Otherwise, the exception will be processed normally upon exit from this method.

Note that __exit__() methods should not reraise the passed-in exception; this is the caller’s responsibility.

I was hoping for a clear description of the __exit__ method arguments. This is lacking but we can deduce them...

Presumably exc_type is the class of the exception.

It says you should not re-raise the passed-in exception. This suggests to us that one of the arguments might be an actual Exception instance ...or maybe you're supposed to instantiate it yourself from the type and value?

We can answer by looking at this article:
http://effbot.org/zone/python-with-statement.htm

For example, the following __exit__ method swallows any TypeError, but lets all other exceptions through:

def __exit__(self, type, value, traceback):
    return isinstance(value, TypeError)

...so clearly value is an Exception instance.

And presumably traceback is a Python traceback object.

Importing Excel into a DataTable Quickly

MS Office Interop is slow and even Microsoft does not recommend Interop usage on server side and cannot be use to import large Excel files. For more details see why not to use OLE Automation from Microsoft point of view.

Instead, you can use any Excel library, like EasyXLS for example. This is a code sample that shows how to read the Excel file:

ExcelDocument workbook = new ExcelDocument();
DataSet ds = workbook.easy_ReadXLSActiveSheet_AsDataSet("excel.xls");
DataTable dataTable = ds.Tables[0];

If your Excel file has multiple sheets or for importing only ranges of cells (for better performances) take a look to more code samples on how to import Excel to DataTable in C# using EasyXLS.

Creating an iframe with given HTML dynamically

Allthough your src = encodeURI should work, I would have gone a different way:

var iframe = document.createElement('iframe');
var html = '<body>Foo</body>';
document.body.appendChild(iframe);
iframe.contentWindow.document.open();
iframe.contentWindow.document.write(html);
iframe.contentWindow.document.close();

As this has no x-domain restraints and is completely done via the iframe handle, you may access and manipulate the contents of the frame later on. All you need to make sure of is, that the contents have been rendered, which will (depending on browser type) start during/after the .write command is issued - but not nescessarily done when close() is called.

A 100% compatible way of doing a callback could be this approach:

<html><body onload="parent.myCallbackFunc(this.window)"></body></html>

Iframes has the onload event, however. Here is an approach to access the inner html as DOM (js):

iframe.onload = function() {
   var div=iframe.contentWindow.document.getElementById('mydiv');
};

Load content of a div on another page

Yes, see "Loading Page Fragments" on http://api.jquery.com/load/.

In short, you add the selector after the URL. For example:

$('#result').load('ajax/test.html #container');

Where Is Machine.Config?

You can run this in powershell:

[System.Runtime.InteropServices.RuntimeEnvironment]::SystemConfigurationFile

Which outputs this for .net 4:

C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config

Note however that this might change depending on whether .net is running as 32 or 64 bit which will result in \Framework\ or \Framework64\ respectively.

Accessing the index in 'for' loops?

If there is no duplicate value in the list:

for i in ints:
    indx = ints.index(i)
    print(i, indx)

iPhone 6 Plus resolution confusion: Xcode or Apple's website? for development

Check out this infographic: http://www.paintcodeapp.com/news/iphone-6-screens-demystified

It explains the differences between old iPhones, iPhone 6 and iPhone 6 Plus. You can see comparison of screen sizes in points, rendered pixels and physical pixels. You will also find answer to your question there:

iPhone 6 Plus - with Retina display HD. Scaling factor is 3 and the image is afterwards downscaled from rendered 2208 × 1242 pixels to 1920 × 1080 pixels.

The downscaling ratio is 1920 / 2208 = 1080 / 1242 = 20 / 23. That means every 23 pixels from the original render have to be mapped to 20 physical pixels. In other words the image is scaled down to approximately 87% of its original size.

Update:

There is an updated version of infographic mentioned above. It contains more detailed info about screen resolution differences and it covers all iPhone models so far, including 4 inch devices.

http://www.paintcodeapp.com/news/ultimate-guide-to-iphone-resolutions

Differences between Octave and MATLAB?

Rather than provide you with a complete list of differences, I'll give you my view on the matter.

If you read carefully the wiki page you provide, you'll often see sentences like "Octave supports both, while MATLAB requires the first" etc. This shows that Octave's developers try to make Octave syntax "superior" to MATLAB's.

This attitude makes Octave lose its purpose completely. The idea behind Octave is (or has become, I should say, see comments below) to have an open source alternative to run m-code. If it tries to be "better", it thus tries to be different, which is not in line with the reasons most people use it for. In my experience, running stuff developed in MATLAB doesn't ever work in one go, except for the really simple, really short stuff -- For any sizable function, I always have to translate a lot of stuff before it works in Octave, if not re-write it from scratch. How this is better, I really don't see...

Also, if you learn Octave, there's a lot of syntax allowed in Octave that's not allowed in MATLAB. Meaning -- code written in Octave often does not work in MATLAB without numerous conversions. It's also not compatible the other way around!

I could go on: The MathWorks has many toolboxes for MATLAB, there's Simulink and its related products for which there really is no equivalent in Octave (yes, you'd have to pay for all that. But often your employer/school does that anyway, and well, it at least exists), proven compliance with several industry standards, testing tools, validation tools, requirement management systems, report generation, a much larger community & user base, etc. etc. etc. MATLAB is only a small part of something much larger. Octave is...just Octave.

So, my advice:

  • Find out if your school will pay for MATLAB. Often they will.
  • If they don't, and if you can scrape together the money, buy MATLAB and learn to use it properly. In the long run it's the better decision.
  • If you really can't get the money -- use Octave, but learn MATLAB's syntax and stay away from Octave-only syntax. (see note)

Why this last point? Because in the sciences, there are often large code bases entirely written in MATLAB. There are professors, engineers, students, professional coders, lots and lots of people who know all the intricate gory details of MATLAB, and not so much of Octave.

If you get a new job, and everyone in your new office speaks Spanish, it's kind of cocky to demand of everyone that they start speaking English from then on, simply because you don't speak/like Spanish. Same with MATLAB and Octave.

NB -- if all downvoters could just leave a comment with their arguments and reasons for disagreeing with me, that'd be great :)

Note: Octave can be run in "traditional mode" (by including the --traditional flag when starting Octave) which makes it give an error when certain Octave-only syntax is used.

Flexbox not giving equal width to elements

There is an important bit that is not mentioned in the article to which you linked and that is flex-basis. By default flex-basis is auto.

From the spec:

If the specified flex-basis is auto, the used flex basis is the value of the flex item’s main size property. (This can itself be the keyword auto, which sizes the flex item based on its contents.)

Each flex item has a flex-basis which is sort of like its initial size. Then from there, any remaining free space is distributed proportionally (based on flex-grow) among the items. With auto, that basis is the contents size (or defined size with width, etc.). As a result, items with bigger text within are being given more space overall in your example.

If you want your elements to be completely even, you can set flex-basis: 0. This will set the flex basis to 0 and then any remaining space (which will be all space since all basises are 0) will be proportionally distributed based on flex-grow.

li {
    flex-grow: 1;
    flex-basis: 0;
    /* ... */
}

This diagram from the spec does a pretty good job of illustrating the point.

And here is a working example with your fiddle.

Using Docker-Compose, how to execute multiple commands

Figured it out, use bash -c.

Example:

command: bash -c "python manage.py migrate && python manage.py runserver 0.0.0.0:8000"

Same example in multilines:

command: >
    bash -c "python manage.py migrate
    && python manage.py runserver 0.0.0.0:8000"

Or:

command: bash -c "
    python manage.py migrate
    && python manage.py runserver 0.0.0.0:8000
  "

Round to at most 2 decimal places (only if necessary)

The big challenge on this seemingly simple task is that we want it to yield psychologically expected results even if the input contains minimal rounding errors to start with (not mentioning the errors which will happen within our calculation). If we know that the real result is exactly 1.005, we expect that rounding to two digits yields 1.01, even if the 1.005 is the result of a large computation with loads of rounding errors on the way.

The problem becomes even more obvious when dealing with floor() instead of round(). For example, when cutting everything away after the last two digits behind the dot of 33.3, we would certainly not expect to get 33.29 as a result, but that is what happens:

_x000D_
_x000D_
console.log(Math.floor(33.3 * 100) / 100)
_x000D_
_x000D_
_x000D_

In simple cases, the solution is to perform calculation on strings instead of floating point numbers, and thus avoid rounding errors completely. However, this option fails at the first non-trivial mathematical operation (including most divsions), and it is slow.

When operating on floating point numbers, the solution is to introduce a parameter which names the amount by which we are willing to deviate from the actual computation result, in order to output the psychologically expected result.

_x000D_
_x000D_
var round = function(num, digits = 2, compensateErrors = 2) {_x000D_
  if (num < 0) {_x000D_
    return -this.round(-num, digits, compensateErrors);_x000D_
  }_x000D_
  const pow = Math.pow(10, digits);_x000D_
  return (Math.round(num * pow * (1 + compensateErrors * Number.EPSILON)) / pow);_x000D_
}_x000D_
_x000D_
/* --- testing --- */_x000D_
_x000D_
console.log("Edge cases mentioned in this thread:")_x000D_
var values = [ 0.015, 1.005, 5.555, 156893.145, 362.42499999999995, 1.275, 1.27499, 1.2345678e+2, 2.175, 5.015, 58.9 * 0.15 ];_x000D_
values.forEach((n) => {_x000D_
  console.log(n + " -> " + round(n));_x000D_
  console.log(-n + " -> " + round(-n));_x000D_
});_x000D_
_x000D_
console.log("\nFor numbers which are so large that rounding cannot be performed anyway within computation precision, only string-based computation can help.")_x000D_
console.log("Standard: " + round(1e+19));_x000D_
console.log("Compensation = 1: " + round(1e+19, 2, 1));_x000D_
console.log("Effectively no compensation: " + round(1e+19, 2, 0.4));
_x000D_
_x000D_
_x000D_

Note: Internet Explorer does not know Number.EPSILON. If you are in the unhappy position of still having to support it, you can use a shim, or just define the constant yourself for that specific browser family.

How to sleep for five seconds in a batch file/cmd

The following hack let's you sleep for 5 seconds

ping -n 6 127.0.0.1 > nul

Since ping waits a second between the pings, you have to specify one more than you need.

Maximum number of threads per process in Linux?

check the stack size per thread with ulimit, in my case Redhat Linux 2.6:

    ulimit -a
...
    stack size              (kbytes, -s) 10240

Each of your threads will get this amount of memory (10MB) assigned for it's stack. With a 32bit program and a maximum address space of 4GB, that is a maximum of only 4096MB / 10MB = 409 threads !!! Minus program code, minus heap-space will probably lead to an observed max. of 300 threads.

You should be able to raise this by compiling and running on 64bit or setting ulimit -s 8192 or even ulimit -s 4096. But if this is advisable is another discussion...

How to copy an object in Objective-C

As always with reference types, there are two notions of "copy". I'm sure you know them, but for completeness.

  1. A bitwise copy. In this, we just copy the memory bit for bit - this is what NSCopyObject does. Nearly always, it's not what you want. Objects have internal state, other objects, etc, and often make assumptions that they're the only ones holding references to that data. Bitwise copies break this assumption.
  2. A deep, logical copy. In this, we make a copy of the object, but without actually doing it bit by bit - we want an object that behaves the same for all intents and purposes, but isn't (necessarily) a memory-identical clone of the original - the Objective C manual calls such an object "functionally independent" from it's original. Because the mechanisms for making these "intelligent" copies varies from class to class, we ask the objects themselves to perform them. This is the NSCopying protocol.

You want the latter. If this is one of your own objects, you need simply adopt the protocol NSCopying and implement -(id)copyWithZone:(NSZone *)zone. You're free to do whatever you want; though the idea is you make a real copy of yourself and return it. You call copyWithZone on all your fields, to make a deep copy. A simple example is

@interface YourClass : NSObject <NSCopying> 
{
   SomeOtherObject *obj;
}

// In the implementation
-(id)copyWithZone:(NSZone *)zone
{
  // We'll ignore the zone for now
  YourClass *another = [[YourClass alloc] init];
  another.obj = [obj copyWithZone: zone];

  return another;
}

How to create named and latest tag in Docker?

You can have multiple tags when building the image:

$ docker build -t whenry/fedora-jboss:latest -t whenry/fedora-jboss:v2.1 .

Reference: https://docs.docker.com/engine/reference/commandline/build/#tag-image-t

Using multiple delimiters in awk

For a field separator of any number 2 through 5 or letter a or # or a space, where the separating character must be repeated at least 2 times and not more than 6 times, for example:

awk -F'[2-5a# ]{2,6}' ...

I am sure variations of this exist using ( ) and parameters

Check if property has attribute

You can use the Attribute.IsDefined method

https://msdn.microsoft.com/en-us/library/system.attribute.isdefined(v=vs.110).aspx

if(Attribute.IsDefined(YourProperty,typeof(YourAttribute)))
{
    //Conditional execution...
}

You could provide the property you're specifically looking for or you could iterate through all of them using reflection, something like:

PropertyInfo[] props = typeof(YourClass).GetProperties();

How exactly does <script defer="defer"> work?

As defer attribute works only with scripts tag with src. Found a way to mimic defer for inline scripts. Use DOMContentLoaded event.

<script defer src="external-script.js"></script>
<script>
document.addEventListener("DOMContentLoaded", function(event) {
    // Your inline scripts which uses methods from external-scripts.
});
</script>

This is because, DOMContentLoaded event fires after defer attributed scripts are completely loaded.

Comparing Java enum members: == or equals()?

I prefer to use == instead of equals:

Other reason, in addition to the others already discussed here, is you could introduce a bug without realizing it. Suppose you have this enums which is exactly the same but in separated pacakges (it's not common, but it could happen):

First enum:

package first.pckg

public enum Category {
    JAZZ,
    ROCK,
    POP,
    POP_ROCK
}

Second enum:

package second.pckg

public enum Category {
    JAZZ,
    ROCK,
    POP,
    POP_ROCK
}

Then suppose you use the equals like next in item.category which is first.pckg.Category but you import the second enum (second.pckg.Category) instead the first without realizing it:

import second.pckg.Category;
...

Category.JAZZ.equals(item.getCategory())

So you will get allways false due is a different enum although you expect true because item.getCategory() is JAZZ. And it could be be a bit difficult to see.

So, if you instead use the operator == you will have a compilation error:

operator == cannot be applied to "second.pckg.Category", "first.pckg.Category"

import second.pckg.Category; 
...

Category.JAZZ == item.getCategory() 

"A connection attempt failed because the connected party did not properly respond after a period of time" using WebClient

I know it's an old post but I came across the exact same issue and I managed to use this by turning off MALWAREBYTES program which was causing the issue.

How to convert CLOB to VARCHAR2 inside oracle pl/sql

Converting VARCHAR2 to CLOB

In PL/SQL a CLOB can be converted to a VARCHAR2 with a simple assignment, SUBSTR, and other methods. A simple assignment will only work if the CLOB is less then or equal to the size of the VARCHAR2. The limit is 32767 in PL/SQL and 4000 in SQL (although 12c allows 32767 in SQL).

For example, this code converts a small CLOB through a simple assignment and then coverts the beginning of a larger CLOB.

declare
    v_small_clob clob := lpad('0', 1000, '0');
    v_large_clob clob := lpad('0', 32767, '0') || lpad('0', 32767, '0');
    v_varchar2   varchar2(32767);
begin
    v_varchar2 := v_small_clob;
    v_varchar2 := substr(v_large_clob, 1, 32767);
end;

LONG?

The above code does not convert the value to a LONG. It merely looks that way because of limitations with PL/SQL debuggers and strings over 999 characters long.

For example, in PL/SQL Developer, open a Test window and add and debug the above code. Right-click on v_varchar2 and select "Add variable to Watches". Step through the code and the value will be set to "(Long Value)". There is a ... next to the text but it does not display the contents. PLSQL Developer Long Value

C#?

I suspect the real problem here is with C# but I don't know how enough about C# to debug the problem.

Java: Sending Multiple Parameters to Method

You can use varargs

public function yourFunction(Parameter... parameters)

See also

Java multiple arguments dot notation - Varargs

How to file split at a line number

file_name=test.log

# set first K lines:
K=1000

# line count (N): 
N=$(wc -l < $file_name)

# length of the bottom file:
L=$(( $N - $K ))

# create the top of file: 
head -n $K $file_name > top_$file_name

# create bottom of file: 
tail -n $L $file_name > bottom_$file_name

Also, on second thought, split will work in your case, since the first split is larger than the second. Split puts the balance of the input into the last split, so

split -l 300000 file_name

will output xaa with 300k lines and xab with 100k lines, for an input with 400k lines.

String format currency

Use this it works and so simple :

  var price=22.5m;
  Console.WriteLine(
     "the price: {0}",price.ToString("C", new System.Globalization.CultureInfo("en-US")));

Insert auto increment primary key to existing table

Export your table, then empty your table, then add field as unique INT, then change it to AUTO_INCREMENT, then import your table again that you exported previously.

How do I check if a string is unicode or ascii?

This may help someone else, I started out testing for the string type of the variable s, but for my application, it made more sense to simply return s as utf-8. The process calling return_utf, then knows what it is dealing with and can handle the string appropriately. The code is not pristine, but I intend for it to be Python version agnostic without a version test or importing six. Please comment with improvements to the sample code below to help other people.

def return_utf(s):
    if isinstance(s, str):
        return s.encode('utf-8')
    if isinstance(s, (int, float, complex)):
        return str(s).encode('utf-8')
    try:
        return s.encode('utf-8')
    except TypeError:
        try:
            return str(s).encode('utf-8')
        except AttributeError:
            return s
    except AttributeError:
        return s
    return s # assume it was already utf-8

Tooltips with Twitter Bootstrap

I think your question boils down to what proper selector to use when setting up your tooltips, and the answer to that is almost whatever you want. If you want to use a class to trigger your tooltips you can do that, take the following for example:

<a href="#" class="link" data-original-title="first tooltip">Hover me for a tooltip</a>

Then you can trigger all links with the .link class attached as tooltips like so:

$('.link').tooltip()

Now, to answer your question as to why the bootstrap developers did not use a class to trigger tooltips that is because it is not needed exactly, you can pretty much use any selectors you want to target your tooltips, such as (my personal favorite) the rel attribute. With this attribute you can target all links or elements with the rel property set to tooltip, like so:

$('[rel=tooltip]').tooltip() 

And your links would look like something like this:

<a href="#" rel="tooltip" data-original-title="first tooltip">Hover me for a tooltip</a>

Of course, you can also use a container class or id to target your tooltips inside an specific container that you want to single out with an specific option or to separate from the rest of your content and you can use it like so:

$('#example').tooltip({
    selector: "a[rel=tooltip]"
})

This selector will target all of your tooltips with the rel attribute "within" your #example div, this way you can add special styles or options to that section alone. In short, you can pretty much use any valid selector to target your tooltips and there is no need to dirty your markup with an extra class to target them.

Example using Hyperlink in WPF

One of the most beautiful ways in my opinion (since it is now commonly available) is using behaviours.

It requires:

  • nuget dependency: Microsoft.Xaml.Behaviors.Wpf
  • if you already have behaviours built in you might have to follow this guide on Microsofts blog.

xaml code:

xmlns:Interactions="http://schemas.microsoft.com/xaml/behaviors"

AND

<Hyperlink NavigateUri="{Binding Path=Link}">
    <Interactions:Interaction.Behaviors>
        <behaviours:HyperlinkOpenBehaviour ConfirmNavigation="True"/>
    </Interactions:Interaction.Behaviors>
    <Hyperlink.Inlines>
        <Run Text="{Binding Path=Link}"/>
    </Hyperlink.Inlines>
</Hyperlink>

behaviour code:

using System.Windows;
using System.Windows.Documents;
using System.Windows.Navigation;
using Microsoft.Xaml.Behaviors;

namespace YourNameSpace
{
    public class HyperlinkOpenBehaviour : Behavior<Hyperlink>
    {
        public static readonly DependencyProperty ConfirmNavigationProperty = DependencyProperty.Register(
            nameof(ConfirmNavigation), typeof(bool), typeof(HyperlinkOpenBehaviour), new PropertyMetadata(default(bool)));

        public bool ConfirmNavigation
        {
            get { return (bool) GetValue(ConfirmNavigationProperty); }
            set { SetValue(ConfirmNavigationProperty, value); }
        }

        /// <inheritdoc />
        protected override void OnAttached()
        {
            this.AssociatedObject.RequestNavigate += NavigationRequested;
            this.AssociatedObject.Unloaded += AssociatedObjectOnUnloaded;
            base.OnAttached();
        }

        private void AssociatedObjectOnUnloaded(object sender, RoutedEventArgs e)
        {
            this.AssociatedObject.Unloaded -= AssociatedObjectOnUnloaded;
            this.AssociatedObject.RequestNavigate -= NavigationRequested;
        }

        private void NavigationRequested(object sender, RequestNavigateEventArgs e)
        {
            if (!ConfirmNavigation || MessageBox.Show("Are you sure?", "Question", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes)
            {
                OpenUrl();
            }

            e.Handled = true;
        }

        private void OpenUrl()
        {
//          Process.Start(new ProcessStartInfo(AssociatedObject.NavigateUri.AbsoluteUri));
            MessageBox.Show($"Opening {AssociatedObject.NavigateUri}");
        }

        /// <inheritdoc />
        protected override void OnDetaching()
        {
            this.AssociatedObject.RequestNavigate -= NavigationRequested;
            base.OnDetaching();
        }
    }
}

How to cherry-pick multiple commits

If you have selective revisions to merge, say A, C, F, J from A,B,C,D,E,F,G,H,I,J commits, simply use below command:

git cherry-pick A C F J

How to replace url parameter with javascript/jquery?

Nowdays that's possible with native JS

var href = new URL('https://google.com?q=cats');
href.searchParams.set('q', 'dogs');
console.log(href.toString()); // https://google.com/?q=dogs

Get SELECT's value and text in jQuery

You can do like this, to get the currently selected value:

$('#myDropdownID').val();

& to get the currently selected text:

$('#myDropdownID:selected').text();

How do I move an existing Git submodule within a Git repository?

You can just add a new submodule and remove the old submodule using standard commands. (should prevent any accidental errors inside of .git)

Example setup:

mkdir foo; cd foo; git init; 
echo "readme" > README.md; git add README.md; git commit -m "First"
## add submodule
git submodule add git://github.com/jquery/jquery.git
git commit -m "Added jquery"
## </setup example>

Examle move 'jquery' to 'vendor/jquery/jquery' :

oldPath="jquery"
newPath="vendor/jquery/jquery"
orginUrl=`git config --local --get submodule.${oldPath}.url`

## add new submodule
mkdir -p `dirname "${newPath}"`
git submodule add -- "${orginUrl}" "${newPath}"

## remove old submodule
git config -f .git/config --remove-section "submodule.${oldPath}"
git config -f .gitmodules --remove-section "submodule.${oldPath}"
git rm --cached "${oldPath}"
rm -rf "${oldPath}"              ## remove old src
rm -rf ".git/modules/${oldPath}" ## cleanup gitdir (housekeeping)

## commit
git add .gitmodules
git commit -m "Renamed ${oldPath} to ${newPath}"

Bonus method for large submodules:

If the submodule is large and you prefer not to wait for the clone, you can create the new submodule using the old as origin, and then switch the origin.

Example (use same example setup)

oldPath="jquery"
newPath="vendor/jquery/jquery"
baseDir=`pwd`
orginUrl=`git config --local --get submodule.${oldPath}.url`

# add new submodule using old submodule as origin
mkdir -p `dirname "${newPath}"`
git submodule add -- "file://${baseDir}/${oldPath}" "${newPath}"

## change origin back to original
git config -f .gitmodules submodule."${newPath}".url "${orginUrl}"
git submodule sync -- "${newPath}"

## remove old submodule
...

Collectors.toMap() keyMapper -- more succinct expression?

We can use an optional merger function also in case of same key collision. For example, If two or more persons have the same getLast() value, we can specify how to merge the values. If we not do this, we could get IllegalStateException. Here is the example to achieve this...

Map<String, Person> map = 
roster
    .stream()
    .collect(
        Collectors.toMap(p -> p.getLast(),
                         p -> p,
                         (person1, person2) -> person1+";"+person2)
    );

CSS selector last row from main table

Your tables should have as immediate children just tbody and thead elements, with the rows within*. So, amend the HTML to be:

<table border="1" width="100%" id="test">
  <tbody>
    <tr>
     <td>
      <table border="1" width="100%">
        <tbody>
          <tr>
            <td>table 2</td>
          </tr>
        </tbody>
      </table>
     </td>
    </tr> 
    <tr><td>table 1</td></tr>
    <tr><td>table 1</td></tr>
    <tr><td>table 1</td></tr>
  </tbody>
</table>

Then amend your selector slightly to this:

#test > tbody > tr:last-child { background:#ff0000; }

See it in action here. That makes use of the child selector, which:

...separates two selectors and matches only those elements matched by the second selector that are direct children of elements matched by the first.

So, you are targeting only direct children of tbody elements that are themselves direct children of your #test table.

Alternative solution

The above is the neatest solution, as you don't need to over-ride any styles. The alternative would be to stick with your current set-up, and over-ride the background style for the inner table, like this:

#test tr:last-child { background:#ff0000; }
#test table tr:last-child { background:transparent; }

* It's not mandatory but most (all?) browsers will add these in, so it's best to make it explicit. As @BoltClock states in the comments:

...it's now set in stone in HTML5, so for a browser to be compliant it basically must behave this way.

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

Using the solution showed in this question, System.Windows.Forms.Clipboard.SetText(...), results in the exception:

Current thread must be set to single thread apartment (STA) mode before OLE calls can be made

To prevent this, you can add the attribute:

[STAThread]

to

static void Main(string[] args)

How to parse JSON string in Typescript

TS has a JavaScript runtime

Typescript has a JavaScript runtime because it gets compiled to JS. This means JS objects which are built in as part of the language such as JSON, Object, and Math are also available in TS. Therefore we can just use the JSON.parse method to parse the JSON string.

Example:

const JSONStr = '{"name": "Bob", "error": false}'

// The JSON object is part of the runtime
const parsedObj = JSON.parse(JSONStr);

console.log(parsedObj);
// [LOG]: {
//   "name": "Bob",
//   "error": false
// } 

// The Object object is also part of the runtime so we can use it in TS
const objKeys = Object.keys(parsedObj);

console.log(objKeys);
// [LOG]: ["name", "error"] 

The only thing now is that parsedObj is type any which is generally a bad practice in TS. We can type the object if we are using type guards. Here is an example:

const JSONStr = '{"name": "Bob", "error": false}'
const parsedObj = JSON.parse(JSONStr);

interface nameErr {
  name: string;
  error: boolean;
}

function isNameErr(arg: any): arg is nameErr {
  if (typeof arg.name === 'string' && typeof arg.error === 'boolean') {
    return true;
  } else {
    return false;
  }
}

if (isNameErr(parsedObj)) {
  // Within this if statement parsedObj is type nameErr;
  parsedObj
}

Append to the end of a file in C

Following the documentation of fopen:

``a'' Open for writing. The file is created if it does not exist. The stream is positioned at the end of the file. Subsequent writes to the file will always end up at the then cur- rent end of file, irrespective of any intervening fseek(3) or similar.

So if you pFile2=fopen("myfile2.txt", "a"); the stream is positioned at the end to append automatically. just do:

FILE *pFile;
FILE *pFile2;
char buffer[256];

pFile=fopen("myfile.txt", "r");
pFile2=fopen("myfile2.txt", "a");
if(pFile==NULL) {
    perror("Error opening file.");
}
else {
    while(fgets(buffer, sizeof(buffer), pFile)) {
        fprintf(pFile2, "%s", buffer);
    }
}
fclose(pFile);
fclose(pFile2);

How to exclude rows that don't join with another table?

Another solution is:

SELECT * FROM TABLE1 WHERE id NOT IN (SELECT id FROM TABLE2)

How do I use a file grep comparison inside a bash if/else statement?

From grep --help, but also see man grep:

Exit status is 0 if any line was selected, 1 otherwise; if any error occurs and -q was not given, the exit status is 2.

if grep --quiet MYSQL_ROLE=master /etc/aws/hosts.conf; then
  echo exists
else
  echo not found
fi

You may want to use a more specific regex, such as ^MYSQL_ROLE=master$, to avoid that string in comments, names that merely start with "master", etc.

This works because the if takes a command and runs it, and uses the return value of that command to decide how to proceed, with zero meaning true and non-zero meaning false—the same as how other return codes are interpreted by the shell, and the opposite of a language like C.

Converting HTML to XML

I was successful using tidy command line utility. On linux I installed it quickly with apt-get install tidy. Then the command:

tidy -q -asxml --numeric-entities yes source.html >file.xml

gave an xml file, which I was able to process with xslt processor. However I needed to set up xhtml1 dtds correctly.

This is their homepage: html-tidy.org (and the legacy one: HTML Tidy)

What's the use of "enum" in Java?

An enum type is a type whose fields consist of a fixed set of constants. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.

public enum Day {
    SUNDAY, MONDAY, TUESDAY, WEDNESDAY,
    THURSDAY, FRIDAY, SATURDAY 
}

You should use enum types any time you need to represent a fixed set of constants. That includes natural enum types such as the planets in our solar system and data sets where you know all possible values at compile time—for example, the choices on a menu, command line flags, and so on.

Here is some code that shows you how to use the Day enum defined above:

public class EnumTest {
    Day day;

    public EnumTest(Day day) {
        this.day = day;
    }

    public void tellItLikeItIs() {
        switch (day) {
            case MONDAY:
                System.out.println("Mondays are bad.");
                break;

            case FRIDAY:
                System.out.println("Fridays are better.");
                break;

            case SATURDAY: case SUNDAY:
                System.out.println("Weekends are best.");
                break;

            default:
                System.out.println("Midweek days are so-so.");
                break;
        }
    }

    public static void main(String[] args) {
        EnumTest firstDay = new EnumTest(Day.MONDAY);
        firstDay.tellItLikeItIs();
        EnumTest thirdDay = new EnumTest(Day.WEDNESDAY);
        thirdDay.tellItLikeItIs();
        EnumTest fifthDay = new EnumTest(Day.FRIDAY);
        fifthDay.tellItLikeItIs();
        EnumTest sixthDay = new EnumTest(Day.SATURDAY);
        sixthDay.tellItLikeItIs();
        EnumTest seventhDay = new EnumTest(Day.SUNDAY);
        seventhDay.tellItLikeItIs();
    }
}

The output is:

Mondays are bad.
Midweek days are so-so.
Fridays are better.
Weekends are best.
Weekends are best.

Java programming language enum types are much more powerful than their counterparts in other languages. The enum declaration defines a class (called an enum type). The enum class body can include methods and other fields. The compiler automatically adds some special methods when it creates an enum. For example, they have a static values method that returns an array containing all of the values of the enum in the order they are declared. This method is commonly used in combination with the for-each construct to iterate over the values of an enum type. For example, this code from the Planet class example below iterates over all the planets in the solar system.

for (Planet p : Planet.values()) {
    System.out.printf("Your weight on %s is %f%n",
                      p, p.surfaceWeight(mass));
}

In addition to its properties and constructor, Planet has methods that allow you to retrieve the surface gravity and weight of an object on each planet. Here is a sample program that takes your weight on earth (in any unit) and calculates and prints your weight on all of the planets (in the same unit):

public enum Planet {
    MERCURY (3.303e+23, 2.4397e6),
    VENUS   (4.869e+24, 6.0518e6),
    EARTH   (5.976e+24, 6.37814e6),
    MARS    (6.421e+23, 3.3972e6),
    JUPITER (1.9e+27,   7.1492e7),
    SATURN  (5.688e+26, 6.0268e7),
    URANUS  (8.686e+25, 2.5559e7),
    NEPTUNE (1.024e+26, 2.4746e7);

    private final double mass;   // in kilograms
    private final double radius; // in meters
    Planet(double mass, double radius) {
        this.mass = mass;
        this.radius = radius;
    }
    private double mass() { return mass; }
    private double radius() { return radius; }

    // universal gravitational constant  (m3 kg-1 s-2)
    public static final double G = 6.67300E-11;

    double surfaceGravity() {
        return G * mass / (radius * radius);
    }
    double surfaceWeight(double otherMass) {
        return otherMass * surfaceGravity();
    }
    public static void main(String[] args) {
        if (args.length != 1) {
            System.err.println("Usage: java Planet <earth_weight>");
            System.exit(-1);
        }
        double earthWeight = Double.parseDouble(args[0]);
        double mass = earthWeight/EARTH.surfaceGravity();
        for (Planet p : Planet.values())
           System.out.printf("Your weight on %s is %f%n",
                             p, p.surfaceWeight(mass));
    }
}

If you run Planet.class from the command line with an argument of 175, you get this output:

$ java Planet 175
Your weight on MERCURY is 66.107583
Your weight on VENUS is 158.374842
Your weight on EARTH is 175.000000
Your weight on MARS is 66.279007
Your weight on JUPITER is 442.847567
Your weight on SATURN is 186.552719
Your weight on URANUS is 158.397260
Your weight on NEPTUNE is 199.207413

Source: http://docs.oracle.com/javase/tutorial/java/javaOO/enum.html

Delete commit on gitlab

  1. git reset --hard CommitId
  2. git push -f origin master

1st command will rest your head to commitid and 2nd command will delete all commit after that commit id on master branch.

Note: Don't forget to add -f in push otherwise it will be rejected.

How to understand nil vs. empty vs. blank in Ruby

enter image description here

  • Everything that is nil? is blank?
  • Everything that is empty? is blank?
  • Nothing that is empty? is nil?
  • Nothing that is nil? is empty?

tl;dr -- only use blank? & present? unless you want to distinguish between "" and " "

How do I disable a jquery-ui draggable?

To enable/disable draggable in jQuery I used:

$("#draggable").draggable({ disabled: true });          

$("#draggable").draggable({ disabled: false });

@Calciphus answer didn't work for me with the opacity problem, so I used:

div.ui-state-disabled.ui-draggable-disabled {opacity: 1;}

Worked on mobile devices either.

Here is the code: http://jsfiddle.net/nn5aL/1/

PHP shell_exec() vs exec()

Here are the differences. Note the newlines at the end.

> shell_exec('date')
string(29) "Wed Mar  6 14:18:08 PST 2013\n"
> exec('date')
string(28) "Wed Mar  6 14:18:12 PST 2013"

> shell_exec('whoami')
string(9) "mark\n"
> exec('whoami')
string(8) "mark"

> shell_exec('ifconfig')
string(1244) "eth0      Link encap:Ethernet  HWaddr 10:bf:44:44:22:33  \n          inet addr:192.168.0.90  Bcast:192.168.0.255  Mask:255.255.255.0\n          inet6 addr: fe80::12bf:ffff:eeee:2222/64 Scope:Link\n          UP BROADCAST RUNNING MULTICAST  MTU:1500  Metric:1\n          RX packets:16264200 errors:0 dropped:1 overruns:0 frame:0\n          TX packets:7205647 errors:0 dropped:0 overruns:0 carrier:0\n          collisions:0 txqueuelen:1000 \n          RX bytes:13151177627 (13.1 GB)  TX bytes:2779457335 (2.7 GB)\n"...
> exec('ifconfig')
string(0) ""

Note that use of the backtick operator is identical to shell_exec().

Update: I really should explain that last one. Looking at this answer years later even I don't know why that came out blank! Daniel explains it above -- it's because exec only returns the last line, and ifconfig's last line happens to be blank.

JQuery .on() method with multiple event handlers to one selector

Also, if you had multiple event handlers attached to the same selector executing the same function, you could use

$('table.planning_grid').on('mouseenter mouseleave', function() {
    //JS Code
});

Trying to get property of non-object - CodeIgniter

In my case, I was looping through a series of objects from an XML file, but some of the instances apparently were not objects which was causing the error. Checking if the object was empty before processing it fixed the problem.

In other words, without checking if the object was empty, the script would error out on any empty object with the error as given below.

Trying to get property of non-object

For Example:

if (!empty($this->xml_data->thing1->thing2))
{
   foreach ($this->xml_data->thing1->thing2 as $thing)
   {

   }
}

Check if a variable exists in a list in Bash

Thought I'd add my solution to the list.

# Checks if element "$1" is in array "$2"
# @NOTE:
#   Be sure that array is passed in the form:
#       "${ARR[@]}"
elementIn () {
    # shopt -s nocasematch # Can be useful to disable case-matching
    local e
    for e in "${@:2}"; do [[ "$e" == "$1" ]] && return 0; done
    return 1
}

# Usage:
list=(11 22 33)
item=22

if elementIn "$item" "${list[@]}"; then
    echo TRUE;
else
    echo FALSE
fi
# TRUE

item=44
elementIn $item "${list[@]}" && echo TRUE || echo FALSE
# FALSE

How to access the last value in a vector?

The dplyr package includes a function last():

last(mtcars$mpg)
# [1] 21.4

Node - was compiled against a different Node.js version using NODE_MODULE_VERSION 51

After trying different things. This worked.

Delete your node modules folder and run

npm i

Expression must have class type

Allow an analysis.

#include <iostream>   // not #include "iostream"
using namespace std;  // in this case okay, but never do that in header files

class A
{
 public:
  void f() { cout<<"f()\n"; }
};

int main()
{
 /*
 // A a; //this works
 A *a = new A(); //this doesn't
 a.f(); // "f has not been declared"
 */ // below


 // system("pause");  <-- Don't do this. It is non-portable code. I guess your 
 //                       teacher told you this?
 //                       Better: In your IDE there is prolly an option somewhere
 //                               to not close the terminal/console-window.
 //                       If you compile on a CLI, it is not needed at all.
}

As a general advice:

0) Prefer automatic variables
  int a;
  MyClass myInstance;
  std::vector<int> myIntVector;

1) If you need data sharing on big objects down 
   the call hierarchy, prefer references:

  void foo (std::vector<int> const &input) {...}
  void bar () { 
       std::vector<int> something;
       ...
       foo (something);
  }


2) If you need data sharing up the call hierarchy, prefer smart-pointers
   that automatically manage deletion and reference counting.

3) If you need an array, use std::vector<> instead in most cases.
   std::vector<> is ought to be the one default container.

4) I've yet to find a good reason for blank pointers.

   -> Hard to get right exception safe

       class Foo {
           Foo () : a(new int[512]), b(new int[512]) {}
           ~Foo() {
               delete [] b;
               delete [] a;
           }
       };

       -> if the second new[] fails, Foo leaks memory, because the
          destructor is never called. Avoid this easily by using 
          one of the standard containers, like std::vector, or
          smart-pointers.

As a rule of thumb: If you need to manage memory on your own, there is generally a superiour manager or alternative available already, one that follows the RAII principle.

How to create a sticky left sidebar menu using bootstrap 3?

Bootstrap 3

Here is a working left sidebar example:

http://bootply.com/90936 (similar to the Bootstrap docs)

The trick is using the affix component along with some CSS to position it:

  #sidebar.affix-top {
    position: static;
    margin-top:30px;
    width:228px;
  }

  #sidebar.affix {
    position: fixed;
    top:70px;
    width:228px;
  }

EDIT- Another example with footer and affix-bottom


Bootstrap 4

The Affix component has been removed in Bootstrap 4, so to create a sticky sidebar, you can use a 3rd party Affix plugin like this Bootstrap 4 sticky sidebar example, or use the sticky-top class is explained in this answer.

Related: Create a responsive navbar sidebar "drawer" in Bootstrap 4?

I get Access Forbidden (Error 403) when setting up new alias

I'm using XAMPP with Apache2.4, I had this same issue. I wanted to leave the default xampp/htdocs folder in place, be able to access it from locahost and have a Virtual Host to point to my dev area...

The full contents of my C:\xampp\apache\conf\extra\http-vhosts.conf file is below...

# Virtual Hosts
#
# Required modules: mod_log_config

# If you want to maintain multiple domains/hostnames on your
# machine you can setup VirtualHost containers for them. Most configurations
# use only name-based virtual hosts so the server doesn't need to worry about
# IP addresses. This is indicated by the asterisks in the directives below.
#
# Please see the documentation at 
# <URL:http://httpd.apache.org/docs/2.4/vhosts/>
# for further details before you try to setup virtual hosts.
#
# You may use the command line option '-S' to verify your virtual host
# configuration.

#
# Use name-based virtual hosting.
#

##NameVirtualHost *:80

#
# VirtualHost example:
# Almost any Apache directive may go into a VirtualHost container.
# The first VirtualHost section is used for all requests that do not
# match a ##ServerName or ##ServerAlias in any <VirtualHost> block.
#
##<VirtualHost *:80>
    ##ServerAdmin [email protected]
    ##DocumentRoot "C:/xampp/htdocs/dummy-host.example.com"
    ##ServerName dummy-host.example.com
    ##ServerAlias www.dummy-host.example.com
    ##ErrorLog "logs/dummy-host.example.com-error.log"
    ##CustomLog "logs/dummy-host.example.com-access.log" common
##</VirtualHost>

##<VirtualHost *:80>
    ##ServerAdmin [email protected]
    ##DocumentRoot "C:/xampp/htdocs/dummy-host2.example.com"
    ##ServerName dummy-host2.example.com
    ##ErrorLog "logs/dummy-host2.example.com-error.log"
    ##CustomLog "logs/dummy-host2.example.com-access.log" common
##</VirtualHost>


<VirtualHost *:80>
    DocumentRoot "C:\xampp\htdocs"
    ServerName localhost
</VirtualHost>


<VirtualHost *:80>
    DocumentRoot "C:\nick\static"
    ServerName dev.middleweek.co.uk
    <Directory "C:\nick\static">
        Allow from all
        Require all granted
    </Directory>
</VirtualHost>

I then updated my C:\windows\System32\drivers\etc\hosts file like this...

# Copyright (c) 1993-2009 Microsoft Corp.
#
# This is a sample HOSTS file used by Microsoft TCP/IP for Windows.
#
# This file contains the mappings of IP addresses to host names. Each
# entry should be kept on an individual line. The IP address should
# be placed in the first column followed by the corresponding host name.
# The IP address and the host name should be separated by at least one
# space.
#
# Additionally, comments (such as these) may be inserted on individual
# lines or following the machine name denoted by a '#' symbol.
#
# For example:
#
#      102.54.94.97     rhino.acme.com          # source server
#       38.25.63.10     x.acme.com              # x client host

# localhost name resolution is handled within DNS itself.
#   127.0.0.1       localhost
#   ::1             localhost

127.0.0.1   dev.middleweek.co.uk
127.0.0.1       localhost

Restart your machine for good measure, open the XAMPP Control Panel and start Apache.

Now open your custom domain in your browser, in the above example, it'll be http://dev.middleweek.co.uk

Hope that helps someone!

And if you want to be able to view directory listings under your new Virtual host, then edit your VirtualHost block in C:\xampp\apache\conf\extra\http-vhosts.conf to include "Options Indexes" like this...

<VirtualHost *:80>
    DocumentRoot "C:\nick\static"
    ServerName dev.middleweek.co.uk
    <Directory "C:\nick\static">
        Allow from all
        Require all granted
        Options Indexes
    </Directory>
</VirtualHost>

Cheers, Nick

Palindrome check in Javascript

I thought I'd share my own solution:

_x000D_
_x000D_
function palindrome(string){_x000D_
    var reverseString = '';_x000D_
    for(var k in string){_x000D_
       reverseString += string[(string.length - k) - 1];_x000D_
    }_x000D_
  if(string === reverseString){_x000D_
    console.log('Hey there palindrome');_x000D_
  }else{_x000D_
    console.log('You are not a palindrome');_x000D_
  }_x000D_
}_x000D_
palindrome('ana');
_x000D_
_x000D_
_x000D_

Hope will help someone.

How to round up a number to nearest 10?

floor() will go down.

ceil() will go up.

round() will go to nearest by default.

Divide by 10, do the ceil, then multiply by 10 to reduce the significant digits.

$number = ceil($input / 10) * 10;

Edit: I've been doing it this way for so long.. but TallGreenTree's answer is cleaner.

Disable PHP in directory (including all sub-directories) with .htaccess

Try to disable the engine option in your .htaccess file:

php_flag engine off

How to consume a webApi from asp.net Web API to store result in database?

For some unexplained reason this solution doesn't work for me (maybe some incompatibility of types), so I came up with a solution for myself:

HttpResponseMessage response = await client.GetAsync("api/yourcustomobjects");
if (response.IsSuccessStatusCode)
{
    var data = await response.Content.ReadAsStringAsync();
    var product = JsonConvert.DeserializeObject<Product>(data);
}

This way my content is parsed into a JSON string and then I convert it to my object.

Java 32-bit vs 64-bit compatibility

Yes to the first question and no to the second question; it's a virtual machine. Your problems are probably related to unspecified changes in library implementation between versions. Although it could be, say, a race condition.

There are some hoops the VM has to go through. Notably references are treated in class files as if they took the same space as ints on the stack. double and long take up two reference slots. For instance fields, there's some rearrangement the VM usually goes through anyway. This is all done (relatively) transparently.

Also some 64-bit JVMs use "compressed oops". Because data is aligned to around every 8 or 16 bytes, three or four bits of the address are useless (although a "mark" bit may be stolen for some algorithms). This allows 32-bit address data (therefore using half as much bandwidth, and therefore faster) to use heap sizes of 35- or 36-bits on a 64-bit platform.

LINQ Group By and select collection

you may also like this

var Grp = Model.GroupBy(item => item.Order.Customer)
      .Select(group => new 
        { 
             Customer = Model.First().Customer, 
             CustomerId= group.Key,  
             Orders= group.ToList() 
       })
      .ToList();

Pass multiple values with onClick in HTML link

Please try this

for static values--onclick="return ReAssign('valuationId','user')"
for dynamic values--onclick="return ReAssign(valuationId,user)"

Add Whatsapp function to website, like sms, tel

Check this link out Launching Your iPhone App Via Custom URL Scheme

and more on the whats up url scheme document

I did a quick mock up and tried it on my iphone with a link like this from a webpage and it opened the app on my iphone.

<a href="whatsapp://send?text=Hello%2C%20World!">whatsapp</a>

I could not try to send a message as I don't have a current Whatsapp account sorry.

Add user name using abid parameter

let's say your whatsapp username was username then it would be

<a href="whatsapp://send?abid=username&text=Hello%2C%20World!">whatsapp</a>

once again sorry I can't test this. Also I have no idea what would happen if the username is the actual user of the current mobile device. eg. You try to whatsapp yourself.

Javascript : Send JSON Object with Ajax?

I struggled for a couple of days to find anything that would work for me as was passing multiple arrays of ids and returning a blob. Turns out if using .NET CORE I'm using 2.1, you need to use [FromBody] and as can only use once you need to create a viewmodel to hold the data.

Wrap up content like below,

var params = {
            "IDs": IDs,
            "ID2s": IDs2,
            "id": 1
        };

In my case I had already json'd the arrays and passed the result to the function

var IDs = JsonConvert.SerializeObject(Model.Select(s => s.ID).ToArray());

Then call the XMLHttpRequest POST and stringify the object

var ajax = new XMLHttpRequest();
ajax.open("POST", '@Url.Action("MyAction", "MyController")', true);
ajax.responseType = "blob";
ajax.setRequestHeader("Content-Type", "application/json;charset=UTF-8");           
ajax.onreadystatechange = function () {
    if (this.readyState == 4) {
       var blob = new Blob([this.response], { type: "application/octet-stream" });
       saveAs(blob, "filename.zip");
    }
};

ajax.send(JSON.stringify(params));

Then have a model like this

public class MyModel
{
    public int[] IDs { get; set; }
    public int[] ID2s { get; set; }
    public int id { get; set; }
}

Then pass in Action like

public async Task<IActionResult> MyAction([FromBody] MyModel model)

Use this add-on if your returning a file

<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.3/FileSaver.min.js"></script>

Matplotlib tight_layout() doesn't take into account figure suptitle

Tight layout doesn't work with suptitle, but constrained_layout does. See this question Improve subplot size/spacing with many subplots in matplotlib

I found adding the subplots at once looked better, i.e.

fig, axs = plt.subplots(rows, cols, constrained_layout=True)

# then iterating over the axes to fill in the plots

But it can also be added at the point the figure is created:

fig = plt.figure(constrained_layout=True)

ax1 = fig.add_subplot(cols, rows, 1)
# etc

Note: To make my subplots closer together, I was also using

fig.subplots_adjust(wspace=0.05)

and constrained_layout doesn't work with this :(

TypeError: Object of type 'bytes' is not JSON serializable

I was dealing with this issue today, and I knew that I had something encoded as a bytes object that I was trying to serialize as json with json.dump(my_json_object, write_to_file.json). my_json_object in this case was a very large json object that I had created, so I had several dicts, lists, and strings to look at to find what was still in bytes format.

The way I ended up solving it: the write_to_file.json will have everything up to the bytes object that is causing the issue.

In my particular case this was a line obtained through

for line in text:
    json_object['line'] = line.strip()

I solved by first finding this error with the help of the write_to_file.json, then by correcting it to:

for line in text:
    json_object['line'] = line.strip().decode()

Python: convert string to byte array

encode function can help you here, encode returns an encoded version of the string

In [44]: str = "ABCD"

In [45]: [elem.encode("hex") for elem in str]
Out[45]: ['41', '42', '43', '44']

or you can use array module

In [49]: import array

In [50]: print array.array('B', "ABCD")
array('B', [65, 66, 67, 68])

How do I test if a string is empty in Objective-C?

Swift Version

Even though this is an Objective C question, I needed to use NSString in Swift so I will also include an answer here.

let myNSString: NSString = ""

if myNSString.length == 0 {
    print("String is empty.")
}

Or if NSString is an Optional:

var myOptionalNSString: NSString? = nil

if myOptionalNSString == nil || myOptionalNSString!.length == 0 {
    print("String is empty.")
}

// or alternatively...
if let myString = myOptionalNSString {
    if myString.length != 0 {
        print("String is not empty.")
    }
}

The normal Swift String version is

let myString: String = ""

if myString.isEmpty {
    print("String is empty.")
}

See also: Check empty string in Swift?

Full Screen Theme for AppCompat

Your "workaround" (hiding the actionBar yourself) is the normal way. But google recommands to always hide the ActionBar when the TitleBar is hidden. Have a look here: https://developer.android.com/training/system-ui/status.html

How do I find the time difference between two datetime objects in python?

To get the hour, minute and second, you can do this

>>> import datetime
>>> first_time = datetime.datetime.now()
>>> later_time = datetime.datetime.now()
>>> difference = later_time - first_time
>>> m,s = divmod(difference.total_seconds(), 60)
>>> print("H:M:S is {}:{}:{}".format(m//60,m%60,s)

CSS3 scrollbar styling on a div

The problem with the css3 scroll bars is that, interaction can only be performed on the content. we can't interact with the scroll bar on touch devices.

Use -notlike to filter out multiple strings in PowerShell

In order to support "matches any of ..." scenarios, I created a function that is pretty easy to read. My version has a lot more to it because its a PowerShell 2.0 cmdlet but the version I'm pasting below should work in 1.0 and has no frills.

You call it like so:

Get-Process | Where-Match Company -Like '*VMWare*','*Microsoft*'
Get-Process | Where-Match Company -Regex '^Microsoft.*'

filter Where-Match($Selector,[String[]]$Like,[String[]]$Regex) {

    if ($Selector -is [String]) { $Value = $_.$Selector }
    elseif ($Selector -is [ScriptBlock]) { $Value = &$Selector }
    else { throw 'Selector must be a ScriptBlock or property name' }

    if ($Like.Length) {
        foreach ($Pattern in $Like) {
            if ($Value -like $Pattern) { return $_ }
        }
    }

    if ($Regex.Length) {
        foreach ($Pattern in $Regex) {
            if ($Value -match $Pattern) { return $_ }
        }
    }

}

filter Where-NotMatch($Selector,[String[]]$Like,[String[]]$Regex) {

    if ($Selector -is [String]) { $Value = $_.$Selector }
    elseif ($Selector -is [ScriptBlock]) { $Value = &$Selector }
    else { throw 'Selector must be a ScriptBlock or property name' }

    if ($Like.Length) {
        foreach ($Pattern in $Like) {
            if ($Value -like $Pattern) { return }
        }
    }

    if ($Regex.Length) {
        foreach ($Pattern in $Regex) {
            if ($Value -match $Pattern) { return }
        }
    }

    return $_

}

Can Rails Routing Helpers (i.e. mymodel_path(model)) be Used in Models?

While there might be a way I would tend to keep that kind of logic out of the Model. I agree that you shouldn't put that in the view (keep it skinny) but unless the model is returning a url as a piece of data to the controller, the routing stuff should be in the controller.

Ignore invalid self-signed ssl certificate in node.js with https.request?

Cheap and insecure answer:

Add

process.env["NODE_TLS_REJECT_UNAUTHORIZED"] = 0;

in code, before calling https.request()

A more secure way (the solution above makes the whole node process insecure) is answered in this question

insert/delete/update trigger in SQL server

the am giving you is the code for trigger for INSERT, UPDATE and DELETE this works fine on Microsoft SQL SERVER 2008 and onwards database i am using is Northwind

/* comment section first create a table to keep track of Insert, Delete, Update
create table Emp_Audit(
                    EmpID int,
                    Activity varchar(20),
                    DoneBy varchar(50),
                    Date_Time datetime NOT NULL DEFAULT GETDATE()
                   );

select * from Emp_Audit*/

create trigger Employee_trigger
on Employees
after UPDATE, INSERT, DELETE
as
declare @EmpID int,@user varchar(20), @activity varchar(20);
if exists(SELECT * from inserted) and exists (SELECT * from deleted)
begin
    SET @activity = 'UPDATE';
    SET @user = SYSTEM_USER;
    SELECT @EmpID = EmployeeID from inserted i;
    INSERT into Emp_Audit(EmpID,Activity, DoneBy) values (@EmpID,@activity,@user);
end

If exists (Select * from inserted) and not exists(Select * from deleted)
begin
    SET @activity = 'INSERT';
    SET @user = SYSTEM_USER;
    SELECT @EmpID = EmployeeID from inserted i;
    INSERT into Emp_Audit(EmpID,Activity, DoneBy) values(@EmpID,@activity,@user);
end

If exists(select * from deleted) and not exists(Select * from inserted)
begin 
    SET @activity = 'DELETE';
    SET @user = SYSTEM_USER;
    SELECT @EmpID = EmployeeID from deleted i;
    INSERT into Emp_Audit(EmpID,Activity, DoneBy) values(@EmpID,@activity,@user);
end

Running Selenium Webdriver with a proxy in Python

Works for me this way (similar to @Amey and @user4642224 code, but shorter a bit):

from selenium import webdriver
from selenium.webdriver.common.proxy import Proxy, ProxyType

prox = Proxy()
prox.proxy_type = ProxyType.MANUAL
prox.http_proxy = "ip_addr:port"
prox.socks_proxy = "ip_addr:port"
prox.ssl_proxy = "ip_addr:port"

capabilities = webdriver.DesiredCapabilities.CHROME
prox.add_to_capabilities(capabilities)

driver = webdriver.Chrome(desired_capabilities=capabilities)

check if file exists on remote host with ssh

On CentOS machine, the oneliner bash that worked for me was:

if ssh <servername> "stat <filename> > /dev/null 2>&1"; then echo "file exists"; else echo "file doesnt exits"; fi

It needed I/O redirection (as the top answer) as well as quotes around the command to be run on remote.

Python function pointer

It's much nicer to be able to just store the function itself, since they're first-class objects in python.

import mypackage

myfunc = mypackage.mymodule.myfunction
myfunc(parameter1, parameter2)

But, if you have to import the package dynamically, then you can achieve this through:

mypackage = __import__('mypackage')
mymodule = getattr(mypackage, 'mymodule')
myfunction = getattr(mymodule, 'myfunction')

myfunction(parameter1, parameter2)

Bear in mind however, that all of that work applies to whatever scope you're currently in. If you don't persist them somehow, you can't count on them staying around if you leave the local scope.

Unexpected 'else' in "else" error

You need to rearrange your curly brackets. Your first statement is complete, so R interprets it as such and produces syntax errors on the other lines. Your code should look like:

if (dsnt<0.05) {
  wilcox.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)
} else if (dst<0.05) {
  wilcox.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)
} else {
  t.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)       
} 

To put it more simply, if you have:

if(condition == TRUE) x <- TRUE
else x <- FALSE

Then R reads the first line and because it is complete, runs that in its entirety. When it gets to the next line, it goes "Else? Else what?" because it is a completely new statement. To have R interpret the else as part of the preceding if statement, you must have curly brackets to tell R that you aren't yet finished:

if(condition == TRUE) {x <- TRUE
 } else {x <- FALSE}

Can I run Keras model on gpu?

I'm using Anaconda on Windows 10, with a GTX 1660 Super. I first installed the CUDA environment following this step-by-step. However there is now a keras-gpu metapackage available on Anaconda which apparently doesn't require installing CUDA and cuDNN libraries beforehand (mine were already installed anyway).

This is what worked for me to create a dedicated environment named keras_gpu:

# need to downgrade from tensorflow 2.1 for my particular setup
conda create --name keras_gpu keras-gpu=2.3.1 tensorflow-gpu=2.0

To add on @johncasey 's answer but for TensorFlow 2.0, adding this block works for me:

import tensorflow as tf
from tensorflow.python.keras import backend as K

# adjust values to your needs
config = tf.compat.v1.ConfigProto( device_count = {'GPU': 1 , 'CPU': 8} )
sess = tf.compat.v1.Session(config=config) 
K.set_session(sess)

This post solved the set_session error I got: you need to use the keras backend from the tensorflow path instead of keras itself.

Javascript to check whether a checkbox is being checked or unchecked

The value attribute of a checkbox is what you set by:

<input type='checkbox' name='test' value='1'>

So when someone checks that box, the server receives a variable named test with a value of 1 - what you want to check for is not the value of it (which will never change, whether it is checked or not) but the checked status of the checkbox.

So, if you replace this code:

if (arrChecks[i].value == "on") 
{
    arrChecks[i].checked = 1;
} else {
    arrChecks[i].checked = 0;
}

With this:

arrChecks[i].checked = !arrChecks[i].checked;

It should work. You should use true and false instead of 0 and 1 for this.

How do I convert a Django QuerySet into list of dicts?

Use the .values() method:

>>> Blog.objects.values()
[{'id': 1, 'name': 'Beatles Blog', 'tagline': 'All the latest Beatles news.'}],
>>> Blog.objects.values('id', 'name')
[{'id': 1, 'name': 'Beatles Blog'}]

Note: the result is a QuerySet which mostly behaves like a list, but isn't actually an instance of list. Use list(Blog.objects.values(…)) if you really need an instance of list.

What's the difference between getRequestURI and getPathInfo methods in HttpServletRequest?

I will put a small comparison table here (just to have it somewhere):

Servlet is mapped as /test%3F/* and the application is deployed under /app.

http://30thh.loc:8480/app/test%3F/a%3F+b;jsessionid=S%3F+ID?p+1=c+d&p+2=e+f#a

Method              URL-Decoded Result           
----------------------------------------------------
getContextPath()        no      /app
getLocalAddr()                  127.0.0.1
getLocalName()                  30thh.loc
getLocalPort()                  8480
getMethod()                     GET
getPathInfo()           yes     /a?+b
getProtocol()                   HTTP/1.1
getQueryString()        no      p+1=c+d&p+2=e+f
getRequestedSessionId() no      S%3F+ID
getRequestURI()         no      /app/test%3F/a%3F+b;jsessionid=S+ID
getRequestURL()         no      http://30thh.loc:8480/app/test%3F/a%3F+b;jsessionid=S+ID
getScheme()                     http
getServerName()                 30thh.loc
getServerPort()                 8480
getServletPath()        yes     /test?
getParameterNames()     yes     [p 2, p 1]
getParameter("p 1")     yes     c d

In the example above the server is running on the localhost:8480 and the name 30thh.loc was put into OS hosts file.

Comments

  • "+" is handled as space only in the query string

  • Anchor "#a" is not transferred to the server. Only the browser can work with it.

  • If the url-pattern in the servlet mapping does not end with * (for example /test or *.jsp), getPathInfo() returns null.

If Spring MVC is used

  • Method getPathInfo() returns null.

  • Method getServletPath() returns the part between the context path and the session ID. In the example above the value would be /test?/a?+b

  • Be careful with URL encoded parts of @RequestMapping and @RequestParam in Spring. It is buggy (current version 3.2.4) and is usually not working as expected.

How to hide UINavigationBar 1px bottom line

I ran into the same issue and none of the answers were truly satisfying. Here is my take for Swift3:

func hideNavigationBarLine() {
    navigationController?.navigationBar.setBackgroundImage(UIImage(), for: .default)
    navigationController?.navigationBar.shadowImage = UIImage()
}

Simply call this from within viewDidLoad().

Android SQLite SELECT Query

Try trimming the string to make sure there is no extra white space:

Cursor c = db.rawQuery("SELECT * FROM tbl1 WHERE TRIM(name) = '"+name.trim()+"'", null);

Also use c.moveToFirst() like @thinksteep mentioned.


This is a complete code for select statements.

SQLiteDatabase db = this.getReadableDatabase();
Cursor c = db.rawQuery("SELECT column1,column2,column3 FROM table ", null);
if (c.moveToFirst()){
    do {
        // Passing values 
        String column1 = c.getString(0);
        String column2 = c.getString(1);
        String column3 = c.getString(2); 
        // Do something Here with values
    } while(c.moveToNext());
}
c.close();
db.close();

Using set_facts and with_items together in Ansible

Updated 2018-06-08: My previous answer was a bit of hack so I have come back and looked at this again. This is a cleaner Jinja2 approach.

- name: Set fact 4
  set_fact:
    foo: "{% for i in foo_result.results %}{% do foo.append(i) %}{% endfor %}{{ foo }}"

I am adding this answer as current best answer for Ansible 2.2+ does not completely cover the original question. Thanks to Russ Huguley for your answer this got me headed in the right direction but it left me with a concatenated string not a list. This solution gets a list but becomes even more hacky. I hope this gets resolved in a cleaner manner.

- name: build foo_string
  set_fact:
    foo_string: "{% for i in foo_result.results %}{{ i.ansible_facts.foo_item }}{% if not loop.last %},{% endif %}{%endfor%}"

- name: set fact foo
  set_fact:
    foo: "{{ foo_string.split(',') }}"

How to convert a time string to seconds?

A little more pythonic way I think would be:

timestr = '00:04:23'

ftr = [3600,60,1]

sum([a*b for a,b in zip(ftr, map(int,timestr.split(':')))])

Output is 263Sec.

I would be interested to see if anyone could simplify it further.

Compile to a stand-alone executable (.exe) in Visual Studio

Anything using the managed environment (which includes anything written in C# and VB.NET) requires the .NET framework. You can simply redistribute your .EXE in that scenario, but they'll need to install the appropriate framework if they don't already have it.

How to insert strings containing slashes with sed?

A simplier alternative is using AWK as on this answer:

awk '$0="prefix"$0' file > new_file

git-upload-pack: command not found, when cloning remote Git repo

Mac OS X and some other Unixes at least have the user path compiled into sshd for security reasons so those of us that install git as /usr/local/git/{bin,lib,...} can run into trouble as the git executables are not in the precompiled path. To override this I prefer to edit my /etc/sshd_config changing:

#PermitUserEnvironment no

to

PermitUserEnvironment yes

and then create ~/.ssh/environment files as needed. My git users have the following in their ~/.ssh/environment file:

PATH=/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/git/bin

Note variable expansion does not occur when the ~/.ssh/environment file is read so:

PATH=$PATH:/usr/local/git/bin

will not work.

How to check for palindrome using Python logic

#!/usr/bin/python

str = raw_input("Enter a string ")
print "String entered above is %s" %str
strlist = [x for x in str ]
print "Strlist is %s" %strlist
strrev = list(reversed(strlist)) 
print "Strrev is %s" %strrev
if strlist == strrev :
   print "String is palindrome"
else :
   print "String is not palindrome"

Trying to Validate URL Using JavaScript

I have found a great resource for comparing different solutions: https://mathiasbynens.be/demo/url-regex

According to that page, only solution from diegoperini passes all tests. Here is that regex:

_^(?:(?:https?|ftp)://)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\x{00a1}-\x{ffff}0-9]+-?)*[a-z\x{00a1}-\x{ffff}0-9]+)(?:\.(?:[a-z\x{00a1}-\x{ffff}0-9]+-?)*[a-z\x{00a1}-\x{ffff}0-9]+)*(?:\.(?:[a-z\x{00a1}-\x{ffff}]{2,})))(?::\d{2,5})?(?:/[^\s]*)?$_iuS

Is it really impossible to make a div fit its size to its content?

it works well on Edge and Chrome:

  width: fit-content;
  height: fit-content;

How to Use UTF-8 Collation in SQL Server database?

Note that as of Microsoft SQL Server 2016, UTF-8 is supported by bcp, BULK_INSERT, and OPENROWSET.

Addendum 2016-12-21: SQL Server 2016 SP1 now enables Unicode Compression (and most other previously Enterprise-only features) for all versions of MS SQL including Standard and Express. This is not the same as UTF-8 support, but it yields a similar benefit if the goal is disk space reduction for Western alphabets.

Thread-safe List<T> property

It seems like many of the people finding this are wanting a thread safe indexed dynamically sized collection. The closest and easiest thing I know of would be.

System.Collections.Concurrent.ConcurrentDictionary<int, YourDataType>

This would require you to ensure your key is properly incriminated if you want normal indexing behavior. If you are careful .count could suffice as the key for any new key value pairs you add.

How do I turn off Oracle password expiration?

For those who are using Oracle 12.1.0 for development purposes:
I found that the above methods would have no effect on the db user: "system", because the account_status would remain in the expired-grace period.

The easiest solution was for me to use SQL Developer:
within SQL Developer, I had to go to: View / DBA / Security and then Users / System and then on the right side: Actions / Expire pw and then: Actions / Edit and I could untick the option for expired.

This cleared the account_status, it shows OPEN again, and the SQL Developer is no longer showing the ORA-28002 message.

How do I solve the INSTALL_FAILED_DEXOPT error?

I needed to disable Instant Run to fix the issue. To disable Instant Run on OS X, go to Android Studio > Preferences > Build, Execution, Deployment > Instant Run then remove the tick from Enable Instant Run to hot swap code/resource changes on deploy (default enabled).

How to set date format in HTML date input tag?

If you're using jQuery, here's a nice simple method

$("#dateField").val(new Date().toISOString().substring(0, 10));

Or there's the old traditional way:

document.getElementById("dateField").value = new Date().toISOString().substring(0, 10)

New to MongoDB Can not run command mongo

This worked for me (if it applies that you also see the lock file):

first>youridhere@ubuntu:/var/lib/mongodb$ sudo service mongodb start 
then >youridhere@ubuntu:/var/lib/mongodb$ sudo rm mongod.lock*

Getting data from Yahoo Finance

Since Yahoo Finances API was disabled, I found Alpha Vantage API

This a stock query sample that I'm using with Excel's Power Query:

https://www.alphavantage.co/query?function=TIME_SERIES_INTRADAY&symbol=MSFT&interval=15min&outputsize=full&apikey=demo

High Quality Image Scaling Library

There's an article on Code Project about using GDI+ for .NET to do photo resizing using, say, Bicubic interpolation.

There was also another article about this topic on another blog (MS employee, I think), but I can't find the link anywhere. :( Perhaps someone else can find it?

SQL Server Insert Example

I hope this will help you

Create table :

create table users (id int,first_name varchar(10),last_name varchar(10));

Insert values into the table :

insert into users (id,first_name,last_name) values(1,'Abhishek','Anand');

Saving an Object (Data persistence)

I think it's a pretty strong assumption to assume that the object is a class. What if it's not a class? There's also the assumption that the object was not defined in the interpreter. What if it was defined in the interpreter? Also, what if the attributes were added dynamically? When some python objects have attributes added to their __dict__ after creation, pickle doesn't respect the addition of those attributes (i.e. it 'forgets' they were added -- because pickle serializes by reference to the object definition).

In all these cases, pickle and cPickle can fail you horribly.

If you are looking to save an object (arbitrarily created), where you have attributes (either added in the object definition, or afterward)… your best bet is to use dill, which can serialize almost anything in python.

We start with a class…

Python 2.7.8 (default, Jul 13 2014, 02:29:54) 
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> class Company:
...     pass
... 
>>> company1 = Company()
>>> company1.name = 'banana'
>>> company1.value = 40
>>> with open('company.pkl', 'wb') as f:
...     pickle.dump(company1, f, pickle.HIGHEST_PROTOCOL)
... 
>>> 

Now shut down, and restart...

Python 2.7.8 (default, Jul 13 2014, 02:29:54) 
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> with open('company.pkl', 'rb') as f:
...     company1 = pickle.load(f)
... 
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 1378, in load
    return Unpickler(file).load()
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 858, in load
dispatch[key](self)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 1090, in load_global
    klass = self.find_class(module, name)
  File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 1126, in find_class
    klass = getattr(mod, name)
AttributeError: 'module' object has no attribute 'Company'
>>> 

Oops… pickle can't handle it. Let's try dill. We'll throw in another object type (a lambda) for good measure.

Python 2.7.8 (default, Jul 13 2014, 02:29:54) 
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import dill       
>>> class Company:
...     pass
... 
>>> company1 = Company()
>>> company1.name = 'banana'
>>> company1.value = 40
>>> 
>>> company2 = lambda x:x
>>> company2.name = 'rhubarb'
>>> company2.value = 42
>>> 
>>> with open('company_dill.pkl', 'wb') as f:
...     dill.dump(company1, f)
...     dill.dump(company2, f)
... 
>>> 

And now read the file.

Python 2.7.8 (default, Jul 13 2014, 02:29:54) 
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import dill
>>> with open('company_dill.pkl', 'rb') as f:
...     company1 = dill.load(f)
...     company2 = dill.load(f)
... 
>>> company1 
<__main__.Company instance at 0x107909128>
>>> company1.name
'banana'
>>> company1.value
40
>>> company2.name
'rhubarb'
>>> company2.value
42
>>>    

It works. The reason pickle fails, and dill doesn't, is that dill treats __main__ like a module (for the most part), and also can pickle class definitions instead of pickling by reference (like pickle does). The reason dill can pickle a lambda is that it gives it a name… then pickling magic can happen.

Actually, there's an easier way to save all these objects, especially if you have a lot of objects you've created. Just dump the whole python session, and come back to it later.

Python 2.7.8 (default, Jul 13 2014, 02:29:54) 
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import dill
>>> class Company:
...     pass
... 
>>> company1 = Company()
>>> company1.name = 'banana'
>>> company1.value = 40
>>> 
>>> company2 = lambda x:x
>>> company2.name = 'rhubarb'
>>> company2.value = 42
>>> 
>>> dill.dump_session('dill.pkl')
>>> 

Now shut down your computer, go enjoy an espresso or whatever, and come back later...

Python 2.7.8 (default, Jul 13 2014, 02:29:54) 
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import dill
>>> dill.load_session('dill.pkl')
>>> company1.name
'banana'
>>> company1.value
40
>>> company2.name
'rhubarb'
>>> company2.value
42
>>> company2
<function <lambda> at 0x1065f2938>

The only major drawback is that dill is not part of the python standard library. So if you can't install a python package on your server, then you can't use it.

However, if you are able to install python packages on your system, you can get the latest dill with git+https://github.com/uqfoundation/dill.git@master#egg=dill. And you can get the latest released version with pip install dill.

How do I find duplicate values in a table in Oracle?

Simplest I can think of:

select job_number, count(*)
from jobs
group by job_number
having count(*) > 1;

Nodejs send file in response

Here's an example program that will send myfile.mp3 by streaming it from disk (that is, it doesn't read the whole file into memory before sending the file). The server listens on port 2000.

[Update] As mentioned by @Aftershock in the comments, util.pump is gone and was replaced with a method on the Stream prototype called pipe; the code below reflects this.

var http = require('http'),
    fileSystem = require('fs'),
    path = require('path');

http.createServer(function(request, response) {
    var filePath = path.join(__dirname, 'myfile.mp3');
    var stat = fileSystem.statSync(filePath);

    response.writeHead(200, {
        'Content-Type': 'audio/mpeg',
        'Content-Length': stat.size
    });

    var readStream = fileSystem.createReadStream(filePath);
    // We replaced all the event handlers with a simple call to readStream.pipe()
    readStream.pipe(response);
})
.listen(2000);

Taken from http://elegantcode.com/2011/04/06/taking-baby-steps-with-node-js-pumping-data-between-streams/

How to use requirements.txt to install all dependencies in a python project

(Taken from my comment)

pip won't handle system level dependencies. You'll have to apt-get install libfreetype6-dev before continuing. (It even says so right in your output. Try skimming over it for such errors next time, usually build outputs are very detailed)

What is the Java equivalent for LINQ?

you can try this library: https://code.google.com/p/qood/

Here are some reasons to use it:

  1. lightweight: only 9 public interface/class to learn.
  2. query like SQL: support group-by, order-by, left join, formula,...etc.
  3. for big data: use File(QFS) instead of Heap Memory.
  4. try to solve Object-relational impedance mismatch.

How do I create a crontab through a script

Crontab files are simply text files and as such can be treated like any other text file. The purpose of the crontab command is to make editing crontab files safer. When edited through this command, the file is checked for errors and only saved if there are none.

crontab [path to file] can be used to specify a crontab stored in a file. Like crontab -e, this will only install the file if it is error free.

Therefore, a script can either directly write cron tab files, or write them to a temporary file and load them with the crontab [path to temp file] command. Writing directly saves having to write a temporary file, but it also avoids the safety check.

How do I increase the RAM and set up host-only networking in Vagrant?

To increase the memory or CPU count when using Vagrant 2, add this to your Vagrantfile

Vagrant.configure("2") do |config|
    # usual vagrant config here

    config.vm.provider "virtualbox" do |v|
        v.memory = 1024
        v.cpus = 2
    end
end

Pandas convert dataframe to array of tuples

list(data_set.itertuples(index=False))

As of 17.1, the above will return a list of namedtuples.

If you want a list of ordinary tuples, pass name=None as an argument:

list(data_set.itertuples(index=False, name=None))

Screenshot sizes for publishing android app on Google Play

You can upload up to 8 screenshots. Those screenshots must be one of the dimensions (sizes) you listed; you can have multiple screenshots of the same dimensions.

Animate background image change with jQuery

The simplest solution would be to wrap the element with a div. That wrapping div would have the hidden background image that would appear as the inner element fades.

Here's some example javascript:

$('#wrapper').hover(function(event){
    $('#inner').fadeOut(300);
}, function(event){
    $('#inner').fadeIn(300);
});

and here's the html to go along with it:

<div id="wrapper"><div id="inner">Your inner text</div></div>

Determining the version of Java SDK on the Mac

Open a terminal and type: java -version, or javac -version.

If you have all the latest updates for Snow Leopard, you should be running JDK 1.6.0_20 at this moment (the same as Oracle's current JDK version).

CASE (Contains) rather than equal statement

Pseudo code, something like:

CASE
  When CHARINDEX('lactulose', dbo.Table.Column) > 0 Then 'BP Medication'
ELSE ''
END AS 'Medication Type'

This does not care where the keyword is found in the list and avoids depending on formatting of spaces and commas.

Determine if an element has a CSS class with jQuery

Without jQuery:

var hasclass=!!(' '+elem.className+' ').indexOf(' check_class ')+1;

Or:

function hasClass(e,c){
    return e&&(e instanceof HTMLElement)&&!!((' '+e.className+' ').indexOf(' '+c+' ')+1);
}
/*example of usage*/
var has_class_medium=hasClass(document.getElementsByTagName('input')[0],'medium');

This is WAY faster than jQuery!

C# Interfaces. Implicit implementation versus Explicit implementation

I use explicit interface implementation most of the time. Here are the main reasons.

Refactoring is safer

When changing an interface, it's better if the compiler can check it. This is harder with implicit implementations.

Two common cases come to mind:

  • Adding a function to an interface, where an existing class that implements this interface already happens to have a method with the same signature as the new one. This can lead to unexpected behavior, and has bitten me hard several times. It's difficult to "see" when debugging because that function is likely not located with the other interface methods in the file (the self-documenting issue mentioned below).

  • Removing a function from an interface. Implicitly implemented methods will be suddenly dead code, but explicitly implemented methods will get caught by compile error. Even if the dead code is good to keep around, I want to be forced to review it and promote it.

It's unfortunate that C# doesn't have a keyword that forces us to mark a method as an implicit implementation, so the compiler could do the extra checks. Virtual methods don't have either of the above problems due to required use of 'override' and 'new'.

Note: for fixed or rarely-changing interfaces (typically from vendor API's), this is not a problem. For my own interfaces, though, I can't predict when/how they will change.

It's self-documenting

If I see 'public bool Execute()' in a class, it's going to take extra work to figure out that it's part of an interface. Somebody will probably have to comment it saying so, or put it in a group of other interface implementations, all under a region or grouping comment saying "implementation of ITask". Of course, that only works if the group header isn't offscreen..

Whereas: 'bool ITask.Execute()' is clear and unambiguous.

Clear separation of interface implementation

I think of interfaces as being more 'public' than public methods because they are crafted to expose just a bit of the surface area of the concrete type. They reduce the type to a capability, a behavior, a set of traits, etc. And in the implementation, I think it's useful to keep this separation.

As I am looking through a class's code, when I come across explicit interface implementations, my brain shifts into "code contract" mode. Often these implementations simply forward to other methods, but sometimes they will do extra state/param checking, conversion of incoming parameters to better match internal requirements, or even translation for versioning purposes (i.e. multiple generations of interfaces all punting down to common implementations).

(I realize that publics are also code contracts, but interfaces are much stronger, especially in an interface-driven codebase where direct use of concrete types is usually a sign of internal-only code.)

Related: Reason 2 above by Jon.

And so on

Plus the advantages already mentioned in other answers here:

Problems

It's not all fun and happiness. There are some cases where I stick with implicits:

  • Value types, because that will require boxing and lower perf. This isn't a strict rule, and depends on the interface and how it's intended to be used. IComparable? Implicit. IFormattable? Probably explicit.
  • Trivial system interfaces that have methods that are frequently called directly (like IDisposable.Dispose).

Also, it can be a pain to do the casting when you do in fact have the concrete type and want to call an explicit interface method. I deal with this in one of two ways:

  1. Add publics and have the interface methods forward to them for the implementation. Typically happens with simpler interfaces when working internally.
  2. (My preferred method) Add a public IMyInterface I { get { return this; } } (which should get inlined) and call foo.I.InterfaceMethod(). If multiple interfaces that need this ability, expand the name beyond I (in my experience it's rare that I have this need).

How do I show my global Git configuration?

On Linux-based systems you can view/edit a configuration file by

vi/vim/nano .git/config

Make sure you are inside the Git init folder.

If you want to work with --global config, it's

vi/vim/nano .gitconfig

on /home/userName

This should help with editing: https://help.github.com/categories/setup/

Multiline TextView in Android?

Simply put '\n' inside your text... no extra attribute required :)

          <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:text="Pigeon\nControl\nServices"
            android:id="@+id/textView5"
            android:layout_gravity="center"
            android:paddingLeft="12dp"/> 

Wordpress - Images not showing up in the Media Library

check .htaccess file in root of wordpress, maybe there is a rule for /uploads directory. if so, remove it. but be careful and check which plugin did it, so disable the plugin, first.

Char array in a struct - incompatible assignment?

This has nothing to do with structs - arrays in C are not assignable:

char a[20];
a = "foo";   // error

you need to use strcpy:

strcpy( a, "foo" );

or in your code:

strcpy( sara.first, "Sara" );

pip install returning invalid syntax

I use Enthought Canopy for my python, at first I used "pip install --upgrade pip", it showed a syntax error like yours, then I added a "!" in front of the pip, then it finally worked.

np.mean() vs np.average() in Python NumPy?

In your invocation, the two functions are the same.

average can compute a weighted average though.

Doc links: mean and average

Eclipse count lines of code

For static analysis, I've used and recommend SonarQube which runs just about all the metrics you could possibly want on a wide range of languages, and is free in the basic version (you have to pay to analyse the sorts of languages I'd only code in with a gun to my head).

You have to install it as a web-app running the analysis off your source code repository, but it also has an Eclipse plugin.

It's overkill if you just want to know, as a one-off, how many lines of code there are in your project. If you want to track metrics through time, compare across projects, fire warnings when a threshold is exceeded, etc., it's fantastic.

Disclosure: I have no financial relationship with SonarSource.

Open a Web Page in a Windows Batch FIle

When you use the start command to a website it will use the default browser by default but if you want to use a specific browser then use start iexplorer.exe www.website.com

Also you cannot have http:// in the url.

How can I find an element by CSS class with XPath?

Most easy way..

//div[@class="Test"]

Assuming you want to find <div class="Test"> as described.

What is the Difference Between read() and recv() , and Between send() and write()?

Per the first hit on Google

read() is equivalent to recv() with a flags parameter of 0. Other values for the flags parameter change the behaviour of recv(). Similarly, write() is equivalent to send() with flags == 0.

jQuery get html of container including the container itself

Oldie but goldie...

Since user is asking for jQuery, I'm going to keep it simple:

var html = $('#container').clone();
console.log(html);

Fiddle here.

How to install crontab on Centos

As seen in Install crontab on CentOS, the crontab package in CentOS is vixie-cron. Hence, do install it with:

yum install vixie-cron

And then start it with:

service crond start

To make it persistent, so that it starts on boot, use:

chkconfig crond on

On CentOS 7 you need to use cronie:

yum install cronie

On CentOS 6 you can install vixie-cron, but the real package is cronie:

yum install vixie-cron

and

yum install cronie

In both cases you get the same output:

.../...
==================================================================
 Package         Arch       Version         Repository      Size
==================================================================
Installing:
 cronie          x86_64     1.4.4-12.el6    base             73 k
Installing for dependencies:
 cronie-anacron  x86_64     1.4.4-12.el6    base             30 k
 crontabs        noarch     1.10-33.el6     base             10 k
 exim            x86_64     4.72-6.el6      epel            1.2 M

Transaction Summary
==================================================================
Install       4 Package(s)

Adding timestamp to a filename with mv in BASH

mv server.log logs/$(date -d "today" +"%Y%m%d%H%M").log

android get real path by Uri.getPath()

This is what I do:

Uri selectedImageURI = data.getData();
imageFile = new File(getRealPathFromURI(selectedImageURI));

and:

private String getRealPathFromURI(Uri contentURI) {
    String result;
    Cursor cursor = getContentResolver().query(contentURI, null, null, null, null);
    if (cursor == null) { // Source is Dropbox or other similar local file path
        result = contentURI.getPath();
    } else { 
        cursor.moveToFirst(); 
        int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA); 
        result = cursor.getString(idx);
        cursor.close();
    }
    return result;
}

NOTE: managedQuery() method is deprecated, so I am not using it.

Last edit: Improvement. We should close cursor!!

Prevent the keyboard from displaying on activity start

To expand upon the accepted answer by @Lucas:

Call this from your activity in one of the early life cycle events:

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

Kotlin Example:

override fun onResume() {
  super.onResume()

  window.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN)
}

Is there a way to make a DIV unselectable?

The following CSS code works almost modern browser:

.unselectable {
    -moz-user-select: -moz-none;
    -khtml-user-select: none;
    -webkit-user-select: none;
    -o-user-select: none;
    user-select: none;
}

For IE, you must use JS or insert attribute in html tag.

<div id="foo" unselectable="on" class="unselectable">...</div>

How to modify memory contents using GDB?

As Nikolai has said you can use the gdb 'set' command to change the value of a variable.

You can also use the 'set' command to change memory locations. eg. Expanding on Nikolai's example:

(gdb) l
6       {
7           int i;
8           struct file *f, *ftmp;
9
(gdb) set variable i = 10
(gdb) p i
$1 = 10

(gdb) p &i
$2 = (int *) 0xbfbb0000
(gdb) set *((int *) 0xbfbb0000) = 20
(gdb) p i
$3 = 20

This should work for any valid pointer, and can be cast to any appropriate data type.

Beginner question: returning a boolean value from a function in Python

Have your tried using the 'return' keyword?

def rps():
    return True

MySQL: ignore errors when importing?

Use the --force (-f) flag on your mysql import. Rather than stopping on the offending statement, MySQL will continue and just log the errors to the console.

For example:

mysql -u userName -p -f -D dbName < script.sql

How to make 'submit' button disabled?

.html

<form [formGroup]="contactForm">

<button [disabled]="contactForm.invalid"  (click)="onSubmit()">SEND</button>

.ts

contactForm: FormGroup;

String comparison in bash. [[: not found

As @Ansgar mentioned, [[ is a bashism, ie built into Bash and not available for other shells. If you want your script to be portable, use [. Comparisons will also need a different syntax: change == to =.

Convert character to ASCII numeric value in java

public class Ascii {
    public static void main(String [] args){
        String a=args[0];
        char [] z=a.toCharArray();
        for(int i=0;i<z.length;i++){ 
            System.out.println((int)z[i]);
        }
    }
}

Unrecognized SSL message, plaintext connection? Exception

I face the same issue from Java application built in Jdevelopr 11.1.1.7 IDE. I solved the issue by unchecking the use of proxy form Project properties.

You can find it in the following: Project Properties -> (from left panle )Run/Debug/Profile ->Click (edit) form the right panel -> Tool Setting from the left panel -> uncheck (Use Proxy) option.

How to secure phpMyAdmin

One of my concerns with phpMyAdmin was that by default, all MySQL users can access the db. If DB's root password is compromised, someone can wreck havoc on the db. I wanted to find a way to avoid that by restricting which MySQL user can login to phpMyAdmin.

I have found using AllowDeny configuration in PhpMyAdmin to be very useful. http://wiki.phpmyadmin.net/pma/Config#AllowDeny_.28rules.29

AllowDeny lets you configure access to phpMyAdmin in a similar way to Apache. If you set the 'order' to explicit, it will only grant access to users defined in 'rules' section. In the rules, section you restrict MySql users who can access use the phpMyAdmin.

$cfg['Servers'][$i]['AllowDeny']['order'] = 'explicit'
$cfg['Servers'][$i]['AllowDeny']['rules'] = array('pma-user from all')

Now you have limited access to the user named pma-user in MySQL, you can grant limited privilege to that user.

grant select on db_name.some_table to 'pma-user'@'app-server'

If Python is interpreted, what are .pyc files?

These are created by the Python interpreter when a .py file is imported, and they contain the "compiled bytecode" of the imported module/program, the idea being that the "translation" from source code to bytecode (which only needs to be done once) can be skipped on subsequent imports if the .pyc is newer than the corresponding .py file, thus speeding startup a little. But it's still interpreted.

Custom exception type

Use the throw statement.

JavaScript doesn't care what the exception type is (as Java does). JavaScript just notices, there's an exception and when you catch it, you can "look" what the exception "says".

If you have different exception types you have to throw, I'd suggest to use variables which contain the string/object of the exception i.e. message. Where you need it use "throw myException" and in the catch, compare the caught exception to myException.

How to display my application's errors in JSF?

Remember that:

FacesContext context = FacesContext.getCurrentInstance();
context.addMessage( null, new FacesMessage( "The message to display in client" ));            

is also valid, because when null is specified as first parameter, it is applied to the whole form.

More info: coreservlets.com //Outdated

Disable Enable Trigger SQL server for a table

if you want to execute ENABLE TRIGGER Directly From Source :

we can't write like this:

Conn.Execute "ENABLE TRIGGER trigger_name ON table_name"

instead, we can write :

Conn.Execute "ALTER TABLE table_name DISABLE TRIGGER trigger_name"

Resize image in PHP

Here is an extended version of the answer @Ian Atkin' gave. I found it worked extremely well. For larger images that is :). You can actually make smaller images larger if you're not careful. Changes: - Supports jpg,jpeg,png,gif,bmp files - Preserves transparency for .png and .gif - Double checks if the the size of the original isnt already smaller - Overrides the image given directly (Its what I needed)

So here it is. The default values of the function are the "golden rule"

function resize_image($file, $w = 1200, $h = 741, $crop = false)
   {
       try {
           $ext = pathinfo(storage_path() . $file, PATHINFO_EXTENSION);
           list($width, $height) = getimagesize($file);
           // if the image is smaller we dont resize
           if ($w > $width && $h > $height) {
               return true;
           }
           $r = $width / $height;
           if ($crop) {
               if ($width > $height) {
                   $width = ceil($width - ($width * abs($r - $w / $h)));
               } else {
                   $height = ceil($height - ($height * abs($r - $w / $h)));
               }
               $newwidth = $w;
               $newheight = $h;
           } else {
               if ($w / $h > $r) {
                   $newwidth = $h * $r;
                   $newheight = $h;
               } else {
                   $newheight = $w / $r;
                   $newwidth = $w;
               }
           }
           $dst = imagecreatetruecolor($newwidth, $newheight);

           switch ($ext) {
               case 'jpg':
               case 'jpeg':
                   $src = imagecreatefromjpeg($file);
                   break;
               case 'png':
                   $src = imagecreatefrompng($file);
                   imagecolortransparent($dst, imagecolorallocatealpha($dst, 0, 0, 0, 127));
                   imagealphablending($dst, false);
                   imagesavealpha($dst, true);
                   break;
               case 'gif':
                   $src = imagecreatefromgif($file);
                   imagecolortransparent($dst, imagecolorallocatealpha($dst, 0, 0, 0, 127));
                   imagealphablending($dst, false);
                   imagesavealpha($dst, true);
                   break;
               case 'bmp':
                   $src = imagecreatefrombmp($file);
                   break;
               default:
                   throw new Exception('Unsupported image extension found: ' . $ext);
                   break;
           }
           $result = imagecopyresampled($dst, $src, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
           switch ($ext) {
               case 'bmp':
                   imagewbmp($dst, $file);
                   break;
               case 'gif':
                   imagegif($dst, $file);
                   break;
               case 'jpg':
               case 'jpeg':
                   imagejpeg($dst, $file);
                   break;
               case 'png':
                   imagepng($dst, $file);
                   break;
           }
           return true;
       } catch (Exception $err) {
           // LOG THE ERROR HERE 
           return false;
       }
   }

Sorting list based on values from another list

Shortest Code

[x for _,x in sorted(zip(Y,X))]

Example:

X = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
Y = [ 0,   1,   1,    0,   1,   2,   2,   0,   1]

Z = [x for _,x in sorted(zip(Y,X))]
print(Z)  # ["a", "d", "h", "b", "c", "e", "i", "f", "g"]

Generally Speaking

[x for _, x in sorted(zip(Y,X), key=lambda pair: pair[0])]

Explained:

  1. zip the two lists.
  2. create a new, sorted list based on the zip using sorted().
  3. using a list comprehension extract the first elements of each pair from the sorted, zipped list.

For more information on how to set\use the key parameter as well as the sorted function in general, take a look at this.


Relative URLs in WordPress

I solved it in my site making this in functions.php

add_action("template_redirect", "start_buffer");
add_action("shutdown", "end_buffer", 999);

function filter_buffer($buffer) {
    $buffer = replace_insecure_links($buffer);
    return $buffer;
}
function start_buffer(){
    ob_start("filter_buffer");
}

function end_buffer(){
    if (ob_get_length()) ob_end_flush();
}

function replace_insecure_links($str) {

   $str = str_replace ( array("http://www.yoursite.com/", "https://www.yoursite.com/") , array("/", "/"), $str);

   return apply_filters("rsssl_fixer_output", $str);

}

I took part of one plugin, cut it into pieces and make this. It replaced ALL links in my site (menus, css, scripts etc.) and everything was working.

Log4j output not displayed in Eclipse console

Sounds like log4j picks up another configuration file than the one you think it does.

Put a breakpoint in log4j where the file is opened and have a look at the files getAbsolutePath().

How to convert DateTime to/from specific string format (both ways, e.g. given Format is "yyyyMMdd")?

no its a string with yyyy/mm/dd and i need it in yyyyMMdd format

If you only need to remove the slashes from a string don't you just replace them?

Example:

myDateString = "2013/03/28";
myDateString = myDateString.Replace("/", "");

myDateString should now be "20130328".

Less of an overkill :)

grep a tab in UNIX

If using GNU grep, you can use the Perl-style regexp:

grep -P '\t' *

Functional, Declarative, and Imperative Programming

imperative and declarative describe two opposing styles of programming. imperative is the traditional "step by step recipe" approach while declarative is more "this is what i want, now you work out how to do it".

these two approaches occur throughout programming - even with the same language and the same program. generally the declarative approach is considered preferable, because it frees the programmer from having to specify so many details, while also having less chance for bugs (if you describe the result you want, and some well-tested automatic process can work backwards from that to define the steps then you might hope that things are more reliable than having to specify each step by hand).

on the other hand, an imperative approach gives you more low level control - it's the "micromanager approach" to programming. and that can allow the programmer to exploit knowledge about the problem to give a more efficient answer. so it's not unusual for some parts of a program to be written in a more declarative style, but for the speed-critical parts to be more imperative.

as you might imagine, the language you use to write a program affects how declarative you can be - a language that has built-in "smarts" for working out what to do given a description of the result is going to allow a much more declarative approach than one where the programmer needs to first add that kind of intelligence with imperative code before being able to build a more declarative layer on top. so, for example, a language like prolog is considered very declarative because it has, built-in, a process that searches for answers.

so far, you'll notice that i haven't mentioned functional programming. that's because it's a term whose meaning isn't immediately related to the other two. at its most simple, functional programming means that you use functions. in particular, that you use a language that supports functions as "first class values" - that means that not only can you write functions, but you can write functions that write functions (that write functions that...), and pass functions to functions. in short - that functions are as flexible and common as things like strings and numbers.

it might seem odd, then, that functional, imperative and declarative are often mentioned together. the reason for this is a consequence of taking the idea of functional programming "to the extreme". a function, in it's purest sense, is something from maths - a kind of "black box" that takes some input and always gives the same output. and that kind of behaviour doesn't require storing changing variables. so if you design a programming language whose aim is to implement a very pure, mathematically influenced idea of functional programming, you end up rejecting, largely, the idea of values that can change (in a certain, limited, technical sense).

and if you do that - if you limit how variables can change - then almost by accident you end up forcing the programmer to write programs that are more declarative, because a large part of imperative programming is describing how variables change, and you can no longer do that! so it turns out that functional programming - particularly, programming in a functional language - tends to give more declarative code.

to summarise, then:

  • imperative and declarative are two opposing styles of programming (the same names are used for programming languages that encourage those styles)

  • functional programming is a style of programming where functions become very important and, as a consequence, changing values become less important. the limited ability to specify changes in values forces a more declarative style.

so "functional programming" is often described as "declarative".

Difference between window.location.href=window.location.href and window.location.reload()

The difference is that

window.location = document.URL;

will not reload the page if there is a hash (#) in the URL (with or without something after it), whereas

window.location.reload();

will reload the page.

Proper way to declare custom exceptions in modern Python?

Try this Example

class InvalidInputError(Exception):
    def __init__(self, msg):
        self.msg = msg
    def __str__(self):
        return repr(self.msg)

inp = int(input("Enter a number between 1 to 10:"))
try:
    if type(inp) != int or inp not in list(range(1,11)):
        raise InvalidInputError
except InvalidInputError:
    print("Invalid input entered")

How do I remove documents using Node.js Mongoose?

mongoose.model.find() returns a Query Object which also has a remove() function.

You can use mongoose.model.findOne() as well, if you want to remove only one unique document.

Else you can follow traditional approach as well where you first retrieving the document and then remove.

yourModelObj.findById(id, function (err, doc) {
    if (err) {
        // handle error
    }

    doc.remove(callback); //Removes the document
})

Following are the ways on model object you can do any of the following to remove document(s):

yourModelObj.findOneAndRemove(conditions, options, callback)

yourModelObj.findByIdAndRemove(id, options, callback)

yourModelObj.remove(conditions, callback);

var query = Comment.remove({ _id: id });
query.exec();

Printing the value of a variable in SQL Developer

DECLARE

  CTABLE USER_OBJECTS.OBJECT_NAME%TYPE;
  CCOLUMN ALL_TAB_COLS.COLUMN_NAME%TYPE;
  V_ALL_COLS VARCHAR2(5000);

  CURSOR CURSOR_TABLE
    IS
    SELECT OBJECT_NAME 
    FROM USER_OBJECTS 
    WHERE OBJECT_TYPE='TABLE'
    AND OBJECT_NAME LIKE 'STG%';

  CURSOR CURSOR_COLUMNS (V_TABLE_NAME IN VARCHAR2)
    IS
    SELECT COLUMN_NAME
    FROM ALL_TAB_COLS
    WHERE TABLE_NAME = V_TABLE_NAME;

BEGIN

  OPEN CURSOR_TABLE;
  LOOP
    FETCH CURSOR_TABLE INTO CTABLE;

    OPEN CURSOR_COLUMNS (CTABLE);
    V_ALL_COLS := NULL;
    LOOP

      FETCH CURSOR_COLUMNS INTO CCOLUMN;
      V_ALL_COLS := V_ALL_COLS || CCOLUMN;
      IF CURSOR_COLUMNS%FOUND THEN
        V_ALL_COLS := V_ALL_COLS || ', ';
      ELSE
        EXIT;
      END IF;
    END LOOP;
   close CURSOR_COLUMNS ;
    DBMS_OUTPUT.PUT_LINE(V_ALL_COLS);
    EXIT WHEN CURSOR_TABLE%NOTFOUND;
  END LOOP;`enter code here`
  CLOSE CURSOR_TABLE;

END;

I have added Close of second cursor. It working and getting output as well...

psql: server closed the connection unexepectedly

this is an old post but...

just surprised that nobody talk about pg_hba file as it can be a good reason to get this error code.

Check here for those who forgot to configure it: http://www.postgresql.org/docs/current/static/auth-pg-hba-conf.html

Typescript import/as vs import/require?

import * as express from "express";

This is the suggested way of doing it because it is the standard for JavaScript (ES6/2015) since last year.

In any case, in your tsconfig.json file, you should target the module option to commonjs which is the format supported by nodejs.

C# DLL config file

It is not trivial to create a .NET configuration file for a .DLL, and for good reason. The .NET configuration mechanism has a lot of features built into it to facilitate easy upgrading/updating of the app, and to protect installed apps from trampling each others configuration files.

There is a big difference between how a DLL is used and how an application is used. You are unlikely to have multiple copies of an application installed on the same machine for the same user. But you may very well have 100 different apps or libraries all making use of some .NET DLL.

Whereas there is rarely a need to track settings separately for different copies of an app within one user profile, it's very unlikely that you would want all of the different usages of a DLL to share configuration with each other. For this reason, when you retrieve a Configuration object using the "normal" method, the object you get back is tied to the configuration of the App Domain you are executing in, rather than the particular assembly.

The App Domain is bound to the root assembly which loaded the assembly which your code is actually in. In most cases this will be the assembly of your main .EXE, which is what loaded up the .DLL. It is possible to spin up other app domains within an application, but you must explicitly provide information on what the root assembly of that app domain is.

Because of all this, the procedure for creating a library-specific config file is not so convenient. It is the same process you would use for creating an arbitrary portable config file not tied to any particular assembly, but for which you want to make use of .NET's XML schema, config section and config element mechanisms, etc. This entails creating an ExeConfigurationFileMap object, loading in the data to identify where the config file will be stored, and then calling ConfigurationManager.OpenMappedExeConfiguration to open it up into a new Configuration instance. This will cut you off from the version protection offered by the automatic path generation mechanism.

Statistically speaking, you're probably using this library in an in-house setting, and it's unlikely you'll have multiple apps making use of it within any one machine/user. But if not, there is something you should keep in mind. If you use a single global config file for your DLL, regardless of the app that is referencing it, you need to worry about access conflicts. If two apps referencing your library happen to be running at the same time, each with their own Configuration object open, then when one saves changes, it will cause an exception next time you try to retrieve or save data in the other app.

The safest and simplest way of getting around this is to require that the assembly which is loading your DLL also provide some information about itself, or to detect it by examining the App Domain of the referencing assembly. Use this to create some sort of folder structure for keeping separate user config files for each app referencing your DLL.

If you are certain you want to have global settings for your DLL no matter where it is referenced, you'll need to determine your location for it rather than .NET figuring out an appropriate one automatically. You'll also need to be aggressive about managing access to the file. You'll need to cache as much as possible, keeping the Configuration instance around ONLY as long as it takes to load or to save, opening immediately before and disposing immediately after. And finally, you'll need a lock mechanism to protect the file while it's being edited by one of the apps that use the library.

Open a facebook link by native Facebook app on iOS

I know the question is old, but in support of the above answers i wanted to share my working code. Just add these two methods to whatever class.The code checks if facebook app is installed, if not installed the url is opened in a browser.And if any errors occur when trying to find the profileId, the page will be opened in a browser. Just pass the url(example, http://www.facebook.com/AlibabaUS) to openUrl: and it will do all the magic. Hope it helps someone!.

NOTE: UrlUtils was the class that had the code for me, you might have to change it to something else to suite your needs.

+(void) openUrlInBrowser:(NSString *) url
{
    if (url.length > 0) {
        NSURL *linkUrl = [NSURL URLWithString:url];
        [[UIApplication sharedApplication] openURL:linkUrl];
    }
}
+(void) openUrl:(NSString *) urlString
{

    //check if facebook app exists
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"fb://"]]) {

        // Facebook app installed
        NSArray *tokens = [urlString componentsSeparatedByString:@"/"];
        NSString *profileName = [tokens lastObject];

        //call graph api
        NSURL *apiUrl = [NSURL URLWithString:[NSString stringWithFormat:@"https://graph.facebook.com/%@",profileName]];
        NSData *apiResponse = [NSData dataWithContentsOfURL:apiUrl];

        NSError *error = nil;
        NSDictionary *jsonDict = [NSJSONSerialization JSONObjectWithData:apiResponse options:NSJSONReadingMutableContainers error:&error];

        //check for parse error
        if (error == nil) {

            NSString *profileId = [jsonDict objectForKey:@"id"];

            if (profileId.length > 0) {//make sure id key is actually available
                NSURL *fbUrl = [NSURL URLWithString:[NSString stringWithFormat:@"fb://profile/%@",profileId]];
                [[UIApplication sharedApplication] openURL:fbUrl];
            }
            else{
                [UrlUtils openUrlInBrowser:urlString];
            }

        }
        else{//parse error occured
            [UrlUtils openUrlInBrowser:urlString];
        }

    }
    else{//facebook app not installed
        [UrlUtils openUrlInBrowser:urlString];
    }

}

Simple way to copy or clone a DataRow?

You can use ImportRow method to copy Row from DataTable to DataTable with the same schema:

var row = SourceTable.Rows[RowNum];
DestinationTable.ImportRow(row);

Update:

With your new Edit, I believe:

var desRow = dataTable.NewRow();
var sourceRow = dataTable.Rows[rowNum];
desRow.ItemArray = sourceRow.ItemArray.Clone() as object[];

will work

Strip / trim all strings of a dataframe

def trim(x):
    if x.dtype == object:
        x = x.str.split(' ').str[0]
    return(x)

df = df.apply(trim)

Why can't I initialize non-const static member or static array in class?

It's because there can only be one definition of A::a that all the translation units use.

If you performed static int a = 3; in a class in a header included in all a translation units then you'd get multiple definitions. Therefore, non out-of-line definition of a static is forcibly made a compiler error.

Using static inline or static const remedies this. static inline only concretises the symbol if it is used in the translation unit and ensures the linker only selects and leaves one copy if it's defined in multiple translation units due to it being in a comdat group. const at file scope makes the compiler never emit a symbol because it's always substituted immediately in the code unless extern is used, which is not permitted in a class.

One thing to note is static inline int b; is treated as a definition whereas static const int b or static const A b; are still treated as a declaration and must be defined out-of-line if you don't define it inside the class. Interestingly static constexpr A b; is treated as a definition, whereas static constexpr int b; is an error and must have an initialiser (this is because they now become definitions and like any const/constexpr definition at file scope, they require an initialiser which an int doesn't have but a class type does because it has an implicit = A() when it is a definition -- clang allows this but gcc requires you to explicitly initialise or it is an error. This is not a problem with inline instead). static const A b = A(); is not allowed and must be constexpr or inline in order to permit an initialiser for a static object with class type i.e to make a static member of class type more than a declaration. So yes in certain situations A a; is not the same as explicitly initialising A a = A(); (the former can be a declaration but if only a declaration is allowed for that type then the latter is an error. The latter can only be used on a definition. constexpr makes it a definition). If you use constexpr and specify a default constructor then the constructor will need to be constexpr

#include<iostream>

struct A
{
    int b =2;
    mutable int c = 3; //if this member is included in the class then const A will have a full .data symbol emitted for it on -O0 and so will B because it contains A.
    static const int a = 3;
};

struct B {
    A b;
    static constexpr A c; //needs to be constexpr or inline and doesn't emit a symbol for A a mutable member on any optimisation level
};

const A a;
const B b;

int main()
{
    std::cout << a.b << b.b.b;
    return 0;
}

A static member is an outright file scope declaration extern int A::a; (which can only be made in the class and out of line definitions must refer to a static member in a class and must be definitions and cannot contain extern) whereas a non-static member is part of the complete type definition of a class and have the same rules as file scope declarations without extern. They are implicitly definitions. So int i[]; int i[5]; is a redefinition whereas static int i[]; int A::i[5]; isn't but unlike 2 externs, the compiler will still detect a duplicate member if you do static int i[]; static int i[5]; in the class.

What is phtml, and when should I use a .phtml extension rather than .php?

There is usually no difference, as far as page rendering goes. It's a huge facility developer-side, though, when your web project grows bigger.

I make use of both in this fashion:

  • .PHP Page doesn't contain view-related code
  • .PHTML Page contains little (if any) data logic and the most part of it is presentation-related

What is the Swift equivalent of respondsToSelector?

Currently (Swift 2.1) you can check it using 3 ways:

  1. Using respondsToSelector answered by @Erik_at_Digit
  2. Using '?' answered by @Sulthan

  3. And using as? operator:

    if let delegateMe = self.delegate as? YourCustomViewController
    {
       delegateMe.onSuccess()
    }
    

Basically it depends on what you are trying to achieve:

  • If for example your app logic need to perform some action and the delegate isn't set or the pointed delegate didn't implement the onSuccess() method (protocol method) so option 1 and 3 are the best choice, though I'd use option 3 which is Swift way.
  • If you don't want to do anything when delegate is nil or method isn't implemented then use option 2.

Are nested try/except blocks in Python a good programming practice?

For your specific example, you don't actually need to nest them. If the expression in the try block succeeds, the function will return, so any code after the whole try/except block will only be run if the first attempt fails. So you can just do:

def __getattribute__(self, item):
    try:
        return object.__getattribute__(item)
    except AttributeError:
        pass
    # execution only reaches here when try block raised AttributeError
    try:
        return self.dict[item]
    except KeyError:
        print "The object doesn't have such attribute"

Nesting them isn't bad, but I feel like leaving it flat makes the structure more clear: you're sequentially trying a series of things and returning the first one that works.

Incidentally, you might want to think about whether you really want to use __getattribute__ instead of __getattr__ here. Using __getattr__ will simplify things because you'll know that the normal attribute lookup process has already failed.

How to store command results in a shell variable?

The syntax to store the command output into a variable is var=$(command).

So you can directly do:

result=$(ls -l | grep -c "rahul.*patle")

And the variable $result will contain the number of matches.

How to get address location from latitude and longitude in Google Map.?

Simply pass latitude, longitude and your Google API Key to the following query string, you will get a json array, fetch your city from there.

https://maps.googleapis.com/maps/api/geocode/json?latlng=44.4647452,7.3553838&key=YOUR_API_KEY

Note: Ensure that no space exists between the latitude and longitude values when passed in the latlng parameter.

Click here to get an API key

XML parsing of a variable string in JavaScript

Most examples on the web (and some presented above) show how to load an XML from a file in a browser compatible manner. This proves easy, except in the case of Google Chrome which does not support the document.implementation.createDocument() method. When using Chrome, in order to load an XML file into a XmlDocument object, you need to use the inbuilt XmlHttp object and then load the file by passing it's URI.

In your case, the scenario is different, because you want to load the XML from a string variable, not a URL. For this requirement however, Chrome supposedly works just like Mozilla (or so I've heard) and supports the parseFromString() method.

Here is a function I use (it's part of the Browser compatibility library I'm currently building):

function LoadXMLString(xmlString)
{
  // ObjectExists checks if the passed parameter is not null.
  // isString (as the name suggests) checks if the type is a valid string.
  if (ObjectExists(xmlString) && isString(xmlString))
  {
    var xDoc;
    // The GetBrowserType function returns a 2-letter code representing
    // ...the type of browser.
    var bType = GetBrowserType();

    switch(bType)
    {
      case "ie":
        // This actually calls into a function that returns a DOMDocument 
        // on the basis of the MSXML version installed.
        // Simplified here for illustration.
        xDoc = new ActiveXObject("MSXML2.DOMDocument")
        xDoc.async = false;
        xDoc.loadXML(xmlString);
        break;
      default:
        var dp = new DOMParser();
        xDoc = dp.parseFromString(xmlString, "text/xml");
        break;
    }
    return xDoc;
  }
  else
    return null;
}

MySQL export into outfile : CSV escaping chars

What happens if you try the following?

Instead of your double REPLACE statement, try:

REPLACE(IFNULL(ts.description, ''),'\r\n', '\n')

Also, I think it should be LINES TERMINATED BY '\r\n' instead of just '\n'

How do check if a PHP session is empty?

The best practice is to check if the array key exists using the built-in array_key_exists function.

How to cast an object in Objective-C

Casting for inclusion is just as important as casting for exclusion for a C++ programmer. Type casting is not the same as with RTTI in the sense that you can cast an object to any type and the resulting pointer will not be nil.

Ng-model does not update controller value

I had the same problem.
The proper way would be setting the 'searchText' to be a property inside an object.

But what if I want to leave it as it is, a string? well, I tried every single method mentioned here, nothing worked.
But then I noticed that the problem is only in the initiation, so I've just set the value attribute and it worked.

<input type="text" ng-model="searchText" value={{searchText}} />

This way the value is just set to '$scope.searchText' value and it's being updated when the input value changes.

I know it's a workaround, but it worked for me..

ResourceDictionary in a separate assembly

An example, just to make this a 15 seconds answer -

Say you have "styles.xaml" in a WPF library named "common" and you want to use it from your main application project:

  1. Add a reference from the main project to "common" project
  2. Your app.xaml should contain:

<Application.Resources>
    <ResourceDictionary>
        <ResourceDictionary.MergedDictionaries>
            <ResourceDictionary Source="pack://application:,,,/Common;component/styles.xaml"/>
        </ResourceDictionary.MergedDictionaries>
    </ResourceDictionary>
</Application.Resources>

How to correct "TypeError: 'NoneType' object is not subscriptable" in recursive function?

What is a when you call Ancestors('A',a)? If a['A'] is None, or if a['A'][0] is None, you'd receive that exception.

anaconda - path environment variable in windows

To export the exact set of paths used by Anaconda, use the command echo %PATH% in Anaconda Prompt. This is needed to avoid problems with certain libraries such as SSL.

Reference: https://stackoverflow.com/a/54240362/663028

How to convert Blob to String and String to Blob in java

How are you setting blob to DB? You should do:

 //imagine u have a a prepared statement like:
 PreparedStatement ps = conn.prepareStatement("INSERT INTO table VALUES (?)");
 String blobString= "This is the string u want to convert to Blob";
oracle.sql.BLOB myBlob = oracle.sql.BLOB.createTemporary(conn, false,oracle.sql.BLOB.DURATION_SESSION);
 byte[] buff = blobString.getBytes();
 myBlob.putBytes(1,buff);
 ps.setBlob(1, myBlob);
 ps.executeUpdate();

What is sys.maxint in Python 3?

The sys.maxint constant was removed, since there is no longer a limit to the value of integers. However, sys.maxsize can be used as an integer larger than any practical list or string index. It conforms to the implementation’s “natural” integer size and is typically the same as sys.maxint in previous releases on the same platform (assuming the same build options).

http://docs.python.org/3.1/whatsnew/3.0.html#integers

Shell command to sum integers, one per line?

sed 's/^/.+/' infile | bc | tail -1

SQL SELECT WHERE field contains words

This should ideally be done with the help of sql server full text search if using. However, if you can't get that working on your DB for some reason, here is a performance intensive solution :-

-- table to search in
CREATE TABLE dbo.myTable
    (
    myTableId int NOT NULL IDENTITY (1, 1),
    code varchar(200) NOT NULL, 
    description varchar(200) NOT NULL -- this column contains the values we are going to search in 
    )  ON [PRIMARY]
GO

-- function to split space separated search string into individual words
CREATE FUNCTION [dbo].[fnSplit] (@StringInput nvarchar(max),
@Delimiter nvarchar(1))
RETURNS @OutputTable TABLE (
  id nvarchar(1000)
)
AS
BEGIN
  DECLARE @String nvarchar(100);

  WHILE LEN(@StringInput) > 0
  BEGIN
    SET @String = LEFT(@StringInput, ISNULL(NULLIF(CHARINDEX(@Delimiter, @StringInput) - 1, -1),
    LEN(@StringInput)));
    SET @StringInput = SUBSTRING(@StringInput, ISNULL(NULLIF(CHARINDEX
    (
    @Delimiter, @StringInput
    ),
    0
    ), LEN
    (
    @StringInput)
    )
    + 1, LEN(@StringInput));

    INSERT INTO @OutputTable (id)
      VALUES (@String);
  END;

  RETURN;
END;
GO

-- this is the search script which can be optionally converted to a stored procedure /function


declare @search varchar(max) = 'infection upper acute genito'; -- enter your search string here
-- the searched string above should give rows containing the following
-- infection in upper side with acute genitointestinal tract
-- acute infection in upper teeth
-- acute genitointestinal pain

if (len(trim(@search)) = 0) -- if search string is empty, just return records ordered alphabetically
begin
 select 1 as Priority ,myTableid, code, Description from myTable order by Description 
 return;
end

declare @splitTable Table(
wordRank int Identity(1,1), -- individual words are assinged priority order (in order of occurence/position)
word varchar(200)
)
declare @nonWordTable Table( -- table to trim out auxiliary verbs, prepositions etc. from the search
id varchar(200)
)

insert into @nonWordTable values
('of'),
('with'),
('at'),
('in'),
('for'),
('on'),
('by'),
('like'),
('up'),
('off'),
('near'),
('is'),
('are'),
(','),
(':'),
(';')

insert into @splitTable
select id from dbo.fnSplit(@search,' '); -- this function gives you a table with rows containing all the space separated words of the search like in this e.g., the output will be -
--  id
-------------
-- infection
-- upper
-- acute
-- genito

delete s from @splitTable s join @nonWordTable n  on s.word = n.id; -- trimming out non-words here
declare @countOfSearchStrings int = (select count(word) from @splitTable);  -- count of space separated words for search
declare @highestPriority int = POWER(@countOfSearchStrings,3);

with plainMatches as
(
select myTableid, @highestPriority as Priority from myTable where Description like @search  -- exact matches have highest priority
union                                      
select myTableid, @highestPriority-1 as Priority from myTable where Description like  @search + '%'  -- then with something at the end
union                                      
select myTableid, @highestPriority-2 as Priority from myTable where Description like '%' + @search -- then with something at the beginning
union                                      
select myTableid, @highestPriority-3 as Priority from myTable where Description like '%' + @search + '%' -- then if the word falls somewhere in between
),
splitWordMatches as( -- give each searched word a rank based on its position in the searched string
                     -- and calculate its char index in the field to search
select myTable.myTableid, (@countOfSearchStrings - s.wordRank) as Priority, s.word,
wordIndex = CHARINDEX(s.word, myTable.Description)  from myTable join @splitTable s on myTable.Description like '%'+ s.word + '%'
-- and not exists(select myTableid from plainMatches p where p.myTableId = myTable.myTableId) -- need not look into myTables that have already been found in plainmatches as they are highest ranked
                                                                              -- this one takes a long time though, so commenting it, will have no impact on the result
),
matchingRowsWithAllWords as (
 select myTableid, count(myTableid) as myTableCount from splitWordMatches group by(myTableid) having count(myTableid) = @countOfSearchStrings
)
, -- trim off the CTE here if you don't care about the ordering of words to be considered for priority
wordIndexRatings as( -- reverse the char indexes retrived above so that words occuring earlier have higher weightage
                     -- and then normalize them to sequential values
select s.myTableid, Priority, word, ROW_NUMBER() over (partition by s.myTableid order by wordindex desc) as comparativeWordIndex 
from splitWordMatches s join matchingRowsWithAllWords m on s.myTableId = m.myTableId
)
,
wordIndexSequenceRatings as ( -- need to do this to ensure that if the same set of words from search string is found in two rows,
                              -- their sequence in the field value is taken into account for higher priority
    select w.myTableid, w.word, (w.Priority + w.comparativeWordIndex + coalesce(sequncedPriority ,0)) as Priority
    from wordIndexRatings w left join 
    (
     select w1.myTableid, w1.priority, w1.word, w1.comparativeWordIndex, count(w1.myTableid) as sequncedPriority
     from wordIndexRatings w1 join wordIndexRatings w2 on w1.myTableId = w2.myTableId and w1.Priority > w2.Priority and w1.comparativeWordIndex>w2.comparativeWordIndex
     group by w1.myTableid, w1.priority,w1.word, w1.comparativeWordIndex
    ) 
    sequencedPriority on w.myTableId = sequencedPriority.myTableId and w.Priority = sequencedPriority.Priority
),
prioritizedSplitWordMatches as ( -- this calculates the cumulative priority for a field value
select  w1.myTableId, sum(w1.Priority) as OverallPriority from wordIndexSequenceRatings w1 join wordIndexSequenceRatings w2 on w1.myTableId =  w2.myTableId 
where w1.word <> w2.word group by w1.myTableid 
),
completeSet as (
select myTableid, priority from plainMatches -- get plain matches which should be highest ranked
union
select myTableid, OverallPriority as priority from prioritizedSplitWordMatches -- get ranked split word matches (which are ordered based on word rank in search string and sequence)
),
maximizedCompleteSet as( -- set the priority of a field value = maximum priority for that field value
select myTableid, max(priority) as Priority  from completeSet group by myTableId
)
select priority, myTable.myTableid , code, Description from maximizedCompleteSet m join myTable  on m.myTableId = myTable.myTableId 
order by Priority desc, Description -- order by priority desc to get highest rated items on top
--offset 0 rows fetch next 50 rows only -- optional paging

Xcode "Build and Archive" from command line

We developed an iPad app with XCode 4.2.1 and wanted to integrate the build into our continuous integration (Jenkins) for OTA distribution. Here's the solution I came up with:

# Unlock keychain
security unlock-keychain -p jenkins /Users/jenkins/Library/Keychains/login.keychain

# Build and sign app
xcodebuild -configuration Distribution clean build

# Set variables
APP_PATH="$PWD/build/Distribution-iphoneos/iPadApp.app"
VERSION=`defaults read $APP_PATH/Info CFBundleShortVersionString`
REVISION=`defaults read $APP_PATH/Info CFBundleVersion`
DATE=`date +"%Y%m%d-%H%M%S"`
ITUNES_LINK="<a href=\"itms-services:\/\/?action=download-manifest\&url=https:\/\/xxx.xxx.xxx\/iPadApp-$VERSION.$REVISION-$DATE.plist\">Download iPad2-App v$VERSION.$REVISION-$DATE<\/a>"

# Package and verify app
xcrun -sdk iphoneos PackageApplication -v build/Distribution-iphoneos/iPadApp.app -o $PWD/iPadApp-$VERSION.$REVISION-$DATE.ipa

# Create plist
cat iPadApp.plist.template | sed -e "s/\${VERSION}/$VERSION/" -e "s/\${DATE}/$DATE/" -e "s/\${REVISION}/$REVISION/" > iPadApp-$VERSION.$REVISION-$DATE.plist

# Update index.html
curl https://xxx.xxx.xxx/index.html -o index.html.$DATE
cat index.html.$DATE | sed -n '1h;1!H;${;g;s/\(<h3>Aktuelle Version<\/h3>\)\(.*\)\(<h3>&Auml;ltere Versionen<\/h3>.<ul>.<li>\)/\1\
${ITUNES_LINK}\
\3\2<\/li>\
<li>/g;p;}' | sed -e "s/\${ITUNES_LINK}/$ITUNES_LINK/" > index.html

Then Jenkins uploads the ipa, plist and html files to our webserver.

This is the plist template:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>items</key>
    <array>
        <dict>
            <key>assets</key>
            <array>
                <dict>
                    <key>kind</key>
                    <string>software-package</string>
                    <key>url</key>
                    <string>https://xxx.xxx.xxx/iPadApp-${VERSION}.${REVISION}-${DATE}.ipa</string>
                </dict>
                <dict>
                    <key>kind</key>
                    <string>full-size-image</string>
                    <key>needs-shine</key>
                    <true/>
                    <key>url</key>
                    <string>https://xxx.xxx.xxx/iPadApp.png</string>
                </dict>
                <dict>
                    <key>kind</key>
                    <string>display-image</string>
                    <key>needs-shine</key>
                    <true/>
                    <key>url</key>
                    <string>https://xxx.xxx.xxx/iPadApp_sm.png</string>
                </dict>
            </array>
            <key>metadata</key>
            <dict>
                <key>bundle-identifier</key>
                <string>xxx.xxx.xxx.iPadApp</string>
                <key>bundle-version</key>
                <string>${VERSION}</string>
                <key>kind</key>
                <string>software</string>
                <key>subtitle</key>
                <string>iPad2-App</string>
                <key>title</key>
                <string>iPadApp</string>
            </dict>
        </dict>
    </array>
</dict>
</plist>

To set this up, you have to import the distribution certificate and provisioning profile into the designated user's keychain.

Facebook API error 191

I fixed this by passing the redirect url to the FacebookRedirectLoginHelper::getAccessToken() in my callback function:

Changing from

try {
        $accessToken = $helper->getAccessToken();
}
...

to

try {
        $accessToken = $helper->getAccessToken($fbRedirectUrl);
}
...

I am developing on a vagrant box, and it seems FacebookRedirectLoginHelper::getCurrentUrl() had issues generating a valid url.

Converting cv::Mat to IplImage*

In case of gray image, I am using this function and it works fine! however you must take care about the function features ;)

CvMat * src=  cvCreateMat(300,300,CV_32FC1);      
IplImage *dist= cvCreateImage(cvGetSize(dist),IPL_DEPTH_32F,3);

cvConvertScale(src, dist, 1, 0);

AngularJS view not updating on model change

Just use $interval

Here is your code modified. http://plnkr.co/edit/m7psQ5rwx4w1yAwAFdyr?p=preview

var app = angular.module('test', []);

app.controller('TestCtrl', function ($scope, $interval) {
   $scope.testValue = 0;

    $interval(function() {
        $scope.testValue++;
    }, 500);
});

How do you create a foreign key relationship in a SQL Server CE (Compact Edition) Database?

I know it's a "very long time" since this question was first asked. Just in case, if it helps someone,

Adding relationships is well supported by MS via SQL Server Compact Tool Box (https://sqlcetoolbox.codeplex.com/). Just install it, then you would get the option to connect to the Compact Database using the Server Explorer Window. Right click on the primary table , select "Table Properties". You should have the following window, which contains "Add Relations" tab allowing you to add relations.

Add Relations Tab - SQL Server Compact Tool Box

TSQL select into Temp table from dynamic sql

Take a look at OPENROWSET, and do something like:

SELECT * INTO #TEMPTABLE FROM OPENROWSET('SQLNCLI'
     , 'Server=(local)\SQL2008;Trusted_Connection=yes;',
     'SELECT * FROM ' + @tableName)