Programs & Examples On #Olap cube

An OLAP cube is a multidimensional database that is optimized for data warehouse and online analytical processing (OLAP) applications.

Symbolicating iPhone App Crash Reports

Here's another issue I have with symbolicatecrash – it won't work with Apps that have spaces in their bundle (i.e. 'Test App.app'). Note I don't think you can have spaces in their name when submitting so you should remove these anyway, but if you already have crashes that need analysing, patch symbolicatecrash (4.3 GM) as such:

240c240
<         my $cmd = "mdfind \"kMDItemContentType == com.apple.application-bundle && kMDItemFSName == $exec_name.app\"";
---
>         my $cmd = "mdfind \"kMDItemContentType == com.apple.application-bundle && kMDItemFSName == '$exec_name.app'\"";
251c251
<             my $cmd = "find \"$archive_path/Products\" -name $exec_name.app";
---
>             my $cmd = "find \"$archive_path/Products\" -name \"$exec_name.app\"";

Linux command line howto accept pairing for bluetooth device without pin

~ $ hciconfig noauth

It worked for me in "Linux mx 4.19"

The exact steps are:

1) open a terminal - run: "hciconfig noauth"
2) use the blueman-manager gui to pair the device (in my case it was a keyboard)
3) from the blueman-manager choose "connect to HID"

step(3) is normally asking for a password - the "hciconfig noauth" makes step(3) passwordless

What is the best open-source java charting library? (other than jfreechart)

For dynamic 2D charts, I have been using JChart2D. It's fast, simple, and being updated regularly. The author has been quick to respond to my one bug report and few feature requests. We, at our company, prefer it over JFreeChart because it was designed for dynamic use, unlike JFreeChart.

How do I test a website using XAMPP?

The webpages on an online server reside in a location which looks somewhat like this: http://www.somerandomsite.com/index.php

Since xampp is Offline, it sets up a local server whose address is like this http://localhost/

Basically, xampp sets up a server (apache and others) in your system. And all the files such as index.php, somethingelse.php, etc., reside in the xampp\htdocs\ folder.

The browser locates the server in localhost and will search through the above folder for any resources available in there.

So create any number of folders inside the "xampp\htdocs\" each folder thus forming a website (as you build it).

Sometimes apache won't even start. This is due to the clashing of ports with some applications. Some of them I commonly encounter is Skype. See to that it is killed completely and restart apache

php - add + 7 days to date format mm dd, YYYY

onClose: function(selectedDate) {

    $("#dpTodate").datepicker("option", "minDate", selectedDate);
    var maxDate = new Date(selectedDate);

     maxDate.setDate(maxDate.getDate() + 6); //6 days extra in from date

     $("#dpTodate").datepicker("option", "maxDate", maxDate);
}

Get: TypeError: 'dict_values' object does not support indexing when using python 3.2.3

A simpler version of your code would be:

dict(zip(names, d.values()))

If you want to keep the same structure, you can change it to:

vlst = list(d.values())
{names[i]: vlst[i] for i in range(len(names))}

