Programs & Examples On #Epg

Electrongic Program Guide, real-time updating menu systems for broadcast radio and TV providing scheduling information for current and upcoming content.

Cordova app not displaying correctly on iPhone X (Simulator)

Just a note that the constant keyword use for safe-area margins has been updated to env for 11.2 beta+

https://webkit.org/blog/7929/designing-websites-for-iphone-x/

How can I serve static html from spring boot?

Static files should be served from resources, not from controller.

Spring Boot will automatically add static web resources located within any of the following directories:

/META-INF/resources/  
/resources/  
/static/  
/public/

refs:
https://spring.io/blog/2013/12/19/serving-static-web-content-with-spring-boot
https://spring.io/guides/gs/serving-web-content/

Why does C++ code for testing the Collatz conjecture run faster than hand-written assembly?

As a generic answer, not specifically directed at this task: In many cases, you can significantly speed up any program by making improvements at a high level. Like calculating data once instead of multiple times, avoiding unnecessary work completely, using caches in the best way, and so on. These things are much easier to do in a high level language.

Writing assembler code, it is possible to improve on what an optimising compiler does, but it is hard work. And once it's done, your code is much harder to modify, so it is much more difficult to add algorithmic improvements. Sometimes the processor has functionality that you cannot use from a high level language, inline assembly is often useful in these cases and still lets you use a high level language.

In the Euler problems, most of the time you succeed by building something, finding why it is slow, building something better, finding why it is slow, and so on and so on. That is very, very hard using assembler. A better algorithm at half the possible speed will usually beat a worse algorithm at full speed, and getting the full speed in assembler isn't trivial.

Java GC (Allocation Failure)

"Allocation Failure" is cause of GC to kick is not correct. It is an outcome of GC operation.

GC kicks in when there is no space to allocate( depending on region minor or major GC is performed). Once GC is performed if space is freed good enough, but if there is not enough size it fails. Allocation Failure is one such failure. Below document have good explanation https://docs.oracle.com/javase/8/docs/technotes/guides/vm/gctuning/g1_gc.html

Content Security Policy "data" not working for base64 Images in Chrome 28

According to the grammar in the CSP spec, you need to specify schemes as scheme:, not just scheme. So, you need to change the image source directive to:

img-src 'self' data:;

Android: How to open a specific folder via Intent and show its content in a file browser?

Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(uri, DocumentsContract.Document.MIME_TYPE_DIR);
startActivity(intent);

Will open files app home screen enter image description here

Best way to increase heap size in catalina.bat file

increase heap size of tomcat for window add this file in apache-tomcat-7.0.42\bin

enter image description here

heap size can be changed based on Requirements.

  set JAVA_OPTS=-Dfile.encoding=UTF-8 -Xms128m -Xmx1024m -XX:PermSize=64m -XX:MaxPermSize=256m

How to read input from console in a batch file?

The code snippet in the linked proposed duplicate reads user input.

ECHO A current build of Test Harness exists.
set /p delBuild=Delete preexisting build [y/n]?: 

The user can type as many letters as they want, and it will go into the delBuild variable.

Change / Add syntax highlighting for a language in Sublime 2/3

Syntax highlighting is controlled by the theme you use, accessible through Preferences -> Color Scheme. Themes highlight different keywords, functions, variables, etc. through the use of scopes, which are defined by a series of regular expressions contained in a .tmLanguage file in a language's directory/package. For example, the JavaScript.tmLanguage file assigns the scopes source.js and variable.language.js to the this keyword. Since Sublime Text 3 is using the .sublime-package zip file format to store all the default settings it's not very straightforward to edit the individual files.

Unfortunately, not all themes contain all scopes, so you'll need to play around with different ones to find one that looks good, and gives you the highlighting you're looking for. There are a number of themes that are included with Sublime Text, and many more are available through Package Control, which I highly recommend installing if you haven't already. Make sure you follow the ST3 directions.

As it so happens, I've developed the Neon Color Scheme, available through Package Control, that you might want to take a look at. My main goal, besides trying to make a broad range of languages look as good as possible, was to identify as many different scopes as I could - many more than are included in the standard themes. While the JavaScript language definition isn't as thorough as Python's, for example, Neon still has a lot more diversity than some of the defaults like Monokai or Solarized.

jQuery highlighted with Neon Theme

I should note that I used @int3h's Better JavaScript language definition for this image instead of the one that ships with Sublime. It can be installed via Package Control.

UPDATE

Of late I've discovered another JavaScript replacement language definition - JavaScriptNext - ES6 Syntax. It has more scopes than the base JavaScript or even Better JavaScript. It looks like this on the same code:

JavaScriptNext

Also, since I originally wrote this answer, @skuroda has released PackageResourceViewer via Package Control. It allows you to seamlessly view, edit and/or extract parts of or entire .sublime-package packages. So, if you choose, you can directly edit the color schemes included with Sublime.

ANOTHER UPDATE

With the release of nearly all of the default packages on Github, changes have been coming fast and furiously. The old JS syntax has been completely rewritten to include the best parts of JavaScript Next ES6 Syntax, and now is as fully ES6-compatible as can be. A ton of other changes have been made to cover corner and edge cases, improve consistency, and just overall make it better. The new syntax has been included in the (at this time) latest dev build 3111.

If you'd like to use any of the new syntaxes with the current beta build 3103, simply clone the Github repo someplace and link the JavaScript (or whatever language(s) you want) into your Packages directory - find it on your system by selecting Preferences -> Browse Packages.... Then, simply do a git pull in the original repo directory from time to time to refresh any changes, and you can enjoy the latest and greatest! I should note that the repo uses the new .sublime-syntax format instead of the old .tmLanguage one, so they will not work with ST3 builds prior to 3084, or with ST2 (in both cases, you should have upgraded to the latest beta or dev build anyway).

I'm currently tweaking my Neon Color Scheme to handle all of the new scopes in the new JS syntax, but most should be covered already.

Twitter - share button, but with image

Look into twitter cards.

The trick is not in the button but rather the page you are sharing. Twitter Cards pull the image from the meta tags similar to facebook sharing.

Example:

<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:site" content="@site_username">
<meta name="twitter:title" content="Top 10 Things Ever">
<meta name="twitter:description" content="Up than 200 characters.">
<meta name="twitter:creator" content="@creator_username">
<meta name="twitter:image" content="http://placekitten.com/250/250">
<meta name="twitter:domain" content="YourDomain.com">

Fitting polynomial model to data in R

Regarding the question 'can R help me find the best fitting model', there is probably a function to do this, assuming you can state the set of models to test, but this would be a good first approach for the set of n-1 degree polynomials:

polyfit <- function(i) x <- AIC(lm(y~poly(x,i)))
as.integer(optimize(polyfit,interval = c(1,length(x)-1))$minimum)

Notes

  • The validity of this approach will depend on your objectives, the assumptions of optimize() and AIC() and if AIC is the criterion that you want to use,

  • polyfit() may not have a single minimum. check this with something like:

    for (i in 2:length(x)-1) print(polyfit(i))
    
  • I used the as.integer() function because it is not clear to me how I would interpret a non-integer polynomial.

  • for testing an arbitrary set of mathematical equations, consider the 'Eureqa' program reviewed by Andrew Gelman here

Update

Also see the stepAIC function (in the MASS package) to automate model selection.

Python set to list

Your code does work (tested with cpython 2.4, 2.5, 2.6, 2.7, 3.1 and 3.2):

>>> a = set(["Blah", "Hello"])
>>> a = list(a) # You probably wrote a = list(a()) here or list = set() above
>>> a
['Blah', 'Hello']

Check that you didn't overwrite list by accident:

>>> assert list == __builtins__.list

Invalid length parameter passed to the LEFT or SUBSTRING function

Something else you can use is isnull:

isnull( SUBSTRING(PostCode, 1 , CHARINDEX(' ', PostCode ) -1), PostCode)

'uint32_t' identifier not found error

I had to run project in VS2010 and I could not introduce any modifications in the code. My solution was to install vS2013 and in VS2010 point VC++ Directories->IncludeDirectories to Program Files(x86)\Microsoft Visual Studio 12.0\VC\include. Then my project compiled without any issues.

onclick="location.href='link.html'" does not load page in Safari

Give this a go:

<option onclick="parent.location='#5.2'">Bookmark 2</option>

How to update a plot in matplotlib?

I have released a package called python-drawnow that provides functionality to let a figure update, typically called within a for loop, similar to Matlab's drawnow.

An example usage:

from pylab import figure, plot, ion, linspace, arange, sin, pi
def draw_fig():
    # can be arbitrarily complex; just to draw a figure
    #figure() # don't call!
    plot(t, x)
    #show() # don't call!

N = 1e3
figure() # call here instead!
ion()    # enable interactivity
t = linspace(0, 2*pi, num=N)
for i in arange(100):
    x = sin(2 * pi * i**2 * t / 100.0)
    drawnow(draw_fig)

This package works with any matplotlib figure and provides options to wait after each figure update or drop into the debugger.

Stopping Docker containers by image name - Ubuntu

Two ways to stop running a container:

1. $docker stop container_ID

2. $docker kill container_ID

You can get running containers using the following command:

$docker ps

Following links for more information:

String to char array Java

A string to char array is as simple as

String str = "someString"; 
char[] charArray = str.toCharArray();

Can you explain a little more on what you are trying to do?

* Update *

if I am understanding your new comment, you can use a byte array and example is provided.

byte[] bytes = ByteBuffer.allocate(4).putInt(1695609641).array();

for (byte b : bytes) {
   System.out.format("0x%x ", b);
}

With the following output

0x65 0x10 0xf3 0x29

GitHub - List commits by author

Just add ?author=<emailaddress> or ?author=<githubUserName> to the url when viewing the "commits" section of a repo.

When do I need to use a semicolon vs a slash in Oracle SQL?

Almost all Oracle deployments are done through SQL*Plus (that weird little command line tool that your DBA uses). And in SQL*Plus a lone slash basically means "re-execute last SQL or PL/SQL command that I just executed".

See

http://ss64.com/ora/syntax-sqlplus.html

Rule of thumb would be to use slash with things that do BEGIN .. END or where you can use CREATE OR REPLACE.

For inserts that need to be unique use

INSERT INTO my_table ()
SELECT <values to be inserted>
FROM dual
WHERE NOT EXISTS (SELECT 
                  FROM my_table
                  WHERE <identify data that you are trying to insert>)

What does "implements" do on a class?

It is called an interface. Many OO languages have this feature. You might want to read through the php explanation here: http://de2.php.net/interface

Generate Java classes from .XSD files...?

The well-known JAXB

There is a maven plugin that could do this for you at any build phase you want.

You could do this stuff in both ways: xsd <-> Java

Rename multiple files based on pattern in Unix

Here's a way to do it using command-line Groovy:

groovy -e 'new File(".").eachFileMatch(~/fgh.*/) {it.renameTo(it.name.replaceFirst("fgh", "jkl"))}'

Cannot create a connection to data source Error (rsErrorOpeningConnection) in SSRS

if you use null values in your stored procedure, you will need to set the parameters to accept null values. That worked for me.

Upload DOC or PDF using PHP

Please add the correct mime-types to your code - at least these ones:

.jpeg -> image/jpeg
.gif  -> image/gif
.png  -> image/png

A list of mime-types can be found here.

Furthermore, simplify the code's logic and report an error number to help the first level support track down problems:

$allowedExts = array(
  "pdf", 
  "doc", 
  "docx"
); 

$allowedMimeTypes = array( 
  'application/msword',
  'text/pdf',
  'image/gif',
  'image/jpeg',
  'image/png'
);

$extension = end(explode(".", $_FILES["file"]["name"]));

if ( 20000 < $_FILES["file"]["size"]  ) {
  die( 'Please provide a smaller file [E/1].' );
}

if ( ! ( in_array($extension, $allowedExts ) ) ) {
  die('Please provide another file type [E/2].');
}

if ( in_array( $_FILES["file"]["type"], $allowedMimeTypes ) ) 
{      
 move_uploaded_file($_FILES["file"]["tmp_name"], "upload/" . $_FILES["file"]["name"]); 
}
else
{
die('Please provide another file type [E/3].');
}

Identify duplicate values in a list in Python

You can use list compression and set to reduce the complexity.

my_list = [3, 5, 2, 1, 4, 4, 1]
opt = [item for item in set(my_list) if my_list.count(item) > 1]

How to use icons and symbols from "Font Awesome" on Native Android Application

In case you only need a few font awesome icons, you can also use http://fa2png.io to generate normal pixel images. But if you add new icons/buttons regularly I'd recommend the .ttf version as its more flexible.

Oracle row count of table by count(*) vs NUM_ROWS from DBA_TABLES

According to the documentation NUM_ROWS is the "Number of rows in the table", so I can see how this might be confusing. There, however, is a major difference between these two methods.

This query selects the number of rows in MY_TABLE from a system view. This is data that Oracle has previously collected and stored.

select num_rows from all_tables where table_name = 'MY_TABLE'

This query counts the current number of rows in MY_TABLE

select count(*) from my_table

By definition they are difference pieces of data. There are two additional pieces of information you need about NUM_ROWS.

  1. In the documentation there's an asterisk by the column name, which leads to this note:

    Columns marked with an asterisk (*) are populated only if you collect statistics on the table with the ANALYZE statement or the DBMS_STATS package.

    This means that unless you have gathered statistics on the table then this column will not have any data.

  2. Statistics gathered in 11g+ with the default estimate_percent, or with a 100% estimate, will return an accurate number for that point in time. But statistics gathered before 11g, or with a custom estimate_percent less than 100%, uses dynamic sampling and may be incorrect. If you gather 99.999% a single row may be missed, which in turn means that the answer you get is incorrect.

If your table is never updated then it is certainly possible to use ALL_TABLES.NUM_ROWS to find out the number of rows in a table. However, and it's a big however, if any process inserts or deletes rows from your table it will be at best a good approximation and depending on whether your database gathers statistics automatically could be horribly wrong.

Generally speaking, it is always better to actually count the number of rows in the table rather then relying on the system tables.

Git: "Corrupt loose object"

I solved this way: I decided to simply copy the uncorrupted object file from the backup's clone to my original repository. This worked just as well. (By the way: If you can't find the object in .git/objects/ by its name, it probably has been [packed][pack] to conserve space.)

Better way to check if a Path is a File or a Directory?

This was the best I could come up with given the behavior of the Exists and Attributes properties:

using System.IO;

public static class FileSystemInfoExtensions
{
    /// <summary>
    /// Checks whether a FileInfo or DirectoryInfo object is a directory, or intended to be a directory.
    /// </summary>
    /// <param name="fileSystemInfo"></param>
    /// <returns></returns>
    public static bool IsDirectory(this FileSystemInfo fileSystemInfo)
    {
        if (fileSystemInfo == null)
        {
            return false;
        }

        if ((int)fileSystemInfo.Attributes != -1)
        {
            // if attributes are initialized check the directory flag
            return fileSystemInfo.Attributes.HasFlag(FileAttributes.Directory);
        }

        // If we get here the file probably doesn't exist yet.  The best we can do is 
        // try to judge intent.  Because directories can have extensions and files
        // can lack them, we can't rely on filename.
        // 
        // We can reasonably assume that if the path doesn't exist yet and 
        // FileSystemInfo is a DirectoryInfo, a directory is intended.  FileInfo can 
        // make a directory, but it would be a bizarre code path.

        return fileSystemInfo is DirectoryInfo;
    }
}

Here's how it tests out:

    [TestMethod]
    public void IsDirectoryTest()
    {
        // non-existing file, FileAttributes not conclusive, rely on type of FileSystemInfo
        const string nonExistentFile = @"C:\TotallyFakeFile.exe";

        var nonExistentFileDirectoryInfo = new DirectoryInfo(nonExistentFile);
        Assert.IsTrue(nonExistentFileDirectoryInfo.IsDirectory());

        var nonExistentFileFileInfo = new FileInfo(nonExistentFile);
        Assert.IsFalse(nonExistentFileFileInfo.IsDirectory());

        // non-existing directory, FileAttributes not conclusive, rely on type of FileSystemInfo
        const string nonExistentDirectory = @"C:\FakeDirectory";

        var nonExistentDirectoryInfo = new DirectoryInfo(nonExistentDirectory);
        Assert.IsTrue(nonExistentDirectoryInfo.IsDirectory());

        var nonExistentFileInfo = new FileInfo(nonExistentDirectory);
        Assert.IsFalse(nonExistentFileInfo.IsDirectory());

        // Existing, rely on FileAttributes
        const string existingDirectory = @"C:\Windows";

        var existingDirectoryInfo = new DirectoryInfo(existingDirectory);
        Assert.IsTrue(existingDirectoryInfo.IsDirectory());

        var existingDirectoryFileInfo = new FileInfo(existingDirectory);
        Assert.IsTrue(existingDirectoryFileInfo.IsDirectory());

        // Existing, rely on FileAttributes
        const string existingFile = @"C:\Windows\notepad.exe";

        var existingFileDirectoryInfo = new DirectoryInfo(existingFile);
        Assert.IsFalse(existingFileDirectoryInfo.IsDirectory());

        var existingFileFileInfo = new FileInfo(existingFile);
        Assert.IsFalse(existingFileFileInfo.IsDirectory());
    }