(You can just as easily put list(d.values()) inside the comprehension instead of vlst; it's just wasteful to do so since it would be re-generating the list every time).

Class method differences in Python: bound, unbound and static

The second one won't work because when you call it like that python internally tries to call it with the a_test instance as the first argument, but your method_two doesn't accept any arguments, so it wont work, you'll get a runtime error. If you want the equivalent of a static method you can use a class method. There's much less need for class methods in Python than static methods in languages like Java or C#. Most often the best solution is to use a method in the module, outside a class definition, those work more efficiently than class methods.

HTTP Status 500 - Servlet.init() for servlet Dispatcher threw exception

You map your dispatcher on *.do:

<servlet-mapping>
   <servlet-name>Dispatcher</servlet-name>
   <url-pattern>*.do</url-pattern>
</servlet-mapping>

but your controller is mapped on an url without .do:

@RequestMapping("/editPresPage")

Try changing this to:

@RequestMapping("/editPresPage.do")

WAMP server, localhost is not working

If you have skype installed, close it completely.

If you have sql server installed, go to:

Control panel -> Administrative Tools -> Services

And stop SQL Server Reporting Services

Port 80 must be free now. Click on Wamp icon -> Restart All Services

Oracle: How to find out if there is a transaction pending?

Matthew Watson can be modified to be used in RAC

select t.inst_id 
       ,s.sid
      ,s.serial#
      ,s.username
      ,s.machine
      ,s.status
      ,s.lockwait
      ,t.used_ublk
      ,t.used_urec
      ,t.start_time
from gv$transaction t
inner join gv$session s on t.addr = s.taddr;

How do you make a deep copy of an object?

One very easy and simple approach is to use Jackson JSON to serialize complex Java Object to JSON and read it back.

From https://github.com/FasterXML/jackson-databind/#5-minute-tutorial-streaming-parser-generator :

JsonFactory f = mapper.getFactory(); // may alternatively construct directly too

// First: write simple JSON output
File jsonFile = new File("test.json");
JsonGenerator g = f.createGenerator(jsonFile);
// write JSON: { "message" : "Hello world!" }
g.writeStartObject();
g.writeStringField("message", "Hello world!");
g.writeEndObject();
g.close();

// Second: read file back
JsonParser p = f.createParser(jsonFile);

JsonToken t = p.nextToken(); // Should be JsonToken.START_OBJECT
t = p.nextToken(); // JsonToken.FIELD_NAME
if ((t != JsonToken.FIELD_NAME) || !"message".equals(p.getCurrentName())) {
   // handle error
}
t = p.nextToken();
if (t != JsonToken.VALUE_STRING) {
   // similarly
}
String msg = p.getText();
System.out.printf("My message to you is: %s!\n", msg);
p.close();

HTML Input Box - Disable

The syntax to disable an HTML input is as follows:

<input type="text" id="input_id" DISABLED />

How do you develop Java Servlets using Eclipse?

I use Eclipse Java EE edition

Create a "Dynamic Web Project"

Install a local server in the server view, for the version of Tomcat I'm using. Then debug, and run on that server for testing.

When I deploy I export the project to a war file.

What is the difference between a var and val definition in Scala?

val means immutable and var means mutable

you can think val as java programming language final key world or c++ language const key world?

Using if elif fi in shell scripts

This is working for me,

 # cat checking.sh
 #!/bin/bash
 echo "You have provided the following arguments $arg1 $arg2 $arg3"
 if [ "$arg1" = "$arg2" ] && [ "$arg1" != "$arg3" ]
 then
     echo "Two of the provided args are equal."
     exit 3
 elif [ $arg1 == $arg2 ] && [ $arg1 = $arg3 ]
 then
     echo "All of the specified args are equal"
     exit 0
 else
     echo "All of the specified args are different"
     exit 4
 fi

 # ./checking.sh
 You have provided the following arguments
 All of the specified args are equal

You can add set -x in script to troubleshoot the errors.

How to convert latitude or longitude to meters?

To convert latitude and longitude in x and y representation you need to decide what type of map projection to use. As for me, Elliptical Mercator seems very well. Here you can find an implementation (in Java too).

Reactive forms - disabled attribute

add disable="true" to html field Example :disable

<amexio-text-input formControlName="LastName" disable="true" [(ngModel)]="emplpoyeeRegistration.lastName" [field-label]="'Last Name'" [place-holder]="'Please enter last name'" [allow-blank]="true" [error-msg]="'errorMsg'" [enable-popover]="true" [min-length]="2"
[min-error-msg]="'Minimum 2 char allowed'" [max-error-msg]="'Maximum 20 char allowed'" name="xyz" [max-length]="20">
[icon-feedback]="true">
</amexio-text-input>

jQuery delete all table rows except first

Another way to accomplish this is using the empty() function of jQuery with the thead and tbody elements in your table.

Example of a table:

<table id="tableId">
<thead>
    <tr><th>Col1</th><th>Col2</th></tr>
</thead>
<tbody>
    <tr><td>some</td><td>content</td></tr>
    <tr><td>to be</td><td>removed</td></tr>
</tbody>
</table>

And the jQuery command:

$("#tableId > tbody").empty();

This will remove every rows contained in the tbody element of your table and keep the thead element where your header should be. It can be useful when you want to refresh only the content of a table.

How to check that a JCheckBox is checked?

By using itemStateChanged(ItemListener) you can track selecting and deselecting checkbox (and do whatever you want based on it):

myCheckBox.addItemListener(new ItemListener() {
    @Override
    public void itemStateChanged(ItemEvent e) {
        if(e.getStateChange() == ItemEvent.SELECTED) {//checkbox has been selected
            //do something...
        } else {//checkbox has been deselected
            //do something...
        };
    }
});

Java Swing itemStateChanged docu should help too. By using isSelected() method you can just test if actual is checkbox selected:

if(myCheckBox.isSelected()){_do_something_if_selected_}

Bootstrap modal appearing under background

CAREFUL WHEN APPENDING TO THE BODY!

This will definitely get that modal from behind the backdrop:

$('#myModal').appendTo("body").modal('show');

However, this adds another modal to the body each time you open it, which can cause head aches when adding controls like gridviews with edits and updates within update panels to the modal. Therefore, you may consider removing it when the modal closes:

For example:

$(document).on('hidden.bs.modal', function () {
        $('.modal').remove();
    });

will remove the the added modal. (of course that's an example, and you might want to use another class name that you added to the modal).

And as already stated by others; you can simply turn off the back-drop from the modal (data-backdrop="false"), or if you cannot live without the darkening of the screen you can adjust the .modal-backdrop css class (either increasing the z-index).

URL encode sees “&” (ampersand) as “&amp;” HTML entity

There is HTML and URI encodings. &amp; is & encoded in HTML while %26 is & in URI encoding.

So before URI encoding your string you might want to HTML decode and then URI encode it :)

var div = document.createElement('div');
div.innerHTML = '&amp;AndOtherHTMLEncodedStuff';
var htmlDecoded = div.firstChild.nodeValue;
var urlEncoded = encodeURIComponent(htmlDecoded);

result %26AndOtherHTMLEncodedStuff

Hope this saves you some time

How to iterate through a list of dictionaries in Jinja template?

{% for i in yourlist %}
  {% for k,v in i.items() %}
    {# do what you want here #}
  {% endfor %}
{% endfor %}

How do I pass a variable to the layout using Laravel' Blade templating?

In the Blade Template : define a variable like this

@extends('app',['title' => 'Your Title Goes Here'])
@section('content')

And in the app.blade.php or any other of your choice ( I'm just following default Laravel 5 setup )

<title>{{ $title or 'Default title Information if not set explicitly' }}</title>

This is my first answer here. Hope it works.Good luck!

ESLint - "window" is not defined. How to allow global variables in package.json

I found it on this page: http://eslint.org/docs/user-guide/configuring

In package.json, this works:

"eslintConfig": {
  "globals": {
    "window": true
  }
}

Page vs Window in WPF?

Page Control can be contained in Window Control but vice versa is not possible

You can use Page control within the Window control using NavigationWindow and Frame controls. Window is the root control that must be used to hold/host other controls (e.g. Button) as container. Page is a control which can be hosted in other container controls like NavigationWindow or Frame. Page control has its own goal to serve like other controls (e.g. Button). Page is to create browser like applications. So if you host Page in NavigationWindow, you will get the navigation implementation built-in. Pages are intended for use in Navigation applications (usually with Back and Forward buttons, e.g. Internet Explorer).

WPF provides support for browser style navigation inside standalone application using Page class. User can create multiple pages, navigate between those pages along with data.There are multiple ways available to Navigate through one page to another page.

Printing object properties in Powershell

To print out object's properties and values in Powershell. Below examples work well for me.

$pool = Get-Item "IIS:\AppPools.NET v4.5"

$pool | Get-Member

   TypeName: Microsoft.IIs.PowerShell.Framework.ConfigurationElement#system.applicationHost/applicationPools#add

Name                        MemberType            Definition
----                        ----------            ----------
Recycle                     CodeMethod            void Recycle()
Start                       CodeMethod            void Start()
Stop                        CodeMethod            void Stop()
applicationPoolSid          CodeProperty          Microsoft.IIs.PowerShell.Framework.CodeProperty
state                       CodeProperty          Microsoft.IIs.PowerShell.Framework.CodeProperty
ClearLocalData              Method                void ClearLocalData()
Copy                        Method                void Copy(Microsoft.IIs.PowerShell.Framework.ConfigurationElement ...
Delete                      Method                void Delete()
...

$pool | Select-Object -Property * # You can omit -Property

name                        : .NET v4.5
queueLength                 : 1000
autoStart                   : True
enable32BitAppOnWin64       : False
managedRuntimeVersion       : v4.0
managedRuntimeLoader        : webengine4.dll
enableConfigurationOverride : True
managedPipelineMode         : Integrated
CLRConfigFile               :
passAnonymousToken          : True
startMode                   : OnDemand
state                       : Started
applicationPoolSid          : S-1-5-82-271721585-897601226-2024613209-625570482-296978595
processModel                : Microsoft.IIs.PowerShell.Framework.ConfigurationElement
...

Convert tabs to spaces in Notepad++

Obsolete: This answer is correct only for an older version of Notepad++. Converting between tabs/spaces is now built into Notepad++ and the TextFX plugin is no longer available in the Plugin Manager dialog.

  • First set the "replace by spaces" setting in Preferences -> Language Menu/Tab Settings.
  • Next, open the document you wish to replace tabs with.
  • Highlight all the text (CTRL+A).
  • Then select TextFX -> TextFX Edit -> Leading spaces to tabs or tabs to spaces.

Note: Make sure TextFX Characters plugin is installed (Plugins -> Plugin manager -> Show plugin manager, Installed tab). Otherwise, there will be no TextFX menu.

Test a string for a substring

There are several other ways, besides using the in operator (easiest):

index()

>>> try:
...   "xxxxABCDyyyy".index("test")
... except ValueError:
...   print "not found"
... else:
...   print "found"
...
not found

find()

>>> if "xxxxABCDyyyy".find("ABCD") != -1:
...   print "found"
...
found

re

>>> import re
>>> if re.search("ABCD" , "xxxxABCDyyyy"):
...  print "found"
...
found

Mac zip compress without __MACOSX folder?

Inside the folder you want to be compressed, in terminal:

zip -r -X Archive.zip *

Where -X means: Exclude those invisible Mac resource files such as “_MACOSX” or “._Filename” and .ds store files

source

Note: Will only work for the folder and subsequent folder tree you are in and has to have the * wildcard.

Is there a way to reduce the size of the git folder?

One scenario where your git repo will get seriously bigger with each commit is one where you are committing binary files that you generate regularly. Their storage won't be as efficient than text file.

Another is one where you have a huge number of files within one repo (which is a limit of git) instead of several subrepos (managed as submodules).

In this article on git space, AlBlue mentions:

Note that Git (and Hg, and other DVCSs) do suffer from a problem where (large) binaries are checked in, then deleted, as they'll still show up in the repository and take up space, even if they're not current.

If you have large binaries stored in your git repo, you may consider:

As I mentioned in "What are the file limits in Git (number and size)?", the more recent (2015, 5 years after this answer) Git LFS from GitHub is a way to manage those large files (by storing them outside the Git repository).

Easy way to build Android UI?

Allow me to be the one to slap a little reality onto this topic. There is no good GUI tool for working with Android. If you're coming from a native application GUI environment like, say, Delphi, you're going to be sadly disappointed in the user experience with the ADK editor and DroidDraw. I've tried several times to work with DroidDraw in a productive way, and I always go back to rolling the XML by hand.

The ADK is a good starting point, but it's not easy to use. Positioning components within layouts is a nightmare. DroidDraw looks like it would be fantastic, but I can't even open existing, functional XML layouts with it. It somehow loses half of the layout and can't pull in the images that I've specified for buttons, backgrounds, etc.

The stark reality is that the Android developer space is in sore need of a flexible, easy-to-use, robust GUI development tool similar to those used for .NET and Delphi development.

How can I install a package with go get?

Command go

Download and install packages and dependencies

Usage:

go get [-d] [-f] [-t] [-u] [-v] [-fix] [-insecure] [build flags] [packages]

Get downloads the packages named by the import paths, along with their dependencies. It then installs the named packages, like 'go install'.

The -d flag instructs get to stop after downloading the packages; that is, it instructs get not to install the packages.

The -f flag, valid only when -u is set, forces get -u not to verify that each package has been checked out from the source control repository implied by its import path. This can be useful if the source is a local fork of the original.

The -fix flag instructs get to run the fix tool on the downloaded packages before resolving dependencies or building the code.

The -insecure flag permits fetching from repositories and resolving custom domains using insecure schemes such as HTTP. Use with caution.

The -t flag instructs get to also download the packages required to build the tests for the specified packages.

The -u flag instructs get to use the network to update the named packages and their dependencies. By default, get uses the network to check out missing packages but does not use it to look for updates to existing packages.

The -v flag enables verbose progress and debug output.

Get also accepts build flags to control the installation. See 'go help build'.

When checking out a new package, get creates the target directory GOPATH/src/. If the GOPATH contains multiple entries, get uses the first one. For more details see: 'go help gopath'.

When checking out or updating a package, get looks for a branch or tag that matches the locally installed version of Go. The most important rule is that if the local installation is running version "go1", get searches for a branch or tag named "go1". If no such version exists it retrieves the default branch of the package.

When go get checks out or updates a Git repository, it also updates any git submodules referenced by the repository.

Get never checks out or updates code stored in vendor directories.

For more about specifying packages, see 'go help packages'.

For more about how 'go get' finds source code to download, see 'go help importpath'.

This text describes the behavior of get when using GOPATH to manage source code and dependencies. If instead the go command is running in module-aware mode, the details of get's flags and effects change, as does 'go help get'. See 'go help modules' and 'go help module-get'.

See also: go build, go install, go clean.


For example, showing verbose output,

$ go get -v github.com/capotej/groupcache-db-experiment/...
github.com/capotej/groupcache-db-experiment (download)
github.com/golang/groupcache (download)
github.com/golang/protobuf (download)
github.com/capotej/groupcache-db-experiment/api
github.com/capotej/groupcache-db-experiment/client
github.com/capotej/groupcache-db-experiment/slowdb
github.com/golang/groupcache/consistenthash
github.com/golang/protobuf/proto
github.com/golang/groupcache/lru
github.com/capotej/groupcache-db-experiment/dbserver
github.com/capotej/groupcache-db-experiment/cli
github.com/golang/groupcache/singleflight
github.com/golang/groupcache/groupcachepb
github.com/golang/groupcache
github.com/capotej/groupcache-db-experiment/frontend
$ 

How can I get the name of an object in Python?

Note that while, as noted, objects in general do not and cannot know what variables are bound to them, functions defined with def do have names in the __name__ attribute (the name used in def). Also if the functions are defined in the same module (as in your example) then globals() will contain a superset of the dictionary you want.

def fun1:
  pass
def fun2:
  pass
def fun3:
  pass

fun_dict = {}
for f in [fun1, fun2, fun3]:
  fun_dict[f.__name__] = f

Java NIO: What does IOException: Broken pipe mean?

You should assume the socket was closed on the other end. Wrap your code with a try catch block for IOException.

You can use isConnected() to determine if the SocketChannel is connected or not, but that might change before your write() invocation finishes. Try calling it in your catch block to see if in fact this is why you are getting the IOException.

jQuery location href

Use:

window.location.replace(...)

See this Stack Overflow question for more information:

How do I redirect to another webpage?

Or perhaps it was this you remember:

var url = "http://stackoverflow.com";
$(location).attr('href',url);

How to check if a process is running via a batch script

I used the script provided by Matt (2008-10-02). The only thing I had trouble with was that it wouldn't delete the search.log file. I expect because I had to cd to another location to start my program. I cd'd back to where the BAT file and search.log are, but it still wouldn't delete. So I resolved that by deleting the search.log file first instead of last.

del search.log

tasklist /FI "IMAGENAME eq myprog.exe" /FO CSV > search.log

FOR /F %%A IN (search.log) DO IF %%-zA EQU 0 GOTO end

cd "C:\Program Files\MyLoc\bin"

myprog.exe myuser mypwd

:end

jQuery validation plugin: accept only alphabetical characters?

to allow letters ans spaces

jQuery.validator.addMethod("lettersonly", function(value, element) {
return this.optional(element) || /^[a-z\s]+$/i.test(value);
}, "Only alphabetical characters");

$('#yourform').validate({
        rules: {
            name_field: {
                lettersonly: true
            }
        }
    });

How do I remove the "extended attributes" on a file in Mac OS X?

Removing a Single Attribute on a Single File

See Bavarious's answer.


To Remove All Extended Attributes On a Single File

Use xattr with the -c flag to "clear" the attributes:

xattr -c yourfile.txt



To Remove All Extended Attributes On Many Files

To recursively remove extended attributes on all files in a directory, combine the -c "clear" flag with the -r recursive flag:

xattr -rc /path/to/directory



A Tip for Mac OS X Users

Have a long path with spaces or special characters?

Open Terminal.app and start typing xattr -rc, include a trailing space, and then then drag the file or folder to the Terminal.app window and it will automatically add the full path with proper escaping.

C# LINQ find duplicates in List

I created a extention to response to this you could includ it in your projects, I think this return the most case when you search for duplicates in List or Linq.

Example:

//Dummy class to compare in list
public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Surname { get; set; }
    public Person(int id, string name, string surname)
    {
        this.Id = id;
        this.Name = name;
        this.Surname = surname;
    }
}


//The extention static class
public static class Extention
{
    public static IEnumerable<T> getMoreThanOnceRepeated<T>(this IEnumerable<T> extList, Func<T, object> groupProps) where T : class
    { //Return only the second and next reptition
        return extList
            .GroupBy(groupProps)
            .SelectMany(z => z.Skip(1)); //Skip the first occur and return all the others that repeats
    }
    public static IEnumerable<T> getAllRepeated<T>(this IEnumerable<T> extList, Func<T, object> groupProps) where T : class
    {
        //Get All the lines that has repeating
        return extList
            .GroupBy(groupProps)
            .Where(z => z.Count() > 1) //Filter only the distinct one
            .SelectMany(z => z);//All in where has to be retuned
    }
}

//how to use it:
void DuplicateExample()
{
    //Populate List
    List<Person> PersonsLst = new List<Person>(){
    new Person(1,"Ricardo","Figueiredo"), //fist Duplicate to the example
    new Person(2,"Ana","Figueiredo"),
    new Person(3,"Ricardo","Figueiredo"),//second Duplicate to the example
    new Person(4,"Margarida","Figueiredo"),
    new Person(5,"Ricardo","Figueiredo")//third Duplicate to the example
    };

    Console.WriteLine("All:");
    PersonsLst.ForEach(z => Console.WriteLine("{0} -> {1} {2}", z.Id, z.Name, z.Surname));
    /* OUTPUT:
        All:
        1 -> Ricardo Figueiredo
        2 -> Ana Figueiredo
        3 -> Ricardo Figueiredo
        4 -> Margarida Figueiredo
        5 -> Ricardo Figueiredo
        */

    Console.WriteLine("All lines with repeated data");
    PersonsLst.getAllRepeated(z => new { z.Name, z.Surname })
        .ToList()
        .ForEach(z => Console.WriteLine("{0} -> {1} {2}", z.Id, z.Name, z.Surname));
    /* OUTPUT:
        All lines with repeated data
        1 -> Ricardo Figueiredo
        3 -> Ricardo Figueiredo
        5 -> Ricardo Figueiredo
        */
    Console.WriteLine("Only Repeated more than once");
    PersonsLst.getMoreThanOnceRepeated(z => new { z.Name, z.Surname })
        .ToList()
        .ForEach(z => Console.WriteLine("{0} -> {1} {2}", z.Id, z.Name, z.Surname));
    /* OUTPUT:
        Only Repeated more than once
        3 -> Ricardo Figueiredo
        5 -> Ricardo Figueiredo
        */
}

How to use a decimal range() step value?

Python's range() can only do integers, not floating point. In your specific case, you can use a list comprehension instead:

[x * 0.1 for x in range(0, 10)]

(Replace the call to range with that expression.)

For the more general case, you may want to write a custom function or generator.

TOMCAT - HTTP Status 404

To get your program to run, please put jsp files under web-content and not under WEB-INF because in Eclipse the files are not accessed there by the server, so try starting the server and browsing to URL:

http://localhost:8080/YourProject/yourfile.jsp

then your problem will be solved.

How to make Twitter bootstrap modal full screen

.modal.in .modal-dialog {
 width:100% !important; 
 min-height: 100%;
 margin: 0 0 0 0 !important;
 bottom: 0px !important;
 top: 0px;
}


.modal-content {
    border:0px solid rgba(0,0,0,.2) !important;
    border-radius: 0px !important;
    -webkit-box-shadow: 0 0px 0px rgba(0,0,0,.5) !important;
    box-shadow: 0 3px 9px rgba(0,0,0,.5) !important;
    height: auto;
    min-height: 100%;
}

.modal-dialog {
 position: fixed !important;
 margin:0px !important;
}

.bootstrap-dialog .modal-header {
    border-top-left-radius: 0px !important; 
    border-top-right-radius: 0px !important;
}


@media (min-width: 768px)
.modal-dialog {
    width: 100% !important;
    margin: 0 !important;
}

Change the "No file chosen":

I'm pretty sure you cannot change the default labels on buttons, they are hard-coded in browsers (each browser rendering the buttons captions its own way). Check out this button styling article

CSS to keep element at "fixed" position on screen

position: sticky;

The sticky element sticks on top of the page (top: 0) when you reach its scroll position.

See example: https://www.w3schools.com/css/tryit.asp?filename=trycss_position_sticky

How to fix .pch file missing on build?

Try Build > Clean Solution, then Build > Build Solution. This works for me.

running php script (php function) in linux bash

just run in linux terminal to get phpinfo .

   php -r 'phpinfo();'

and to run file like index.php

    php -f index.php

Keyboard shortcut to comment lines in Sublime Text 3

On OSX Yosemite, I fixed this by going System Preferences, Keyboard, then Shortcuts. Under App Shortcuts, disable Show Help menu which was bound to CMD+SHIFT+7.

keyboard settings

My keyboard layout is Norwegian, with English as the OS language.

How can I change the color of AlertDialog title and the color of the line under it

    ForegroundColorSpan foregroundColorSpan = new ForegroundColorSpan(Color.BLACK);

    String title = context.getString(R.string.agreement_popup_message);
    SpannableStringBuilder ssBuilder = new SpannableStringBuilder(title);
    ssBuilder.setSpan(
            foregroundColorSpan,
            0,
            title.length(),
            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
    );

AlertDialog.Builder alertDialogBuilderUserInput = new AlertDialog.Builder(context);
alertDialogBuilderUserInput.setTitle(ssBuilder)

Setting environment variables for accessing in PHP when using Apache

Something along the lines:

<VirtualHost hostname:80>
   ...
   SetEnv VARIABLE_NAME variable_value
   ...
</VirtualHost>

The smallest difference between 2 Angles

A simple method, which I use in C++ is:

double deltaOrientation = angle1 - angle2;
double delta =  remainder(deltaOrientation, 2*M_PI);

Unicode characters in URLs

Not sure if it is a good idea, but as mentioned in other comments and as I interpret it, many Unicode chars are valid in HTML5 URLs.

E.g., href docs say http://www.w3.org/TR/html5/links.html#attr-hyperlink-href:

The href attribute on a and area elements must have a value that is a valid URL potentially surrounded by spaces.

Then the definition of "valid URL" points to http://url.spec.whatwg.org/, which defines URL code points as:

ASCII alphanumeric, "!", "$", "&", "'", "(", ")", "*", "+", ",", "-", ".", "/", ":", ";", "=", "?", "@", "_", "~", and code points in the ranges U+00A0 to U+D7FF, U+E000 to U+FDCF, U+FDF0 to U+FFFD, U+10000 to U+1FFFD, U+20000 to U+2FFFD, U+30000 to U+3FFFD, U+40000 to U+4FFFD, U+50000 to U+5FFFD, U+60000 to U+6FFFD, U+70000 to U+7FFFD, U+80000 to U+8FFFD, U+90000 to U+9FFFD, U+A0000 to U+AFFFD, U+B0000 to U+BFFFD, U+C0000 to U+CFFFD, U+D0000 to U+DFFFD, U+E1000 to U+EFFFD, U+F0000 to U+FFFFD, U+100000 to U+10FFFD.

The term "URL code points" is then used in a few parts of the parsing algorithm, e.g. for the relative path state:

If c is not a URL code point and not "%", parse error.

Also the validator http://validator.w3.org/ passes for URLs like "??", and does not pass for URLs with characters like spaces "a b"

Related: Which characters make a URL invalid?

Sending mass email using PHP

I would insert all the emails into a database (sort of like a queue), then process them one at a time as you have done in your code (if you want to use swiftmailer or phpmailer etc, you can do that too.)

After each mail is sent, update the database to record the date/time it was sent.

By putting them in the database first you have

  1. a record of who you sent it to
  2. if your script times out or fails and you have to run it again, then you won't end up sending the same email out to people twice
  3. you can run the send process from a cron job and do a batch at a time, so that your mail server is not overwhelmed, and keep track of what has been sent

Keep in mind, how to automate bounced emails or invalid emails so they can automatically removed from your list.

If you are sending that many emails you are bound to get a few bounces.

How to use auto-layout to move other views when a view is hidden?

This is an old question but still I hope it will helps. Coming from Android, in this platform you have an handy method isVisible to hide it from the view but also not have the frame considered when the autolayout draw the view.

using extension and "extend" uiview you could do a similar function in ios (not sure why it is not in UIKit already) here an implementation in swift 3:

    func isVisible(_ isVisible: Bool) {
        self.isHidden = !isVisible
        self.translatesAutoresizingMaskIntoConstraints = isVisible
        if isVisible { //if visible we remove the hight constraint 
            if let constraint = (self.constraints.filter{$0.firstAttribute == .height}.first){
                self.removeConstraint(constraint)
            }
        } else { //if not visible we add a constraint to force the view to have a hight set to 0
            let height = NSLayoutConstraint(item: self, attribute: .height, relatedBy: .equal , toItem: nil, attribute: .notAnAttribute, multiplier: 0, constant: 0)
            self.addConstraint(height)
        }
        self.layoutIfNeeded()
    }

Hide/Show Action Bar Option Menu Item for different fragments

Hello I got the best solution of this, suppose if u have to hide a particular item at on create Menu method and show that item in other fragment. I am taking an example of two menu item one is edit and other is delete. e.g menu xml is as given below:

sell_menu.xml

 <?xml version="1.0" encoding="utf-8"?>
 <menu xmlns:android="http://schemas.android.com/apk/res/android"
 xmlns:app="http://schemas.android.com/apk/res-auto">

<item
    android:id="@+id/action_edit"
    android:icon="@drawable/ic_edit_white_shadow_24dp"
    app:showAsAction="always"
    android:title="Edit" />

<item
    android:id="@+id/action_delete"
    android:icon="@drawable/ic_delete_white_shadow_24dp"
    app:showAsAction="always"
    android:title="Delete" />

Now Override the two method in your activity & make a field variable mMenu as:

  private Menu mMenu;         //  field variable    


  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.sell_menu, menu);
    this.mMenu = menu;

    menu.findItem(R.id.action_delete).setVisible(false);
    return super.onCreateOptionsMenu(menu);
  }

 @Override
 public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == R.id.action_delete) {
       // do action
        return true;
    } else if (item.getItemId() == R.id.action_edit) {
      // do action
        return true;
    }

    return super.onOptionsItemSelected(item);
 }

Make two following method in your Activity & call them from fragment to hide and show your menu item. These method are as:

public void showDeleteImageOption(boolean status) {
    if (menu != null) {
        menu.findItem(R.id.action_delete).setVisible(status);
    }
}

public void showEditImageOption(boolean status) {
    if (menu != null) {
        menu.findItem(R.id.action_edit).setVisible(status);
    }
}

That's Solve from my side,I think this explanation will help you.

Cheap way to search a large text file for a string

If it is "pretty large" file, then access the lines sequentially and don't read the whole file into memory:

with open('largeFile', 'r') as inF:
    for line in inF:
        if 'myString' in line:
            # do_something

Making heatmap from pandas DataFrame

If you don't need a plot per say, and you're simply interested in adding color to represent the values in a table format, you can use the style.background_gradient() method of the pandas data frame. This method colorizes the HTML table that is displayed when viewing pandas data frames in e.g. the JupyterLab Notebook and the result is similar to using "conditional formatting" in spreadsheet software:

import numpy as np 
import pandas as pd


index= ['aaa', 'bbb', 'ccc', 'ddd', 'eee']
cols = ['A', 'B', 'C', 'D']
df = pd.DataFrame(abs(np.random.randn(5, 4)), index=index, columns=cols)
df.style.background_gradient(cmap='Blues')

enter image description here

For detailed usage, please see the more elaborate answer I provided on the same topic previously and the styling section of the pandas documentation.

Android ImageView's onClickListener does not work

Check if other view has the property match_parent or fill_parent ,those properties may cover your ImageView which has shown in your RelativeLayout.By the way,the accepted answer does not work in my case.

Django set default form values

I hope this can help you:

form.instance.updatedby = form.cleaned_data['updatedby'] = request.user.id

How to compile C programming in Windows 7?

Microsoft Visual Studio Express

It's a full IDE, with powerful debugging tools, syntax highlighting, etc.

How do I use the Tensorboard callback of Keras?

If you are using google-colab simple visualization of the graph would be :

import tensorboardcolab as tb

tbc = tb.TensorBoardColab()
tensorboard = tb.TensorBoardColabCallback(tbc)


history = model.fit(x_train,# Features
                    y_train, # Target vector
                    batch_size=batch_size, # Number of observations per batch
                    epochs=epochs, # Number of epochs
                    callbacks=[early_stopping, tensorboard], # Early stopping
                    verbose=1, # Print description after each epoch
                    validation_split=0.2, #used for validation set every each epoch
                    validation_data=(x_test, y_test)) # Test data-set to evaluate the model in the end of training

Installing PHP Zip Extension

This is how I installed it on my machine (ubuntu):

php 7:

sudo apt-get install php7.0-zip

php 5:

sudo apt-get install php5-zip

Edit:
Make sure to restart your server afterwards.

sudo /etc/init.d/apache2 restart or sudo service nginx restart

PS: If you are using centOS, please check above cweiske's answer
But if you are using a Debian derivated OS, this solution should help you installing php zip extension.

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 &");

How do I specify local .gem files in my Gemfile?

By default Bundler will check your system first and if it can't find a gem it will use the sources specified in your Gemfile.

How to view the list of compile errors in IntelliJ?

A more up to date answer for anyone else who comes across this:

(from https://www.jetbrains.com/help/idea/eclipse.html, §Auto-compilation; click for screenshots)

Compile automatically:

To enable automatic compilation, navigate to Settings/Preferences | Build, Execution, Deployment | Compiler and select the Build project automatically option

Show all errors in one place:

The Problems tool window appears if the Make project automatically option is enabled in the Compiler settings. It shows a list of problems that were detected on project compilation.

Use the Eclipse compiler: This is actually bundled in IntelliJ. It gives much more useful error messages, in my opinion, and, according to this blog, it's much faster since it was designed to run in the background of an IDE and uses incremental compilation.

While Eclipse uses its own compiler, IntelliJ IDEA uses the javac compiler bundled with the project JDK. If you must use the Eclipse compiler, navigate to Settings/Preferences | Build, Execution, Deployment | Compiler | Java Compiler and select it... The biggest difference between the Eclipse and javac compilers is that the Eclipse compiler is more tolerant to errors, and sometimes lets you run code that doesn't compile.

add image to uitableview cell

Swift 4 solution:

    cell.imageView?.image = UIImage(named: "yourImageName")

VBScript to send email without running Outlook

You can send email without Outlook in VBScript using the CDO.Message object. You will need to know the address of your SMTP server to use this:

Set MyEmail=CreateObject("CDO.Message")

MyEmail.Subject="Subject"
MyEmail.From="[email protected]"
MyEmail.To="[email protected]"
MyEmail.TextBody="Testing one two three."

MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusing")=2

'SMTP Server
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserver")="smtp.server.com"

'SMTP Port
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserverport")=25 

MyEmail.Configuration.Fields.Update
MyEmail.Send

set MyEmail=nothing

If your SMTP server requires a username and password then paste these lines in above the MyEmail.Configuration.Fields.Update line:

'SMTP Auth (For Windows Auth set this to 2)
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate")=1
'Username
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusername")="username" 
'Password
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendpassword")="password"

More information on using CDO to send email with VBScript can be found on the link below: http://www.paulsadowski.com/wsh/cdo.htm

Proper way to restrict text input values (e.g. only numbers)

I think a custom ControlValueAccessor is the best option.

Not tested but as far as I remember, this should work:

<input [(ngModel)]="value" pattern="[0-9]">

Open page in new window without popup blocking

As a general rule, pop up blockers target windows that launch without user interaction. Usually a click event can open a window without it being blocked. (unless it's a really bad popup blocker)

Try launching after a click event

Why when a constructor is annotated with @JsonCreator, its arguments must be annotated with @JsonProperty?

It is possible to avoid constructor annotations with jdk8 where optionally the compiler will introduce metadata with the names of the constructor parameters. Then with jackson-module-parameter-names module Jackson can use this constructor. You can see an example at post Jackson without annotations

Find Facebook user (url to profile page) by known email address

Maybe this is a little bit late but I found a web site which gives social media account details by know email addreess. It is https://www.fullcontact.com

You can use Person Api there and get the info.

This is a type of get : https://api.fullcontact.com/v2/person.xml?email=someone@****&apiKey=********

Also there is xml or json choice.

Maintaining Session through Angular.js

You would use a service for that in Angular. A service is a function you register with Angular, and that functions job is to return an object which will live until the browser is closed/refreshed. So it's a good place to store state in, and to synchronize that state with the server asynchronously as that state changes.

How to decrypt the password generated by wordpress

You will not be able to retrieve a plain text password from wordpress.

Wordpress use a 1 way encryption to store the passwords using a variation of md5. There is no way to reverse this.

See this article for more info http://wordpress.org/support/topic/how-is-the-user-password-encrypted-wp_hash_password

In Bootstrap open Enlarge image in modal

So I have put together a very rough modal in jsfiddle for you to take hints from.

JSFiddle

$("#pop").on("click", function(e) {
  // e.preventDefault() this is stopping the redirect to the image its self
  e.preventDefault();
  // #the-modal is the img tag that I use as the modal.
  $('#the-modal').modal('toggle');
});

The part that you are missing is the hidden modal that you want to display when the link is clicked. In the example I used a second image as the modal and added the Bootstap classes.

How to prevent page from reloading after form submit - JQuery

The <button> element, when placed in a form, will submit the form automatically unless otherwise specified. You can use the following 2 strategies:

  1. Use <button type="button"> to override default submission behavior
  2. Use event.preventDefault() in the onSubmit event to prevent form submission

Solution 1:

  • Advantage: simple change to markup
  • Disadvantage: subverts default form behavior, especially when JS is disabled. What if the user wants to hit "enter" to submit?

Insert extra type attribute to your button markup:

<button id="button" type="button" value="send" class="btn btn-primary">Submit</button>

Solution 2:

  • Advantage: form will work even when JS is disabled, and respects standard form UI/UX such that at least one button is used for submission

Prevent default form submission when button is clicked. Note that this is not the ideal solution because you should be in fact listening to the submit event, not the button click event:

$(document).ready(function () {
  // Listen to click event on the submit button
  $('#button').click(function (e) {

    e.preventDefault();

    var name = $("#name").val();
    var email = $("#email").val();

    $.post("process.php", {
      name: name,
      email: email
    }).complete(function() {
        console.log("Success");
      });
  });
});

Better variant:

In this improvement, we listen to the submit event emitted from the <form> element:

$(document).ready(function () {
  // Listen to submit event on the <form> itself!
  $('#main').submit(function (e) {

    e.preventDefault();

    var name = $("#name").val();
    var email = $("#email").val();

    $.post("process.php", {
      name: name,
      email: email
    }).complete(function() {
        console.log("Success");
      });
  });
});

Even better variant: use .serialize() to serialize your form, but remember to add name attributes to your input:

The name attribute is required for .serialize() to work, as per jQuery's documentation:

For a form element's value to be included in the serialized string, the element must have a name attribute.

<input type="text" id="name" name="name" class="form-control mb-2 mr-sm-2 mb-sm-0" id="inlineFormInput" placeholder="Jane Doe">
<input type="text" id="email" name="email" class="form-control" id="inlineFormInputGroup" placeholder="[email protected]">

And then in your JS:

$(document).ready(function () {
  // Listen to submit event on the <form> itself!
  $('#main').submit(function (e) {

    // Prevent form submission which refreshes page
    e.preventDefault();

    // Serialize data
    var formData = $(this).serialize();

    // Make AJAX request
    $.post("process.php", formData).complete(function() {
      console.log("Success");
    });
  });
});

Change Activity's theme programmatically

As docs say you have to call setTheme before any view output. It seems that super.onCreate() takes part in view processing.

So, to switch between themes dynamically you simply need to call setTheme before super.onCreate like this:

public void onCreate(Bundle savedInstanceState) {
    setTheme(android.R.style.Theme);
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_second);
}

Cannot GET / Nodejs Error

Much like leonardocsouza, I had the same problem. To clarify a bit, this is what my folder structure looked like when I ran node server.js

node_modules/
app/
  index.html
  server.js

After printing out the __dirname path, I realized that the __dirname path was where my server was running (app/).

So, the answer to your question is this:

If your server.js file is in the same folder as the files you are trying to render, then

app.use( express.static( path.join( application_root, 'site') ) );

should actually be

app.use(express.static(application_root));

The only time you would want to use the original syntax that you had would be if you had a folder tree like so:

app/
  index.html
node_modules
server.js

where index.html is in the app/ directory, whereas server.js is in the root directory (i.e. the same level as the app/ directory).

Side note: Intead of calling the path utility, you can use the syntax application_root + 'site' to join a path.

Overall, your code could look like:

// Module dependencies.
var application_root = __dirname,
express = require( 'express' ), //Web framework
mongoose = require( 'mongoose' ); //MongoDB integration

//Create server
var app = express();

// Configure server
app.configure( function() {

    //Don't change anything here...

    //Where to serve static content
    app.use( express.static( application_root ) );

    //Nothing changes here either...
});

//Start server --- No changes made here
var port = 5000;
app.listen( port, function() {
    console.log( 'Express server listening on port %d in %s mode', port, app.settings.env );
});

Open Excel file for reading with VBA without display

Using ADO (AnonJr already explained) and utilizing SQL is possibly the best option for fetching data from a closed workbook without opening that in conventional way. Please watch this VIDEO.

OTHERWISE, possibly GetObject(<filename with path>) is the most CONCISE way. Worksheets remain invisible, however will appear in project explorer window in VBE just like any other workbook opened in conventional ways.

Dim wb As Workbook

Set wb = GetObject("C:\MyData.xlsx")  'Worksheets will remain invisible, no new window appears in the screen
' your codes here
wb.Close SaveChanges:=False

If you want to read a particular sheet, need not even define a Workbook variable

Dim sh As Worksheet
Set sh = GetObject("C:\MyData.xlsx").Worksheets("MySheet")
' your codes here
sh.Parent.Close SaveChanges:=False 'Closes the associated workbook

What are file descriptors, explained in simple terms?

File Descriptors (FD) :

  • In Linux/Unix, everything is a file. Regular file, Directories, and even Devices are files. Every File has an associated number called File Descriptor (FD).
  • Your screen also has a File Descriptor. When a program is executed the output is sent to File Descriptor of the screen, and you see program output on your monitor. If the output is sent to File Descriptor of the printer, the program output would have been printed.

    Error Redirection :
    Whenever you execute a program/command at the terminal, 3 files are always open
    1. standard input
    2. standard output
    3. standard error.

    These files are always present whenever a program is run. As explained before a file descriptor, is associated with each of these files.
    File                                        File Descriptor
    Standard Input STDIN              0
    Standard Output STDOUT       1
    Standard Error STDERR          2

  • For instance, while searching for files, one typically gets permission denied errors or some other kind of errors. These errors can be saved to a particular file.
    Example 1

$ ls mydir 2>errorsfile.txt

The file descriptor for standard error is 2.
If there is no any directory named as mydir then the output of command will be save to file errorfile.txt
Using "2>" we re-direct the error output to a file named "errorfile.txt"
Thus, program output is not cluttered with errors.

I hope you got your answer.

Getting the location from an IP address

I like the free GeoLite City from Maxmind which works for most applications and from which you can upgrade to a paying version if it's not precise enough. There is a PHP API included, as well as for other languages. And if you are running Lighttpd as a webserver, you can even use a module to get the information in the SERVER variable for every visitor if that's what you need.

I should add there is also a free Geolite Country (which would be faster if you don't need to pinpoint the city the IP is from) and Geolite ASN (if you want to know who owns the IP) and that finally all these are downloadable on your own server, are updated every month and are pretty quick to lookup with the provided APIs as they state "thousands of lookups per second".

Is it possible to include one CSS file in another?

sing the CSS @import Rule here

@import url('/css/header.css') screen;
@import url('/css/content.css') screen;
@import url('/css/sidebar.css') screen;
@import url('/css/print.css') print;

Date in to UTC format Java

SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" );
// or SimpleDateFormat sdf = new SimpleDateFormat( "MM/dd/yyyy KK:mm:ss a Z" );
sdf.setTimeZone( TimeZone.getTimeZone( "UTC" ) );
System.out.println( sdf.format( new Date() ) );

jQuery add required to input fields

You can do it by using attr, the mistake that you made is that you put the true inside quotes. instead of that try this:

$("input").attr("required", true);

How to define Typescript Map of key value pair. where key is a number and value is an array of objects

First thing, define a type or interface for your object, it will make things much more readable:

type Product = { productId: number; price: number; discount: number };

You used a tuple of size one instead of array, it should look like this:

let myarray: Product[];
let priceListMap : Map<number, Product[]> = new Map<number, Product[]>();

So now this works fine:

myarray.push({productId : 1 , price : 100 , discount : 10});
myarray.push({productId : 2 , price : 200 , discount : 20});
myarray.push({productId : 3 , price : 300 , discount : 30});
priceListMap.set(1 , this.myarray);
myarray = null;

(code in playground)

Is it possible to disable scrolling on a ViewPager

A simple solution is to create your own subclass of ViewPager that has a private boolean flag, isPagingEnabled. Then override the onTouchEvent and onInterceptTouchEvent methods. If isPagingEnabled equals true invoke the super method, otherwise return.

public class CustomViewPager extends ViewPager {

    private boolean isPagingEnabled = true;

    public CustomViewPager(Context context) {
        super(context);
    }

    public CustomViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        return this.isPagingEnabled && super.onTouchEvent(event);
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent event) {
        return this.isPagingEnabled && super.onInterceptTouchEvent(event);
    }

    public void setPagingEnabled(boolean b) {
        this.isPagingEnabled = b;
    }
}

Then in your Layout.XML file replace any <com.android.support.V4.ViewPager> tags with <com.yourpackage.CustomViewPager> tags.

This code was adapted from this blog post.

How do I get the name of a Ruby class?

Here's the correct answer, extracted from comments by Daniel Rikowski and pseidemann. I'm tired of having to weed through comments to find the right answer...

If you use Rails (ActiveSupport):

result.class.name.demodulize

If you use POR (plain-ol-Ruby):

result.class.name.split('::').last

How to select rows for a specific date, ignoring time in SQL Server

I know this is an old topic, but I managed to do it in this simple way:

select count(*) from `tablename`
where date(`datecolumn`) = '2021-02-17';

NoClassDefFoundError - Eclipse and Android

sometimes you have to take the whole external project as library and not only the jar:

my problem solved by adding the whole project (in my case google-play-services_lib) as library and not only the jar. the steps to to it (from @style answer):

  1. File->New->Other
  2. Select Android Project
  3. Select "Create Project from existing source"
  4. Click "Browse..." button and navigate to the wanted project
  5. Finish (Now action bar project in your workspace)
  6. Right-click on your project -> Properties
  7. In Android->Library section click Add
  8. select recently added project -> Ok

WHERE statement after a UNION in SQL?

If you want to apply the WHERE clause to the result of the UNION, then you have to embed the UNION in the FROM clause:

SELECT *
  FROM (SELECT * FROM TableA
        UNION
        SELECT * FROM TableB
       ) AS U
 WHERE U.Col1 = ...

I'm assuming TableA and TableB are union-compatible. You could also apply a WHERE clause to each of the individual SELECT statements in the UNION, of course.

app.config for a class library

In fact, the class library you are implementing, is retrieving information from app.config inside the application that is consuming it, so, the most correct way to implement configuration for class libraries at .net in VS is to prepare app.config in the application to configure everything it consumes, like libraries configuration.

I have worked a little with log4net, and I found that the one who prepared the application always had a section for log4net configuration inside main app.config.

I hope you find this information useful.

See you, and post comments about the solution you found.

EDIT:

At the next link you have an app.config with the section for log4net:

http://weblogs.asp.net/tgraham/archive/2007/03/15/a-realistic-log4net-config.aspx

Is it possible to pull just one file in Git?

git checkout master -- myplugin.js

master = branch name

myplugin.js = file name

How to check if element exists using a lambda expression?

Try to use anyMatch of Lambda Expression. It is much better approach.

 boolean idExists = tabPane.getTabs().stream()
            .anyMatch(t -> t.getId().equals(idToCheck));

svn over HTTP proxy

Okay, this topic is somewhat outdated, but as I found it on google and have a solution this might be interesting for someone:

Basically (of course) this is not possible on every http proxy but works on proxies allowing http connect on port 3690. This method is used by http proxies on port 443 to provide a way for secure https connections. If your administrator configures the proxy to open port 3690 for http connect you can setup your local machine to establish a tunnel through the proxy.

I just was in the need to check out some files from svn.openwrt.org within our companies network. An easy solution to create a tunnel is adding the following line to your /etc/hosts

127.0.0.1 svn.openwrt.org

Afterwards, you can use socat to create a tcp tunnel to a local port:

while true; do socat tcp-listen:3690 proxy:proxy.at.your.company:svn.openwrt.org:3690; done

You should execute the command as root. It opens the local port 3690 and on connection creates a tunnel to svn.openwrt.org on the same port.

Just replace the port and server addresses on your own needs.

Making text bold using attributed string in swift

Super easy way to do this.

    let text = "This string is having multiple font"
    let attributedText = 
    NSMutableAttributedString.getAttributedString(fromString: text)

    attributedText.apply(font: UIFont.boldSystemFont(ofSize: 24), subString: 
    "This")

    attributedText.apply(font: UIFont.boldSystemFont(ofSize: 24), onRange: 
    NSMakeRange(5, 6))

For more detail click here: https://github.com/iOSTechHub/AttributedString

Compiling php with curl, where is curl installed?

php curl lib is just a wrapper of cUrl, so, first of all, you should install cUrl. Download the cUrl source to your linux server. Then, use the follow commands to install:

tar zxvf cUrl_src_taz
cd cUrl_src_taz
./configure --prefix=/curl/install/home
make
make test    (optional)
make install
ln -s  /curl/install/home/bin/curl-config /usr/bin/curl-config

Then, copy the head files in the "/curl/install/home/include/" to "/usr/local/include". After all above steps done, the php curl extension configuration could find the original curl, and you can use the standard php extension method to install php curl.
Hope it helps you, :)