How to start IDLE (Python editor) without using the shortcut on Windows Vista?

You can also assign hotkeys to Windows shortcuts directly (at least in Windows 95 you could, I haven't checked again since then, but I think the option should be still there ^_^).

How do I get a platform-dependent new line character?

You can use

System.getProperty("line.separator");

to get the line separator

Make a UIButton programmatically in Swift

Swift 5.0

        let button = self.makeButton(title: "Login", titleColor: .blue, font: UIFont.init(name: "Arial", size: 18.0), background: .white, cornerRadius: 3.0, borderWidth: 2, borderColor: .black)
        view.addSubview(button)
        // Adding Constraints
        button.heightAnchor.constraint(equalToConstant: 40).isActive = true
        button.leftAnchor.constraint(equalTo: view.leftAnchor, constant: 40).isActive = true
        button.rightAnchor.constraint(equalTo: view.rightAnchor, constant: -40).isActive = true
        button.bottomAnchor.constraint(equalTo: view.bottomAnchor, constant: -400).isActive = true
        button.addTarget(self, action: #selector(pressed(_ :)), for: .touchUpInside)

       // Define commmon method
        func makeButton(title: String? = nil,
                           titleColor: UIColor = .black,
                           font: UIFont? = nil,
                           background: UIColor = .clear,
                           cornerRadius: CGFloat = 0,
                           borderWidth: CGFloat = 0,
                           borderColor: UIColor = .clear) -> UIButton {
        let button = UIButton()
        button.translatesAutoresizingMaskIntoConstraints = false
        button.setTitle(title, for: .normal)
        button.backgroundColor = background
        button.setTitleColor(titleColor, for: .normal)
        button.titleLabel?.font = font
        button.layer.cornerRadius = 6.0
        button.layer.borderWidth = 2
        button.layer.borderColor = UIColor.red.cgColor
        return button
      }
        // Button Action
         @objc func pressed(_ sender: UIButton) {
                print("Pressed")
          }

enter image description here

How to save final model using keras?

You can use model.save(filepath) to save a Keras model into a single HDF5 file which will contain:

  • the architecture of the model, allowing to re-create the model.
  • the weights of the model.
  • the training configuration (loss, optimizer)
  • the state of the optimizer, allowing to resume training exactly where you left off.

In your Python code probable the last line should be:

model.save("m.hdf5")

This allows you to save the entirety of the state of a model in a single file. Saved models can be reinstantiated via keras.models.load_model().

The model returned by load_model() is a compiled model ready to be used (unless the saved model was never compiled in the first place).

model.save() arguments:

  • filepath: String, path to the file to save the weights to.
  • overwrite: Whether to silently overwrite any existing file at the target location, or provide the user with a manual prompt.
  • include_optimizer: If True, save optimizer's state together.

Enable Hibernate logging

Your log4j.properties file should be on the root level of your capitolo2.ear (not in META-INF), that is, here:

MyProject
¦   build.xml
¦   
+---build
¦   ¦   capitolo2-ejb.jar
¦   ¦   capitolo2-war.war
¦   ¦   JBoss4.dpf
¦   ¦   log4j.properties

How to make an empty div take space

Slight update to @no1cobla answer. This hides the period. This solution works in IE8+.

.class:after
{
    content: '.';
    visibility: hidden;
}

My eclipse won't open, i download the bundle pack it keeps saying error log

Make sure you have the prerequisite, a JVM (http://wiki.eclipse.org/Eclipse/Installation#Install_a_JVM) installed.

This will be a JRE and JDK package.

There are a number of sources which includes: http://www.oracle.com/technetwork/java/javase/downloads/index.html.

Multiline strings in VB.NET

Well, since you seem to be up on your python, may I suggest that you copy your text into python, like:

 s="""this is gonna 
last quite a 
few lines"""

then do a:

  for i in s.split('\n'):
    print 'mySB.AppendLine("%s")' % i

#    mySB.AppendLine("this is gonna")
#    mySB.AppendLine("last quite a")
#    mySB.AppendLine("few lines")

or

  print ' & _ \n'.join(map(lambda s: '"%s"' % s, s.split('\n')))

#    "this is gonna" & _ 
#    "last quite a" & _ 
#    "few lines"

then at least you can copy that out and put it in your VB code. Bonus points if you bind a hotkey (fastest to get with:Autohotkey) to do this for for whatever is in your paste buffer. The same idea works well for a SQL formatter.

Laravel Eloquent where field is X or null

Using coalesce() converts null to 0:

$query = Model::where('field1', 1)
    ->whereNull('field2')
    ->where(DB::raw('COALESCE(datefield_at,0)'), '<', $date)
;

Why is Node.js single threaded?

The issue with the "one thread per request" model for a server is that they don't scale well for several scenarios compared to the event loop thread model.

Typically, in I/O intensive scenarios the requests spend most of the time waiting for I/O to complete. During this time, in the "one thread per request" model, the resources linked to the thread (such as memory) are unused and memory is the limiting factor. In the event loop model, the loop thread selects the next event (I/O finished) to handle. So the thread is always busy (if you program it correctly of course).

The event loop model as all new things seems shiny and the solution for all issues but which model to use will depend on the scenario you need to tackle. If you have an intensive I/O scenario (like a proxy), the event base model will rule, whereas a CPU intensive scenario with a low number of concurrent processes will work best with the thread-based model.

In the real world most of the scenarios will be a bit in the middle. You will need to balance the real need for scalability with the development complexity to find the correct architecture (e.g. have an event base front-end that delegates to the backend for the CPU intensive tasks. The front end will use little resources waiting for the task result.) As with any distributed system it requires some effort to make it work.

If you are looking for the silver bullet that will fit with any scenario without any effort, you will end up with a bullet in your foot.

Angular and debounce

We can create a [debounce] directive which overwrites ngModel's default viewToModelUpdate function with an empty one.

Directive Code

@Directive({ selector: '[debounce]' })
export class MyDebounce implements OnInit {
    @Input() delay: number = 300;

    constructor(private elementRef: ElementRef, private model: NgModel) {
    }

    ngOnInit(): void {
        const eventStream = Observable.fromEvent(this.elementRef.nativeElement, 'keyup')
            .map(() => {
                return this.model.value;
            })
            .debounceTime(this.delay);

        this.model.viewToModelUpdate = () => {};

        eventStream.subscribe(input => {
            this.model.viewModel = input;
            this.model.update.emit(input);
        });
    }
}

How to use it

<div class="ui input">
  <input debounce [delay]=500 [(ngModel)]="myData" type="text">
</div>

Create a copy of a table within the same database DB2

CREATE TABLE NEW_TABLENAME LIKE OLD_TABLENAME;

Works for DB2 V 9.7

Convert Java Date to UTC String

If XStream is a dependency, try:

new com.thoughtworks.xstream.converters.basic.DateConverter().toString(date)

How can I build multiple submit buttons django form?

You can use self.data in the clean_email method to access the POST data before validation. It should contain a key called newsletter_sub or newsletter_unsub depending on which button was pressed.

# in the context of a django.forms form

def clean(self):
    if 'newsletter_sub' in self.data:
        # do subscribe
    elif 'newsletter_unsub' in self.data:
        # do unsubscribe

Overriding css style?

You just have to reset the values you don't want to their defaults. No need to get into a mess by using !important.

#zoomTarget .slikezamenjanje img {
    max-height: auto;
    padding-right: 0px;
}

Hatting

I think the key datum you are missing is that CSS comes with default values. If you want to override a value, set it back to its default, which you can look up.

For example, all CSS height and width attributes default to auto.

How to import Google Web Font in CSS file?

Add the Below code in your CSS File to import Google Web Fonts.

@import url(https://fonts.googleapis.com/css?family=Open+Sans);

Replace the Open+Sans parameter value with your Font name.

Your CSS file should look like:

@import url(https://fonts.googleapis.com/css?family=Open+Sans);

body{
   font-family: 'Open Sans',serif;
}

Capitalize the first letter of both words in a two word string

Alternative way with substring and regexpr:

substring(name, 1) <- toupper(substring(name, 1, 1))
pos <- regexpr(" ", name, perl=TRUE) + 1
substring(name, pos) <- toupper(substring(name, pos, pos))

Alternating Row Colors in Bootstrap 3 - No Table

There isn't really a way to do this without the css getting a little convoluted, but here's the cleanest solution I could put together (the breakpoints in this are just for example purposes, change them to whatever breakpoints you're actually using.) The key is :nth-of-type (or :nth-child -- either would work in this case.)

Smallest viewport:

@media (max-width:$smallest-breakpoint) {

  .row div {
     background: #eee;
   }

  .row div:nth-of-type(2n) {
     background: #fff;
   }

}

Medium viewport:

@media (min-width:$smallest-breakpoint) and (max-width:$mid-breakpoint) {

  .row div {
    background: #eee;
  }

  .row div:nth-of-type(4n+1), .row div:nth-of-type(4n+2) {
    background: #fff;
  }

}

Largest viewport:

@media (min-width:$mid-breakpoint) and (max-width:9999px) {

  .row div {
    background: #eee;
  }

  .row div:nth-of-type(6n+4), 
  .row div:nth-of-type(6n+5), 
  .row div:nth-of-type(6n+6) {
      background: #fff;
  }
}

Working fiddle here

Downloading all maven dependencies to a directory NOT in repository?

Please check if you have some config files in ${MAVEN_HOME}/conf directory like settings.xml. Those files overrides settings from .m2 folder and because of that, repository folder from .m2 might not be visible or discarded.

How to create large PDF files (10MB, 50MB, 100MB, 200MB, 500MB, 1GB, etc.) for testing purposes?

Have you tried using cat to combine the files?

cat 10MB.pdf 10MB.pdf > 20MB.pdf

That should result in a 20MB file.

AmazonS3 putObject with InputStream length example

While writing to S3, you need to specify the length of S3 object to be sure that there are no out of memory errors.

Using IOUtils.toByteArray(stream) is also prone to OOM errors because this is backed by ByteArrayOutputStream

So, the best option is to first write the inputstream to a temp file on local disk and then use that file to write to S3 by specifying the length of temp file.

How can I show data using a modal when clicking a table row (using bootstrap)?

The best practice is to ajax load the order information when click tr tag, and render the information html in $('#orderDetails') like this:

  $.get('the_get_order_info_url', { order_id: the_id_var }, function(data){
    $('#orderDetails').html(data);
  }, 'script')

Alternatively, you can add class for each td that contains the order info, and use jQuery method $('.class').html(html_string) to insert specific order info into your #orderDetails BEFORE you show the modal, like:

  <% @restaurant.orders.each do |order| %>
  <!-- you should add more class and id attr to help control the DOM -->
  <tr id="order_<%= order.id %>" onclick="orderModal(<%= order.id  %>);">
    <td class="order_id"><%= order.id %></td>
    <td class="customer_id"><%= order.customer_id %></td>
    <td class="status"><%= order.status %></td>
  </tr>
  <% end %>

js:

function orderModal(order_id){
  var tr = $('#order_' + order_id);
  // get the current info in html table 
  var customer_id = tr.find('.customer_id');
  var status = tr.find('.status');

  // U should work on lines here:
  var info_to_insert = "order: " + order_id + ", customer: " + customer_id + " and status : " + status + ".";
  $('#orderDetails').html(info_to_insert);

  $('#orderModal').modal({
    keyboard: true,
    backdrop: "static"
  });
};

That's it. But I strongly recommend you to learn sth about ajax on Rails. It's pretty cool and efficient.

How to sort an associative array by its values in Javascript?

Continued discussion & other solutions covered at How to sort an (associative) array by value? with the best solution (for my case) being by saml (quoted below).

Arrays can only have numeric indexes. You'd need to rewrite this as either an Object, or an Array of Objects.

var status = new Array();
status.push({name: 'BOB', val: 10});
status.push({name: 'TOM', val: 3});
status.push({name: 'ROB', val: 22});
status.push({name: 'JON', val: 7});

If you like the status.push method, you can sort it with:

status.sort(function(a,b) {
    return a.val - b.val;
});

How to echo out the values of this array?

foreach ($array as $key => $val) {
   echo $val;
}

Using JSON POST Request

An example using jQuery is below. Hope this helps

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<title>My jQuery JSON Web Page</title>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">

JSONTest = function() {

    var resultDiv = $("#resultDivContainer");

    $.ajax({
        url: "https://example.com/api/",
        type: "POST",
        data: { apiKey: "23462", method: "example", ip: "208.74.35.5" },
        dataType: "json",
        success: function (result) {
            switch (result) {
                case true:
                    processResponse(result);
                    break;
                default:
                    resultDiv.html(result);
            }
        },
        error: function (xhr, ajaxOptions, thrownError) {
        alert(xhr.status);
        alert(thrownError);
        }
    });
};

</script>
</head>
<body>

<h1>My jQuery JSON Web Page</h1>

<div id="resultDivContainer"></div>

<button type="button" onclick="JSONTest()">JSON</button>

</body>
</html> 

Firebug debug process

Firebug XHR debug process

How to clear APC cache entries?

A good solution for me was to simply not using the outdated user cache any more after deploy.

If you add prefix to each of you keys you can change the prefix on changing the data structure of cache entries. This will help you to get the following behavior on deploy:

  1. Don't use outdated cache entries after deploy of only updated structures
  2. Don't clean the whole cache on deploy to not slow down your page
  3. Some old cached entries can be reused after reverting your deploy (If the entries wasn't automatically removed already)
  4. APC will remove old cache entries after expire OR on missing cache space

This is possible for user cache only.

How to display the value of the bar on each bar with pyplot.barh()?

For pandas people :

ax = s.plot(kind='barh') # s is a Series (float) in [0,1]
[ax.text(v, i, '{:.2f}%'.format(100*v)) for i, v in enumerate(s)];

That's it. Alternatively, for those who prefer apply over looping with enumerate:

it = iter(range(len(s)))
s.apply(lambda x: ax.text(x, next(it),'{:.2f}%'.format(100*x)));

Also, ax.patches will give you the bars that you would get with ax.bar(...). In case you want to apply the functions of @SaturnFromTitan or techniques of others.

How to convert a pandas DataFrame subset of columns AND rows into a numpy array?

.loc accept row and column selectors simultaneously (as do .ix/.iloc FYI) This is done in a single pass as well.

In [1]: df = DataFrame(np.random.rand(4,5), columns = list('abcde'))

In [2]: df
Out[2]: 
          a         b         c         d         e
0  0.669701  0.780497  0.955690  0.451573  0.232194
1  0.952762  0.585579  0.890801  0.643251  0.556220
2  0.900713  0.790938  0.952628  0.505775  0.582365
3  0.994205  0.330560  0.286694  0.125061  0.575153

In [5]: df.loc[df['c']>0.5,['a','d']]
Out[5]: 
          a         d
0  0.669701  0.451573
1  0.952762  0.643251
2  0.900713  0.505775

And if you want the values (though this should pass directly to sklearn as is); frames support the array interface

In [6]: df.loc[df['c']>0.5,['a','d']].values
Out[6]: 
array([[ 0.66970138,  0.45157274],
       [ 0.95276167,  0.64325143],
       [ 0.90071271,  0.50577509]])

How to print an unsigned char in C?

There are two bugs in this code. First, in most C implementations with signed char, there is a problem in char ch = 212 because 212 does not fit in an 8-bit signed char, and the C standard does not fully define the behavior (it requires the implementation to define the behavior). It should instead be:

unsigned char ch = 212;

Second, in printf("%u",ch), ch will be promoted to an int in normal C implementations. However, the %u specifier expects an unsigned int, and the C standard does not define behavior when the wrong type is passed. It should instead be:

printf("%u", (unsigned) ch);

Simulating group_concat MySQL function in Microsoft SQL Server 2005?

SQL Server 2017 does introduce a new aggregate function

STRING_AGG ( expression, separator).

Concatenates the values of string expressions and places separator values between them. The separator is not added at the end of string.

The concatenated elements can be ordered by appending WITHIN GROUP (ORDER BY some_expression)

For versions 2005-2016 I typically use the XML method in the accepted answer.

This can fail in some circumstances however. e.g. if the data to be concatenated contains CHAR(29) you see

FOR XML could not serialize the data ... because it contains a character (0x001D) which is not allowed in XML.

A more robust method that can deal with all characters would be to use a CLR aggregate. However applying an ordering to the concatenated elements is more difficult with this approach.

The method of assigning to a variable is not guaranteed and should be avoided in production code.

How to hide a View programmatically?

You can call view.setVisibility(View.GONE) if you want to remove it from the layout.

Or view.setVisibility(View.INVISIBLE) if you just want to hide it.

From Android Docs:

INVISIBLE

This view is invisible, but it still takes up space for layout purposes. Use with setVisibility(int) and android:visibility.

GONE

This view is invisible, and it doesn't take any space for layout purposes. Use with setVisibility(int) and android:visibility.

Copy array items into another array

There are a number of answers talking about Array.prototype.push.apply. Here is a clear example:

_x000D_
_x000D_
var dataArray1 = [1, 2];_x000D_
var dataArray2 = [3, 4, 5];_x000D_
var newArray = [ ];_x000D_
Array.prototype.push.apply(newArray, dataArray1); // newArray = [1, 2]_x000D_
Array.prototype.push.apply(newArray, dataArray2); // newArray = [1, 2, 3, 4, 5]_x000D_
console.log(JSON.stringify(newArray)); // Outputs: [1, 2, 3, 4, 5]
_x000D_
_x000D_
_x000D_

If you have ES6 syntax:

_x000D_
_x000D_
var dataArray1 = [1, 2];_x000D_
var dataArray2 = [3, 4, 5];_x000D_
var newArray = [ ];_x000D_
newArray.push(...dataArray1); // newArray = [1, 2]_x000D_
newArray.push(...dataArray2); // newArray = [1, 2, 3, 4, 5]_x000D_
console.log(JSON.stringify(newArray)); // Outputs: [1, 2, 3, 4, 5]
_x000D_
_x000D_
_x000D_

Powershell v3 Invoke-WebRequest HTTPS error

I tried searching for documentation on the EM7 OpenSource REST API. No luck so far.

http://blog.sciencelogic.com/sciencelogic-em7-the-next-generation/05/2011

There's a lot of talk about OpenSource REST API, but no link to the actual API or any documentation. Maybe I was impatient.

Here are few things you can try out

$a = Invoke-RestMethod -Uri https://IPADDRESS/resource -Credential $cred -certificate $cert 
$a.Results | ConvertFrom-Json

Try this to see if you can filter out the columns that you are getting from the API

$a.Results | ft

or, you can try using this also

$b = Invoke-WebRequest -Uri https://IPADDRESS/resource -Credential $cred -certificate $cert 
$b.Content | ConvertFrom-Json

Curl Style Headers

$b.Headers

I tested the IRM / IWR with the twitter JSON api.

$a = Invoke-RestMethod http://search.twitter.com/search.json?q=PowerShell 

Hope this helps.

Is there a way to use shell_exec without waiting for the command to complete?

This will execute a command and disconnect from the running process. Of course, it can be any command you want. But for a test, you can create a php file with a sleep(20) command it.

exec("nohup /usr/bin/php -f sleep.php > /dev/null 2>&1 &");

Why is my Git Submodule HEAD detached from master?

EDIT:

See @Simba Answer for valid solution

submodule.<name>.update is what you want to change, see the docs - default checkout
submodule.<name>.branch specify remote branch to be tracked - default master


OLD ANSWER:

Personally I hate answers here which direct to external links which may stop working over time and check my answer here (Unless question is duplicate) - directing to question which does cover subject between the lines of other subject, but overall equals: "I'm not answering, read the documentation."

So back to the question: Why does it happen?

Situation you described

After pulling changes from server, many times my submodule head gets detached from master branch.

This is a common case when one does not use submodules too often or has just started with submodules. I believe that I am correct in stating, that we all have been there at some point where our submodule's HEAD gets detached.

  • Cause: Your submodule is not tracking correct branch (default master).
    Solution: Make sure your submodule is tracking the correct branch
$ cd <submodule-path>
# if the master branch already exists locally:
# (From git docs - branch)
# -u <upstream>
# --set-upstream-to=<upstream>
#    Set up <branchname>'s tracking information so <upstream>
#    is considered <branchname>'s upstream branch.
#    If no <branchname> is specified, then it defaults to the current branch.
$ git branch -u <origin>/<branch> <branch>
# else:
$ git checkout -b <branch> --track <origin>/<branch>
  • Cause: Your parent repo is not configured to track submodules branch.
    Solution: Make your submodule track its remote branch by adding new submodules with the following two commands.
    • First you tell git to track your remote <branch>.
    • you tell git to perform rebase or merge instead of checkout
    • you tell git to update your submodule from remote.
    $ git submodule add -b <branch> <repository> [<submodule-path>]
    $ git config -f .gitmodules submodule.<submodule-path>.update rebase
    $ git submodule update --remote
  • If you haven't added your existing submodule like this you can easily fix that:
    • First you want to make sure that your submodule has the branch checked out which you want to be tracked.
    $ cd <submodule-path>
    $ git checkout <branch>
    $ cd <parent-repo-path>
    # <submodule-path> is here path releative to parent repo root
    # without starting path separator
    $ git config -f .gitmodules submodule.<submodule-path>.branch <branch>
    $ git config -f .gitmodules submodule.<submodule-path>.update <rebase|merge>

In the common cases, you already have fixed by now your DETACHED HEAD since it was related to one of the configuration issues above.

fixing DETACHED HEAD when .update = checkout

$ cd <submodule-path> # and make modification to your submodule
$ git add .
$ git commit -m"Your modification" # Let's say you forgot to push it to remote.
$ cd <parent-repo-path>
$ git status # you will get
Your branch is up-to-date with '<origin>/<branch>'.
Changes not staged for commit:
    modified:   path/to/submodule (new commits)
# As normally you would commit new commit hash to your parent repo
$ git add -A
$ git commit -m"Updated submodule"
$ git push <origin> <branch>.
$ git status
Your branch is up-to-date with '<origin>/<branch>'.
nothing to commit, working directory clean
# If you now update your submodule
$ git submodule update --remote
Submodule path 'path/to/submodule': checked out 'commit-hash'
$ git status # will show again that (submodule has new commits)
$ cd <submodule-path>
$ git status
HEAD detached at <hash>
# as you see you are DETACHED and you are lucky if you found out now
# since at this point you just asked git to update your submodule
# from remote master which is 1 commit behind your local branch
# since you did not push you submodule chage commit to remote. 
# Here you can fix it simply by. (in submodules path)
$ git checkout <branch>
$ git push <origin>/<branch>
# which will fix the states for both submodule and parent since 
# you told already parent repo which is the submodules commit hash 
# to track so you don't see it anymore as untracked.

But if you managed to make some changes locally already for submodule and commited, pushed these to remote then when you executed 'git checkout ', Git notifies you:

$ git checkout <branch>
Warning: you are leaving 1 commit behind, not connected to any of your branches:
If you want to keep it by creating a new branch, this may be a good time to do so with:

The recommended option to create a temporary branch can be good, and then you can just merge these branches etc. However I personally would use just git cherry-pick <hash> in this case.

$ git cherry-pick <hash> # hash which git showed you related to DETACHED HEAD
# if you get 'error: could not apply...' run mergetool and fix conflicts
$ git mergetool
$ git status # since your modifications are staged just remove untracked junk files
$ rm -rf <untracked junk file(s)>
$ git commit # without arguments
# which should open for you commit message from DETACHED HEAD
# just save it or modify the message.
$ git push <origin> <branch>
$ cd <parent-repo-path>
$ git add -A # or just the unstaged submodule
$ git commit -m"Updated <submodule>"
$ git push <origin> <branch>

Although there are some more cases you can get your submodules into DETACHED HEAD state, I hope that you understand now a bit more how to debug your particular case.

Iterating over and deleting from Hashtable in Java

You need to use an explicit java.util.Iterator to iterate over the Map's entry set rather than being able to use the enhanced For-loop syntax available in Java 6. The following example iterates over a Map of Integer, String pairs, removing any entry whose Integer key is null or equals 0.

Map<Integer, String> map = ...

Iterator<Map.Entry<Integer, String>> it = map.entrySet().iterator();

while (it.hasNext()) {
  Map.Entry<Integer, String> entry = it.next();

  // Remove entry if key is null or equals 0.
  if (entry.getKey() == null || entry.getKey() == 0) {
    it.remove();
  }
}

basic authorization command for curl

How do I set up the basic authorization?

All you need to do is use -u, --user USER[:PASSWORD]. Behind the scenes curl builds the Authorization header with base64 encoded credentials for you.

Example:

curl -u username:password -i -H 'Accept:application/json' http://example.com

HTTP 404 when accessing .svc file in IIS

In my case Win 10. the file applicationHost.config is corrupted by VS 2012. And you can get the copy the history of this file under C:\inetpub\history. Then restart IIS and it works properly.

What does `void 0` mean?

void is a reserved JavaScript keyword. It evaluates the expression and always returns undefined.

how to concat two columns into one with the existing column name in mysql?

You can try this simple way for combining columns:

select some_other_column,first_name || ' ' || last_name AS First_name from customer;

Prevent direct access to a php include file

Besides the .htaccess way, I have seen a useful pattern in various frameworks, for example in ruby on rails. They have a separate pub/ directory in the application root directory and the library directories are living in directories at the same level as pub/. Something like this (not ideal, but you get the idea):

app/
 |
 +--pub/
 |
 +--lib/
 |
 +--conf/
 |
 +--models/
 |
 +--views/
 |
 +--controllers/

You set up your web server to use pub/ as document root. This offers better protection to your scripts: while they can reach out from the document root to load necessary components it is impossible to access the components from the internet. Another benefit besides security is that everything is in one place.

This setup is better than just creating checks in every single included file because "access not permitted" message is a clue to attackers, and it is better than .htaccess configuration because it is not white-list based: if you screw up the file extensions it will not be visible in the lib/, conf/ etc. directories.

Set up Python 3 build system with Sublime Text 3

Steps to Make Sublime Text a Python IDE (Windows)

Tested successfully on Sublime Text 3. Assuming Sublime Text and package control are already installed . . .

  1. Install Python (python.org) and pay attention to where it is installed or choose a simple location like the C drive, agreeing to remove character limit at the end of the installation.

  2. Install package SublimeREPL (Cntrl + Shift + P, Package Control - Install Package, SublimeREPL, Enter).

  3. Go to Preferences, Package Settings, SublimeREPL, Settings - User.

  4. Paste in the following, updating the file path to your python installation folder, as needed. You may customize these and choose whatever syntax you like (last line) but I prefer my output in plain text.

    {
      "default_extend_env": {"PATH":"C:\\Program Files\\Python36\\"},
      "repl_view_settings": {
      "translate_tabs_to_spaces": false,
      "auto_indent": false,
      "smart_indent": false,
      "spell_check": false,
      "indent_subsequent_lines": false,
      "detect_indentation": false,
      "auto_complete": true,
      "line_numbers": false,
      "gutter": false,
      "syntax": "Packages/Text/Plain text.tmLanguage"
      }
    }
    
  5. Save and close the file (SublimeREPL.sublime-settings).

  6. Go to Tools, Build System, New Build System.

  7. Replace all existing text with the following:

    {
    "target": "run_existing_window_command", 
    "id": "repl_python_run",
    "file": "config/Python/Main.sublime-menu"
    }
    
  8. Cntrl + S or save as "C:\Users[username]\AppData\Roaming\Sublime Text 3\Packages\User\SublimeREPL-python.sublime-build" updating username or path as needed. This should be wherever your settings and builds are stored by Sublime Text.

  9. Go to Tools, Build System, select SublimeREPL-python.

  10. All done--now to test. Open or create a simple python file, having a *.py extension and save it wherever desired.

  11. Make sure the file is open and selected in Sublime Text. Now, when you press Cntrl + B to build and run it, it will open another tab, titled "REPL [python]", executing and displaying the results of your python code.

If you would like to go a step further, I highly recommend making the follow changes, to allow Sublime to reload your executed python in the same window, when you press Cntrl+B (Build), instead of it opening a new tab each time:

Add the following line in the "repl_python_run" command in (Preferences, Browse Packages) SublimeREPL\config\Python\Main.sublime-menu, right before the "external_id": "python" argument:

"view_id": "*REPL* [python]",

and then to change the line:

if view.id() == view_id

into:

if view.name() == view_id

in SublimeREPL\sublimerepl.py.

Subset data.frame by date

Well, it's clearly not a number since it has dashes in it. The error message and the two comments tell you that it is a factor but the commentators are apparently waiting and letting the message sink in. Dirk is suggesting that you do this:

 EPL2011_12$Date2 <- as.Date( as.character(EPL2011_12$Date), "%d-%m-%y")

After that you can do this:

 EPL2011_12FirstHalf <- subset(EPL2011_12, Date2 > as.Date("2012-01-13") )

R date functions assume the format is either "YYYY-MM-DD" or "YYYY/MM/DD". You do need to compare like classes: date to date, or character to character.

How to install the current version of Go in Ubuntu Precise

  1. Download say, go1.6beta1.linux-amd64.tar.gz from https://golang.org/dl/ into /tmp

wget https://storage.googleapis.com/golang/go1.6beta1.linux-amd64.tar.gz -o /tmp/go1.6beta1.linux-amd64.tar.gz

  1. un-tar into /usr/local/bin

sudo tar -zxvf go1.6beta1.linux-amd64.tar.gz -C /usr/local/bin/

  1. Set GOROOT, GOPATH, [on ubuntu add following to ~/.bashrc]

mkdir ~/go export GOPATH=~/go export PATH=$PATH:$GOPATH/bin export GOROOT=/usr/local/bin/go export PATH=$PATH:$GOROOT/bin

  1. Verify

go version should show be

go version go1.6beta1 linux/amd64

go env should show be

GOARCH="amd64" GOBIN="" GOEXE="" GOHOSTARCH="amd64" GOHOSTOS="linux" GOOS="linux" GOPATH="/home/vats/go" GORACE="" GOROOT="/usr/local/bin/go" GOTOOLDIR="/usr/local/bin/go/pkg/tool/linux_amd64" GO15VENDOREXPERIMENT="1" CC="gcc" GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0" CXX="g++" CGO_ENABLED="1"

Force DOM redraw/refresh on Chrome/Mac

Hiding an element and then showing it again within a setTimeout of 0 will force a redraw.

$('#page').hide();
setTimeout(function() {
    $('#page').show();
}, 0);

Call static method with reflection

I prefer simplicity...

private void _InvokeNamespaceClassesStaticMethod(string namespaceName, string methodName, params object[] parameters) {
    foreach(var _a in AppDomain.CurrentDomain.GetAssemblies()) {
        foreach(var _t in _a.GetTypes()) {
            try {
                if((_t.Namespace == namespaceName) && _t.IsClass) _t.GetMethod(methodName, (BindingFlags.Static | BindingFlags.Public))?.Invoke(null, parameters);
            } catch { }
        }
    }
}

Usage...

    _InvokeNamespaceClassesStaticMethod("mySolution.Macros", "Run");

But in case you're looking for something a little more robust, including the handling of exceptions...

private InvokeNamespaceClassStaticMethodResult[] _InvokeNamespaceClassStaticMethod(string namespaceName, string methodName, bool throwExceptions, params object[] parameters) {
    var results = new List<InvokeNamespaceClassStaticMethodResult>();
    foreach(var _a in AppDomain.CurrentDomain.GetAssemblies()) {
        foreach(var _t in _a.GetTypes()) {
            if((_t.Namespace == namespaceName) && _t.IsClass) {
                var method_t = _t.GetMethod(methodName, parameters.Select(_ => _.GetType()).ToArray());
                if((method_t != null) && method_t.IsPublic && method_t.IsStatic) {
                    var details_t = new InvokeNamespaceClassStaticMethodResult();
                    details_t.Namespace = _t.Namespace;
                    details_t.Class = _t.Name;
                    details_t.Method = method_t.Name;
                    try {
                        if(method_t.ReturnType == typeof(void)) {
                            method_t.Invoke(null, parameters);
                            details_t.Void = true;
                        } else {
                            details_t.Return = method_t.Invoke(null, parameters);
                        }
                    } catch(Exception ex) {
                        if(throwExceptions) {
                            throw;
                        } else {
                            details_t.Exception = ex;
                        }
                    }
                    results.Add(details_t);
                }
            }
        }
    }
    return results.ToArray();
}

private class InvokeNamespaceClassStaticMethodResult {
    public string Namespace;
    public string Class;
    public string Method;
    public object Return;
    public bool Void;
    public Exception Exception;
}

Usage is pretty much the same...

_InvokeNamespaceClassesStaticMethod("mySolution.Macros", "Run", false);

How to read a list of files from a folder using PHP?

There is a glob. In this webpage there are good article how to list files in very simple way:

How to read a list of files from a folder using PHP

OpenCV - DLL missing, but it's not?

You just need to add the folder of the needed dll file (or files) to your system "Environment Variables" in "Path". Your problem will 100% be resolved. I had this problem too.

html5: display video inside canvas

Here's a solution that uses more modern syntax and is less verbose than the ones already provided:

const canvas = document.querySelector("canvas");
const ctx = canvas.getContext("2d");
const video = document.querySelector("video");

video.addEventListener('play', () => {
  function step() {
    ctx.drawImage(video, 0, 0, canvas.width, canvas.height)
    requestAnimationFrame(step)
  }
  requestAnimationFrame(step);
})

Some useful links:

Find package name for Android apps to use Intent to launch Market app from web

It depends where exactly you want to get the information from. You have a bunch of options:

  • If you have a copy of the .apk, it's just a case of opening it as a zip file and looking at the AndroidManifest.xml file. The top level <manifest> element will have a package attribute.
  • If you have the app installed on a device and can connect using adb, you can launch adb shell and execute pm list packages -f, which shows the package name for each installed apk.
  • If you just want to manually find a couple of package names, you can search for the app on http://www.cyrket.com/m/android/, and the package name is shown in the URL
  • You can also do it progmatically from an Android app using the PackageManager

Once you've got the package name, you simply link to market://search?q=pname:<package_name> or http://market.android.com/search?q=pname:<package_name>. Both will open the market on an Android device; the latter obviously has the potential to work on other hardware as well (it doesn't at the minute).

Empty brackets '[]' appearing when using .where

A good bet is to utilize Rails' Arel SQL manager, which explicitly supports case-insensitive ActiveRecord queries:

t = Guide.arel_table Guide.where(t[:title].matches('%attack')) 

Here's an interesting blog post regarding the portability of case-insensitive queries using Arel. It's worth a read to understand the implications of utilizing Arel across databases.

AssertContains on strings in jUnit

If you add in Hamcrest and JUnit4, you could do:

String x = "foo bar";
Assert.assertThat(x, CoreMatchers.containsString("foo"));

With some static imports, it looks a lot better:

assertThat(x, containsString("foo"));

The static imports needed would be:

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.CoreMatchers.containsString;

How to get my project path?

You can use

string wanted_path = Path.GetDirectoryName(Path.GetDirectoryName(System.IO.Directory.GetCurrentDirectory()));

Using Ajax.BeginForm with ASP.NET MVC 3 Razor

Darin Dimitrov's solution worked for me with one exception. When I submitted the partial view with (intentional) validation errors, I ended up with duplicate forms being returned in the dialog:

enter image description here

To fix this I had to wrap the Html.BeginForm in a div:

<div id="myForm">
    @using (Html.BeginForm("CreateDialog", "SupportClass1", FormMethod.Post, new { @class = "form-horizontal" }))
    {
        //form contents
    }
</div>

When the form was submitted, I cleared the div in the success function and output the validated form:

    $('form').submit(function () {
        if ($(this).valid()) {
            $.ajax({
                url: this.action,
                type: this.method,
                data: $(this).serialize(),
                success: function (result) {
                    $('#myForm').html('');
                    $('#result').html(result);
                }
            });
        }
        return false;
    });
});

browser sessionStorage. share between tabs?

Using sessionStorage for this is not possible.

From the MDN Docs

Opening a page in a new tab or window will cause a new session to be initiated.

That means that you can't share between tabs, for this you should use localStorage

Read input from a JOptionPane.showInputDialog box

Your problem is that, if the user clicks cancel, operationType is null and thus throws a NullPointerException. I would suggest that you move

if (operationType.equalsIgnoreCase("Q")) 

to the beginning of the group of if statements, and then change it to

if(operationType==null||operationType.equalsIgnoreCase("Q")). 

This will make the program exit just as if the user had selected the quit option when the cancel button is pushed.

Then, change all the rest of the ifs to else ifs. This way, once the program sees whether or not the input is null, it doesn't try to call anything else on operationType. This has the added benefit of making it more efficient - once the program sees that the input is one of the options, it won't bother checking it against the rest of them.

composer laravel create project

composer create-project laravel/laravel ProjectName 

jquery .html() vs .append()

They are not the same. The first one replaces the HTML without creating another jQuery object first. The second creates an additional jQuery wrapper for the second div, then appends it to the first.

One jQuery Wrapper (per example):

$("#myDiv").html('<div id="mySecondDiv"></div>');

$("#myDiv").append('<div id="mySecondDiv"></div>');

Two jQuery Wrappers (per example):

var mySecondDiv=$('<div id="mySecondDiv"></div>');
$('#myDiv').html(mySecondDiv);

var mySecondDiv=$('<div id="mySecondDiv"></div>');
$('#myDiv').append(mySecondDiv);

You have a few different use cases going on. If you want to replace the content, .html is a great call since its the equivalent of innerHTML = "...". However, if you just want to append content, the extra $() wrapper set is unneeded.

Only use two wrappers if you need to manipulate the added div later on. Even in that case, you still might only need to use one:

var mySecondDiv = $("<div id='mySecondDiv'></div>").appendTo("#myDiv");
// other code here
mySecondDiv.hide();

Get the time difference between two datetimes

This should work fine.

var now  = "04/09/2013 15:00:00";
var then = "02/09/2013 14:20:30";

var ms = moment(now,"DD/MM/YYYY HH:mm:ss").diff(moment(then,"DD/MM/YYYY HH:mm:ss"));
var d = moment.duration(ms);

console.log(d.days() + ':' + d.hours() + ':' + d.minutes() + ':' + d.seconds());

CSS override rules and specificity

The important needs to be inside the ;

td.rule2 div {     background-color: #ffff00 !important; } 

in fact i believe this should override it

td.rule2 { background-color: #ffff00 !important; } 

Error retrieving parent for item: No resource found that matches the given name '@android:style/TextAppearance.Holo.Widget.ActionBar.Title'

Make sure you've set your target API (different from the target SDK) in the Project Properties (not the manifest) to be at least 4.0/API 14.

Reverse of JSON.stringify?

JSON.parse is the opposite of JSON.stringify.

How do I allow HTTPS for Apache on localhost?

2021 Update

I’m posting this answer since I struggled with this myself and Chrome updated their security with requiring Subject Alternative Name which a lot of posts do not have as it was not required when they were posted as an answer. I’m assuming that WAMP is already installed.

STEP 1

Download OpenSSL Light and install


**STEP 2 (Optional)**

Although this part is optional, but it makes it easier later to execute commands. If you skip this step, you’ll have to provide full path to openssl.exe where you will execute the command. If you prefer to set it then update the openssl.exe path in Environment Variables.

Environment Variables -> System Variables -> Path -> Edit -> New -> c:\Program Files\OpenSSL-Win64\bin


**STEP 3**

Create a folder named “key” in the c:/wamp64/bin/apache/apache2.4.27(your version number)/conf/ directory.

Create configuration file for your CA MyCompanyCA.cnf with contents (you can change it to your needs):

[ req ]
distinguished_name  = req_distinguished_name
x509_extensions     = root_ca

[ req_distinguished_name ]
countryName             = Country Name (2 letter code)
countryName_min         = 2
countryName_max         = 2
stateOrProvinceName     = State or Province Name (full name)
localityName            = Locality Name (eg, city)
0.organizationName      = Organization Name (eg, company)
organizationalUnitName  = Organizational Unit Name (eg, section)
commonName              = Common Name (eg, fully qualified host name)
commonName_max          = 64
emailAddress            = Email Address
emailAddress_max        = 64

[ root_ca ]
basicConstraints            = critical, CA:true

Create the extensions configuration file MyCompanyLocalhost.ext for your web server certificate:

subjectAltName = @alt_names
extendedKeyUsage = serverAuth

[alt_names]
DNS.1   = localhost
DNS.2   = mycy.mycompany.com

**STEP 4**

Execute these commands in the given order to generate the key and certificates:

openssl req -x509 -newkey rsa:2048 -out MyCompanyCA.cer -outform PEM -keyout MyCompanyCA.pvk -days 10000 -verbose -config MyCompanyCA.cnf -nodes -sha256 -subj "/CN=MyCompany CA"
openssl req -newkey rsa:2048 -keyout MyCompanyLocalhost.pvk -out MyCompanyLocalhost.req -subj /CN=localhost -sha256 -nodes
openssl x509 -req -CA MyCompanyCA.cer -CAkey MyCompanyCA.pvk -in MyCompanyLocalhost.req -out MyCompanyLocalhost.cer -days 10000 -extfile MyCompanyLocalhost.ext -sha256 -set_serial 0x1111

As a result, you will have MyCompanyCA.cer, MyCompanyLocalhost.cer and MyCompanyLocalhost.pvk files.


**STEP 5**

Install MyCompanyCA.cer under

Control Panel -> Manage User Certificates -> Trusted Root Certification Authorities -> Certificates

To install MyCompanyLocalhost.cer just double click it.


**STEP 6**

Open c:/wamp64/bin/apache/apache2.4.27(your version number)/conf/httpd.conf and un-comment (remove the #) the following 3 lines:

LoadModule ssl_module modules/mod_ssl.so
Include conf/extra/httpd-ssl.conf
LoadModule socache_shmcb_module modules/mod_socache_shmcb.so

**STEP 7**

Open c:/wamp64/bin/apache/apache2.4.37/conf/extra/httpd-ssl.conf and change all the parameters to the ones shown below:

Directory "c:/wamp64/www"
DocumentRoot "c:/wamp64/www"
ServerName localhost:443
ServerAdmin [email protected]
ErrorLog "c:/wamp64/bin/apache/apache2.4.27/logs/error.log"
TransferLog "c:/wamp64/bin/apache/apache2.4.27/logs/access.log"
SSLCertificateFile "c:/wamp64/bin/apache/apache2.4.27/conf/key/MyCompanyLocalhost.cer"
SSLCertificateKeyFile "c:/wamp64/bin/apache/apache2.4.27/conf/key/MyCompanyLocalhost.pvk"
SSLSessionCache "shmcb:c:/wamp64/bin/apache/apache2.4.27/logs/ssl_scache(512000)"
CustomLog "c:/wamp64/bin/apache/apache2.4.27/logs/ssl_request.log" \
          "%t %h %{SSL_PROTOCOL}x %{SSL_CIPHER}x \"%r\" %b"

Note: This is the tricky part. If you make any small mistake while editing this file, SSL won’t work. Make a copy of it before you edit it.


**STEP 8**

Restart Wamp and Chrome. Localhost is now secure: https://localhost

How can I solve a connection pool problem between ASP.NET and SQL Server?

This problem I have encountered before. It ended up being an issue with the firewall. I just added a rule to the firewall. I had to open port 1433 so the SQL server can connect to the server.

Pandas split column of lists into multiple columns

Much simpler solution:

pd.DataFrame(df2["teams"].to_list(), columns=['team1', 'team2'])

Yields,

  team1 team2
-------------
0    SF   NYG
1    SF   NYG
2    SF   NYG
3    SF   NYG
4    SF   NYG
5    SF   NYG
6    SF   NYG
7    SF   NYG

If you wanted to split a column of delimited strings rather than lists, you could similarly do:

pd.DataFrame(df["teams"].str.split('<delim>', expand=True).values,
             columns=['team1', 'team2'])

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');

AngularJS dynamic routing

In the $routeProvider URI patters, you can specify variable parameters, like so: $routeProvider.when('/page/:pageNumber' ... , and access it in your controller via $routeParams.

There is a good example at the end of the $route page: http://docs.angularjs.org/api/ng.$route

EDIT (for the edited question):

The routing system is unfortunately very limited - there is a lot of discussion on this topic, and some solutions have been proposed, namely via creating multiple named views, etc.. But right now, the ngView directive serves only ONE view per route, on a one-to-one basis. You can go about this in multiple ways - the simpler one would be to use the view's template as a loader, with a <ng-include src="myTemplateUrl"></ng-include> tag in it ($scope.myTemplateUrl would be created in the controller).

I use a more complex (but cleaner, for larger and more complicated problems) solution, basically skipping the $route service altogether, that is detailed here:

http://www.bennadel.com/blog/2420-Mapping-AngularJS-Routes-Onto-URL-Parameters-And-Client-Side-Events.htm

How can I format my grep output to show line numbers at the end of the line, and also the hit count?

use grep -n -i null myfile.txt to output the line number in front of each match.

I dont think grep has a switch to print the count of total lines matched, but you can just pipe grep's output into wc to accomplish that:

grep -n -i null myfile.txt | wc -l

Get the length of a String

test1.characters.count

will get you the number of letters/numbers etc in your string.

ex:

test1 = "StackOverflow"

print(test1.characters.count)

(prints "13")

How to change the hosts file on android

That didn't really work in my case - i.e. in order to overwrite hosts file you have to follow it's directions, ie:

./emulator -avd myEmulatorName -partition-size 280

and then in other term window (pushing new hosts file /tmp/hosts):

./adb remount
./adb push /tmp/hosts /system/etc

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

Based on the answers by Ben Carp and Wallace Sidhrée:

This is what I use to copy my entire build folder to my wamp public folder.

package.json

{
  "name": "[your project name]",
  "homepage": "http://localhost/[your project name]/",
  "version": "0.0.1",
  [...]
  "scripts": {
    "build": "react-scripts build",
    "postbuild": "@powershell -NoProfile -ExecutionPolicy Unrestricted -Command ./post_build.ps1",
    [...]
  },
}

post_build.ps1

Copy-Item "./build/*" -Destination "C:/wamp64/www/[your project name]" -Recurse -force

The homepage line is only needed if you are deploying to a subfolder on your server (See This answer from another question).

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

This issue appears when you have a running console at the time you try to run other (or the same) program.

I had this problem during executing a program on Sublime Text while I had another one running on DevC++ already.

How do I check if an object's type is a particular subclass in C++?

I don't know if I understand your problem correctly, so let me restate it in my own words...

Problem: Given classes B and D, determine if D is a subclass of B (or vice-versa?)

Solution: Use some template magic! Okay, seriously you need to take a look at LOKI, an excellent template meta-programming library produced by the fabled C++ author Andrei Alexandrescu.

More specifically, download LOKI and include header TypeManip.h from it in your source code then use the SuperSubclass class template as follows:

if(SuperSubClass<B,D>::value)
{
...
}

According to documentation, SuperSubClass<B,D>::value will be true if B is a public base of D, or if B and D are aliases of the same type.

i.e. either D is a subclass of B or D is the same as B.

I hope this helps.

edit:

Please note the evaluation of SuperSubClass<B,D>::value happens at compile time unlike some methods which use dynamic_cast, hence there is no penalty for using this system at runtime.

Twitter-Bootstrap-2 logo image on top of navbar

i use this code for navbar on bootstrap 3.2.0, the image should be at most 50px high, or else it will bleed the standard bs navbar.

Notice that i purposely do not use the class='navbar-brand' as that introduces padding on the image

<div class="navbar navbar-default navbar-fixed-top" role="navigation">
    <div class="container">
    <!-- Brand and toggle get grouped for better mobile display -->
    <div class="navbar-header">
      <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse">
        <span class="sr-only">Toggle navigation</span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
      </button>
      <a class="" href="/"><img src='img/anyWidthx50.png'/></a>
    </div>

    <!-- Collect the nav links, forms, and other content for toggling -->
    <div class="collapse navbar-collapse navbar-ex1-collapse">
       <ul class="nav navbar-nav">
        <li class="active"><a href="#">Active Link</a></li>
        <li><a href="#">More Links</a></li>
      </ul>
    </div><!-- /.navbar-collapse -->
  </div>
</div>

How do I get my Maven Integration tests to run

You can set up Maven's Surefire to run unit tests and integration tests separately. In the standard unit test phase you run everything that does not pattern match an integration test. You then create a second test phase that runs just the integration tests.

Here is an example:

    <plugin>
      <groupId>org.apache.maven.plugins</groupId>
      <artifactId>maven-surefire-plugin</artifactId>
      <configuration>
        <excludes>
          <exclude>**/*IntegrationTest.java</exclude>
        </excludes>
      </configuration>
      <executions>
        <execution>
          <id>integration-test</id>
          <goals>
            <goal>test</goal>
          </goals>
          <phase>integration-test</phase>
          <configuration>
            <excludes>
              <exclude>none</exclude>
            </excludes>
            <includes>
              <include>**/*IntegrationTest.java</include>
            </includes>
          </configuration>
        </execution>
      </executions>
    </plugin>

Integer to hex string in C++

Just have a look on my solution,[1] that I verbatim copied from my project, so there a German is API doc included. My goal was to combine flexibility and safety within my actual needs:[2]

  • no 0x prefix added: caller may decide
  • automatic width deduction: less typing
  • explicit width control: widening for formatting, (lossless) shrinking to save space
  • capable for dealing with long long
  • restricted to integral types: avoid surprises by silent conversions
  • ease of understanding
  • no hard-coded limit
#include <string>
#include <sstream>
#include <iomanip>

/// Vertextet einen Ganzzahlwert val im Hexadezimalformat.
/// Auf die Minimal-Breite width wird mit führenden Nullen aufgefüllt;
/// falls nicht angegeben, wird diese Breite aus dem Typ des Arguments
/// abgeleitet. Funktion geeignet von char bis long long.
/// Zeiger, Fließkommazahlen u.ä. werden nicht unterstützt, ihre
/// Übergabe führt zu einem (beabsichtigten!) Compilerfehler.
/// Grundlagen aus: http://stackoverflow.com/a/5100745/2932052
template <typename T>
inline std::string int_to_hex(T val, size_t width=sizeof(T)*2)
{
    std::stringstream ss;
    ss << std::setfill('0') << std::setw(width) << std::hex << (val|0);
    return ss.str();
}

[1] based on the answer by Kornel Kisielewicz
[2] Translated into the language of CppTest, this is how it reads:

TEST_ASSERT(int_to_hex(char(0x12)) == "12");
TEST_ASSERT(int_to_hex(short(0x1234)) == "1234");
TEST_ASSERT(int_to_hex(long(0x12345678)) == "12345678");
TEST_ASSERT(int_to_hex((long long)(0x123456789abcdef0)) == "123456789abcdef0");
TEST_ASSERT(int_to_hex(0x123, 1) == "123");
TEST_ASSERT(int_to_hex(0x123, 8) == "00000123");
// with deduction test as suggested by Lightness Races in Orbit:
TEST_ASSERT(int_to_hex(short(0x12)) == "0012"); 

How to upgrade rubygems

Or:

gem update `gem outdated | cut -d ' ' -f 1`

How to break lines at a specific character in Notepad++?

Let's assume ], is the character where we wanted to break at

  1. Open notePad++
  2. Open Find window Ctrl+F
  3. Switch to Replace Tab
  4. Choose Search Mode to Extended
  5. Type ], in Find What field
  6. Type \nin Replace with field
  7. Hit Replace All
  8. Boom

How to copy file from host to container using Dockerfile

I faced this issue, I was not able to copy zeppelin [1GB] directory into docker container and was getting issue

COPY failed: stat /var/lib/docker/tmp/docker-builder977188321/zeppelin-0.7.2-bin-all: no such file or directory

I am using docker Version: 17.09.0-ce and resolved the issue with the following steps.

Step 1: copy zeppelin directory [which i want to copy into docker package]into directory contain "Dockfile"

Step 2: edit Dockfile and add command [location where we want to copy] ADD ./zeppelin-0.7.2-bin-all /usr/local/

Step 3: go to directory which contain DockFile and run command [alternatives also available] docker build

Step 4: docker image created Successfully with logs

Step 5/9 : ADD ./zeppelin-0.7.2-bin-all /usr/local/ ---> 3691c902d9fe

Step 6/9 : WORKDIR $ZEPPELIN_HOME ---> 3adacfb024d8 .... Successfully built b67b9ea09f02

'Static readonly' vs. 'const'

My preference is to use const whenever I can, which, as mentioned in previous answers, is limited to literal expressions or something that does not require evaluation.

If I hit up against that limitation, then I fallback to static readonly, with one caveat. I would generally use a public static property with a getter and a backing private static readonly field as Marc mentions here.

PHP date() format when inserting into datetime in MySQL

I use this function (PHP 7)

function getDateForDatabase(string $date): string {
    $timestamp = strtotime($date);
    $date_formated = date('Y-m-d H:i:s', $timestamp);
    return $date_formated;
}

Older versions of PHP (PHP < 7)

function getDateForDatabase($date) {
    $timestamp = strtotime($date);
    $date_formated = date('Y-m-d H:i:s', $timestamp);
    return $date_formated;
}

Change drawable color programmatically

You can try this for svg vector drawable

DrawableCompat.setTint(
    DrawableCompat.wrap(myImageView.getDrawable()),
    ContextCompat.getColor(context, R.color.another_nice_color)
);

Lodash remove duplicates from array

_.unique no longer works for the current version of Lodash as version 4.0.0 has this breaking change. The functionality of _.unique was splitted into _.uniq, _.sortedUniq, _.sortedUniqBy, and _.uniqBy.

You could use _.uniqBy like this:

_.uniqBy(data, function (e) {
  return e.id;
});

...or like this:

_.uniqBy(data, 'id');

Documentation: https://lodash.com/docs#uniqBy


For older versions of Lodash (< 4.0.0 ):

Assuming that the data should be uniqued by each object's id property and your data is stored in data variable, you can use the _.unique() function like this:

_.unique(data, function (e) {
  return e.id;
});

Or simply like this:

_.uniq(data, 'id');

MySQL load NULL values from CSV data

This will do what you want. It reads the fourth field into a local variable, and then sets the actual field value to NULL, if the local variable ends up containing an empty string:

LOAD DATA INFILE '/tmp/testdata.txt'
INTO TABLE moo
FIELDS TERMINATED BY ","
LINES TERMINATED BY "\n"
(one, two, three, @vfour, five)
SET four = NULLIF(@vfour,'')
;

If they're all possibly empty, then you'd read them all into variables and have multiple SET statements, like this:

LOAD DATA INFILE '/tmp/testdata.txt'
INTO TABLE moo
FIELDS TERMINATED BY ","
LINES TERMINATED BY "\n"
(@vone, @vtwo, @vthree, @vfour, @vfive)
SET
one = NULLIF(@vone,''),
two = NULLIF(@vtwo,''),
three = NULLIF(@vthree,''),
four = NULLIF(@vfour,'')
;

Oracle SQL Developer: Unable to find a JVM

I just installed SQL Developer 4.0.0.13 and the SetJavaHome can now be overridden by a user-specific configuration file (not sure if this is new to 4.0.0.13 or not).

The location of this user-specific configuration file can be seen in the user.conf property under 'Help -> About' on the 'Properties' tab. For example, mine was set to:

C:\Users\username\AppData\Roaming\sqldeveloper\1.0.0.0.0\product.conf

On Windows 7.

The first section of this file is used to set the JDK that SQLDeveloper should use:

#
# By default, the product launcher will search for a JDK to use, and if none
# can be found, it will ask for the location of a JDK and store its location
# in this file. If a particular JDK should be used instead, uncomment the
# line below and set the path to your preferred JDK.
#
SetJavaHome C:\Program Files (x86)\Java\jdk1.7.0_03

This setting overrides the setting in sqldeveloper.conf

$http.get(...).success is not a function

This might be redundant but the above most voted answer says .then(function (success) and that didn't work for me as of Angular version 1.5.8. Instead use response then inside the block response.data got me my json data I was looking for.

$http({
    method: 'get', 
    url: 'data/data.json'
}).then(function (response) {
    console.log(response, 'res');
    data = response.data;
},function (error){
    console.log(error, 'can not get data.');
});

C: Run a System Command and Get Output?

You need some sort of Inter Process Communication. Use a pipe or a shared buffer.

Disable Chrome strict MIME type checking

In case you are using node.js (with express)

If you want to serve static files in node.js, you need to use a function. Add the following code to your js file:

app.use(express.static("public"));

Where app is:

const express = require("express");
const app = express();

Then create a folder called public in you project folder. (You could call it something else, this is just good practice but remember to change it from the function as well.)

Then in this file create another folder named css (and/or images file under css if you want to serve static images as well.) then add your css files to this folder.

After you add them change the stylesheet accordingly. For example if it was:

href="cssFileName.css"

and

src="imgName.png"

Make them:

href="css/cssFileName.css"
src="css/images/imgName.png"

That should work

PHP - find entry by object property from an array of objects

Try

$entry = current(array_filter($array, function($e) use($v){ return $e->ID==$v; }));

working example here

Use string.Contains() with switch()

Stegmenn nalied it for me but I had one change for when you have an IEnumerbale instead of a string = message like in his example.

private static string GetRoles(IEnumerable<External.Role> roles)
    {
            string[] switchStrings = { "Staff", "Board Member" };
            switch (switchStrings.FirstOrDefault<string>(s => roles.Select(t => t.RoleName).Contains(s)))
            {
                case
                    "Staff":
                    roleNameValues += "Staff,";
                    break;
                case
                    "Board Member":
                    roleNameValues += "Director,";
                    break;
                default:
                    break;
            }

Padding In bootstrap

The suggestion from @Dawood is good if that works for you.

If you need more fine-tuning than that, one option is to use padding on the text elements, here's an example: http://jsfiddle.net/panchroma/FtBwe/

CSS

p, h2 {
    padding-left:10px;
}

Swift Modal View Controller with transparent background

You can do it like this:

In your main view controller:

func showModal() {
    let modalViewController = ModalViewController()
    modalViewController.modalPresentationStyle = .overCurrentContext
    presentViewController(modalViewController, animated: true, completion: nil)
}

In your modal view controller:

class ModalViewController: UIViewController {
    override func viewDidLoad() {
        view.backgroundColor = UIColor.clearColor()
        view.opaque = false
    }
}

If you are working with a storyboard:

Just add a Storyboard Segue with Kind set to Present Modally to your modal view controller and on this view controller set the following values:

  • Background = Clear Color
  • Drawing = Uncheck the Opaque checkbox
  • Presentation = Over Current Context

As Crashalot pointed out in his comment: Make sure the segue only uses Default for both Presentation and Transition. Using Current Context for Presentation makes the modal turn black instead of remaining transparent.

Android: findviewbyid: finding view by id when view is not on the same layout invoked by setContentView

Another way to do this is:

// inflate the layout
View myLayout = LayoutInflater.from(this).inflate(R.layout.MY_LAYOUT,null);

// load the text view
TextView myView = (TextView) myLayout.findViewById(R.id.MY_VIEW);

How do you get a directory listing sorted by creation date in python?

For completeness with os.scandir (2x faster over pathlib):

import os
sorted(os.scandir('/tmp/test'), key=lambda d: d.stat().st_mtime)

Submit form without page reloading

You will need to use JavaScript without resulting to an iframe (ugly approach).

You can do it in JavaScript; using jQuery will make it painless.

I suggest you check out AJAX and Posting.

Dropdown using javascript onchange

It does not work because your script in JSFiddle is running inside it's own scope (see the "OnLoad" drop down on the left?).

One way around this is to bind your event handler in javascript (where it should be):

document.getElementById('optionID').onchange = function () {
    document.getElementById("message").innerHTML = "Having a Baby!!";
};

Another way is to modify your code for the fiddle environment and explicitly declare your function as global so it can be found by your inline event handler:

window.changeMessage() {
    document.getElementById("message").innerHTML = "Having a Baby!!";
};

?

VB.NET Empty String Array

try this Dim Arraystr() as String ={}

Mean Squared Error in Numpy?

Just for kicks

mse = (np.linalg.norm(A-B)**2)/len(A)

connect local repo with remote repo

git remote add origin <remote_repo_url>
git push --all origin

If you want to set all of your branches to automatically use this remote repo when you use git pull, add --set-upstream to the push:

git push --all --set-upstream origin

foreach vs someList.ForEach(){}

We had some code here (in VS2005 and C#2.0) where the previous engineers went out of their way to use list.ForEach( delegate(item) { foo;}); instead of foreach(item in list) {foo; }; for all the code that they wrote. e.g. a block of code for reading rows from a dataReader.

I still don't know exactly why they did this.

The drawbacks of list.ForEach() are:

  • It is more verbose in C# 2.0. However, in C# 3 onwards, you can use the "=>" syntax to make some nicely terse expressions.

  • It is less familiar. People who have to maintain this code will wonder why you did it that way. It took me awhile to decide that there wasn't any reason, except maybe to make the writer seem clever (the quality of the rest of the code undermined that). It was also less readable, with the "})" at the end of the delegate code block.

  • See also Bill Wagner's book "Effective C#: 50 Specific Ways to Improve Your C#" where he talks about why foreach is preferred to other loops like for or while loops - the main point is that you are letting the compiler decide the best way to construct the loop. If a future version of the compiler manages to use a faster technique, then you will get this for free by using foreach and rebuilding, rather than changing your code.

  • a foreach(item in list) construct allows you to use break or continue if you need to exit the iteration or the loop. But you cannot alter the list inside a foreach loop.

I'm surprised to see that list.ForEach is slightly faster. But that's probably not a valid reason to use it throughout , that would be premature optimisation. If your application uses a database or web service that, not loop control, is almost always going to be be where the time goes. And have you benchmarked it against a for loop too? The list.ForEach could be faster due to using that internally and a for loop without the wrapper would be even faster.

I disagree that the list.ForEach(delegate) version is "more functional" in any significant way. It does pass a function to a function, but there's no big difference in the outcome or program organisation.

I don't think that foreach(item in list) "says exactly how you want it done" - a for(int 1 = 0; i < count; i++) loop does that, a foreach loop leaves the choice of control up to the compiler.

My feeling is, on a new project, to use foreach(item in list) for most loops in order to adhere to the common usage and for readability, and use list.Foreach() only for short blocks, when you can do something more elegantly or compactly with the C# 3 "=>" operator. In cases like that, there may already be a LINQ extension method that is more specific than ForEach(). See if Where(), Select(), Any(), All(), Max() or one of the many other LINQ methods doesn't already do what you want from the loop.

No visible cause for "Unexpected token ILLEGAL"

I changed all space areas to &nbsp, just like that and it worked without problem.

val.replace(" ", "&nbsp");

I hope it helps someone.

Find unused npm packages in package.json

You can use an npm module called depcheck (requires at least version 10 of Node).

  1. Install the module:

     npm install depcheck -g
    
     or
    
     yarn global add depcheck
    
  2. Run it and find the unused dependencies:

     depcheck
    

The good thing about this approach is that you don't have to remember the find or grep command.

To run without installing use npx:

npx depcheck 

Maven : error in opening zip file when running maven

Accidently I found a simple workaroud to this issue. Running Maven with -X option forces it to try other servers to download source code. Instead of trash HTML inside some jar files there is correct content.

mvn clean install -X > d:\log.txt

And in the log file you find messages like these:

Downloading: https://repository.apache.org/content/groups/public/org/apache/axis2/mex/1.6.1-wso2v2/mex-1.6.1-wso2v2-impl.jar
[DEBUG] Writing resolution tracking file D:\wso2_local_repository\org\apache\axis2\mex\1.6.1-wso2v2\mex-1.6.1-wso2v2-impl.jar.lastUpdated
Downloading: http://maven.wso2.org/nexus/content/groups/wso2-public/org/apache/axis2/mex/1.6.1-wso2v2/mex-1.6.1-wso2v2-impl.jar

You see, Maven switched repository.apache.org to maven.wso2.org when it encountered a download problem. So the following error is now gone:

[ERROR] error: error reading D:\wso2_local_repository\org\apache\axis2\mex\1.6.1-wso2v2\mex-1.6.1-wso2v2-impl.jar; error in opening zip file

IOError: [Errno 32] Broken pipe: Python

A "Broken Pipe" error occurs when you try to write to a pipe that has been closed on the other end. Since the code you've shown doesn't involve any pipes directly, I suspect you're doing something outside of Python to redirect the standard output of the Python interpreter to somewhere else. This could happen if you're running a script like this:

python foo.py | someothercommand

The issue you have is that someothercommand is exiting without reading everything available on its standard input. This causes your write (via print) to fail at some point.

I was able to reproduce the error with the following command on a Linux system:

python -c 'for i in range(1000): print i' | less

If I close the less pager without scrolling through all of its input (1000 lines), Python exits with the same IOError you have reported.

What is the difference between C# and .NET?

When people talk about the ".net framework" they tend to be combining two main areas - the runtime library and the virtual machine that actually runs the .net code.

When you create a class library in Visual Studio in C#, the DLL follows a prescribed format - very roughly, there is section that contains meta data that describes what classes are included in it and what functions they have, etc.. and that describes where in the binary those objects exist. This common .net format is what allows libraries to be shared between .net languages (C#, VB.Net, F# and others) easily. Although much of the .net "runtime library" is written in C# now (I believe), you can imagine how many of them could have been written in unmanaged languages but arranged in this prescribed format so that they could be consumed by .net languages.

The real "meat" of the library that you build consists of CIL ("Common Intermediate Language") which is a bit like the assembly language of .net - again, this language is the common output of all .net languages, which is what makes .net libraries consumable by any .net language.

Using the tool "ildasm.exe", which is freely available in Microsoft SDKs (and might already be on your computer), you can see how C# code is converted into meta data and IL. I've included a sample at the bottom of this answer as an example.

When you run execute .net code, what is commonly happening is the .net virtual machine is reading that IL and processing it. This is the other side of .net and, again, you can likely imagine that this could easily be written in an unmanaged language - it "only" needs to read VM instructions and run them (and integrate with the garbage collector, which also need not be .net code).

What I've described is (again, roughly) what happens when you build an executable in Visual Studio (for more information, I highly recommend the book "CLR via C# by Jeffrey Richter" - it's very detailed and excellently written).

However, there are times that you might write C# that will not be executed within a .net environment - for example, Bridge.NET "compiles" C# code into JavaScript which is then run in the browser (the team that produce it have gone to the effort of writing versions of the .net runtime library that are written in JavaScript and so the power and flexibility of the .net library is available to the generated JavaScript). This is a perfect example of the separation between C# and .net - it's possible to write C# for different "targets"; you might target the .net runtime environment (when you build an executable) or you might target the browser environment (when you use Bridge.NET).

A (very) simple example class:

using System;

namespace Example
{
    public class Class1
    {
        public void SayHello()
        {
            Console.WriteLine("Hello");
        }
    }
}

The resulting meta data and IL (retrieved via ildasm.exe):

// Metadata version: v4.0.30319
.assembly extern mscorlib
{
  .publickeytoken = (B7 7A 5C 56 19 34 E0 89 )                         // .z\V.4..
  .ver 4:0:0:0
}
.assembly Example
{
  .custom instance void [mscorlib]System.Runtime.CompilerServices.CompilationRelaxationsAttribute::.ctor(int32) = ( 01 00 08 00 00 00 00 00 ) 
  .custom instance void [mscorlib]System.Runtime.CompilerServices.RuntimeCompatibilityAttribute::.ctor() = ( 01 00 01 00 54 02 16 57 72 61 70 4E 6F 6E 45 78   // ....T..WrapNonEx
                                                                                                            63 65 70 74 69 6F 6E 54 68 72 6F 77 73 01 )       // ceptionThrows.

  // --- The following custom attribute is added automatically, do not uncomment -------
  //  .custom instance void [mscorlib]System.Diagnostics.DebuggableAttribute::.ctor(valuetype [mscorlib]System.Diagnostics.DebuggableAttribute/DebuggingModes) = ( 01 00 07 01 00 00 00 00 ) 

  .custom instance void [mscorlib]System.Reflection.AssemblyTitleAttribute::.ctor(string) = ( 01 00 0A 54 65 73 74 49 4C 44 41 53 4D 00 00 )    // ...TestILDASM..
  .custom instance void [mscorlib]System.Reflection.AssemblyDescriptionAttribute::.ctor(string) = ( 01 00 00 00 00 ) 
  .custom instance void [mscorlib]System.Reflection.AssemblyConfigurationAttribute::.ctor(string) = ( 01 00 00 00 00 ) 
  .custom instance void [mscorlib]System.Reflection.AssemblyCompanyAttribute::.ctor(string) = ( 01 00 00 00 00 ) 
  .custom instance void [mscorlib]System.Reflection.AssemblyProductAttribute::.ctor(string) = ( 01 00 0A 54 65 73 74 49 4C 44 41 53 4D 00 00 )    // ...TestILDASM..
  .custom instance void [mscorlib]System.Reflection.AssemblyCopyrightAttribute::.ctor(string) = ( 01 00 12 43 6F 70 79 72 69 67 68 74 20 C2 A9 20   // ...Copyright .. 
                                                                                                  20 32 30 31 36 00 00 )                            //  2016..
  .custom instance void [mscorlib]System.Reflection.AssemblyTrademarkAttribute::.ctor(string) = ( 01 00 00 00 00 ) 
  .custom instance void [mscorlib]System.Runtime.InteropServices.ComVisibleAttribute::.ctor(bool) = ( 01 00 00 00 00 ) 
  .custom instance void [mscorlib]System.Runtime.InteropServices.GuidAttribute::.ctor(string) = ( 01 00 24 31 39 33 32 61 32 30 65 2D 61 37 36 64   // ..$1932a20e-a76d
                                                                                                  2D 34 36 33 35 2D 62 36 38 66 2D 36 63 35 66 36   // -4635-b68f-6c5f6
                                                                                                  32 36 36 31 36 37 62 00 00 )                      // 266167b..
  .custom instance void [mscorlib]System.Reflection.AssemblyFileVersionAttribute::.ctor(string) = ( 01 00 07 31 2E 30 2E 30 2E 30 00 00 )             // ...1.0.0.0..
  .custom instance void [mscorlib]System.Runtime.Versioning.TargetFrameworkAttribute::.ctor(string) = ( 01 00 1C 2E 4E 45 54 46 72 61 6D 65 77 6F 72 6B   // ....NETFramework
                                                                                                        2C 56 65 72 73 69 6F 6E 3D 76 34 2E 35 2E 32 01   // ,Version=v4.5.2.
                                                                                                        00 54 0E 14 46 72 61 6D 65 77 6F 72 6B 44 69 73   // .T..FrameworkDis
                                                                                                        70 6C 61 79 4E 61 6D 65 14 2E 4E 45 54 20 46 72   // playName..NET Fr
                                                                                                        61 6D 65 77 6F 72 6B 20 34 2E 35 2E 32 )          // amework 4.5.2
  .hash algorithm 0x00008004
  .ver 1:0:0:0
}
.module Example.dll
// MVID: {80A91E4C-0994-4773-9B73-2C4977BB1F17}
.imagebase 0x10000000
.file alignment 0x00000200
.stackreserve 0x00100000
.subsystem 0x0003       // WINDOWS_CUI
.corflags 0x00000001    //  ILONLY
// Image base: 0x05DB0000

// =============== CLASS MEMBERS DECLARATION ===================

.class public auto ansi beforefieldinit Example.Class1
       extends [mscorlib]System.Object
{
  .method public hidebysig instance void 
          SayHello() cil managed
  {
    // Code size       13 (0xd)
    .maxstack  8
    IL_0000:  nop
    IL_0001:  ldstr      "Hello"
    IL_0006:  call       void [mscorlib]System.Console::WriteLine(string)
    IL_000b:  nop
    IL_000c:  ret
  } // end of method Class1::SayHello

  .method public hidebysig specialname rtspecialname 
          instance void  .ctor() cil managed
  {
    // Code size       8 (0x8)
    .maxstack  8
    IL_0000:  ldarg.0
    IL_0001:  call       instance void [mscorlib]System.Object::.ctor()
    IL_0006:  nop
    IL_0007:  ret
  } // end of method Class1::.ctor

} // end of class Example.Class1

// =============================================================

How to Deserialize XML document

How about you just save the xml to a file, and use xsd to generate C# classes?

  1. Write the file to disk (I named it foo.xml)
  2. Generate the xsd: xsd foo.xml
  3. Generate the C#: xsd foo.xsd /classes

Et voila - and C# code file that should be able to read the data via XmlSerializer:

    XmlSerializer ser = new XmlSerializer(typeof(Cars));
    Cars cars;
    using (XmlReader reader = XmlReader.Create(path))
    {
        cars = (Cars) ser.Deserialize(reader);
    }

(include the generated foo.cs in the project)

Missing styles. Is the correct theme chosen for this layout?

This is because you select not a theme of your project. Try to do next:

enter image description here

Ruby on Rails: Clear a cached page

This line in development.rb ensures that caching is not happening.

config.action_controller.perform_caching             = false

You can clear the Rails cache with

Rails.cache.clear

That said - I am not convinced this is a caching issue. Are you making changes to the page and not seeing them reflected? You aren't perhaps looking at the live version of that page? I have done that once (blush).

Update:

You can call that command from in the console. Are you sure you are running the application in development?

The only alternative is that the page that you are trying to render isn't the page that is being rendered.

If you watch the server output you should be able to see the render command when the page is rendered similar to this:

Rendered shared_partials/_latest_featured_video (31.9ms)
Rendered shared_partials/_s_invite_friends (2.9ms)
Rendered layouts/_sidebar (2002.1ms)
Rendered layouts/_footer (2.8ms)
Rendered layouts/_busy_indicator (0.6ms)

How do I install Composer on a shared hosting?

It depends on the host, but you probably simply can't (you can't on my shared host on Rackspace Cloud Sites - I asked them).

What you can do is set up an environment on your dev machine that roughly matches your shared host, and do all of your management through the command line locally. Then when everything is set (you've pulled in all the dependencies, updated, managed with git, etc.) you can "push" that to your shared host over (s)FTP.

GC overhead limit exceeded

From Java SE 6 HotSpot[tm] Virtual Machine Garbage Collection Tuning

the following

Excessive GC Time and OutOfMemoryError

The concurrent collector will throw an OutOfMemoryError if too much time is being spent in garbage collection: if more than 98% of the total time is spent in garbage collection and less than 2% of the heap is recovered, an OutOfMemoryError will be thrown. This feature is designed to prevent applications from running for an extended period of time while making little or no progress because the heap is too small. If necessary, this feature can be disabled by adding the option -XX:-UseGCOverheadLimit to the command line.

The policy is the same as that in the parallel collector, except that time spent performing concurrent collections is not counted toward the 98% time limit. In other words, only collections performed while the application is stopped count toward excessive GC time. Such collections are typically due to a concurrent mode failure or an explicit collection request (e.g., a call to System.gc()).

in conjunction with a passage further down

One of the most commonly encountered uses of explicit garbage collection occurs with RMIs distributed garbage collection (DGC). Applications using RMI refer to objects in other virtual machines. Garbage cannot be collected in these distributed applications without occasionally collection the local heap, so RMI forces full collections periodically. The frequency of these collections can be controlled with properties. For example,

java -Dsun.rmi.dgc.client.gcInterval=3600000

-Dsun.rmi.dgc.server.gcInterval=3600000 specifies explicit collection once per hour instead of the default rate of once per minute. However, this may also cause some objects to take much longer to be reclaimed. These properties can be set as high as Long.MAX_VALUE to make the time between explicit collections effectively infinite, if there is no desire for an upper bound on the timeliness of DGC activity.

Seems to imply that the evaluation period for determining the 98% is one minute long, but it might be configurable on Sun's JVM with the correct define.

Of course, other interpretations are possible.

How to obtain the start time and end time of a day?

I tried this code and it works well!

final ZonedDateTime now = ZonedDateTime.now(ZoneOffset.UTC);
final ZonedDateTime startofDay =
    now.toLocalDate().atStartOfDay(ZoneOffset.UTC);
final ZonedDateTime endOfDay =
    now.toLocalDate().atTime(LocalTime.MAX).atZone(ZoneOffset.UTC);

How to show disable HTML select option in by default?

Electron + React Let your two first options be like this

<option hidden="true>Choose Tagging</option>
<option disabled="disabled" default="true">Choose Tagging</option>

First to display when closed Second to display first when the list opens

How to execute multiple SQL statements from java

you can achieve that using Following example uses addBatch & executeBatch commands to execute multiple SQL commands simultaneously.

Batch Processing allows you to group related SQL statements into a batch and submit them with one call to the database. reference

When you send several SQL statements to the database at once, you reduce the amount of communication overhead, thereby improving performance.

  • JDBC drivers are not required to support this feature. You should use the DatabaseMetaData.supportsBatchUpdates() method to determine if the target database supports batch update processing. The method returns true if your JDBC driver supports this feature.
  • The addBatch() method of Statement, PreparedStatement, and CallableStatement is used to add individual statements to the batch. The executeBatch() is used to start the execution of all the statements grouped together.
  • The executeBatch() returns an array of integers, and each element of the array represents the update count for the respective update statement.
  • Just as you can add statements to a batch for processing, you can remove them with the clearBatch() method. This method removes all the statements you added with the addBatch() method. However, you cannot selectively choose which statement to remove.

EXAMPLE:

import java.sql.*;

public class jdbcConn {
   public static void main(String[] args) throws Exception{
      Class.forName("org.apache.derby.jdbc.ClientDriver");
      Connection con = DriverManager.getConnection
      ("jdbc:derby://localhost:1527/testDb","name","pass");

      Statement stmt = con.createStatement
      (ResultSet.TYPE_SCROLL_SENSITIVE,
      ResultSet.CONCUR_UPDATABLE);
      String insertEmp1 = "insert into emp values
      (10,'jay','trainee')";
      String insertEmp2 = "insert into emp values
      (11,'jayes','trainee')";
      String insertEmp3 = "insert into emp values
      (12,'shail','trainee')";
      con.setAutoCommit(false);
      stmt.addBatch(insertEmp1);//inserting Query in stmt
      stmt.addBatch(insertEmp2);
      stmt.addBatch(insertEmp3);
      ResultSet rs = stmt.executeQuery("select * from emp");
      rs.last();
      System.out.println("rows before batch execution= "
      + rs.getRow());
      stmt.executeBatch();
      con.commit();
      System.out.println("Batch executed");
      rs = stmt.executeQuery("select * from emp");
      rs.last();
      System.out.println("rows after batch execution= "
      + rs.getRow());
   }
} 

refer http://www.tutorialspoint.com/javaexamples/jdbc_executebatch.htm

How to update an object in a List<> in C#

This was a new discovery today - after having learned the class/struct reference lesson!

You can use Linq and "Single" if you know the item will be found, because Single returns a variable...

myList.Single(x => x.MyProperty == myValue).OtherProperty = newValue;

Elasticsearch error: cluster_block_exception [FORBIDDEN/12/index read-only / allow delete (api)], flood stage disk watermark exceeded

By default, Elasticsearch installed goes into read-only mode when you have less than 5% of free disk space. If you see errors similar to this:

Elasticsearch::Transport::Transport::Errors::Forbidden: [403] {"error":{"root_cause":[{"type":"cluster_block_exception","reason":"blocked by: [FORBIDDEN/12/index read-only / allow delete (api)];"}],"type":"cluster_block_exception","reason":"blocked by: [FORBIDDEN/12/index read-only / allow delete (api)];"},"status":403}

Or in /usr/local/var/log/elasticsearch.log you can see logs similar to:

flood stage disk watermark [95%] exceeded on [nCxquc7PTxKvs6hLkfonvg][nCxquc7][/usr/local/var/lib/elasticsearch/nodes/0] free: 15.3gb[4.1%], all indices on this node will be marked read-only

Then you can fix it by running the following commands:

curl -XPUT -H "Content-Type: application/json" http://localhost:9200/_cluster/settings -d '{ "transient": { "cluster.routing.allocation.disk.threshold_enabled": false } }'
curl -XPUT -H "Content-Type: application/json" http://localhost:9200/_all/_settings -d '{"index.blocks.read_only_allow_delete": null}'

Spring Boot Remove Whitelabel Error Page

Spring Boot by default has a “whitelabel” error page which you can see in a browser if you encounter a server error. Whitelabel Error Page is a generic Spring Boot error page which is displayed when no custom error page is found.

Set “server.error.whitelabel.enabled=false” to switch of the default error page

Best way to encode text data for XML in Java?

This has worked well for me to provide an escaped version of a text string:

public class XMLHelper {

/**
 * Returns the string where all non-ascii and <, &, > are encoded as numeric entities. I.e. "&lt;A &amp; B &gt;"
 * .... (insert result here). The result is safe to include anywhere in a text field in an XML-string. If there was
 * no characters to protect, the original string is returned.
 * 
 * @param originalUnprotectedString
 *            original string which may contain characters either reserved in XML or with different representation
 *            in different encodings (like 8859-1 and UFT-8)
 * @return
 */
public static String protectSpecialCharacters(String originalUnprotectedString) {
    if (originalUnprotectedString == null) {
        return null;
    }
    boolean anyCharactersProtected = false;

    StringBuffer stringBuffer = new StringBuffer();
    for (int i = 0; i < originalUnprotectedString.length(); i++) {
        char ch = originalUnprotectedString.charAt(i);

        boolean controlCharacter = ch < 32;
        boolean unicodeButNotAscii = ch > 126;
        boolean characterWithSpecialMeaningInXML = ch == '<' || ch == '&' || ch == '>';

        if (characterWithSpecialMeaningInXML || unicodeButNotAscii || controlCharacter) {
            stringBuffer.append("&#" + (int) ch + ";");
            anyCharactersProtected = true;
        } else {
            stringBuffer.append(ch);
        }
    }
    if (anyCharactersProtected == false) {
        return originalUnprotectedString;
    }

    return stringBuffer.toString();
}

}

Making Maven run all tests, even when some fail

I just found the "-fae" parameter, which causes Maven to run all tests and not stop on failure.

add id to dynamically created <div>

Here is an example of what I made to created ID's with my JavaScript.

function abs_demo_DemandeEnvoyee_absence(){

    var iDateInitiale = document.getElementById("abs_t_date_JourInitial_absence").value; /* On récupère la date initiale*/
    var iDateFinale = document.getElementById("abs_t_date_JourFinal_absence").value;     /*On récupère la date finale*/
    var sMotif = document.getElementById("abs_txt_motif_absence").value;                 /*On récupère le motif*/  
    var iCompteurDivNumero = 1;                                                         /*Le compteur est initialisé à 1 parce que la div 1 existe*/
    var TestDivVide = document.getElementById("abs_Autorisation_"+iCompteurDivNumero+"_absence") == undefined; //Boléenne, renvoie false si la div existe déjà
    var NewDivCreation = "";                                                            /*Initialisée en string vide pour concaténation*/
    var NewIdCreation;                                                                  /*Utilisée pour créer l'id d'une div dynamiquement*/
    var NewDivVersHTML;                                                                 /*Utilisée pour insérer la nouvelle div dans le html*/


    while(TestDivVide == false){                                                        /*Tant que la div pointée existe*/
        iCompteurDivNumero++;                                                           /*On incrémente le compteur de 1*/
        TestDivVide = document.getElementById("abs_Autorisation_"+iCompteurDivNumero+"_absence") == undefined; /*Abs_autorisation_1_ est écrite en dur.*/   
    }

    NewIdCreation = "abs_Autorisation_"+iCompteurDivNumero+"_absence"                   /*On crée donc la nouvelle ID de DIV*/

                                                                                        /*On crée la nouvelle DIV avec l'ID précédemment créée*/
    NewDivCreation += "<div class=\"abs_AutorisationsDynamiques_absence\" id=\""+NewIdCreation+"\">Votre demande d'autorisation d'absence du <b>"+iDateInitiale+"</b> au <b>"+iDateFinale+"</b>, pour le motif suivant : <i>\""+sMotif+"\"</i> a bien été <span class=\"abs_CouleurTexteEnvoye_absence\">envoyée</span>.</div>";

    document.getElementById("abs_AffichagePanneauDeControle_absence").innerHTML+=NewDivCreation; /*Et on concatenne la nouvelle div créée*/ 

    document.getElementById("abs_Autorisation_1_absence").style.display = 'none'; /*On cache la première div qui contient le message "vous n'avez pas de demande en attente" */

}

Will provide text translation if asked. :)

Counter in foreach loop in C#

From MSDN:

The foreach statement repeats a group of embedded statements for each element in an array or an object collection that implements the System.Collections.IEnumerable or System.Collections.Generic.IEnumerable(Of T) interface.

So, it's not necessarily Array. It could even be a lazy collection with no idea about the count of items in the collection.

How do I use brew installed Python as the default Python?

No idea what you mean with default Python. I consider it bad practice to replace the system Python interpreter with a different version. System functionality may depend in some way on the system Python and specific modules or a specific Python version. Instead install your custom Python installations in a safe different place and adjust your $PATH as needed in order to call you Python through a path lookup instead of looking for the default Python.

Move a view up only when the keyboard covers an input field

This code moves up the text field you are editing so that you can view it in Swift 3 for this answer you also have to make your view a UITextFieldDelegate:

var moveValue: CGFloat!
var moved: Bool = false
var activeTextField = UITextField()

func textFieldDidBeginEditing(_ textField: UITextField) {
    self.activeTextField = textField
}
func textFieldDidEndEditing(_ textField: UITextField) {
    if moved == true{
    self.animateViewMoving(up: false, moveValue: moveValue )
        moved = false
    }
}
func animateViewMoving (up:Bool, moveValue :CGFloat){
    let movementDuration:TimeInterval = 0.3
    let movement:CGFloat = ( up ? -moveValue : moveValue)

    UIView.beginAnimations("animateView", context: nil)
    UIView.setAnimationBeginsFromCurrentState(true)
    UIView.setAnimationDuration(movementDuration)

    self.view.frame = self.view.frame.offsetBy(dx: 0, dy: movement)
    UIView.commitAnimations()
}

And then in viewDidLoad:

NotificationCenter.default.addObserver(self, selector: #selector(keyboardWillShow), name: .UIKeyboardWillShow, object: nil)

Which calls (outside viewDidLoad):

func keyboardWillShow(notification: Notification) {
    if let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.cgRectValue {
        let keyboardHeight = keyboardSize.height
        if (view.frame.size.height-self.activeTextField.frame.origin.y) - self.activeTextField.frame.size.height < keyboardHeight{
            moveValue = keyboardHeight - ((view.frame.size.height-self.activeTextField.frame.origin.y) - self.activeTextField.frame.size.height)
            self.animateViewMoving(up: true, moveValue: moveValue )
            moved = true
        }
    }
}

Can I fade in a background image (CSS: background-image) with jQuery?

It's not possible to do it just like that, but you can overlay an opaque div between the div with the background-image and the text and fade that one out, hence giving the appearance that the background is fading in.

'dispatch' is not a function when argument to mapToDispatchToProps() in Redux

You are just missing the first argument to connect, which is the mapStateToProps method. Excerpt from the Redux todo app:

const mapStateToProps = (state) => {
  return {
    todos: getVisibleTodos(state.todos, state.visibilityFilter)
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    onTodoClick: (id) => {
      dispatch(toggleTodo(id))
    }
  }
}

const VisibleTodoList = connect(
  mapStateToProps,
  mapDispatchToProps
)(TodoList)

How to add a right button to a UINavigationController?

Why are you subclasses UINavigationController? There is no need to subclass it if all you need to do is add a button to it.

Set up a hierarchy with a UINavigationController at the top, and then in your root view controller's viewDidLoad: method: set up the button and attach it to the navigation item by calling

[[self navigationItem] setRightBarButtonItem:myBarButtonItem];

multiple plot in one figure in Python

EDIT: I just realised after reading your question again, that i did not answer your question. You want to enter multiple lines in the same plot. However, I'll leave it be, because this served me very well multiple times. I hope you find usefull someday

I found this a while back when learning python

import matplotlib.pyplot as plt
import matplotlib.gridspec as gridspec

fig = plt.figure() 
# create figure window

gs = gridspec.GridSpec(a, b)
# Creates grid 'gs' of a rows and b columns 


ax = plt.subplot(gs[x, y])
# Adds subplot 'ax' in grid 'gs' at position [x,y]


ax.set_ylabel('Foo') #Add y-axis label 'Foo' to graph 'ax' (xlabel for x-axis)


fig.add_subplot(ax) #add 'ax' to figure

you can make different sizes in one figure as well, use slices in that case:

 gs = gridspec.GridSpec(3, 3)
 ax1 = plt.subplot(gs[0,:]) # row 0 (top) spans all(3) columns

consult the docs for more help and examples. This little bit i typed up for myself once, and is very much based/copied from the docs as well. Hope it helps... I remember it being a pain in the #$% to get acquainted with the slice notation for the different sized plots in one figure. After that i think it's very simple :)

How to open VMDK File of the Google-Chrome-OS bundle 2012?

you can also use vmware-mount from VMwares VDDK (Virtual Disk Development Kit): http://communities.vmware.com/community/vmtn/developer/forums/vddk

this allows you to mount VMDK files as disk drives in windows or linux

Why does GitHub recommend HTTPS over SSH?

Also see: the official Which remote URL should I use? answer on help.github.com.

EDIT:

It seems that it's no longer necessary to have write access to a public repo to use an SSH URL, rendering my original explanation invalid.

ORIGINAL:

Apparently the main reason for favoring HTTPS URLs is that SSH URL's won't work with a public repo if you don't have write access to that repo.

The use of SSH URLs is encouraged for deployment to production servers, however - presumably the context here is services like Heroku.

Find UNC path of a network drive?

If you have Microsoft Office:

  1. RIGHT-drag the drive, folder or file from Windows Explorer into the body of a Word document or Outlook email
  2. Select 'Create Hyperlink Here'

The inserted text will be the full UNC of the dragged item.

Electron: jQuery is not defined

1.Install jQuery using npm.

npm install jquery --save

2.

<!--firstly try to load jquery as browser-->
<script src="./jquery-3.3.1.min.js"></script>
<!--if first not work. load using require()-->
<script>
  if (typeof jQuery == "undefined"){window.$ = window.jQuery = require('jquery');}
</script>

How to use Oracle's LISTAGG function with a unique filter?

In 11g you can use the undocumented function wm_concat like this:

     select wm_concat(distinct name) as names from demotable group by group_id

PUT vs. POST in REST

So, which one should be used to create a resource? Or one needs to support both?

You should use PATCH. You PATCH the list of questions like

PATCH /questions HTTP/1.1

with a list containing your to be created object like

[
    {
        "title": "I said semantics!",
        "content": "Is this serious?",
        "answer": "Not really"
    }
]

It's a PATCH request as

  • you modify the existing list of resources without providing the whole new content
  • you change the state of your new question from non-existing to existing without providing all the data (the server will most probably add an id).

A great advantage of this method is that you can create multiple entities using a single request, simply by providing them all in the list.

This is something PUT obviously can't. You could use POST for creating multiple entities as it's the kitchen sink of HTTP and can do basically everything.

A disadvantage is that probably nobody uses PATCH this way. I'm afraid, I just invented it, but I hope, I provided a good argumentation.

You could use CREATE instead, as custom HTTP verbs are allowed, it's just that they mayn't work with some tools.

Concerning semantics, CREATE is IMHO the only right choice, everything else is a square peg in a round hole. Unfortunately, all we have are round holes.

Jquery - How to make $.post() use contentType=application/json?

$.ajax({
  url:url,
  type:"POST",
  data:data,
  contentType:"application/json; charset=utf-8",
  dataType:"json",
  success: function(){
    ...
  }
})

See : jQuery.ajax()

How do you get a timestamp in JavaScript?

function getTimeStamp() {
    var now = new Date();
    return ((now.getMonth() + 1) + '/' +
            (now.getDate()) + '/' +
             now.getFullYear() + " " +
             now.getHours() + ':' +
             ((now.getMinutes() < 10)
                 ? ("0" + now.getMinutes())
                 : (now.getMinutes())) + ':' +
             ((now.getSeconds() < 10)
                 ? ("0" + now.getSeconds())
                 : (now.getSeconds())));
}

Java String new line

I use this code String result = args[0].replace("\\n", "\n");

public class HelloWorld {

    public static void main(String[] args) {
        String result = args[0].replace("\\n", "\n");
        System.out.println(result);
    }
}

with terminal I can use arg I\\nam\\na\\boy to make System.out.println print out

I
am
a
boy

enter image description here

how to pass this element to javascript onclick function and add a class to that clicked element

Use this html to get the clicked element:

<div class="row" style="padding-left:21px;">
    <ul class="nav nav-tabs" style="padding-left:40px;">
        <li class="active filter"><a href="#month" onclick="Data('month', this)">This Month</a></li>
        <li class="filter"><a href="#year" onclick="Data('year', this)">Year</a></li>
        <li class="filter"><a href="#last60" onclick="Data('last60', this)">60 Days</a></li>
        <li class="filter"><a href="#last90" onclick="Data('last90', this)">90 Days</a></li>
    </ul> 
</div>

Script:

 function Data(string, el)
 {
     $('.filter').removeClass('active');
     $(el).parent().addClass('active');
 } 

How can I access and process nested objects, arrays or JSON?

Accessing dynamically multi levels object.

var obj = {
  name: "john doe",
  subobj: {
    subsubobj: {
      names: "I am sub sub obj"
    }
  }
};

var level = "subobj.subsubobj.names";
level = level.split(".");

var currentObjState = obj;

for (var i = 0; i < level.length; i++) {
  currentObjState = currentObjState[level[i]];
}

console.log(currentObjState);

Working fiddle: https://jsfiddle.net/andreitodorut/3mws3kjL/

Accessing last x characters of a string in Bash

You can use tail:

$ foo="1234567890"
$ echo -n $foo | tail -c 3
890

A somewhat roundabout way to get the last three characters would be to say:

echo $foo | rev | cut -c1-3 | rev

Get the first element of an array

PHP 5.4+:

array_values($array)[0];

current/duration time of html5 video?

HTML:

<video
    id="video-active"
    class="video-active"
    width="640"
    height="390"
    controls="controls">
    <source src="myvideo.mp4" type="video/mp4">
</video>
<div id="current">0:00</div>
<div id="duration">0:00</div>

JavaScript:

$(document).ready(function(){
  $("#video-active").on(
    "timeupdate", 
    function(event){
      onTrackedVideoFrame(this.currentTime, this.duration);
    });
});

function onTrackedVideoFrame(currentTime, duration){
    $("#current").text(currentTime); //Change #current to currentTime
    $("#duration").text(duration)
}

Notes:

Every 15 to 250ms, or whenever the MediaController's media controller position changes, whichever happens least often, the user agent must queue a task to fire a simple event named timeupdate at the MediaController.

http://www.w3.org/TR/html5/embedded-content-0.html#media-controller-position

RegEx: How can I match all numbers greater than 49?

Next matches all greater or equal to 11100:

^([1-9][1-9][1-9]\d{2}\d*|[1-9][2-9]\d{3}\d*|[2-9]\d{4}\d*|\d{6}\d*)$

For greater or equal 50:

^([5-9]\d{1}\d*|\d{3}\d*)$

See pattern and modify to any number. Also it would be great to find some recursive forward/backward operators for large numbers.

Calculating the distance between 2 points

Given points (X1,Y1) and (X2,Y2) then:

dX = X1 - X2;
dY = Y1 - Y2;

if (dX*dX + dY*dY > (5*5))
{
    //your code
}

Getting "Lock wait timeout exceeded; try restarting transaction" even though I'm not using a transaction

In my instance, I was running an abnormal query to fix data. If you lock the tables in your query, then you won't have to deal with the Lock timeout:

LOCK TABLES `customer` WRITE;
update customer set account_import_id = 1;
UNLOCK TABLES;

This is probably not a good idea for normal use.

For more info see: MySQL 8.0 Reference Manual

Convert string into integer in bash script - "Leading Zero" number error

The leading 0 is leading to bash trying to interpret your number as an octal number, but octal numbers are 0-7, and 8 is thus an invalid token.

If I were you, I would add some logic to remove a leading 0, add one, and re-add the leading 0 if the result is < 10.

jQuery UI themes and HTML tables

dochoffiday's answer is a great starting point, but for me it did not cut it (the CSS part needed a buff) so I made a modified version with several improvements.

See it in action, then come back for the description.

JavaScript

(function ($) {
    $.fn.styleTable = function (options) {
        var defaults = {
            css: 'ui-styled-table'
        };
        options = $.extend(defaults, options);

        return this.each(function () {
            $this = $(this);
            $this.addClass(options.css);

            $this.on('mouseover mouseout', 'tbody tr', function (event) {
                $(this).children().toggleClass("ui-state-hover",
                                               event.type == 'mouseover');
            });

            $this.find("th").addClass("ui-state-default");
            $this.find("td").addClass("ui-widget-content");
            $this.find("tr:last-child").addClass("last-child");
        });
    };
})(jQuery);

Differences with the original version:

  • the default CSS class has been changed to ui-styled-table (it sounds more consistent)
  • the .live call was replaced with the recommended .on for jQuery 1.7 upwards
  • the explicit conditional has been replaced by .toggleClass (a terser equivalent)
  • code that sets the misleadingly-named CSS class first on table cells has been removed
  • the code that dynamically adds .last-child to the last table row is necessary to fix a visual glitch on Internet Explorer 7 and Internet Explorer 8; for browsers that support :last-child it is not necessary

CSS

/* Internet Explorer 7: setting "separate" results in bad visuals; all other browsers work fine with either value. */
/* If set to "separate", then this rule is also needed to prevent double vertical borders on hover:
table.ui-styled-table tr * + th, table.ui-styled-table tr * + td  { border-left-width: 0px !important; } */
table.ui-styled-table { border-collapse: collapse; }

/* Undo the "bolding" that jQuery UI theme may cause on hovered elements
/* Internet Explorer 7: does not support "inherit", so use a MS proprietary expression along with an Internet Explorer <= 7 targeting hack
        to make the visuals consistent across all supported browsers */
table.ui-styled-table td.ui-state-hover {
    font-weight: inherit;
    *font-weight: expression(this.parentNode.currentStyle['fontWeight']);
}

/* Initally remove bottom border for all cells. */
table.ui-styled-table th, table.ui-styled-table td { border-bottom-width: 0px !important; }

/* Hovered-row cells should show bottom border (will be highlighted) */
table.ui-styled-table tbody tr:hover th,
table.ui-styled-table tbody tr:hover td
{ border-bottom-width: 1px !important; }

/* Remove top border if the above row is being hovered to prevent double horizontal borders. */
table.ui-styled-table tbody tr:hover + tr th,
table.ui-styled-table tbody tr:hover + tr td
{ border-top-width: 0px !important; }

/* Last-row cells should always show bottom border (not necessarily highlighted if not hovered). */
/* Internet Explorer 7, Internet Explorer 8: selector dependent on CSS classes because of no support for :last-child */
table.ui-styled-table tbody tr.last-child th,
table.ui-styled-table tbody tr.last-child td
{ border-bottom-width: 1px !important; }

/* Last-row cells should always show bottom border (not necessarily highlighted if not hovered). */
/* Internet Explorer 8 BUG: if these (unsupported) selectors are added to a rule, other selectors for that rule will stop working as well! */
/* Internet Explorer 9 and later, Firefox, Chrome: make sure the visuals are working even without the CSS classes crutch. */
table.ui-styled-table tbody tr:last-child th,
table.ui-styled-table tbody tr:last-child td
{ border-bottom-width: 1px !important; }

Notes

I have tested this on Internet Explorer 7 and upwards, Firefox 11 and Google Chrome 18 and confirmed that it works perfectly. I have not tested reasonably earlier versions of Firefox and Chrome or any version of Opera; however, those browsers are well-known for good CSS support and since we are not using any bleeding-edge functionality here I assume it will work just fine there as well.

If you are not interested in Internet Explorer 7 support there is one CSS attribute (introduced with the star hack) that can go.

If you are not interested in Internet Explorer 8 support either, the CSS and JavaScript related to adding and targeting the last-child CSS class can go as well.

Bootstrap 3 offset on right not left

Bootstrap rows always contain their floats and create new lines. You don't need to worry about filling blank columns, just make sure they don't add up to more than 12.

_x000D_
_x000D_
<link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">_x000D_
_x000D_
<div class="container">_x000D_
  <div class="row">_x000D_
    <div class="col-xs-3 col-xs-offset-9">_x000D_
      I'm a right column of 3_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class="row">_x000D_
    <div class="col-xs-3">_x000D_
      I'm a left column of 3_x000D_
    </div>_x000D_
  </div>_x000D_
  <div class="panel panel-default">_x000D_
    <div class="panel-body">_x000D_
      And I'm some content below both columns_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to access parameters in a Parameterized Build?

Hope the following piece of code works for you:

def item = hudson.model.Hudson.instance.getItem('MyJob')

def value = item.lastBuild.getEnvironment(null).get('foo')

Parsing Query String in node.js

There's also the QueryString module's parse() method:

var http = require('http'),
    queryString = require('querystring');

http.createServer(function (oRequest, oResponse) {

    var oQueryParams;

    // get query params as object
    if (oRequest.url.indexOf('?') >= 0) {
        oQueryParams = queryString.parse(oRequest.url.replace(/^.*\?/, ''));

        // do stuff
        console.log(oQueryParams);
    }

    oResponse.writeHead(200, {'Content-Type': 'text/plain'});
    oResponse.end('Hello world.');

}).listen(1337, '127.0.0.1');

Can't change z-index with JQuery

zIndex is part of javaScript notation.(camelCase)
but jQuery.css uses same as CSS syntax.
so it is z-index.

you forgot .css("attr","value"). use ' or " in both, attr and val. so, .css("z-index","3000");

Setting attribute disabled on a SPAN element does not prevent click events

The disabled attribute's standard behavior only happens for form elements. Try unbinding the event:

$("span").unbind("click");

The ternary (conditional) operator in C

In C, the real utility of it is that it's an expression instead of a statement; that is, you can have it on the right-hand side (RHS) of a statement. So you can write certain things more concisely.

What is a 'workspace' in Visual Studio Code?

As of May 2018, it seems that a workspace in Visual Studio Code allows you to have quick access to different but related projects. All without having to open a different folder.

And you can have multiple workspaces too. See references here and you will get the full picture of it:

Reference 1
Reference 2

How to simplify a null-safe compareTo() implementation?

Another Apache ObjectUtils example. Able to sort other types of objects.

@Override
public int compare(Object o1, Object o2) {
    String s1 = ObjectUtils.toString(o1);
    String s2 = ObjectUtils.toString(o2);
    return s1.toLowerCase().compareTo(s2.toLowerCase());
}

Open window in JavaScript with HTML inserted

You can use window.open to open a new window/tab(according to browser setting) in javascript.

By using document.write you can write HTML content to the opened window.

Find which version of package is installed with pip

The easiest way is this:

import jinja2
print jinja2.__version__

List of All Locales and Their Short Codes?

If you are using php-intl to localize your application, you probably want to use ResourceBundle::getLocales() instead of static list that you maintain yourself. It can also give you locales for particular language.

<?php
print_r(ResourceBundle::getLocales(''));

/* Output might show
  * Array
  * (
  *    [0] => af
  *    [1] => af_NA
  *    [2] => af_ZA
  *    [3] => am
  *    [4] => am_ET
  *    [5] => ar
  *    [6] => ar_AE
  *    [7] => ar_BH
  *    [8] => ar_DZ
  *    [9] => ar_EG
  *    [10] => ar_IQ
  *  ...
  */
?>

Can you get the number of lines of code from a GitHub repository?

You can use GitHub API to get the sloc like the following function

function getSloc(repo, tries) {

    //repo is the repo's path
    if (!repo) {
        return Promise.reject(new Error("No repo provided"));
    }

    //GitHub's API may return an empty object the first time it is accessed
    //We can try several times then stop
    if (tries === 0) {
        return Promise.reject(new Error("Too many tries"));
    }

    let url = "https://api.github.com/repos" + repo + "/stats/code_frequency";

    return fetch(url)
        .then(x => x.json())
        .then(x => x.reduce((total, changes) => total + changes[1] + changes[2], 0))
        .catch(err => getSloc(repo, tries - 1));
}

Personally I made an chrome extension which shows the number of SLOC on both github project list and project detail page. You can also set your personal access token to access private repositories and bypass the api rate limit.

You can download from here https://chrome.google.com/webstore/detail/github-sloc/fkjjjamhihnjmihibcmdnianbcbccpnn

Source code is available here https://github.com/martianyi/github-sloc

Undo a particular commit in Git that's been pushed to remote repos

Identify the hash of the commit, using git log, then use git revert <commit> to create a new commit that removes these changes. In a way, git revert is the converse of git cherry-pick -- the latter applies the patch to a branch that's missing it, the former removes it from a branch that has it.

concatenate variables

Note that if strings has spaces then quotation marks are needed at definition and must be chopped while concatenating:

rem The retail files set
set FILES_SET="(*.exe *.dll"

rem The debug extras files set
set DEBUG_EXTRA=" *.pdb"

rem Build the DEBUG set without any
set FILES_SET=%FILES_SET:~1,-1%%DEBUG_EXTRA:~1,-1%

rem Append the closing bracket
set FILES_SET=%FILES_SET%)

echo %FILES_SET%

Cheers...

How to allow only one radio button to be checked?

All the radio buttons options must have the same name for you to be able to select one option at a time.

How do you redirect HTTPS to HTTP?

this works for me.

<VirtualHost *:443>
    ServerName www.example.com
    # ... SSL configuration goes here
    Redirect "https://www.example.com/" "http://www.example.com/"
</VirtualHost>

<VirtualHost *:80>
    ServerName www.example.com
    # ... 
</VirtualHost>

be sure to listen to both ports 80 and 443.

Creating a config file in PHP

Here is my way.

    <?php

    define('DEBUG',0);

    define('PRODUCTION',1);



    #development_mode : DEBUG / PRODUCTION

    $development_mode = PRODUCTION;



    #Website root path for links

    $app_path = 'http://192.168.0.234/dealer/';



    #User interface files path

    $ui_path = 'ui/';

    #Image gallery path

    $gallery_path = 'ui/gallery/';


    $mysqlserver = "localhost";
    $mysqluser = "root";
    $mysqlpass = "";
    $mysqldb = "dealer_plus";

   ?>

Any doubts please comment

Tomcat Server not starting with in 45 seconds

try clean Tomcat working directory,it works for me

Java: using switch statement with enum under subclass

This is how I am using it. And it is working fantastically -

public enum Button {
        REPORT_ISSUES(0),
        CANCEL_ORDER(1),
        RETURN_ORDER(2);

        private int value;

        Button(int value) {
            this.value = value;
        }

        public int getValue() {
            return value;
        }
    }

And the switch-case as shown below

@Override
public void onClick(MyOrderDetailDelgate.Button button, int position) {
    switch (button) {
        case REPORT_ISSUES: {
            break;
        }
        case CANCEL_ORDER: {
            break;
        }
        case RETURN_ORDER: {
            break;
        }
    }
}

What is the minimum I have to do to create an RPM file?

If make config works for your program or you have a shell script which copies your two files to the appropriate place you can use checkinstall. Just go to the directory where your makefile is in and call it with the parameter -R (for RPM) and optionally with the installation script.

What is the difference between MVC and MVVM?

From what I can tell, the MVVM maps to the MV of MVC - meaning that in a traditional MVC pattern the V does not communicate directly with the M. In the second version of MVC, there is a direct link between M and V. MVVM appears to take all tasks related to M and V communication, and couple it to decouple it from the C. In effect, there's still the larger scope application workflow (or implementation of the use scenarios) that are not fully accounted for in MVVM. This is the role of the controller. By removing these lower level aspects from the controllers, they are cleaner and makes it easier to modify the application's use scenario and business logic, also making controllers more reusable.

How to determine the last Row used in VBA including blank spaces in between

The Problem is the "as string" in your function. Replace it with "as double" or "as long" to make it work. This way it even works if the last row is bigger than the "large number" proposed in the accepted answer.

So this should work

Function ultimaFilaBlanco(col As double) As Long        
    Dim lastRow As Long
    With ActiveSheet
        lastRow = ActiveSheet.Cells(ActiveSheet.Rows.Count, col).End(xlUp).row
    End With            
    ultimaFilaBlanco = lastRow          
End Function

If statement in select (ORACLE)

use the variable, Oracle does not support SQL in that context without an INTO. With a properly named variable your code will be more legible anyway.

iOS / Android cross platform development

If you've ever used LUA, you might try Corona SDK can create apps that run on IOS and Android

https://coronalabs.com/

I've downloaded it and messed around some, I find LUA a very easy to learn scripting language without the usual scripting language hassles/limitations....

AngularJs: Reload page

You can use the reload method of the $route service. Inject $route in your controller and then create a method reloadRoute on your $scope.

$scope.reloadRoute = function() {
   $route.reload();
}

Then you can use it on the link like this:

<a ng-click="reloadRoute()" class="navbar-brand" title="home"  data-translate>PORTAL_NAME</a>

This method will cause the current route to reload. If you however want to perform a full refresh, you could inject $window and use that:

$scope.reloadRoute = function() {
   $window.location.reload();
}


Later edit (ui-router):

As mentioned by JamesEddyEdwards and Dunc in their answers, if you are using angular-ui/ui-router you can use the following method to reload the current state / route. Just inject $state instead of $route and then you have:

$scope.reloadRoute = function() {
    $state.reload();
};

Is there a way to iterate over a range of integers?

iter is a very small package that just provides a syntantically different way to iterate over integers.

for i := range iter.N(4) {
    fmt.Println(i)
}

Rob Pike (an author of Go) has criticized it:

It seems that almost every time someone comes up with a way to avoid doing something like a for loop the idiomatic way, because it feels too long or cumbersome, the result is almost always more keystrokes than the thing that is supposedly shorter. [...] That's leaving aside all the crazy overhead these "improvements" bring.

java.lang.RuntimeException: Unable to instantiate org.apache.hadoop.hive.ql.metadata.SessionHiveMetaStoreClient

If you're just playing around in local mode, you can drop metastore DB and reinstate it:

rm -rf metastore_db/
$HIVE_HOME/bin/schematool -initSchema -dbType derby

SQLException : String or binary data would be truncated

this type of error generally occurs when you have to put characters or values more than that you have specified in Database table like in that case: you specify transaction_status varchar(10) but you actually trying to store _transaction_status which contain 19 characters. that's why you faced this type of error in this code

How to echo with different colors in the Windows command line

I just converted from Win 7 Home to Win 10 Pro and wanted to replace the batch I call from other batches to echo info in color. Reviewing what is discussed above I use the following which will directly replace my previous batch. NOTE the addition of "~" to the message so that messages with spaces may be used. Instead of remembering codes I use letters for the colors I needed.

If %2 contains spaces requires "..." %1 Strong Colors on black: R=Red G=GREEN Y=YELLOW W=WHITE

ECHO OFF
IF "%1"=="R" ECHO ^[91m%~2[0m
IF "%1"=="G" ECHO ^[92m%~2[0m
IF "%1"=="Y" ECHO ^[93m%~2[0m
IF "%1"=="W" ECHO ^[97m%~2[0m

Sample settings.xml

A standard Maven settings.xml file is as follows:

<settings xmlns="http://maven.apache.org/SETTINGS/1.1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.1.0 http://maven.apache.org/xsd/settings-1.1.0.xsd">
  <localRepository/>
  <interactiveMode/>
  <usePluginRegistry/>
  <offline/>

  <proxies>
    <proxy>
      <active/>
      <protocol/>
      <username/>
      <password/>
      <port/>
      <host/>
      <nonProxyHosts/>
      <id/>
    </proxy>
  </proxies>

  <servers>
    <server>
      <username/>
      <password/>
      <privateKey/>
      <passphrase/>
      <filePermissions/>
      <directoryPermissions/>
      <configuration/>
      <id/>
    </server>
  </servers>

  <mirrors>
    <mirror>
      <mirrorOf/>
      <name/>
      <url/>
      <layout/>
      <mirrorOfLayouts/>
      <id/>
    </mirror>
  </mirrors>

  <profiles>
    <profile>
      <activation>
        <activeByDefault/>
        <jdk/>
        <os>
          <name/>
          <family/>
          <arch/>
          <version/>
        </os>
        <property>
          <name/>
          <value/>
        </property>
        <file>
          <missing/>
          <exists/>
        </file>
      </activation>
      <properties>
        <key>value</key>
      </properties>

      <repositories>
        <repository>
          <releases>
            <enabled/>
            <updatePolicy/>
            <checksumPolicy/>
          </releases>
          <snapshots>
            <enabled/>
            <updatePolicy/>
            <checksumPolicy/>
          </snapshots>
          <id/>
          <name/>
          <url/>
          <layout/>
        </repository>
      </repositories>
      <pluginRepositories>
        <pluginRepository>
          <releases>
            <enabled/>
            <updatePolicy/>
            <checksumPolicy/>
          </releases>
          <snapshots>
            <enabled/>
            <updatePolicy/>
            <checksumPolicy/>
          </snapshots>
          <id/>
          <name/>
          <url/>
          <layout/>
        </pluginRepository>
      </pluginRepositories>
      <id/>
    </profile>
  </profiles>

  <activeProfiles/>
  <pluginGroups/>
</settings>

To access a proxy, you can find detailed information on the official Maven page here:

Maven-Settings - Settings

I hope it helps for someone.