Heroku: How to push different local Git branches to Heroku/master

The safest command to push different local Git branches to Heroku/master.

git push -f heroku branch_name:master

Note: Although, you can push without using the -f, the -f (force flag) is recommended in order to avoid conflicts with other developers’ pushes.

Simulate string split function in Excel formula

The following returns the first word in cell A1 when separated by a space (works in Excel 2003):

=LEFT(A1, SEARCH(" ",A1,1))

How to get URL parameter using jQuery or plain JavaScript?

Yet another alternative function...

function param(name) {
    return (location.search.split(name + '=')[1] || '').split('&')[0];
}

.rar, .zip files MIME Type

In a linked question, there's some Objective-C code to get the mime type for a file URL. I've created a Swift extension based on that Objective-C code to get the mime type:

import Foundation
import MobileCoreServices

extension URL {
    var mimeType: String? {
        guard self.pathExtension.count != 0 else {
            return nil
        }

        let pathExtension = self.pathExtension as CFString
        if let preferredIdentifier = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, pathExtension, nil) {
            guard let mimeType = UTTypeCopyPreferredTagWithClass(preferredIdentifier.takeRetainedValue(), kUTTagClassMIMEType) else {
                return nil
            }
            return mimeType.takeRetainedValue() as String
        }

        return nil
    }
}

Display animated GIF in iOS

You can use SwiftGif from this link

Usage:

imageView.loadGif(name: "jeremy")

How to trim white spaces of array values in php

array_map('trim', $data) would convert all subarrays into null. If it is needed to trim spaces only for strings and leave other types as it is, you can use:

$data = array_map(
    function ($item) {
        return is_string($item) ? trim($item) : $item;
    },
    $data
);

How to check if the string is empty?

I would test noneness before stripping. Also, I would use the fact that empty strings are False (or Falsy). This approach is similar to Apache's StringUtils.isBlank or Guava's Strings.isNullOrEmpty

This is what I would use to test if a string is either None OR Empty OR Blank:

def isBlank (myString):
    if myString and myString.strip():
        #myString is not None AND myString is not empty or blank
        return False
    #myString is None OR myString is empty or blank
    return True

And, the exact opposite to test if a string is not None NOR Empty NOR Blank:

def isNotBlank (myString):
    if myString and myString.strip():
        #myString is not None AND myString is not empty or blank
        return True
    #myString is None OR myString is empty or blank
    return False

More concise forms of the above code:

def isBlank (myString):
    return not (myString and myString.strip())

def isNotBlank (myString):
    return bool(myString and myString.strip())

CSS Outside Border

IsisCode gives you a good solution. Another one is to position border div inside parent div. Check this example http://jsfiddle.net/A2tu9/

UPD: You can also use pseudo element :after (:before), in this case HTML will not be polluted with extra markup:

.my-div {
    position: relative;
    padding: 4px;
    ...
}
.my-div:after {
    content: '';
    position: absolute;
    top: -3px;
    left: -3px;
    bottom: -3px;
    right: -3px;
    border: 1px #888 solid;
}

Demo: http://jsfiddle.net/A2tu9/191/

Dropdownlist width in IE

A full fledged jQuery plugin is available. It supports non-breaking layout and keyboard interactions, check out the demo page: http://powerkiki.github.com/ie_expand_select_width/

disclaimer: I coded that thing, patches welcome

JQuery datepicker not working

The problem is you are not linking to the jQuery UI library (which is where datepicker resides):

http://jsfiddle.net/5AkyC/

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<link rel="stylesheet" type="text/css" href="style.css" media="screen" />
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/jquery-ui.js"></script>
<script>
$(function() {
    $( "#datepicker" ).datepicker();
});
</script>
</head>
<body>
    <div class="demo">
    <p>Date: <input type="text" id="datepicker"></p>
    </div><!-- End demo -->
</body>
</HTML>

Best way to unselect a <select> in jQuery?

Thanks a lot for the solution.

The solution for single choice combo list works perfectly. I found this after searching on many sites.

$("#selectID").attr('selectedIndex', '-1').children("option:selected").removeAttr("selected");

equivalent to push() or pop() for arrays?

You can use Arrays.copyOf() with a little reflection to make a nice helper function.

public class ArrayHelper {
    public static <T> T[] push(T[] arr, T item) {
        T[] tmp = Arrays.copyOf(arr, arr.length + 1);
        tmp[tmp.length - 1] = item;
        return tmp;
    }

    public static <T> T[] pop(T[] arr) {
        T[] tmp = Arrays.copyOf(arr, arr.length - 1);
        return tmp;
    }
}

Usage:

String[] items = new String[]{"a", "b", "c"};

items = ArrayHelper.push(items, "d");
items = ArrayHelper.push(items, "e");

items = ArrayHelper.pop(items);

Results

Original: a,b,c

Array after push calls: a,b,c,d,e

Array after pop call: a,b,c,d

What is private bytes, virtual bytes, working set?

The definition of the perfmon counters has been broken since the beginning and for some reason appears to be too hard to correct.

A good overview of Windows memory management is available in the video "Mysteries of Memory Management Revealed" on MSDN: It covers more topics than needed to track memory leaks (eg working set management) but gives enough detail in the relevant topics.


To give you a hint of the problem with the perfmon counter descriptions, here is the inside story about private bytes from "Private Bytes Performance Counter -- Beware!" on MSDN:

Q: When is a Private Byte not a Private Byte?

A: When it isn't resident.

The Private Bytes counter reports the commit charge of the process. That is to say, the amount of space that has been allocated in the swap file to hold the contents of the private memory in the event that it is swapped out. Note: I'm avoiding the word "reserved" because of possible confusion with virtual memory in the reserved state which is not committed.


From "Performance Planning" on MSDN:

3.3 Private Bytes

3.3.1 Description

Private memory, is defined as memory allocated for a process which cannot be shared by other processes. This memory is more expensive than shared memory when multiple such processes execute on a machine. Private memory in (traditional) unmanaged dlls usually constitutes of C++ statics and is of the order of 5% of the total working set of the dll.

Private properties in JavaScript ES6 classes

Completing @d13 and the comments by @johnny-oshika and @DanyalAytekin:

I guess in the example provided by @johnny-oshika we could use normal functions instead of arrow functions and then .bind them with the current object plus a _privates object as a curried parameter:

something.js

function _greet(_privates) {
  return 'Hello ' + _privates.message;
}

function _updateMessage(_privates, newMessage) {
  _privates.message = newMessage;
}

export default class Something {
  constructor(message) {
    const _privates = {
      message
    };

    this.say = _greet.bind(this, _privates);
    this.updateMessage = _updateMessage.bind(this, _privates);
  }
}

main.js

import Something from './something.js';

const something = new Something('Sunny day!');

const message1 = something.say();
something.updateMessage('Cloudy day!');
const message2 = something.say();

console.log(message1 === 'Hello Sunny day!');  // true
console.log(message2 === 'Hello Cloudy day!');  // true

// the followings are not public
console.log(something._greet === undefined);  // true
console.log(something._privates === undefined);  // true
console.log(something._updateMessage === undefined);  // true

// another instance which doesn't share the _privates
const something2 = new Something('another Sunny day!');

const message3 = something2.say();

console.log(message3 === 'Hello another Sunny day!'); // true

Benefits I can think of:

  • we can have private methods (_greet and _updateMessage act like private methods as long as we don't export the references)
  • although they're not on the prototype, the above mentioned methods will save memory because the instances are created once, outside the class (as opposed to defining them in the constructor)
  • we don't leak any globals since we're inside a module
  • we can also have private properties using the binded _privates object

Some drawbacks I can think of:

A running snippet can be found here: http://www.webpackbin.com/NJgI5J8lZ

When to use a linked list over an array/array list?

Arrays have O(1) random access, but are really expensive to add stuff onto or remove stuff from.

Linked lists are really cheap to add or remove items anywhere and to iterate, but random access is O(n).

Decreasing height of bootstrap 3.0 navbar

After spending few hours, adding the following css class fixed my issue.

Work with Bootstrap 3.0.*

.tnav .navbar .container { height: 28px; }

Work with Bootstrap 3.3.4

.navbar-nav > li > a, .navbar-brand {
    padding-top:4px !important; 
    padding-bottom:0 !important;
    height: 28px;
}
.navbar {min-height:28px !important;}

Update Complete code to customize and decrease height of navbar with screenshot.

enter image description here

CSS:

/* navbar */
.navbar-primary .navbar { background:#9f58b5; border-bottom:none; }
.navbar-primary .navbar .nav > li > a {color: #501762;}
.navbar-primary .navbar .nav > li > a:hover {color: #fff; background-color: #8e49a3;}
.navbar-primary .navbar .nav .active > a,.navbar .nav .active > a:hover {color: #fff; background-color: #501762;}
.navbar-primary .navbar .nav li > a .caret, .tnav .navbar .nav li > a:hover .caret {border-top-color: #fff;border-bottom-color: #fff;}
.navbar-primary .navbar .nav > li.dropdown.open.active > a:hover {}
.navbar-primary .navbar .nav > li.dropdown.open > a {color: #fff;background-color: #9f58b5;border-color: #fff;}
.navbar-primary .navbar .nav > li.dropdown.open.active > a:hover .caret, .tnav .navbar .nav > li.dropdown.open > a .caret {border-top-color: #fff;}
.navbar-primary .navbar .navbar-brand {color:#fff;}
.navbar-primary .navbar .nav.pull-right {margin-left: 10px; margin-right: 0;}
.navbar-xs .navbar-primary .navbar { min-height:28px; height: 28px; }
.navbar-xs .navbar-primary .navbar .navbar-brand{ padding: 0px 12px;font-size: 16px;line-height: 28px; }
.navbar-xs .navbar-primary .navbar .navbar-nav > li > a {  padding-top: 0px; padding-bottom: 0px; line-height: 28px; }
.navbar-sm .navbar-primary .navbar { min-height:40px; height: 40px; }
.navbar-sm .navbar-primary .navbar .navbar-brand{ padding: 0px 12px;font-size: 16px;line-height: 40px; }
.navbar-sm .navbar-primary .navbar .navbar-nav > li > a {  padding-top: 0px; padding-bottom: 0px; line-height: 40px; }

Usage Code:

<div class="navbar-xs">
   <div class="navbar-primary">
       <nav class="navbar navbar-static-top" role="navigation">
          <!-- Brand and toggle get grouped for better mobile display -->
          <div class="navbar-header">
              <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#bs-example-navbar-collapse-8">
                 <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="navbar-brand" href="#">Brand</a>
          </div>
          <!-- Collect the nav links, forms, and other content for toggling -->
          <div class="collapse navbar-collapse" id="bs-example-navbar-collapse-8">
              <ul class="nav navbar-nav">
                  <li class="active"><a href="#">Home</a></li>
                  <li><a href="#">Link</a></li>
                   <li><a href="#">Link</a></li>
              </ul>
          </div><!-- /.navbar-collapse -->
      </nav>
  </div>
</div>

Abstract methods in Python

You have to implement an abstract base class (ABC).

Check python docs

convert big endian to little endian in C [without using provided func]

#include <stdint.h>


//! Byte swap unsigned short
uint16_t swap_uint16( uint16_t val ) 
{
    return (val << 8) | (val >> 8 );
}

//! Byte swap short
int16_t swap_int16( int16_t val ) 
{
    return (val << 8) | ((val >> 8) & 0xFF);
}

//! Byte swap unsigned int
uint32_t swap_uint32( uint32_t val )
{
    val = ((val << 8) & 0xFF00FF00 ) | ((val >> 8) & 0xFF00FF ); 
    return (val << 16) | (val >> 16);
}

//! Byte swap int
int32_t swap_int32( int32_t val )
{
    val = ((val << 8) & 0xFF00FF00) | ((val >> 8) & 0xFF00FF ); 
    return (val << 16) | ((val >> 16) & 0xFFFF);
}

Update : Added 64bit byte swapping

int64_t swap_int64( int64_t val )
{
    val = ((val << 8) & 0xFF00FF00FF00FF00ULL ) | ((val >> 8) & 0x00FF00FF00FF00FFULL );
    val = ((val << 16) & 0xFFFF0000FFFF0000ULL ) | ((val >> 16) & 0x0000FFFF0000FFFFULL );
    return (val << 32) | ((val >> 32) & 0xFFFFFFFFULL);
}

uint64_t swap_uint64( uint64_t val )
{
    val = ((val << 8) & 0xFF00FF00FF00FF00ULL ) | ((val >> 8) & 0x00FF00FF00FF00FFULL );
    val = ((val << 16) & 0xFFFF0000FFFF0000ULL ) | ((val >> 16) & 0x0000FFFF0000FFFFULL );
    return (val << 32) | (val >> 32);
}

print variable and a string in python

'''

If the python version you installed is 3.6.1, you can print strings and a variable through
a single line of code.
For example the first string is "I have", the second string is "US
Dollars" and the variable, **card.price** is equal to 300, we can write
the code this way:

'''

print("I have", card.price, "US Dollars")

#The print() function outputs strings to the screen.  
#The comma lets you concatenate and print strings and variables together in a single line of code.

What does localhost:8080 mean?

http: //localhost:8080/web

Where

  • localhost ( hostname ) is the machine name or IP address of the host server e.g Glassfish, Tomcat.
  • 8080 ( port ) is the address of the port on which the host server is listening for requests.

http ://localhost/web

Where

  • localhost ( hostname ) is the machine name or IP address of the host server e.g Glassfish, Tomcat.
  • host server listening to default port 80.

How to debug JavaScript / jQuery event bindings with Firebug or similar tools?

Looks like FireBug crew is working on an EventBug extension. It will add another panel to FireBug - Events.

"The events panel will list all of the event handlers on the page grouped by event type. For each event type you can open up to see the elements the listeners are bound to and summary of the function source." EventBug Rising

Although they cannot say right now when it will be released.

Easy way to export multiple data.frame to multiple Excel worksheets

You can also use the openxlsx library to export multiple datasets to multiple sheets in a single workbook.The advantage of openxlsx over xlsx is that openxlsx removes the dependencies on java libraries.

Write a list of data.frames to individual worksheets using list names as worksheet names.

require(openxlsx)
list_of_datasets <- list("Name of DataSheet1" = dataframe1, "Name of Datasheet2" = dataframe2)
write.xlsx(list_of_datasets, file = "writeXLSX2.xlsx")

Start an activity from a fragment

mFragmentFavorite in your code is a FragmentActivity which is not the same thing as a Fragment. That's why you're getting the type mismatch. Also, you should never call new on an Activity as that is not the proper way to start one.

If you want to start a new instance of mFragmentFavorite, you can do so via an Intent.

From a Fragment:

Intent intent = new Intent(getActivity(), mFragmentFavorite.class);
startActivity(intent);

From an Activity

Intent intent = new Intent(this, mFragmentFavorite.class);
startActivity(intent);

If you want to start aFavorite instead of mFragmentFavorite then you only need to change out their names in the created Intent.

Also, I recommend changing your class names to be more accurate. Calling something mFragmentFavorite is improper in that it's not a Fragment at all. Also, class declarations in Java typically start with a capital letter. You'd do well to name your class something like FavoriteActivity to be more accurate and conform to the language conventions. You will also need to rename the file to FavoriteActivity.java if you choose to do this since Java requires class names match the file name.

UPDATE

Also, it looks like you actually meant formFragmentFavorite to be a Fragment instead of a FragmentActivity based on your use of onCreateView. If you want mFragmentFavorite to be a Fragment then change the following line of code:

public class mFragmentFavorite extends FragmentActivity{

Make this instead read:

public class mFragmentFavorite extends Fragment {

Get file path of image on Android

Try out with mImageCaptureUri.getPath(); By Below Way :

if (requestCode == CAMERA_REQUEST && resultCode == RESULT_OK) {  

            //Get your Image Path
            String Path=mImageCaptureUri.getPath();

            Bitmap photo = (Bitmap) data.getExtras().get("data"); 
            imageView.setImageBitmap(photo);
            knop.setVisibility(Button.VISIBLE);
            System.out.println(mImageCaptureUri);
        }  

Prevent WebView from displaying "web page not available"

Check out the discussion at Android WebView onReceivedError(). It's quite long, but the consensus seems to be that a) you can't stop the "web page not available" page appearing, but b) you could always load an empty page after you get an onReceivedError

How to update/modify an XML file in python?

To make this process more robust, you could consider using the SAX parser (that way you don't have to hold the whole file in memory), read & write till the end of tree and then start appending.

How to mark-up phone numbers?

Although Apple recommends tel: in their docs for Mobile Safari, currently (iOS 4.3) it accepts callto: just the same. So I recommend using callto: on a generic web site as it works with both Skype and iPhone and I expect it will work on Android phones, too.

Update (June 2013)

This is still a matter of deciding what you want your web page to offer. On my websites I provide both tel: and callto: links (the latter labeled as being for Skype) since Desktop browsers on Mac don't do anything with tel: links while mobile Android doesn't do anything with callto: links. Even Google Chrome with the Google Talk plugin does not respond to tel: links. Still, I prefer offering both links on the desktop in case someone has gone to the trouble of getting tel: links to work on their computer.

If the site design dictated that I only provide one link, I'd use a tel: link that I would try to change to callto: on desktop browsers.

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at

The server at x3.chatforyoursite.com needs to output the following header:

Access-Control-Allow-Origin: http://www.example.com

Where http://www.example.com is your website address. You should check your settings on chatforyoursite.com to see if you can enable this - if not their technical support would probably be the best way to resolve this. However to answer your question, you need the remote site to allow your site to access AJAX responses client side.

How to use parameters with HttpPost

You can also use this approach in case you want to pass some http parameters and send a json request:

(note: I have added in some extra code just incase it helps any other future readers)

public void postJsonWithHttpParams() throws URISyntaxException, UnsupportedEncodingException, IOException {

    //add the http parameters you wish to pass
    List<NameValuePair> postParameters = new ArrayList<>();
    postParameters.add(new BasicNameValuePair("param1", "param1_value"));
    postParameters.add(new BasicNameValuePair("param2", "param2_value"));

    //Build the server URI together with the parameters you wish to pass
    URIBuilder uriBuilder = new URIBuilder("http://google.ug");
    uriBuilder.addParameters(postParameters);

    HttpPost postRequest = new HttpPost(uriBuilder.build());
    postRequest.setHeader("Content-Type", "application/json");

    //this is your JSON string you are sending as a request
    String yourJsonString = "{\"str1\":\"a value\",\"str2\":\"another value\"} ";

    //pass the json string request in the entity
    HttpEntity entity = new ByteArrayEntity(yourJsonString.getBytes("UTF-8"));
    postRequest.setEntity(entity);

    //create a socketfactory in order to use an http connection manager
    PlainConnectionSocketFactory plainSocketFactory = PlainConnectionSocketFactory.getSocketFactory();
    Registry<ConnectionSocketFactory> connSocketFactoryRegistry = RegistryBuilder.<ConnectionSocketFactory>create()
            .register("http", plainSocketFactory)
            .build();

    PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(connSocketFactoryRegistry);

    connManager.setMaxTotal(20);
    connManager.setDefaultMaxPerRoute(20);

    RequestConfig defaultRequestConfig = RequestConfig.custom()
            .setSocketTimeout(HttpClientPool.connTimeout)
            .setConnectTimeout(HttpClientPool.connTimeout)
            .setConnectionRequestTimeout(HttpClientPool.readTimeout)
            .build();

    // Build the http client.
    CloseableHttpClient httpclient = HttpClients.custom()
            .setConnectionManager(connManager)
            .setDefaultRequestConfig(defaultRequestConfig)
            .build();

    CloseableHttpResponse response = httpclient.execute(postRequest);

    //Read the response
    String responseString = "";

    int statusCode = response.getStatusLine().getStatusCode();
    String message = response.getStatusLine().getReasonPhrase();

    HttpEntity responseHttpEntity = response.getEntity();

    InputStream content = responseHttpEntity.getContent();

    BufferedReader buffer = new BufferedReader(new InputStreamReader(content));
    String line;

    while ((line = buffer.readLine()) != null) {
        responseString += line;
    }

    //release all resources held by the responseHttpEntity
    EntityUtils.consume(responseHttpEntity);

    //close the stream
    response.close();

    // Close the connection manager.
    connManager.close();
}

SQL keys, MUL vs PRI vs UNI

It means that the field is (part of) a non-unique index. You can issue

show create table <table>;

To see more information about the table structure.

How do you plot bar charts in gnuplot?

plot "data.dat" using 2: xtic(1) with histogram

Here data.dat contains data of the form

title 1
title2 3
"long title" 5

Create Excel files from C# without office

If you're interested in making .xlsx (Office 2007 and beyond) files, you're in luck. Office 2007+ uses OpenXML which for lack of a more apt description is XML files inside of a zip named .xlsx

Take an excel file (2007+) and rename it to .zip, you can open it up and take a look. If you're using .NET 3.5 you can use the System.IO.Packaging library to manipulate the relationships & zipfile itself, and linq to xml to play with the xml (or just DOM if you're more comfortable).

Otherwise id reccomend DotNetZip, a powerfull library for manipulation of zipfiles.

OpenXMLDeveloper has lots of resources about OpenXML and you can find more there.

If you want .xls (2003 and below) you're going to have to look into 3rd party libraries or perhaps learn the file format yourself to achieve this without excel installed.

How to name and retrieve a stash by name in git?

git stash save is deprecated as of 2.15.x/2.16, instead you can use git stash push -m "message"

You can use it like this:

git stash push -m "message"

where "message" is your note for that stash.

In order to retrieve the stash you can use: git stash list. This will output a list like this, for example:

stash@{0}: On develop: perf-spike
stash@{1}: On develop: node v10

Then you simply use apply giving it the stash@{index}:

git stash apply stash@{1}

References git stash man page

Oracle SELECT TOP 10 records

you may use this query for selecting top records in oracle. Rakesh B

select * from User_info where id >= (select max(id)-10 from User_info);

How to get the result of OnPostExecute() to main activity because AsyncTask is a separate class?

You can call the get() method of AsyncTask (or the overloaded get(long, TimeUnit)). This method will block until the AsyncTask has completed its work, at which point it will return you the Result.

It would be wise to be doing other work between the creation/start of your async task and calling the get method, otherwise you aren't utilizing the async task very efficiently.

Setting href attribute at runtime

In jQuery 1.6+ it's better to use:

$(selector).prop('href',"http://www...") to set the value, and

$(selector).prop('href') to get the value

In short, .prop gets and sets values on the DOM object, and .attr gets and sets values in the HTML. This makes .prop a little faster and possibly more reliable in some contexts.

How to make a Generic Type Cast function

Something like this?

public static T ConvertValue<T>(string value)
{
    return (T)Convert.ChangeType(value, typeof(T));
}

You can then use it like this:

int val = ConvertValue<int>("42");

Edit:

You can even do this more generic and not rely on a string parameter provided the type U implements IConvertible - this means you have to specify two type parameters though:

public static T ConvertValue<T,U>(U value) where U : IConvertible
{
    return (T)Convert.ChangeType(value, typeof(T));
}

I considered catching the InvalidCastException exception that might be raised by Convert.ChangeType() - but what would you return in this case? default(T)? It seems more appropriate having the caller deal with the exception.

How to create a GUID/UUID in Python

2019 Answer (for Windows):

If you want a permanent UUID that identifies a machine uniquely on Windows, you can use this trick: (Copied from my answer at https://stackoverflow.com/a/58416992/8874388).

from typing import Optional
import re
import subprocess
import uuid

def get_windows_uuid() -> Optional[uuid.UUID]:
    try:
        # Ask Windows for the device's permanent UUID. Throws if command missing/fails.
        txt = subprocess.check_output("wmic csproduct get uuid").decode()

        # Attempt to extract the UUID from the command's result.
        match = re.search(r"\bUUID\b[\s\r\n]+([^\s\r\n]+)", txt)
        if match is not None:
            txt = match.group(1)
            if txt is not None:
                # Remove the surrounding whitespace (newlines, space, etc)
                # and useless dashes etc, by only keeping hex (0-9 A-F) chars.
                txt = re.sub(r"[^0-9A-Fa-f]+", "", txt)

                # Ensure we have exactly 32 characters (16 bytes).
                if len(txt) == 32:
                    return uuid.UUID(txt)
    except:
        pass # Silence subprocess exception.

    return None

print(get_windows_uuid())

Uses Windows API to get the computer's permanent UUID, then processes the string to ensure it's a valid UUID, and lastly returns a Python object (https://docs.python.org/3/library/uuid.html) which gives you convenient ways to use the data (such as 128-bit integer, hex string, etc).

Good luck!

PS: The subprocess call could probably be replaced with ctypes directly calling Windows kernel/DLLs. But for my purposes this function is all I need. It does strong validation and produces correct results.

How do I horizontally center a span element inside a div

One option is to give the <a> a display of inline-block and then apply text-align: center; on the containing block (remove the float as well):

div { 
    background: red;
    overflow: hidden; 
    text-align: center;
}

span a {
    background: #222;
    color: #fff;
    display: inline-block;
    /* float:left;  remove */
    margin: 10px 10px 0 0;
    padding: 5px 10px
}

http://jsfiddle.net/Adrift/cePe3/

How do you compare two version Strings in Java?

It's really easy using Maven:

import org.apache.maven.artifact.versioning.DefaultArtifactVersion;

DefaultArtifactVersion minVersion = new DefaultArtifactVersion("1.0.1");
DefaultArtifactVersion maxVersion = new DefaultArtifactVersion("1.10");

DefaultArtifactVersion version = new DefaultArtifactVersion("1.11");

if (version.compareTo(minVersion) < 0 || version.compareTo(maxVersion) > 0) {
    System.out.println("Sorry, your version is unsupported");
}

You can get the right dependency string for Maven Artifact from this page:

<dependency>
<groupId>org.apache.maven</groupId>
<artifactId>maven-artifact</artifactId>
<version>3.0.3</version>
</dependency>

TortoiseSVN icons not showing up under Windows 7

Halt ye!

Before doing anything to your registry or similar procedures listed in Kris Erickson's (excellent) answer or the ones below, there's something to consider...

Are you on a network drive?

If so, go to Tortoise SVN settings (right click any folder > TortoiseSVN > Settings), then go to 'Icon Overlays'

Make sure you've checked 'Network Drives' as pictured:

alt text

By default on a fresh Tortoise install, network drives don't have the icons added.

This solved the problem for us. If this fails for you then obviously you can go through the (slightly) more involved solutions listed here.

using stored procedure in entity framework

You need to create a model class that contains all stored procedure properties like below. Also because Entity Framework model class needs primary key, you can create a fake key by using Guid.

public class GetFunctionByID
{
    [Key]
    public Guid? GetFunctionByID { get; set; }

    // All the other properties.
}

then register the GetFunctionByID model class in your DbContext.

public class FunctionsContext : BaseContext<FunctionsContext>
{
    public DbSet<App_Functions> Functions { get; set; }
    public DbSet<GetFunctionByID> GetFunctionByIds {get;set;}
}

When you call your stored procedure, just see below:

var functionId = yourIdParameter;
var result =  db.Database.SqlQuery<GetFunctionByID>("GetFunctionByID @FunctionId", new SqlParameter("@FunctionId", functionId)).ToList());

Mutex example / tutorial?

Here goes my humble attempt to explain the concept to newbies around the world: (a color coded version on my blog too)

A lot of people run to a lone phone booth (they don't have mobile phones) to talk to their loved ones. The first person to catch the door-handle of the booth, is the one who is allowed to use the phone. He has to keep holding on to the handle of the door as long as he uses the phone, otherwise someone else will catch hold of the handle, throw him out and talk to his wife :) There's no queue system as such. When the person finishes his call, comes out of the booth and leaves the door handle, the next person to get hold of the door handle will be allowed to use the phone.

A thread is : Each person
The mutex is : The door handle
The lock is : The person's hand
The resource is : The phone

Any thread which has to execute some lines of code which should not be modified by other threads at the same time (using the phone to talk to his wife), has to first acquire a lock on a mutex (clutching the door handle of the booth). Only then will a thread be able to run those lines of code (making the phone call).

Once the thread has executed that code, it should release the lock on the mutex so that another thread can acquire a lock on the mutex (other people being able to access the phone booth).

[The concept of having a mutex is a bit absurd when considering real-world exclusive access, but in the programming world I guess there was no other way to let the other threads 'see' that a thread was already executing some lines of code. There are concepts of recursive mutexes etc, but this example was only meant to show you the basic concept. Hope the example gives you a clear picture of the concept.]

With C++11 threading:

#include <iostream>
#include <thread>
#include <mutex>

std::mutex m;//you can use std::lock_guard if you want to be exception safe
int i = 0;

void makeACallFromPhoneBooth() 
{
    m.lock();//man gets a hold of the phone booth door and locks it. The other men wait outside
      //man happily talks to his wife from now....
      std::cout << i << " Hello Wife" << std::endl;
      i++;//no other thread can access variable i until m.unlock() is called
      //...until now, with no interruption from other men
    m.unlock();//man lets go of the door handle and unlocks the door
}

int main() 
{
    //This is the main crowd of people uninterested in making a phone call

    //man1 leaves the crowd to go to the phone booth
    std::thread man1(makeACallFromPhoneBooth);
    //Although man2 appears to start second, there's a good chance he might
    //reach the phone booth before man1
    std::thread man2(makeACallFromPhoneBooth);
    //And hey, man3 also joined the race to the booth
    std::thread man3(makeACallFromPhoneBooth);

    man1.join();//man1 finished his phone call and joins the crowd
    man2.join();//man2 finished his phone call and joins the crowd
    man3.join();//man3 finished his phone call and joins the crowd
    return 0;
}

Compile and run using g++ -std=c++0x -pthread -o thread thread.cpp;./thread

Instead of explicitly using lock and unlock, you can use brackets as shown here, if you are using a scoped lock for the advantage it provides. Scoped locks have a slight performance overhead though.

Simple way to change the position of UIView?

Other way:

CGPoint position = CGPointMake(100,30);
[self setFrame:(CGRect){
      .origin = position,
      .size = self.frame.size
}];

This i save size parameters and change origin only.

Python Array with String Indices

Even better, try an OrderedDict (assuming you want something like a list). Closer to a list than a regular dict since the keys have an order just like list elements have an order. With a regular dict, the keys have an arbitrary order.

Note that this is available in Python 3 and 2.7. If you want to use with an earlier version of Python you can find installable modules to do that.

Tensorflow import error: No module named 'tensorflow'

The reason Python 3.5 environment is unable to import Tensorflow is that Anaconda does not store the tensorflow package in the same environment.

One solution is to create a new separate environment in Anaconda dedicated to TensorFlow with its own Spyder

conda create -n newenvt anaconda python=3.5
activate newenvt

and then install tensorflow into newenvt

I found this primer helpful

Checking for empty result (php, pdo, mysql)

You're throwing away a result row when you do $sth->fetchColumn(). That's not how you check if there's any results. you do

if ($sth->rowCount() > 0) {
  ... got results ...
} else {
   echo 'nothing';
}

relevant docs here: http://php.net/manual/en/pdostatement.rowcount.php

convert:not authorized `aaaa` @ error/constitute.c/ReadImage/453

Note: the solution in this and other answers involves disabling safety measures that are there to fix arbitrary code execution vulnerabilities. See for instance this ghostscript-related and this ubuntu-related announcement. Only go forward with these solutions if the input to convert comes from a trusted source.

I use ImageMagick in php (v.7.1) to slice PDF file to images.

First I got errors like:

Exception type: ImagickException

Exception message: not authorized ..... @ error/constitute.c/ReadImage/412

After some changes in /etc/ImageMagick-6/policy.xml I start getting erroes like:

Exception type: ImagickException

Exception message: unable to create temporary file ..... Permission denied @ error/pdf.c/ReadPDFImage/465

My fix:

In file /etc/ImageMagick-6/policy.xml (or /etc/ImageMagick/policy.xml)

  1. comment line

    <!-- <policy domain="coder" rights="none" pattern="MVG" /> -->
    
  2. change line

    <policy domain="coder" rights="none" pattern="PDF" />
    

    to

    <policy domain="coder" rights="read|write" pattern="PDF" />
    
  3. add line

    <policy domain="coder" rights="read|write" pattern="LABEL" />
    

Then restart your web server (nginx, apache).

Getting rid of \n when using .readlines()

I recently used this to read all the lines from a file:

alist = open('maze.txt').read().split()

or you can use this for that little bit of extra added safety:

with f as open('maze.txt'):
    alist = f.read().split()

It doesn't work with whitespace in-between text in a single line, but it looks like your example file might not have whitespace splitting the values. It is a simple solution and it returns an accurate list of values, and does not add an empty string: '' for every empty line, such as a newline at the end of the file.

How to redirect to another page using AngularJS?

The simple way I use is

app.controller("Back2Square1Controller", function($scope, $location) {
    window.location.assign(basePath + "/index.html");
});

What's the point of 'meta viewport user-scalable=no' in the Google Maps API

Disabling user-scalable (namely, the ability to double tap to zoom) allows the browser to reduce the click delay. In touch-enable browsers, when the user expects the double tap to zoom, the browser generally waits 300ms before firing the click event, waiting to see if the user will double tap. Disabling user-scalable allows for the Chrome browser to fire the click event immediately, allowing for a better user experience.

From Google IO 2013 session https://www.youtube.com/watch?feature=player_embedded&v=DujfpXOKUp8#t=1435s

Update: its not true anymore, <meta name="viewport" content="width=device-width"> is enough to remove 300ms delay

CSS: how do I create a gap between rows in a table?

Create an another <tr> just below and add some space or height to content of <td>

enter image description here

Checkout the fiddle for example

https://jsfiddle.net/jd_dev777/wx63norf/9/

remove double quotes from Json return data using Jquery

Someone here suggested using eval() to remove the quotes from a string. Don't do that, that's just begging for code injection.

Another way to do this that I don't see listed here is using:

let message = JSON.stringify(your_json_here); // "Hello World"
console.log(JSON.parse(message))              // Hello World

Assign static IP to Docker container

If you want your container to have it's own virtual ethernet socket (with it's own MAC address), iptables, then use the Macvlan driver. This may be necessary to route traffic out to your/ISPs router.

https://docs.docker.com/engine/userguide/networking/get-started-macvlan

AWK to print field $2 first, then field $1

Maybe your file contains CRLF terminator. Every lines followed by \r\n.

awk recognizes the $2 actually $2\r. The \r means goto the start of the line.

{print $2\r$1} will print $2 first, then return to the head, then print $1. So the field 2 is overlaid by the field 1.

Is there a list of Pytz Timezones?

EDIT: I would appreciate it if you do not downvote this answer further. This answer is wrong, but I would rather retain it as a historical note. While it is arguable whether the pytz interface is error-prone, it can do things that dateutil.tz cannot do, especially regarding daylight-saving in the past or in the future. I have honestly recorded my experience in an article "Time zones in Python".


If you are on a Unix-like platform, I would suggest you avoid pytz and look just at /usr/share/zoneinfo. dateutil.tz can utilize the information there.

The following piece of code shows the problem pytz can give. I was shocked when I first found it out. (Interestingly enough, the pytz installed by yum on CentOS 7 does not exhibit this problem.)

import pytz
import dateutil.tz
from datetime import datetime
print((datetime(2017,2,13,14,29,29, tzinfo=pytz.timezone('Asia/Shanghai'))
     - datetime(2017,2,13,14,29,29, tzinfo=pytz.timezone('UTC')))
     .total_seconds())
print((datetime(2017,2,13,14,29,29, tzinfo=dateutil.tz.gettz('Asia/Shanghai'))
     - datetime(2017,2,13,14,29,29, tzinfo=dateutil.tz.tzutc()))
     .total_seconds())

-29160.0
-28800.0

I.e. the timezone created by pytz is for the true local time, instead of the standard local time people observe. Shanghai conforms to +0800, not +0806 as suggested by pytz:

pytz.timezone('Asia/Shanghai')
<DstTzInfo 'Asia/Shanghai' LMT+8:06:00 STD>

EDIT: Thanks to Mark Ransom's comment and downvote, now I know I am using pytz the wrong way. In summary, you are not supposed to pass the result of pytz.timezone(…) to datetime, but should pass the datetime to its localize method.

Despite his argument (and my bad for not reading the pytz documentation more carefully), I am going to keep this answer. I was answering the question in one way (how to enumerate the supported timezones, though not with pytz), because I believed pytz did not provide a correct solution. Though my belief was wrong, this answer is still providing some information, IMHO, which is potentially useful to people interested in this question. Pytz's correct way of doing things is counter-intuitive. Heck, if the tzinfo created by pytz should not be directly used by datetime, it should be a different type. The pytz interface is simply badly designed. The link provided by Mark shows that many people, not just me, have been misled by the pytz interface.

NSDictionary - Need to check whether dictionary contains key-value pair or not

Just ask it for the objectForKey:@"b". If it returns nil, no object is set at that key.

if ([xyz objectForKey:@"b"]) {
    NSLog(@"There's an object set for key @\"b\"!");
} else {
    NSLog(@"No object set for key @\"b\"");
}

Edit: As to your edited second question, it's simply NSUInteger mCount = [xyz count];. Both of these answers are documented well and easily found in the NSDictionary class reference ([1] [2]).

How can I create an MSI setup?

You can purchase InstallShield, the market leader for creating installation packages. It offers many features beyond what you get with freeware solutions.

Warning: InstallShield is insanely expensive!

How can I check if a view is visible or not in Android?

Although View.getVisibility() does get the visibility, its not a simple true/false. A view can have its visibility set to one of three things.

View.VISIBLE The view is visible.

View.INVISIBLE The view is invisible, but any spacing it would normally take up will still be used. Its "invisible"

View.GONE The view is gone, you can't see it and it doesn't take up the "spot".

So to answer your question, you're looking for:

if (myImageView.getVisibility() == View.VISIBLE) {
    // Its visible
} else {
    // Either gone or invisible
}

Clang vs GCC for my Linux Development project

EDIT:

The gcc guys really improved the diagnosis experience in gcc (ah competition). They created a wiki page to showcase it here. gcc 4.8 now has quite good diagnostics as well (gcc 4.9x added color support). Clang is still in the lead, but the gap is closing.


Original:

For students, I would unconditionally recommend Clang.

The performance in terms of generated code between gcc and Clang is now unclear (though I think that gcc 4.7 still has the lead, I haven't seen conclusive benchmarks yet), but for students to learn it does not really matter anyway.

On the other hand, Clang's extremely clear diagnostics are definitely easier for beginners to interpret.

Consider this simple snippet:

#include <string>
#include <iostream>

struct Student {
std::string surname;
std::string givenname;
}

std::ostream& operator<<(std::ostream& out, Student const& s) {
  return out << "{" << s.surname << ", " << s.givenname << "}";
}

int main() {
  Student me = { "Doe", "John" };
  std::cout << me << "\n";
}

You'll notice right away that the semi-colon is missing after the definition of the Student class, right :) ?

Well, gcc notices it too, after a fashion:

prog.cpp:9: error: expected initializer before ‘&’ token
prog.cpp: In function ‘int main()’:
prog.cpp:15: error: no match for ‘operator<<’ in ‘std::cout << me’
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:112: note: candidates are: std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(std::basic_ostream<_CharT, _Traits>& (*)(std::basic_ostream<_CharT, _Traits>&)) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:121: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(std::basic_ios<_CharT, _Traits>& (*)(std::basic_ios<_CharT, _Traits>&)) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:131: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(std::ios_base& (*)(std::ios_base&)) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:169: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(long int) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:173: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(long unsigned int) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:177: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(bool) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/bits/ostream.tcc:97: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(short int) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:184: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(short unsigned int) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/bits/ostream.tcc:111: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(int) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:195: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(unsigned int) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:204: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(long long int) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:208: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(long long unsigned int) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:213: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(double) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:217: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(float) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:225: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(long double) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/ostream:229: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(const void*) [with _CharT = char, _Traits = std::char_traits<char>]
/usr/lib/gcc/i686-pc-linux-gnu/4.3.4/include/g++-v4/bits/ostream.tcc:125: note:                 std::basic_ostream<_CharT, _Traits>& std::basic_ostream<_CharT, _Traits>::operator<<(std::basic_streambuf<_CharT, _Traits>*) [with _CharT = char, _Traits = std::char_traits<char>]

And Clang is not exactly starring here either, but still:

/tmp/webcompile/_25327_1.cc:9:6: error: redefinition of 'ostream' as different kind of symbol
std::ostream& operator<<(std::ostream& out, Student const& s) {
     ^
In file included from /tmp/webcompile/_25327_1.cc:1:
In file included from /usr/include/c++/4.3/string:49:
In file included from /usr/include/c++/4.3/bits/localefwd.h:47:
/usr/include/c++/4.3/iosfwd:134:33: note: previous definition is here
  typedef basic_ostream<char>           ostream;        ///< @isiosfwd
                                        ^
/tmp/webcompile/_25327_1.cc:9:13: error: expected ';' after top level declarator
std::ostream& operator<<(std::ostream& out, Student const& s) {
            ^
            ;
2 errors generated.

I purposefully choose an example which triggers an unclear error message (coming from an ambiguity in the grammar) rather than the typical "Oh my god Clang read my mind" examples. Still, we notice that Clang avoids the flood of errors. No need to scare students away.

How to copy static files to build directory with Webpack?

Most likely you should use CopyWebpackPlugin which was mentioned in kevlened answer. Alternativly for some kind of files like .html or .json you can also use raw-loader or json-loader. Install it via npm install -D raw-loader and then what you only need to do is to add another loader to our webpack.config.js file.

Like:

{
    test: /\.html/,
    loader: 'raw'
}

Note: Restart the webpack-dev-server for any config changes to take effect.

And now you can require html files using relative paths, this makes it much easier to move folders around.

template: require('./nav.html')  

Oracle client ORA-12541: TNS:no listener

According to oracle online documentation

ORA-12541: TNS:no listener

Cause: The connection request could not be completed because the listener is not running.

Action: Ensure that the supplied destination address matches one of the addresses used by 
the listener - compare the TNSNAMES.ORA entry with the appropriate LISTENER.ORA file (or  
TNSNAV.ORA if the connection is to go by way of an Interchange). Start the listener on 
the remote machine.

What is the difference between the remap, noremap, nnoremap and vnoremap mapping commands in Vim?

I think the Vim documentation should've explained the meaning behind the naming of these commands. Just telling you what they do doesn't help you remember the names.

map is the "root" of all recursive mapping commands. The root form applies to "normal", "visual+select", and "operator-pending" modes. (I'm using the term "root" as in linguistics.)

noremap is the "root" of all non-recursive mapping commands. The root form applies to the same modes as map. (Think of the nore prefix to mean "non-recursive".)

(Note that there are also the ! modes like map! that apply to insert & command-line.)

See below for what "recursive" means in this context.

Prepending a mode letter like n modify the modes the mapping works in. It can choose a subset of the list of applicable modes (e.g. only "visual"), or choose other modes that map wouldn't apply to (e.g. "insert").

Use help map-modes will show you a few tables that explain how to control which modes the mapping applies to.

Mode letters:

  • n: normal only
  • v: visual and select
  • o: operator-pending
  • x: visual only
  • s: select only
  • i: insert
  • c: command-line
  • l: insert, command-line, regexp-search (and others. Collectively called "Lang-Arg" pseudo-mode)

"Recursive" means that the mapping is expanded to a result, then the result is expanded to another result, and so on.

The expansion stops when one of these is true:

  1. the result is no longer mapped to anything else.
  2. a non-recursive mapping has been applied (i.e. the "noremap" [or one of its ilk] is the final expansion).

At that point, Vim's default "meaning" of the final result is applied/executed.

"Non-recursive" means the mapping is only expanded once, and that result is applied/executed.

Example:

 nmap K H
 nnoremap H G
 nnoremap G gg

The above causes K to expand to H, then H to expand to G and stop. It stops because of the nnoremap, which expands and stops immediately. The meaning of G will be executed (i.e. "jump to last line"). At most one non-recursive mapping will ever be applied in an expansion chain (it would be the last expansion to happen).

The mapping of G to gg only applies if you press G, but not if you press K. This mapping doesn't affect pressing K regardless of whether G was mapped recursively or not, since it's line 2 that causes the expansion of K to stop, so line 3 wouldn't be used.

Specifying ssh key in ansible playbook file

The variable name you're looking for is ansible_ssh_private_key_file.

You should set it at 'vars' level:

  • in the inventory file:

    myHost ansible_ssh_private_key_file=~/.ssh/mykey1.pem
    myOtherHost ansible_ssh_private_key_file=~/.ssh/mykey2.pem
    
  • in the host_vars:

    # hosts_vars/myHost.yml
    ansible_ssh_private_key_file: ~/.ssh/mykey1.pem
    
    # hosts_vars/myOtherHost.yml
    ansible_ssh_private_key_file: ~/.ssh/mykey2.pem
    
  • in a group_vars file if you use the same key for a group of hosts

  • in the vars section of your play:

    - hosts: myHost
      remote_user: ubuntu
      vars_files:
        - vars.yml
      vars:
        ansible_ssh_private_key_file: "{{ key1 }}"
      tasks:
        - name: Echo a hello message
          command: echo hello
    

Inventory documentation

Android: Changing Background-Color of the Activity (Main View)

if you put your full code here so i can help you. if your setting the listener in XML and calling the set background color on View so it will change the background color of the view means it ur Botton so put ur listener in ur activity and then change the color of your view

HTML5 event handling(onfocus and onfocusout) using angular 2

<input name="date" type="text" (focus)="focusFunction()" (focusout)="focusOutFunction()">

works for me from Pardeep Jain

List files committed for a revision

From remote repo:

svn log -v -r 42 --stop-on-copy --non-interactive --no-auth-cache --username USERNAME --password PASSWORD http://repourl/projectname/

How to center cards in bootstrap 4?

Update 2018

There is no need for extra CSS, and there are multiple centering methods in Bootstrap 4:

  • text-center for center display:inline elements
  • mx-auto for centering display:block elements inside display:flex (d-flex)
  • offset-* or mx-auto can be used to center grid columns
  • or justify-content-center on row to center grid columns

mx-auto (auto x-axis margins) will center inside display:flex elements that have a defined width, (%, vw, px, etc..). Flexbox is used by default on grid columns, so there are also various centering methods.

In your case, you can simply mx-auto to the cards.

C# code to validate email address

In case you are using FluentValidation you could write something as simple as this:

public cass User
{
    public string Email { get; set; }
}

public class UserValidator : AbstractValidator<User>
{
    public UserValidator()
    {
        RuleFor(x => x.Email).EmailAddress().WithMessage("The text entered is not a valid email address.");
    }
}

// Validates an user. 
var validationResult = new UserValidator().Validate(new User { Email = "açflkdj" });

// This will return false, since the user email is not valid.
bool userIsValid = validationResult.IsValid;

Fastest way to check if a file exist using standard C++/C++11/C?

In C++17 :

#include <experimental/filesystem>

bool is_file_exist(std::string& str) {   
    namespace fs = std::experimental::filesystem;
    fs::path p(str);
    return fs::exists(p);
}

android download pdf from url then open it with a pdf reader

Download source code from here (Open Pdf from url in Android Programmatically)

MainActivity.java

package com.deepshikha.openpdf;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ProgressBar;

public class MainActivity extends AppCompatActivity {
    WebView webview;
    ProgressBar progressbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        webview = (WebView)findViewById(R.id.webview);
        progressbar = (ProgressBar) findViewById(R.id.progressbar);
        webview.getSettings().setJavaScriptEnabled(true);
        String filename ="http://www3.nd.edu/~cpoellab/teaching/cse40816/android_tutorial.pdf";
        webview.loadUrl("http://docs.google.com/gview?embedded=true&url=" + filename);

        webview.setWebViewClient(new WebViewClient() {

            public void onPageFinished(WebView view, String url) {
                // do your stuff here
                progressbar.setVisibility(View.GONE);
            }
        });

    }
}

Thanks!

Oracle query to fetch column names

The below query worked for me in Oracle database.

select COLUMN_NAME from ALL_TAB_COLUMNS where TABLE_NAME='MyTableName';

What is the difference between == and equals() in Java?

== is an operator and equals() is a method.

Operators are generally used for primitive type comparisons and thus == is used for memory address comparison and equals() method is used for comparing objects.

How to get the groups of a user in Active Directory? (c#, asp.net)

If you're on .NET 3.5 or up, you can use the new System.DirectoryServices.AccountManagement (S.DS.AM) namespace which makes this a lot easier than it used to be.

Read all about it here: Managing Directory Security Principals in the .NET Framework 3.5

Update: older MSDN magazine articles aren't online anymore, unfortunately - you'll need to download the CHM for the January 2008 MSDN magazine from Microsoft and read the article in there.

Basically, you need to have a "principal context" (typically your domain), a user principal, and then you get its groups very easily:

public List<GroupPrincipal> GetGroups(string userName)
{
   List<GroupPrincipal> result = new List<GroupPrincipal>();

   // establish domain context
   PrincipalContext yourDomain = new PrincipalContext(ContextType.Domain);

   // find your user
   UserPrincipal user = UserPrincipal.FindByIdentity(yourDomain, userName);

   // if found - grab its groups
   if(user != null)
   {
      PrincipalSearchResult<Principal> groups = user.GetAuthorizationGroups();

      // iterate over all groups
      foreach(Principal p in groups)
      {
         // make sure to add only group principals
         if(p is GroupPrincipal)
         {
             result.Add((GroupPrincipal)p);
         }
      }
   }

   return result;
}

and that's all there is! You now have a result (a list) of authorization groups that user belongs to - iterate over them, print out their names or whatever you need to do.

Update: In order to access certain properties, which are not surfaced on the UserPrincipal object, you need to dig into the underlying DirectoryEntry:

public string GetDepartment(Principal principal)
{
    string result = string.Empty;

    DirectoryEntry de = (principal.GetUnderlyingObject() as DirectoryEntry);

    if (de != null)
    {
       if (de.Properties.Contains("department"))
       {
          result = de.Properties["department"][0].ToString();
       }
    }

    return result;
}

Update #2: seems shouldn't be too hard to put these two snippets of code together.... but ok - here it goes:

public string GetDepartment(string username)
{
    string result = string.Empty;

    // if you do repeated domain access, you might want to do this *once* outside this method, 
    // and pass it in as a second parameter!
    PrincipalContext yourDomain = new PrincipalContext(ContextType.Domain);

    // find the user
    UserPrincipal user = UserPrincipal.FindByIdentity(yourDomain, username);

    // if user is found
    if(user != null)
    {
       // get DirectoryEntry underlying it
       DirectoryEntry de = (user.GetUnderlyingObject() as DirectoryEntry);

       if (de != null)
       {
          if (de.Properties.Contains("department"))
          {
             result = de.Properties["department"][0].ToString();
          }
       }
    }

    return result;
}

plot is not defined

Change that import to

from matplotlib.pyplot import *

Note that this style of imports (from X import *) is generally discouraged. I would recommend using the following instead:

import matplotlib.pyplot as plt
plt.plot([1,2,3,4])

How to search for an element in a golang slice

You can use sort.Slice() plus sort.Search()

type Person struct {
    Name string
}

func main() {
    crowd := []Person{{"Zoey"}, {"Anna"}, {"Benni"}, {"Chris"}}

    sort.Slice(crowd, func(i, j int) bool {
        return crowd[i].Name <= crowd[j].Name
    })

    needle := "Benni"
    idx := sort.Search(len(crowd), func(i int) bool {
        return string(crowd[i].Name) >= needle
    })

    if crowd[idx].Name == needle {
        fmt.Println("Found:", idx, crowd[idx])
    } else {
        fmt.Println("Found noting: ", idx)
    }
}

See: https://play.golang.org/p/47OPrjKb0g_c

How do I count the number of rows and columns in a file using bash?

You can use bash. Note for very large files in terms of GB, use awk/wc. However it should still be manageable in performance for files with a few MB.

declare -i count=0
while read
do
    ((count++))
done < file    
echo "line count: $count"

Creating a class object in c++

1) What is the difference between both the way of creating class objects.

a) pointer

Example* example=new Example();
// you get a pointer, and when you finish it use, you have to delete it:

delete example;

b) Simple declaration

Example example;

you get a variable, not a pointer, and it will be destroyed out of scope it was declared.

2) Singleton C++

This SO question may helps you

How to fix "set SameSite cookie to none" warning?

As the new feature comes, SameSite=None cookies must also be marked as Secure or they will be rejected.

One can find more information about the change on chromium updates and on this blog post

Note: not quite related directly to the question, but might be useful for others who landed here as it was my concern at first during development of my website:

if you are seeing the warning from question that lists some 3rd party sites (in my case it was google.com, huh) - that means they need to fix it and it's nothing to do with your site. Of course unless the warning mentions your site, in which case adding Secure should fix it.

Windows Task Scheduler doesn't start batch file task

For me, the problem was caused by the .bat included a cd to a network drive. This failed, and then the later call to the program in that network drive did nothing.

I figured this out by adding > log.txt in the Add arguments field of the Edit action window for the task.

git with development, staging and production branches

The thought process here is that you spend most of your time in development. When in development, you create a feature branch (off of development), complete the feature, and then merge back into development. This can then be added to the final production version by merging into production.

See A Successful Git Branching Model for more detail on this approach.

Change visibility of ASP.NET label with JavaScript

This is the easiest way I found:

        BtnUpload.Style.Add("display", "none");
        FileUploader.Style.Add("display", "none");
        BtnAccept.Style.Add("display", "inherit");
        BtnClear.Style.Add("display", "inherit");

I have the opposite in the Else, so it handles displaying them as well. This can go in the Page's Load or in a method to refresh the controls on the page.

How to prevent form from submitting multiple times from client side?

Disable the submit button soon after a click. Make sure you handle validations properly. Also keep an intermediate page for all processing or DB operations and then redirect to next page. THis makes sure that Refreshing the second page does not do another processing.

How do I get the directory of the PowerShell script I execute?

PowerShell 3 has the $PSScriptRoot automatic variable:

Contains the directory from which a script is being run.

In Windows PowerShell 2.0, this variable is valid only in script modules (.psm1). Beginning in Windows PowerShell 3.0, it is valid in all scripts.

Don't be fooled by the poor wording. PSScriptRoot is the directory of the current file.

In PowerShell 2, you can calculate the value of $PSScriptRoot yourself:

# PowerShell v2
$PSScriptRoot = Split-Path -Parent -Path $MyInvocation.MyCommand.Definition

PHP salt and hash SHA256 for login password

These examples are from php.net. Thanks to you, I also just learned about the new php hashing functions.

Read the php documentation to find out about the possibilities and best practices: http://www.php.net/manual/en/function.password-hash.php

Save a password hash:

$options = [
    'cost' => 11,
];
// Get the password from post
$passwordFromPost = $_POST['password'];

$hash = password_hash($passwordFromPost, PASSWORD_BCRYPT, $options);

// Now insert it (with login or whatever) into your database, use mysqli or pdo!

Get the password hash:

// Get the password from the database and compare it to a variable (for example post)
$passwordFromPost = $_POST['password'];
$hashedPasswordFromDB = ...;

if (password_verify($passwordFromPost, $hashedPasswordFromDB)) {
    echo 'Password is valid!';
} else {
    echo 'Invalid password.';
}

Bash: Syntax error: redirection unexpected

do it the simpler way,

direc=$(basename `pwd`)

Or use the shell

$ direc=${PWD##*/}

How to prune local tracking branches that do not exist on remote anymore

There's a neat NPM package that does it for you (and it should work cross platform).

Install it with: npm install -g git-removed-branches

And then git removed-branches will show you all the stale local branches, and git removed-branches --prune to actually delete them.

More info here.

How to set the authorization header using curl

This worked for me:

 curl -H "Authorization: Token xxxxxxxxxxxxxx" https://www.example.com/

No compiler is provided in this environment. Perhaps you are running on a JRE rather than a JDK?

In addition to answer above, I could say that just try to run Maven from the terminal (outside of Eclipse). In this way, if it builds from outside but not in Eclipse, you can understand that the problem should be in Eclipse.

Make EditText ReadOnly

If you just want to be able to copy text from the control but not be able to edit it you might want to use a TextView instead and set text is selectable.

code:

myTextView.setTextIsSelectable(true);
myTextView.setFocusable(true);
myTextView.setFocusableInTouchMode(true);
// myTextView.setSelectAllOnFocus(true);

xml:

<TextView
    android:textIsSelectable="true"
    android:focusable="true"
    android:focusableInTouchMode="true"     
    ...
/>
<!--android:selectAllOnFocus="true"-->


The documentation of setTextIsSelectable says:

When you call this method to set the value of textIsSelectable, it sets the flags focusable, focusableInTouchMode, clickable, and longClickable to the same value...

However I had to explicitly set focusable and focusableInTouchMode to true to make it work with touch input.

How to execute a shell script from C in Linux?

You can use system:

system("/usr/local/bin/foo.sh");

This will block while executing it using sh -c, then return the status code.

Batch Script to Run as Administrator

You could put it as a startup item... Startup items don't show off a prompt to run as an administrator at all.

Check this article Elevated Program Shortcut Without UAC rompt

How to disable keypad popup when on edittext?

If you are using Xamarin you can add this

Activity[(WindowSoftInputMode = SoftInput.StateAlwaysHidden)]

thereafter you can add this line in OnCreate() method

youredittext.ShowSoftInputOnFocus = false;

If the targeted device does not support the above code, you can use the code below in EditText click event

InputMethodManager Imm = (InputMethodManager)this.GetSystemService(Context.InputMethodService);
Imm.HideSoftInputFromWindow(youredittext.WindowToken, HideSoftInputFlags.None);

Singleton in Android

Tip: To create singleton class In Android Studio, right click in your project and open menu:

New -> Java Class -> Choose Singleton from dropdown menu

enter image description here

Android Gradle Could not reserve enough space for object heap

For Android Studio 1.3 : (Method 1)

Step 1 : Open gradle.properties file in your Android Studio project.

Step 2 : Add this line at the end of the file

org.gradle.jvmargs=-XX\:MaxHeapSize\=256m -Xmx256m

Above methods seems to work but if in case it won't then do this (Method 2)

Step 1 : Start Android studio and close any open project (File > Close Project).

Step 2 : On Welcome window, Go to Configure > Settings.

Step 3 : Go to Build, Execution, Deployment > Compiler

Step 4 : Change Build process heap size (Mbytes) to 1024 and Additional build process to VM Options to -Xmx512m.

Step 5 : Close or Restart Android Studio.

SOLVED - Andriod Studio 1.3 Gradle Could not reserve enough space for object heap Issue

How do I create a Linked List Data Structure in Java?

//slightly improved code without using collection framework

package com.test;

public class TestClass {

    private static Link last;
    private static Link first;

    public static void main(String[] args) {

        //Inserting
        for(int i=0;i<5;i++){
            Link.insert(i+5);
        }
        Link.printList();

        //Deleting
        Link.deletefromFirst();
        Link.printList();
    }


    protected  static class Link {
        private int data;
        private Link nextlink;

        public Link(int d1) {
            this.data = d1;
        }

        public static void insert(int d1) {
            Link a = new Link(d1);
            a.nextlink = null;
            if (first != null) {
                last.nextlink = a;
                last = a;
            } else {
                first = a;
                last = a;
            }
            System.out.println("Inserted -:"+d1);
        }

        public static void deletefromFirst() {
            if(null!=first)
            {
                System.out.println("Deleting -:"+first.data);
                first = first.nextlink;
            }
            else{
                System.out.println("No elements in Linked List");
            }
        }

        public static void printList() {
            System.out.println("Elements in the list are");
            System.out.println("-------------------------");
            Link temp = first;
            while (temp != null) {
                System.out.println(temp.data);
                temp = temp.nextlink;
            }
        }
    }
}

The name 'InitializeComponent' does not exist in the current context

I've encountered this a couple times and keep forgetting what causes it. I ran into this when I renamed the namespace on my code behind file but not in my XAML.

So check if you've done the same.

The namespace and class names need to match since they are both part of a partial class

namespace ZZZ
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow
    {
         //...
    }
}

<!-- XAML -->
<Window x:Class="ZZZ.MainWindow">

Convert UIImage to NSData and convert back to UIImage in Swift?

For safe execution of code, use if-let block with Data to prevent app crash & , as function UIImagePNGRepresentation returns an optional value.

if let img = UIImage(named: "TestImage.png") {
    if let data:Data = UIImagePNGRepresentation(img) {
       // Handle operations with data here...         
    }
}

Note: Data is Swift 3+ class. Use Data instead of NSData with Swift 3+

Generic image operations (like png & jpg both):

if let img = UIImage(named: "TestImage.png") {  //UIImage(named: "TestImage.jpg")
        if let data:Data = UIImagePNGRepresentation(img) {
               handleOperationWithData(data: data)     
        } else if let data:Data = UIImageJPEGRepresentation(img, 1.0) {
               handleOperationWithData(data: data)     
        }
}

*******
func handleOperationWithData(data: Data) {
     // Handle operations with data here...
     if let image = UIImage(data: data) {
        // Use image...
     }
}

By using extension:

extension UIImage {

    var pngRepresentationData: Data? {
        return UIImagePNGRepresentation(self)
    }

    var jpegRepresentationData: Data? {
        return UIImageJPEGRepresentation(self, 1.0)
    }
}

*******
if let img = UIImage(named: "TestImage.png") {  //UIImage(named: "TestImage.jpg")
      if let data = img.pngRepresentationData {
              handleOperationWithData(data: data)     
      } else if let data = img.jpegRepresentationData {
              handleOperationWithData(data: data)     
     }
}

*******
func handleOperationWithData(data: Data) {
     // Handle operations with data here...
     if let image = UIImage(data: data) {
        // Use image...
     }
}

Git 'fatal: Unable to write new index file'

This worked for me:

rm -f ./.git/index.lock

Where is the visual studio HTML Designer?

The default HTML editor (for static HTML) doesn't have a design view. To set the default editor to the Web forms editor which does have a design view,

  1. Right click any HTML file in the Solution Explorer in Visual Studio and click on Open with
  2. Select the HTML (web forms) editor
  3. Click on Set as default
  4. Click on the OK button

Once you have done that, all you need to do is click on design or split view as shown below:

Screenshot showing the location of said options

Putting HTML inside Html.ActionLink(), plus No Link Text?

Here is an uber expansion of @tvanfosson's answer. I was inspired by it and decide to make it more generic.

    public static MvcHtmlString NestedActionLink(this HtmlHelper htmlHelper, string linkText, string actionName,
        string controllerName, object routeValues = null, object htmlAttributes = null,
        RouteValueDictionary childElements = null)
    {
        var htmlAttributesDictionary = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes);

        if (childElements != null)
        {
            var urlHelper = new UrlHelper(htmlHelper.ViewContext.RequestContext);

            var anchorTag = new TagBuilder("a");
            anchorTag.MergeAttribute("href",
                routeValues == null
                    ? urlHelper.Action(actionName, controllerName)
                    : urlHelper.Action(actionName, controllerName, routeValues));
            anchorTag.MergeAttributes(htmlAttributesDictionary);
            TagBuilder childTag = null;

            if (childElements != null)
            {
                foreach (var childElement in childElements)
                {
                    childTag = new TagBuilder(childElement.Key.Split('|')[0]);
                    object elementAttributes;
                    childElements.TryGetValue(childElement.Key, out elementAttributes);

                    var attributes = HtmlHelper.AnonymousObjectToHtmlAttributes(elementAttributes);

                    foreach (var attribute in attributes)
                    {
                        switch (attribute.Key)
                        {
                            case "@class":
                                childTag.AddCssClass(attribute.Value.ToString());
                                break;
                            case "InnerText":
                                childTag.SetInnerText(attribute.Value.ToString());
                                break;
                            default:
                                childTag.MergeAttribute(attribute.Key, attribute.Value.ToString());
                                break;
                        }
                    }
                    childTag.ToString(TagRenderMode.SelfClosing);
                    if (childTag != null) anchorTag.InnerHtml += childTag.ToString();
                }                    
            }
            return MvcHtmlString.Create(anchorTag.ToString(TagRenderMode.Normal));
        }
        else
        {
            return htmlHelper.ActionLink(linkText, actionName, controllerName, routeValues, htmlAttributesDictionary);
        }
    }

Are 2 dimensional Lists possible in c#?

another work around which i have used was...

List<int []> itemIDs = new List<int[]>();

itemIDs.Add( new int[2] { 101, 202 } );

The library i'm working on has a very formal class structure and i didn't wan't extra stuff in there effectively for the privilege of recording two 'related' ints.

Relies on the programmer entering only a 2 item array but as it's not a common item i think it works.

How to add months to a date in JavaScript?

I would highly recommend taking a look at datejs. With it's api, it becomes drop dead simple to add a month (and lots of other date functionality):

var one_month_from_your_date = your_date_object.add(1).month();

What's nice about datejs is that it handles edge cases, because technically you can do this using the native Date object and it's attached methods. But you end up pulling your hair out over edge cases, which datejs has taken care of for you.

Plus it's open source!