Programs & Examples On #Rusage

How to get memory usage at runtime using C++?

The existing answers are better for how to get the correct value, but I can at least explain why getrusage isn't working for you.

man 2 getrusage:

The above struct [rusage] was taken from BSD 4.3 Reno. Not all fields are meaningful under Linux. Right now (Linux 2.4, 2.6) only the fields ru_utime, ru_stime, ru_minflt, ru_majflt, and ru_nswap are maintained.

How to convert HTML to PDF using iText

You can do it with the HTMLWorker class (deprecated) like this:

import com.itextpdf.text.html.simpleparser.HTMLWorker;
//...
try {
    String k = "<html><body> This is my Project </body></html>";
    OutputStream file = new FileOutputStream(new File("C:\\Test.pdf"));
    Document document = new Document();
    PdfWriter.getInstance(document, file);
    document.open();
    HTMLWorker htmlWorker = new HTMLWorker(document);
    htmlWorker.parse(new StringReader(k));
    document.close();
    file.close();
} catch (Exception e) {
    e.printStackTrace();
}

or using the XMLWorker, (download from this jar) using this code:

import com.itextpdf.tool.xml.XMLWorkerHelper;
//...
try {
    String k = "<html><body> This is my Project </body></html>";
    OutputStream file = new FileOutputStream(new File("C:\\Test.pdf"));
    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, file);
    document.open();
    InputStream is = new ByteArrayInputStream(k.getBytes());
    XMLWorkerHelper.getInstance().parseXHtml(writer, document, is);
    document.close();
    file.close();
} catch (Exception e) {
    e.printStackTrace();
}

Pressed <button> selector

Should we include a little JS? Because CSS was not basically created for this job. CSS was just a style sheet to add styles to the HTML, but its pseudo classes can do something that the basic CSS can't do. For example button:active active is pseudo.

Reference:

http://css-tricks.com/pseudo-class-selectors/ You can learn more about pseudo here!

Your code:

The code that you're having the basic but helpfull. And yes :active will only occur once the click event is triggered.

button {
font-size: 18px;
border: 2px solid gray;
border-radius: 100px;
width: 100px;
height: 100px;
}

button:active {
font-size: 18px;
border: 2px solid red;
border-radius: 100px;
width: 100px;
height: 100px;
}

This is what CSS would do, what rlemon suggested is good, but that would as he suggested would require a tag.

How to use CSS:

You can use :focus too. :focus would work once the click is made and would stay untill you click somewhere else, this was the CSS, you were trying to use CSS, so use :focus to make the buttons change.

What JS would do:

The JavaScript's jQuery library is going to help us for this code. Here is the example:

$('button').click(function () {
  $(this).css('border', '1px solid red');
}

This will make sure that the button stays red even if the click gets out. To change the focus type (to change the color of red to other) you can use this:

$('button').click(function () {
  $(this).css('border', '1px solid red');
  // find any other button with a specific id, and change it back to white like
  $('button#red').css('border', '1px solid white');
}

This way, you will create a navigation menu. Which will automatically change the color of the tabs as you click on them. :)

Hope you get the answer. Good luck! Cheers.

openssl s_client -cert: Proving a client certificate was sent to the server

I know this is an old question but it does not yet appear to have an answer. I've duplicated this situation, but I'm writing the server app, so I've been able to establish what happens on the server side as well. The client sends the certificate when the server asks for it and if it has a reference to a real certificate in the s_client command line. My server application is set up to ask for a client certificate and to fail if one is not presented. Here is the command line I issue:

Yourhostname here -vvvvvvvvvv s_client -connect <hostname>:443 -cert client.pem -key cckey.pem -CAfile rootcert.pem -cipher ALL:!ADH:!LOW:!EXP:!MD5:@STRENGTH -tls1 -state

When I leave out the "-cert client.pem" part of the command the handshake fails on the server side and the s_client command fails with an error reported. I still get the report "No client certificate CA names sent" but I think that has been answered here above.

The short answer then is that the server determines whether a certificate will be sent by the client under normal operating conditions (s_client is not normal) and the failure is due to the server not recognizing the CA in the certificate presented. I'm not familiar with many situations in which two-way authentication is done although it is required for my project.

You are clearly sending a certificate. The server is clearly rejecting it.

The missing information here is the exact manner in which the certs were created and the way in which the provider loaded the cert, but that is probably all wrapped up by now.

Laravel 5 Class 'form' not found

I have tried everything, but only this helped:

php artisan route:clear
php artisan cache:clear

Receive result from DialogFragment

Well its too late may be to answer but here is what i did to get results back from the DialogFragment. very similar to @brandon's answer. Here i am calling DialogFragment from a fragment, just place this code where you are calling your dialog.

FragmentManager fragmentManager = getFragmentManager();
            categoryDialog.setTargetFragment(this,1);
            categoryDialog.show(fragmentManager, "dialog");

where categoryDialog is my DialogFragment which i want to call and after this in your implementation of dialogfragment place this code where you are setting your data in intent. The value of resultCode is 1 you can set it or use system Defined.

            Intent intent = new Intent();
            intent.putExtra("listdata", stringData);
            getTargetFragment().onActivityResult(getTargetRequestCode(), resultCode, intent);
            getDialog().dismiss();

now its time to get back to to the calling fragment and implement this method. check for data validity or result success if you want with resultCode and requestCode in if condition.

 @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);        
        //do what ever you want here, and get the result from intent like below
        String myData = data.getStringExtra("listdata");
Toast.makeText(getActivity(),data.getStringExtra("listdata"),Toast.LENGTH_SHORT).show();
    }

Professional jQuery based Combobox control?

Why don't you try http://jqueryajax.codeplex.com/. It is a collection of ASP.NET controls that contains multicolumn drop down as well.

how to use concatenate a fixed string and a variable in Python

With python 3.6+:

msg['Subject'] = f"Auto Hella Restart Report {sys.argv[1]}"

Java: Date from unix timestamp

For 1280512800, multiply by 1000, since java is expecting milliseconds:

java.util.Date time=new java.util.Date((long)timeStamp*1000);

If you already had milliseconds, then just new java.util.Date((long)timeStamp);

From the documentation:

Allocates a Date object and initializes it to represent the specified number of milliseconds since the standard base time known as "the epoch", namely January 1, 1970, 00:00:00 GMT.

How to remove and clear all localStorage data

Using .one ensures this is done only once and not repeatedly.

$(window).one("focus", function() {
    localStorage.clear();
});

It is okay to put several document.ready event listeners (if you need other events to execute multiple times) as long as you do not overdo it, for the sake of readability.

.one is especially useful when you want local storage to be cleared only once the first time a web page is opened or when a mobile application is installed the first time.

   // Fired once when document is ready
   $(document).one('ready', function () {
       localStorage.clear();
   });

How to get browser width using JavaScript code?

Here is a shorter version of the function presented above:

function getWidth() {
    if (self.innerWidth) {
       return self.innerWidth;
    }
    else if (document.documentElement && document.documentElement.clientHeight){
        return document.documentElement.clientWidth;
    }
    else if (document.body) {
        return document.body.clientWidth;
    }
    return 0;
}

Select single item from a list

Maybe I'm missing something here, but usually calling .SingleOrDefault() is the way to go to return either the single element in the list, or a default value (null for reference or nullable types) if the list is empty. It generates an exception if the list contains more than one element.

Use FirstOrDefault() to cover the case where you could have more than one.

What exactly is node.js used for?

What can we build with NodeJS:

  • REST APIs and Backend Applications
  • Real-Time services (Chat, Games etc)
  • Blogs, CMS, Social Applications.
  • Utilities and Tools
  • Anything that is not CPU intensive.

How to customize an end time for a YouTube video?

Use parameters(seconds) i.e. youtube.com/v/VIDEO_ID?start=4&end=117

Live DEMO:
https://puvox.software/software/youtube_trimmer.php

Loop through files in a folder in matlab

Looping through all the files in the folder is relatively easy:

files = dir('*.csv');
for file = files'
    csv = load(file.name);
    % Do some stuff
end

What is the best way to determine a session variable is null or empty in C#?

The 'as' notation in c# 3.0 is very clean. Since all session variables are nullable objects, this lets you grab the value and put it into your own typed variable without worry of throwing an exception. Most objects can be handled this way.

string mySessionVar = Session["mySessionVar"] as string;

My concept is that you should pull your Session variables into local variables and then handle them appropriately. Always assume your Session variables could be null and never cast them into a non-nullable type.

If you need a non-nullable typed variable you can then use TryParse to get that.

int mySessionInt;
if (!int.TryParse(mySessionVar, out mySessionInt)){
   // handle the case where your session variable did not parse into the expected type 
   // e.g. mySessionInt = 0;
}

How to set text color to a text view programmatically

Great answers. Adding one that loads the color from an Android resources xml but still sets it programmatically:

textView.setTextColor(getResources().getColor(R.color.some_color));

Please note that from API 23, getResources().getColor() is deprecated. Use instead:

textView.setTextColor(ContextCompat.getColor(context, R.color.some_color));

where the required color is defined in an xml as:

<resources>
  <color name="some_color">#bdbdbd</color>
</resources>

Update:

This method was deprecated in API level 23. Use getColor(int, Theme) instead.

Check this.

Rails: How does the respond_to block work?

What type of variable is format?

From a java POV, format is an implemtation of an anonymous interface. This interface has one method named for each mime type. When you invoke one of those methods (passing it a block), then if rails feels that the user wants that content type, then it will invoke your block.

The twist, of course, is that this anonymous glue object doesn't actually implement an interface - it catches the method calls dynamically and works out if its the name of a mime type that it knows about.

Personally, I think it looks weird: the block that you pass in is executed. It would make more sense to me to pass in a hash of format labels and blocks. But - that's how its done in RoR, it seems.

POST request with a simple string in body with Alamofire

I modified @Silmaril's answer to extend Alamofire's Manager. This solution uses EVReflection to serialize an object directly:

//Extend Alamofire so it can do POSTs with a JSON body from passed object
extension Alamofire.Manager {
    public class func request(
        method: Alamofire.Method,
        _ URLString: URLStringConvertible,
          bodyObject: EVObject)
        -> Request
    {
        return Manager.sharedInstance.request(
            method,
            URLString,
            parameters: [:],
            encoding: .Custom({ (convertible, params) in
                let mutableRequest = convertible.URLRequest.copy() as! NSMutableURLRequest
                mutableRequest.HTTPBody = bodyObject.toJsonString().dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
                return (mutableRequest, nil)
            })
        )
    }
}

Then you can use it like this:

Alamofire.Manager.request(.POST, endpointUrlString, bodyObject: myObjectToPost)

Oracle date format picture ends before converting entire input string

Perhaps you should check NLS_DATE_FORMAT and use the date string conforming the format. Or you can use to_date function within the INSERT statement, like the following:

insert into visit
values(123456, 
       to_date('19-JUN-13', 'dd-mon-yy'),
       to_date('13-AUG-13 12:56 A.M.', 'dd-mon-yyyy hh:mi A.M.'));

Additionally, Oracle DATE stores date and time information together.

'Access-Control-Allow-Origin' issue when API call made from React (Isomorphic app)

I was having the same problem with the fetch command. A quick look at the docs from here tells us this:

If the server you are requesting from doesn't support CORS, you should get an error in the console indicating that the cross-origin request is blocked due to the CORS Access-Control-Allow-Origin header being missing.

You can use no-cors mode to request opaque resources.

fetch('https://bar.com/data.json', {
  mode: 'no-cors' // 'cors' by default
})
.then(function(response) {
  // Do something with response
});

Multiple left joins on multiple tables in one query

The JOIN statements are also part of the FROM clause, more formally a join_type is used to combine two from_item's into one from_item, multiple one of which can then form a comma-separated list after the FROM. See http://www.postgresql.org/docs/9.1/static/sql-select.html .

So the direct solution to your problem is:

SELECT something
FROM
    master as parent LEFT JOIN second as parentdata
        ON parent.secondary_id = parentdata.id,
    master as child LEFT JOIN second as childdata
        ON child.secondary_id = childdata.id
WHERE parent.id = child.parent_id AND parent.parent_id = 'rootID'

A better option would be to only use JOIN's, as it has already been suggested.

How to custom switch button?

You can use the regular Switch widget and just call setTextOn() and setTextOff(), or use the android:textOn and android:textOff attributes.

Does Spring @Transactional attribute work on a private method?

By default the @Transactional attribute works only when calling an annotated method on a reference obtained from applicationContext.

public class Bean {
  public void doStuff() {
    doTransactionStuff();
  }
  @Transactional
  public void doTransactionStuff() {

  }
}

This will open a transaction:

Bean bean = (Bean)appContext.getBean("bean");
bean.doTransactionStuff();

This will not:

Bean bean = (Bean)appContext.getBean("bean");
bean.doStuff();

Spring Reference: Using @Transactional

Note: In proxy mode (which is the default), only 'external' method calls coming in through the proxy will be intercepted. This means that 'self-invocation', i.e. a method within the target object calling some other method of the target object, won't lead to an actual transaction at runtime even if the invoked method is marked with @Transactional!

Consider the use of AspectJ mode (see below) if you expect self-invocations to be wrapped with transactions as well. In this case, there won't be a proxy in the first place; instead, the target class will be 'weaved' (i.e. its byte code will be modified) in order to turn @Transactional into runtime behavior on any kind of method.

PHP Configuration: It is not safe to rely on the system's timezone settings

Tchalvak, who commented on the original question, hit the nail on the head for me. I've been editing (I use Debian):

/etc/php5/apache2/php.ini

...which had the correct timezone for me and was the only .ini file being loaded with date.timezone within it, but I was receiving the above error when I ran a script through Bash. I had no idea that I should have been editing:

/etc/php5/cli/php.ini

as well. (Well, for me it was 'as well', for you it might be different of course, but I'm going to keep my Apache and CLI versions of php.ini synchronised now).

How to add a “readonly” attribute to an <input>?

Check the code below:

<input id="mail">

<script>

 document.getElementById('mail').readOnly = true; // makes input readonline
 document.getElementById('mail').readOnly = false; // makes input writeable again

</script>

How do I change the JAVA_HOME for ant?

JAVA_HOME needs to point to a JDK home if you're trying to compile code. Check to see if '/usr/tomcat/jre/bin/javac' exists. I doubt it does.

If you don't have a JDK, then you can work around it by getting the ECJ (eclipse compiler) library, dropping it into '~/.ant/lib' and adding a system property to the command-line to use that compiler - check the Ant manual for details.

http://ant.apache.org/

How do I perform the SQL Join equivalent in MongoDB?

We can merge two collection by using mongoDB sub query. Here is example, Commentss--

`db.commentss.insert([
  { uid:12345, pid:444, comment:"blah" },
  { uid:12345, pid:888, comment:"asdf" },
  { uid:99999, pid:444, comment:"qwer" }])`

Userss--

db.userss.insert([
  { uid:12345, name:"john" },
  { uid:99999, name:"mia"  }])

MongoDB sub query for JOIN--

`db.commentss.find().forEach(
    function (newComments) {
        newComments.userss = db.userss.find( { "uid": newComments.uid } ).toArray();
        db.newCommentUsers.insert(newComments);
    }
);`

Get result from newly generated Collection--

db.newCommentUsers.find().pretty()

Result--

`{
    "_id" : ObjectId("5511236e29709afa03f226ef"),
    "uid" : 12345,
    "pid" : 444,
    "comment" : "blah",
    "userss" : [
        {
            "_id" : ObjectId("5511238129709afa03f226f2"),
            "uid" : 12345,
            "name" : "john"
        }
    ]
}
{
    "_id" : ObjectId("5511236e29709afa03f226f0"),
    "uid" : 12345,
    "pid" : 888,
    "comment" : "asdf",
    "userss" : [
        {
            "_id" : ObjectId("5511238129709afa03f226f2"),
            "uid" : 12345,
            "name" : "john"
        }
    ]
}
{
    "_id" : ObjectId("5511236e29709afa03f226f1"),
    "uid" : 99999,
    "pid" : 444,
    "comment" : "qwer",
    "userss" : [
        {
            "_id" : ObjectId("5511238129709afa03f226f3"),
            "uid" : 99999,
            "name" : "mia"
        }
    ]
}`

Hope so this will help.

Regular expression for checking if capital letters are found consecutively in a string?

Whenever one writes [A-Z] or [a-z], one explicitly commits to processing nothing but 7-bit ASCII data from the 1960s. If that’s really ok, then fine. But if it’s not ok, then Unicode character properties exist to help you with handling modern character data.

There are three cases in Unicode, not two. Furthermore, you also have noncased letters. Letters in general are specified by the \pL property, and each of these also belongs to exactly one of five subcategories:

  1. uppercase letters, specified with \p{Lu}; eg: AÇ?ÞSSS??ST
  2. titlecase letters, specified with \p{Lt}; eg: ??Ss?St (actually Ss and St are an upper- and then a lowercase letter, but they are what you get if you ask for the titlecase of ß and ?, respectively)
  3. lowercase letters, specified with \p{Ll}; eg: aaç??sþß??
  4. modifier letters, specified with \p{Lm}; eg: ????"'???
  5. other letters, specified with \p{Lo}; eg: ?????

You can take the complement of any of these, but do be careful, because something like \P{Lu} does not mean a letter that isn’t uppercase! It means any character that isn’t an uppercase letter.

For a letter that’s either of uppercase or titlecase, use [\p{Lu}\p{Lt}]. So you could use for your pattern:

 ^([\p{Lu}\p{Lt}]\p{Ll}+)+$

If you don’t mean to limit the letters following the first to the “casing” letters alone, then you might prefer:

 ^([\p{Lu}\p{Lt}][\p{Ll}\p{Lm}\p{Lo}]+)+$

If you’re trying to match so-called “CamelCase” identifiers, then the actual rules depend on the programming language, but usually include the underscore character and the decimal numbers (\p{Nd}), and may also include a literal dollar sign and other language-dependent characters. If so, you may wish to add some of these to one or the other of the two character classes provided above.

For example, you may wish to add underscore to both but digits only to the second, leaving you with:

 ^([_\p{Lu}\p{Lt}][_\p{Nd}\p{Ll}\p{Lm}\p{Lo}]+)+$

If, though, you are dealing with certain “words” from various RFCs and ISO standards, these are often specified as containing ASCII only. If so, you can get by with the literal [A-Z] idea. It’s just not kind to impose that restriction if it doesn’t actually exist.

ORA-12528: TNS Listener: all appropriate instances are blocking new connections. Instance "CLRExtProc", status UNKNOWN

If you are using 11G XE with Windows, along with tns listener restart, make sure Windows Event Log service is started.

Stuck while installing Visual Studio 2015 (Update for Microsoft Windows (KB2999226))

Same thing happened to me and I got it working doing this:

  • Do not cancel the installation (using the cancel button), instead force showdown your computer so the process is killed and you get a reboot.
  • After the reboot, just start the install process again.

This worked for me.

Reading an Excel file in python using pandas

Here is an updated method with syntax that is more common in python code. It also prevents you from opening the same file multiple times.

import pandas as pd

sheet1, sheet2 = None, None
with pd.ExcelFile("PATH\FileName.xlsx") as reader:
    sheet1 = pd.read_excel(reader, sheet_name='Sheet1')
    sheet2 = pd.read_excel(reader, sheet_name='Sheet2')

https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.read_excel.html

Select box arrow style

for any1 using ie8 and dont want to use a plugin i've made something inspired by Rohit Azad and Bacotasan's blog, i just added a span using JS to show the selected value.

the html:

<div class="styled-select">
   <select>
      <option>Here is the first option</option>
      <option>The second option</option>
   </select>
   <span>Here is the first option</span>
</div>

the css (i used only an arrow for BG but you could put a full image and drop the positioning):

.styled-select div
{
    display:inline-block;
    border: 1px solid darkgray;
    width:100px;
    background:url("/Style Library/Nifgashim/Images/drop_arrrow.png") no-repeat 10px 10px;
    position:relative;
}

.styled-select div select
{
    height: 30px;
    width: 100px;
    font-size:14px;
    font-family:ariel;

    -moz-opacity: 0.00;
    opacity: .00;
    filter: alpha(opacity=00);
}

.styled-select div span
{
    position: absolute;
    right: 10px;
    top: 6px;
    z-index: -5;
}

the js:

$(".styled-select select").change(function(e){
     $(".styled-select span").html($(".styled-select select").val());
});

Why are arrays of references illegal?

When you store something in an array , its size needs to be known (since array indexing relies on the size). Per the C++ standard It is unspecified whether or not a reference requires storage, as a result indexing an array of references would not be possible.

SQL Server: Multiple table joins with a WHERE clause

try this

DECLARE @Application TABLE(Id INT PRIMARY KEY, NAME VARCHAR(20))
INSERT @Application ( Id, NAME )
VALUES  ( 1,'Word' ), ( 2,'Excel' ), ( 3,'PowerPoint' )
DECLARE @software TABLE(Id INT PRIMARY KEY, ApplicationId INT, Version INT)
INSERT @software ( Id, ApplicationId, Version )
VALUES  ( 1,1, 2003 ), ( 2,1,2007 ), ( 3,2, 2003 ), ( 4,2,2007 ),( 5,3, 2003 ), ( 6,3,2007 )

DECLARE @Computer TABLE(Id INT PRIMARY KEY, NAME VARCHAR(20))
INSERT @Computer ( Id, NAME )
VALUES  ( 1,'Name1' ), ( 2,'Name2' )

DECLARE @Software_Computer  TABLE(Id INT PRIMARY KEY, SoftwareId int, ComputerId int)
INSERT @Software_Computer ( Id, SoftwareId, ComputerId )
VALUES  ( 1,1, 1 ), ( 2,4,1 ), ( 3,2, 2 ), ( 4,5,2 )

SELECT Computer.Name ComputerName, Application.Name ApplicationName, MAX(Software2.Version) Version
FROM @Application Application 
JOIN @Software Software
    ON Application.ID = Software.ApplicationID
CROSS JOIN @Computer Computer
LEFT JOIN @Software_Computer Software_Computer
    ON Software_Computer.ComputerId = Computer.Id AND Software_Computer.SoftwareId = Software.Id
LEFT JOIN @Software Software2
    ON Software2.ID = Software_Computer.SoftwareID
WHERE Computer.ID = 1 
GROUP BY Computer.Name, Application.Name

How do I start my app on startup?

This is how to make an activity start running after android device reboot:

Insert this code in your AndroidManifest.xml file, within the <application> element (not within the <activity> element):

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

<receiver
    android:enabled="true"
    android:exported="true" 
    android:name="yourpackage.yourActivityRunOnStartup"
    android:permission="android.permission.RECEIVE_BOOT_COMPLETED">

    <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
        <action android:name="android.intent.action.QUICKBOOT_POWERON" />
        <category android:name="android.intent.category.DEFAULT" />
    </intent-filter>

</receiver>

Then create a new class yourActivityRunOnStartup (matching the android:name specified for the <receiver> element in the manifest):

package yourpackage;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;

public class yourActivityRunOnStartup extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
            Intent i = new Intent(context, MainActivity.class);
            i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(i);
        }
    }

}

Note: The call i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); is important because the activity is launched from a context outside the activity. Without this, the activity will not start.

Also, the values android:enabled, android:exported and android:permission in the <receiver> tag do not seem mandatory. The app receives the event without these values. See the example here.

What is the difference between "px", "dip", "dp" and "sp"?

Moreover you should have clear understanding about the following concepts:

Screen size:

Actual physical size, measured as the screen's diagonal. For simplicity, Android groups all actual screen sizes into four generalized sizes: small, normal, large, and extra large.

Screen density:

The quantity of pixels within a physical area of the screen; usually referred to as dpi (dots per inch). For example, a "low" density screen has fewer pixels within a given physical area, compared to a "normal" or "high" density screen. For simplicity, Android groups all actual screen densities into four generalized densities: low, medium, high, and extra high.

Orientation:

The orientation of the screen from the user's point of view. This is either landscape or portrait, meaning that the screen's aspect ratio is either wide or tall, respectively. Be aware that not only do different devices operate in different orientations by default, but the orientation can change at runtime when the user rotates the device.

Resolution:

The total number of physical pixels on a screen. When adding support for multiple screens, applications do not work directly with resolution; applications should be concerned only with screen size and density, as specified by the generalized size and density groups.

Density-independent pixel (dp):

A virtual pixel unit that you should use when defining UI layout, to express layout dimensions or position in a density-independent way. The density-independent pixel is equivalent to one physical pixel on a 160 dpi screen, which is the baseline density assumed by the system for a "medium" density screen. At runtime, the system transparently handles any scaling of the dp units, as necessary, based on the actual density of the screen in use. The conversion of dp units to screen pixels is simple: px = dp * (dpi / 160). For example, on a 240 dpi screen, 1 dp equals 1.5 physical pixels. You should always use dp units when defining your application's UI, to ensure proper display of your UI on screens with different densities.

Reference: Android developers site

What does the "@" symbol do in SQL?

You may be used to MySQL's syntax: Microsoft SQL @ is the same as the MySQL's ?

How do I use sudo to redirect output to a location I don't have permission to write to?

A trick I figured out myself was

sudo ls -hal /root/ | sudo dd of=/root/test.out

Linq code to select one item

Just to make someone's life easier, the linq query with lambda expression

(from x in Items where x.Id == 123 select x).FirstOrDefault();

does result in an SQL query with a select top (1) in it.

How should I deal with "package 'xxx' is not available (for R version x.y.z)" warning?

1. You can't spell

The first thing to test is have you spelled the name of the package correctly? Package names are case sensitive in R.


2. You didn't look in the right repository

Next, you should check to see if the package is available. Type

setRepositories()

See also ?setRepositories.

To see which repositories R will look in for your package, and optionally select some additional ones. At the very least, you will usually want CRAN to be selected, and CRAN (extras) if you use Windows, and the Bioc* repositories if you do any [gen/prote/metabol/transcript]omics biological analyses.

To permanently change this, add a line like setRepositories(ind = c(1:6, 8)) to your Rprofile.site file.


3. The package is not in the repositories you selected

Return all the available packages using

ap <- available.packages()

See also Names of R's available packages, ?available.packages.

Since this is a large matrix, you may wish to use the data viewer to examine it. Alternatively, you can quickly check to see if the package is available by testing against the row names.

View(ap)
"foobarbaz" %in% rownames(ap)

Alternatively, the list of available packages can be seen in a browser for CRAN, CRAN (extras), Bioconductor, R-forge, RForge, and github.

Another possible warnings message you may get when interacting with CRAN mirrors is:

Warning: unable to access index for repository

Which may indicate the selected CRAN repository is currently be unavailable. You can select a different mirror with chooseCRANmirror() and try the installation again.


There are several reasons why a package may not be available.


4. You don't want a package

Perhaps you don't really want a package. It is common to be confused about the difference between a package and a library, or a package and a dataset.

A package is a standardized collection of material extending R, e.g. providing code, data, or documentation. A library is a place (directory) where R knows to find packages it can use

To see available datasets, type

data()

5. R or Bioconductor is out of date

It may have a dependency on a more recent version of R (or one of the packages that it imports/depends upon does). Look at

ap["foobarbaz", "Depends"]

and consider updating your R installation to the current version. On Windows, this is most easily done via the installr package.

library(installr)
updateR()

(Of course, you may need to install.packages("installr") first.)

Equivalently for Bioconductor packages, you may need to update your Bioconductor installation.

source("http://bioconductor.org/biocLite.R")
biocLite("BiocUpgrade")

6. The package is out of date

It may have been archived (if it is no longer maintained and no longer passes R CMD check tests).

In this case, you can load an old version of the package using install_version()

library(remotes)
install_version("foobarbaz", "0.1.2")

An alternative is to install from the github CRAN mirror.

library(remotes)
install_github("cran/foobarbaz")

7. There is no Windows/OS X/Linux binary

It may not have a Windows binary due to requiring additional software that CRAN does not have. Additionally, some packages are available only via the sources for some or all platforms. In this case, there may be a version in the CRAN (extras) repository (see setRepositories above).

If the package requires compiling code (e.g. C, C++, FORTRAN) then on Windows install Rtools or on OS X install the developer tools accompanying XCode, and install the source version of the package via:

install.packages("foobarbaz", type = "source")

# Or equivalently, for Bioconductor packages:
source("http://bioconductor.org/biocLite.R")
biocLite("foobarbaz", type = "source")

On CRAN, you can tell if you'll need special tools to build the package from source by looking at the NeedsCompilation flag in the description.


8. The package is on github/Bitbucket/Gitorious

It may have a repository on Github/Bitbucket/Gitorious. These packages require the remotes package to install.

library(remotes)
install_github("packageauthor/foobarbaz")
install_bitbucket("packageauthor/foobarbaz")
install_gitorious("packageauthor/foobarbaz")

(As with installr, you may need to install.packages("remotes") first.)


9. There is no source version of the package

Although the binary version of your package is available, the source version is not. You can turn off this check by setting

options(install.packages.check.source = "no")

as described in this SO answer by imanuelc and the Details section of ?install.packages.


10. The package is in a non-standard repository

Your package is in a non-standard repository (e.g. Rbbg). Assuming that it is reasonably compliant with CRAN standards, you can still download it using install.packages; you just have to specify the repository URL.

install.packages("Rbbg", repos = "http://r.findata.org")

RHIPE on the other hand isn't in a CRAN-like repository and has its own installation instructions.

How to tell if node.js is installed or not

Open the command prompt in Windows or terminal in Linux and Mac.Type

node -v

If node is install it will show its version.For eg.,

v6.9.5

Else download it from nodejs.org

How to get the system uptime in Windows?

I use this little PowerShell snippet:

function Get-SystemUptime {
    $operatingSystem = Get-WmiObject Win32_OperatingSystem
    "$((Get-Date) - ([Management.ManagementDateTimeConverter]::ToDateTime($operatingSystem.LastBootUpTime)))"
}

which then yields something like the following:

PS> Get-SystemUptime
6.20:40:40.2625526

#pragma mark in Swift?

Try this:

// MARK: Reload TableView

func reloadTableView(){

    tableView.reload()
}

How to use Servlets and Ajax?

Ajax (also AJAX) an acronym for Asynchronous JavaScript and XML) is a group of interrelated web development techniques used on the client-side to create asynchronous web applications. With Ajax, web applications can send data to, and retrieve data from, a server asynchronously Below is example code:

Jsp page java script function to submit data to servlet with two variable firstName and lastName:

function onChangeSubmitCallWebServiceAJAX()
    {
      createXmlHttpRequest();
      var firstName=document.getElementById("firstName").value;
      var lastName=document.getElementById("lastName").value;
      xmlHttp.open("GET","/AJAXServletCallSample/AjaxServlet?firstName="
      +firstName+"&lastName="+lastName,true)
      xmlHttp.onreadystatechange=handleStateChange;
      xmlHttp.send(null);

    }

Servlet to read data send back to jsp in xml format ( You could use text as well. Just you need to change response content to text and render data on javascript function.)

/**
 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
 */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

    String firstName = request.getParameter("firstName");
    String lastName = request.getParameter("lastName");

    response.setContentType("text/xml");
    response.setHeader("Cache-Control", "no-cache");
    response.getWriter().write("<details>");
    response.getWriter().write("<firstName>"+firstName+"</firstName>");
    response.getWriter().write("<lastName>"+lastName+"</lastName>");
    response.getWriter().write("</details>");
}

How to conditional format based on multiple specific text in Excel

Suppose your "Don't Check" list is on Sheet2 in cells A1:A100, say, and your current client IDs are in Sheet1 in Column A.

What you would do is:

  1. Select the whole data table you want conditionally formatted in Sheet1
  2. Click Conditional Formatting > New Rule > Use a Formula to determine which cells to format
  3. In the formula bar, type in =ISNUMBER(MATCH($A1,Sheet2!$A$1:$A$100,0)) and select how you want those rows formatted

And that should do the trick.

How do I pass JavaScript variables to PHP?

Your code has a few things wrong with it.

  • You define a JavaScript function, func_load3(), but do not call it.
  • Your function is defined in the wrong place. When it is defined in your page, the HTML objects it refers to have not yet been loaded. Most JavaScript code checks whether the document is fully loaded before executing, or you can just move your code past the elements it refers to in the page.
  • Your form has no means to submit it. It needs a submit button.
  • You do not check whether your form has been submitted.

It is possible to set a JavaScript variable in a hidden variable in a form, then submit it, and read the value back in PHP. Here is a simple example that shows this:

<?php
if (isset($_POST['hidden1'])) {
   echo "You submitted {$_POST['hidden1']}";
   die;
}

echo <<<HTML
   <form name="myform" action="{$_SERVER['PHP_SELF']}" method="post" id="myform">
      <input type="submit" name="submit" value="Test this mess!" />
      <input type="hidden" name="hidden1" id="hidden1" />
   </form>

   <script type="text/javascript">
      document.getElementById("hidden1").value = "This is an example";
   </script>
HTML;
?>

Error You must specify a region when running command aws ecs list-container-instances

I think you need to use for example:

aws ecs list-container-instances --cluster default --region us-east-1

This depends of your region of course.

Change Bootstrap tooltip color

This worked for me .

.tooltip .arrow:before {
    border-top-color: #008ec3 !important;
}

.tooltip .tooltip-inner {
    background-color: #008ec3;
}

Why can I not switch branches?

You end up with both modified in the output of git status if there were conflicts produced by a merge. git isn't letting you change branch until you've resolved these conflicts. If you edit that file, you should see some conflict markers in it - there's a guide to resolving those conflicts in the git manual. (Since kernel.org is currently down, you can find that guide here instead.)

Alternatively, if you think the merge was a mistake, you could undo it with: git reset --merge

Dynamically Add Images React Webpack

Using url-loader, described here (SurviveJS - Loading Images), you can then use in your code :

import LogoImg from 'YOUR_PATH/logo.png';

and

<img src={LogoImg}/>

Edit: a precision, images are inlined in the js archive with this technique. It can be worthy for small images, but use the technique wisely.

Can't escape the backslash with regex?

The backslash \ is the escape character for regular expressions. Therefore a double backslash would indeed mean a single, literal backslash.

\ (backslash) followed by any of [\^$.|?*+(){} escapes the special character to suppress its special meaning.

ref : http://www.regular-expressions.info/reference.html

How to fix Uncaught InvalidValueError: setPosition: not a LatLng or LatLngLiteral: in property lat: not a number?

You're probably passing null value if you're loading the coordinates dynamically, set a check before you call the map loader ie: if(mapCords){loadMap}

Concatenate a list of pandas dataframes together

You also can do it with functional programming:

from functools import reduce
reduce(lambda df1, df2: df1.merge(df2, "outer"), mydfs)

Javascript - Track mouse position

Here’s a combination of the two requirements: track the mouse position, every 100 milliseconds:

var period = 100,
    tracking;

window.addEventListener("mousemove", function(e) {
    if (!tracking) {
        return;
    }

    console.log("mouse location:", e.clientX, e.clientY)
    schedule();
});

schedule();

function schedule() {
    tracking = false;

    setTimeout(function() {
        tracking = true;
    }, period);
}

This tracks & acts on the mouse position, but only every period milliseconds.

How can I get my webapp's base URL in ASP.NET MVC?

This is a conversion of an asp.net property to MVC . It's a pretty much all singing all dancing get root url method.

Declare a helper class:

namespace MyTestProject.Helpers
{
    using System.Web;

    public static class PathHelper
    {
        public static string FullyQualifiedApplicationPath(HttpRequestBase httpRequestBase)
        {
            string appPath = string.Empty;

            if (httpRequestBase != null)
            {
                //Formatting the fully qualified website url/name
                appPath = string.Format("{0}://{1}{2}{3}",
                            httpRequestBase.Url.Scheme,
                            httpRequestBase.Url.Host,
                            httpRequestBase.Url.Port == 80 ? string.Empty : ":" + httpRequestBase.Url.Port,
                            httpRequestBase.ApplicationPath);
            }

            if (!appPath.EndsWith("/"))
            {
                appPath += "/";
            }

            return appPath;
        }
    }
}

Usage:

To use from a controller:

PathHelper.FullyQualifiedApplicationPath(ControllerContext.RequestContext.HttpContext.Request)

To use in a view:

@using MyTestProject.Helpers

PathHelper.FullyQualifiedApplicationPath(Request)

How can I convert JSON to a HashMap using Gson?

This code works:

Gson gson = new Gson(); 
String json = "{\"k1\":\"v1\",\"k2\":\"v2\"}";
Map<String,Object> map = new HashMap<String,Object>();
map = (Map<String,Object>) gson.fromJson(json, map.getClass());

Mysql: Select rows from a table that are not in another

A standard LEFT JOIN could resolve the problem and, if the fields on join are indexed,
should also be faster

SELECT *
FROM Table1 as t1 LEFT JOIN Table2 as t2 
ON t1.FirstName = t2.FirstName AND t1.LastName=t2.LastName
WHERE t2.BirthDate Is Null

Change auto increment starting number?

You can use ALTER TABLE to change the auto_increment initial value:

ALTER TABLE tbl AUTO_INCREMENT = 5;

See the MySQL reference for more details.

Git - What is the difference between push.default "matching" and "simple"

Git v2.0 Release Notes

Backward compatibility notes

When git push [$there] does not say what to push, we have used the traditional "matching" semantics so far (all your branches were sent to the remote as long as there already are branches of the same name over there). In Git 2.0, the default is now the "simple" semantics, which pushes:

  • only the current branch to the branch with the same name, and only when the current branch is set to integrate with that remote branch, if you are pushing to the same remote as you fetch from; or

  • only the current branch to the branch with the same name, if you are pushing to a remote that is not where you usually fetch from.

You can use the configuration variable "push.default" to change this. If you are an old-timer who wants to keep using the "matching" semantics, you can set the variable to "matching", for example. Read the documentation for other possibilities.

When git add -u and git add -A are run inside a subdirectory without specifying which paths to add on the command line, they operate on the entire tree for consistency with git commit -a and other commands (these commands used to operate only on the current subdirectory). Say git add -u . or git add -A . if you want to limit the operation to the current directory.

git add <path> is the same as git add -A <path> now, so that git add dir/ will notice paths you removed from the directory and record the removal. In older versions of Git, git add <path> used to ignore removals. You can say git add --ignore-removal <path> to add only added or modified paths in <path>, if you really want to.

C# Checking if button was clicked

button1, button2 and button3 have same even handler

private void button1_Click(Object sender, EventArgs e)
    {
        Button btnSender = (Button)sender;
        if (btnSender == button1 || btnSender == button2)
        {
            //some code here
        }
        else if (btnSender == button3)
            //some code here
    }

Padding In bootstrap

I have not used Bootstrap but I worked on Zurb Foundation. On that I used to add space like this.

<div id="main" class="container" role="main">
    <div class="row">

        <div class="span5 offset1">
            <h2>Welcome</h2>
            <p>Hello and welcome to my website.</p>
        </div>
        <div class="span6">
            Image Here (TODO)
        </div>
    </div>

Visit this link: http://getbootstrap.com/2.3.2/scaffolding.html and read the section: Offsetting columns.

I think I know what you are doing wrong. If you are applying padding to the span6 like this:

<div class="span6" style="padding-left:5px;">
    <h2>Welcome</h2>
    <p>Hello and welcome to my website.</p>
</div>

It is wrong. What you have to do is add padding to the elements inside:

<div class="span6">
    <h2 style="padding-left:5px;">Welcome</h2>
    <p  style="padding-left:5px;">Hello and welcome to my website.</p>
</div>

Why do you need to put #!/bin/bash at the beginning of a script file?

It's called a shebang. In unix-speak, # is called sharp (like in music) or hash (like hashtags on twitter), and ! is called bang. (You can actually reference your previous shell command with !!, called bang-bang). So when put together, you get haSH-BANG, or shebang.

The part after the #! tells Unix what program to use to run it. If it isn't specified, it will try with bash (or sh, or zsh, or whatever your $SHELL variable is) but if it's there it will use that program. Plus, # is a comment in most languages, so the line gets ignored in the subsequent execution.

git diff file against its last change

If you are fine using a graphical tool this works very well:

gitk <file>

gitk now shows all commits where the file has been updated. Marking a commit will show you the diff against the previous commit in the list. This also works for directories, but then you also get to select the file to diff for the selected commit. Super useful!

How to generate List<String> from SQL query?

If you would like to query all columns

List<Users> list_users = new List<Users>();
MySqlConnection cn = new MySqlConnection("connection");
MySqlCommand cm = new MySqlCommand("select * from users",cn);
try
{
    cn.Open();
    MySqlDataReader dr = cm.ExecuteReader();
    while (dr.Read())
    {
        list_users.Add(new Users(dr));
    }
}
catch { /* error */ }
finally { cn.Close(); }

The User's constructor would do all the "dr.GetString(i)"

How to load my app from Eclipse to my Android phone instead of AVD

For those who are trying to find how to enable debugging on devices running Jelly Bean 4.2 (e.g Google Nexus), you have to go to Settings > Apps > About tablet and tap the text "Build number" 7 times slowly. Go back to the now available Settings > Developer options and check USB debugging as stated in previous posts.

VBA setting the formula for a cell

If Cells(1, 1).Formula gives a 1004 error, like in my case, changes it to:

Cells(1, 1).FormulaLocal

Selecting non-blank cells in Excel with VBA

If you are looking for the last row of a column, use:

Sub SelectFirstColumn()
   SelectEntireColumn (1)
End Sub

Sub SelectSecondColumn()
    SelectEntireColumn (2)
End Sub

Sub SelectEntireColumn(columnNumber)
    Dim LastRow
    Sheets("sheet1").Select
    LastRow = ActiveSheet.Columns(columnNumber).SpecialCells(xlLastCell).Row

    ActiveSheet.Range(Cells(1, columnNumber), Cells(LastRow, columnNumber)).Select
End Sub

Other commands you will need to get familiar with are copy and paste commands:

Sub CopyOneToTwo()
    SelectEntireColumn (1)
    Selection.Copy

    Sheets("sheet1").Select
    ActiveSheet.Range("B1").PasteSpecial Paste:=xlPasteValues
End Sub

Finally, you can reference worksheets in other workbooks by using the following syntax:

Dim book2
Set book2 = Workbooks.Open("C:\book2.xls")
book2.Worksheets("sheet1")

What does it mean to bind a multicast (UDP) socket?

The "bind" operation is basically saying, "use this local UDP port for sending and receiving data. In other words, it allocates that UDP port for exclusive use for your application. (Same holds true for TCP sockets).

When you bind to "0.0.0.0" (INADDR_ANY), you are basically telling the TCP/IP layer to use all available adapters for listening and to choose the best adapter for sending. This is standard practice for most socket code. The only time you wouldn't specify 0 for the IP address is when you want to send/receive on a specific network adapter.

Similarly if you specify a port value of 0 during bind, the OS will assign a randomly available port number for that socket. So I would expect for UDP multicast, you bind to INADDR_ANY on a specific port number where multicast traffic is expected to be sent to.

The "join multicast group" operation (IP_ADD_MEMBERSHIP) is needed because it basically tells your network adapter to listen not only for ethernet frames where the destination MAC address is your own, it also tells the ethernet adapter (NIC) to listen for IP multicast traffic as well for the corresponding multicast ethernet address. Each multicast IP maps to a multicast ethernet address. When you use a socket to send to a specific multicast IP, the destination MAC address on the ethernet frame is set to the corresponding multicast MAC address for the multicast IP. When you join a multicast group, you are configuring the NIC to listen for traffic sent to that same MAC address (in addition to its own).

Without the hardware support, multicast wouldn't be any more efficient than plain broadcast IP messages. The join operation also tells your router/gateway to forward multicast traffic from other networks. (Anyone remember MBONE?)

If you join a multicast group, all the multicast traffic for all ports on that IP address will be received by the NIC. Only the traffic destined for your binded listening port will get passed up the TCP/IP stack to your app. In regards to why ports are specified during a multicast subscription - it's because multicast IP is just that - IP only. "ports" are a property of the upper protocols (UDP and TCP).

You can read more about how multicast IP addresses map to multicast ethernet addresses at various sites. The Wikipedia article is about as good as it gets:

The IANA owns the OUI MAC address 01:00:5e, therefore multicast packets are delivered by using the Ethernet MAC address range 01:00:5e:00:00:00 - 01:00:5e:7f:ff:ff. This is 23 bits of available address space. The first octet (01) includes the broadcast/multicast bit. The lower 23 bits of the 28-bit multicast IP address are mapped into the 23 bits of available Ethernet address space.

How to send multiple data fields via Ajax?

var countries = new Array();
countries[0] = 'ga';
countries[1] = 'cd';

after that you can do like:

var new_countries = countries.join(',')

after:

$.ajax({
    type: "POST",
    url: "Concessions.aspx/GetConcessions",
    data: new_countries,
    ...

This thing work as JSON string format.

PHP how to get value from array if key is in a variable

$value = ( array_key_exists($key, $array) && !empty($array[$key]) ) 
         ? $array[$key] 
         : 'non-existant or empty value key';

Formatting floats without trailing zeros

You can simply use format() to achieve this:

format(3.140, '.10g') where 10 is the precision you want.

Proxies with Python 'Requests' module

It’s a bit late but here is a wrapper class that simplifies scraping proxies and then making an http POST or GET:

ProxyRequests

https://github.com/rootVIII/proxy_requests

How to change color of Android ListView separator line?

Use below code in your xml file

<ListView 
    android:id="@+id/listView"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:divider="#000000" 
    android:dividerHeight="1dp">
</ListView> 

What is the (function() { } )() construct in JavaScript?

This is an Immediately Invoked Function Expression in Javascript:

To understand IIFE in JS, lets break it down:

  1. Expression: Something that returns a value
    Example: Try out following in chrome console. These are expressions in JS.
a = 10 
output = 10 
(1+3) 
output = 4
  1. Function Expression:
    Example:
// Function Expression 
var greet = function(name){
   return 'Namaste' + ' ' + name;
}

greet('Santosh');

How function expression works:
- When JS engine runs for the first time (Execution Context - Create Phase), this function (on the right side of = above) does not get executed or stored in the memory. Variable 'greet' is assigned 'undefined' value by the JS engine.
- During execution (Execution Context - Execute phase), the funtion object is created on the fly (its not executed yet), gets assigned to 'greet' variable and it can be invoked using 'greet('somename')'.

3. Immediately Invoked Funtion Expression:

Example:

// IIFE
var greeting = function(name) {
    return 'Namaste' + ' ' + name;
}('Santosh')

console.log(greeting)  // Namaste Santosh. 

How IIFE works:
- Notice the '()' immediately after the function declaration. Every funtion object has a 'CODE' property attached to it which is callable. And we can call it (or invoke it) using '()' braces.
- So here, during the execution (Execution Context - Execute Phase), the function object is created and its executed at the same time - So now, the greeting variable, instead of having the funtion object, has its return value ( a string )

Typical usecase of IIFE in JS:

The following IIFE pattern is quite commonly used.

// IIFE 
// Spelling of Function was not correct , result into error
(function (name) {
   var greeting = 'Namaste';
   console.log(greeting + ' ' + name);
})('Santosh');
  • we are doing two things over here. a) Wrapping our function expression inside braces (). This goes to tell the syntax parser the whatever placed inside the () is an expression (function expression in this case) and is a valid code.
    b) We are invoking this funtion at the same time using the () at the end of it.

So this function gets created and executed at the same time (IIFE).

Important usecase for IIFE:

IIFE keeps our code safe.
- IIFE, being a function, has its own execution context, meaning all the variables created inside it are local to this function and are not shared with the global execution context.

Suppose I've another JS file (test1.js) used in my applicaiton along with iife.js (see below).

// test1.js

var greeting = 'Hello';

// iife.js
// Spelling of Function was not correct , result into error
(function (name) { 
   var greeting = 'Namaste';
   console.log(greeting + ' ' + name);
})('Santosh');

console.log(greeting)   // No collision happens here. It prints 'Hello'.

So IIFE helps us to write safe code where we are not colliding with the global objects unintentionally.

How to unlock a file from someone else in Team Foundation Server

I was able to undo another user's checkout with the following command:

tf undo {file path} /workspace:{workspace};{username}

You'll need to wrap that semicolon in double-quotes if you're running the command from PowerShell. We're running TFS 2010 (and VS 2010).

Disclaimer: I got this from the FCI-H blog at http://fci-h.blogspot.com/2011/01/how-to-force-undo-checkout-tfs.html

Create Elasticsearch curl query for not null and not empty("")

We are using Elasticsearch version 1.6 and I used this query from a co-worker to cover not null and not empty for a field:

{
  "query": {
    "filtered": {
      "query": {
        "match_all": {}
      },
      "filter": {
        "bool": {
          "must": [
            {
              "exists": {
                "field": "myfieldName"
              }
            },
            {
              "not": {
                "filter": {
                  "term": {
                    "myfieldName": ""
                  }
                }
              }
            }
          ]
        }
      }
    }
  }
}

What are the differences between virtual memory and physical memory?

I am shamelessly copying the excerpts from man page of top

VIRT -- Virtual Image (kb) The total amount of virtual memory used by the task. It includes all code, data and shared libraries plus pages that have been swapped out and pages that have been mapped but not used.

SWAP -- Swapped size (kb) Memory that is not resident but is present in a task. This is memory that has been swapped out but could include additional non- resident memory. This column is calculated by subtracting physical memory from virtual memory

Text in Border CSS HTML

Text in Border with transparent text background

_x000D_
_x000D_
.box{
    background-image: url("https://i.stack.imgur.com/N39wV.jpg");
    width: 350px;
    padding: 10px;
}

/*begin first box*/
.first{
    width: 300px;
    height: 100px;
    margin: 10px;
    border-width: 0 2px 0 2px;
    border-color: #333;
    border-style: solid;
    position: relative;
}

.first span {
    position: absolute;
    display: flex;
    right: 0;
    left: 0;
    align-items: center;
}
.first .foo{
    top: -8px;
}
.first .bar{
    bottom: -8.5px;
}
.first span:before{
    margin-right: 15px;
}
.first span:after {
    margin-left: 15px;
}
.first span:before , .first span:after {
    content: ' ';
    height: 2px;
    background: #333;
    display: block;
    width: 50%;
}


/*begin second box*/
.second{
    width: 300px;
    height: 100px;
    margin: 10px;
    border-width: 2px 0 2px 0;
    border-color: #333;
    border-style: solid;
    position: relative;
}

.second span {
    position: absolute;
    top: 0;
    bottom: 0;
    display: flex;
    flex-direction: column;
    align-items: center;
}
.second .foo{
    left: -15px;
}
.second .bar{
    right: -15.5px;
}
.second span:before{
    margin-bottom: 15px;
}
.second span:after {
    margin-top: 15px;
}
.second span:before , .second span:after {
    content: ' ';
    width: 2px;
    background: #333;
    display: block;
    height: 50%;
}
_x000D_
<div class="box">
    <div class="first">
        <span class="foo">FOO</span>
        <span class="bar">BAR</span>
    </div>

   <br>

    <div class="second">
        <span class="foo">FOO</span>
        <span class="bar">BAR</span>
    </div>
</div>
_x000D_
_x000D_
_x000D_

How to vertically align text inside a flexbox?

Instead of using align-self: center use align-items: center.

There's no need to change flex-direction or use text-align.

Here's your code, with one adjustment, to make it all work:

ul {
  height: 100%;
}

li {
  display: flex;
  justify-content: center;
  /* align-self: center;    <---- REMOVE */
  align-items: center;   /* <---- NEW    */
  background: silver;
  width: 100%;
  height: 20%; 
}

The align-self property applies to flex items. Except your li is not a flex item because its parent – the ul – does not have display: flex or display: inline-flex applied.

Therefore, the ul is not a flex container, the li is not a flex item, and align-self has no effect.

The align-items property is similar to align-self, except it applies to flex containers.

Since the li is a flex container, align-items can be used to vertically center the child elements.

_x000D_
_x000D_
* {_x000D_
  padding: 0;_x000D_
  margin: 0;_x000D_
}_x000D_
html, body {_x000D_
  height: 100%;_x000D_
}_x000D_
ul {_x000D_
  height: 100%;_x000D_
}_x000D_
li {_x000D_
  display: flex;_x000D_
  justify-content: center;_x000D_
  /* align-self: center; */_x000D_
  align-items: center;_x000D_
  background: silver;_x000D_
  width: 100%;_x000D_
  height: 20%;_x000D_
}
_x000D_
<ul>_x000D_
  <li>This is the text</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

codepen demo


Technically, here's how align-items and align-self work...

The align-items property (on the container) sets the default value of align-self (on the items). Therefore, align-items: center means all flex items will be set to align-self: center.

But you can override this default by adjusting the align-self on individual items.

For example, you may want equal height columns, so the container is set to align-items: stretch. However, one item must be pinned to the top, so it is set to align-self: flex-start.

example


How is the text a flex item?

Some people may be wondering how a run of text...

<li>This is the text</li>

is a child element of the li.

The reason is that text that is not explicitly wrapped by an inline-level element is algorithmically wrapped by an inline box. This makes it an anonymous inline element and child of the parent.

From the CSS spec:

9.2.2.1 Anonymous inline boxes

Any text that is directly contained inside a block container element must be treated as an anonymous inline element.

The flexbox specification provides for similar behavior.

4. Flex Items

Each in-flow child of a flex container becomes a flex item, and each contiguous run of text that is directly contained inside a flex container is wrapped in an anonymous flex item.

Hence, the text in the li is a flex item.

@POST in RESTful web service

Please find example below, it might help you

package jersey.rest.test;

import javax.ws.rs.DELETE;
import javax.ws.rs.GET;
import javax.ws.rs.HEAD;
import javax.ws.rs.POST;
import javax.ws.rs.PUT;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;

@Path("/hello")
public class SimpleService {
    @GET
    @Path("/{param}")
    public Response getMsg(@PathParam("param") String msg) {
        String output = "Get:Jersey say : " + msg;
        return Response.status(200).entity(output).build();
    }

    @POST
    @Path("/{param}")
    public Response postMsg(@PathParam("param") String msg) {
        String output = "POST:Jersey say : " + msg;
        return Response.status(200).entity(output).build();
    }

    @POST
    @Path("/post")
    //@Consumes(MediaType.TEXT_XML)
    public Response postStrMsg( String msg) {
        String output = "POST:Jersey say : " + msg;
        return Response.status(200).entity(output).build();
    }

    @PUT
    @Path("/{param}")
    public Response putMsg(@PathParam("param") String msg) {
        String output = "PUT: Jersey say : " + msg;
        return Response.status(200).entity(output).build();
    }

    @DELETE
    @Path("/{param}")
    public Response deleteMsg(@PathParam("param") String msg) {
        String output = "DELETE:Jersey say : " + msg;
        return Response.status(200).entity(output).build();
    }

    @HEAD
    @Path("/{param}")
    public Response headMsg(@PathParam("param") String msg) {
        String output = "HEAD:Jersey say : " + msg;
        return Response.status(200).entity(output).build();
    }
}

for testing you can use any tool like RestClient (http://code.google.com/p/rest-client/)

How to count the number of occurrences of a character in an Oracle varchar value?

I justed faced very similar problem... BUT RegExp_Count couldn't resolved it. How many times string '16,124,3,3,1,0,' contains ',3,'? As we see 2 times, but RegExp_Count returns just 1. Same thing is with ''bbaaaacc' and when looking in it 'aa' - should be 3 times and RegExp_Count returns just 2.

select REGEXP_COUNT('336,14,3,3,11,0,' , ',3,') from dual;
select REGEXP_COUNT('bbaaaacc' , 'aa') from dual;

I lost some time to research solution on web. Couldn't' find... so i wrote my own function that returns TRUE number of occurance. Hope it will be usefull.

CREATE OR REPLACE FUNCTION EXPRESSION_COUNT( pEXPRESSION VARCHAR2, pPHRASE VARCHAR2 ) RETURN NUMBER AS
  vRET NUMBER := 0;
  vPHRASE_LENGTH NUMBER := 0;
  vCOUNTER NUMBER := 0;
  vEXPRESSION VARCHAR2(4000);
  vTEMP VARCHAR2(4000);
BEGIN
  vEXPRESSION := pEXPRESSION;
  vPHRASE_LENGTH := LENGTH( pPHRASE );
  LOOP
    vCOUNTER := vCOUNTER + 1;
    vTEMP := SUBSTR( vEXPRESSION, 1, vPHRASE_LENGTH);
    IF (vTEMP = pPHRASE) THEN        
        vRET := vRET + 1;
    END IF;
    vEXPRESSION := SUBSTR( vEXPRESSION, 2, LENGTH( vEXPRESSION ) - 1);
  EXIT WHEN ( LENGTH( vEXPRESSION ) = 0 ) OR (vEXPRESSION IS NULL);
  END LOOP;
  RETURN vRET;
END;

How to get a list of properties with a given attribute?

var props = t.GetProperties().Where(
                prop => Attribute.IsDefined(prop, typeof(MyAttribute)));

This avoids having to materialize any attribute instances (i.e. it is cheaper than GetCustomAttribute[s]().

How do I check if a property exists on a dynamic anonymous type in c#?

This works also for DynamicJsonObject:

  public static bool PropertyExists(dynamic settings, string name)
  {
    if (settings is ExpandoObject)
      return ((IDictionary<string, object>)settings).ContainsKey(name);
    else if (settings is DynamicJsonObject)
      return ((DynamicJsonObject)settings).GetDynamicMemberNames().Contains(name);

    return settings.GetType().GetProperty(name) != null;
  }

How can I remove jenkins completely from linux

On Centos7, It is important to note that while you remove jenkins using following command: sudo yum remove jenkins

it will not remove your users and other information. For that you will have to do following: sudo rm -r /var/lib/jenkins

Regex number between 1 and 100

Regular Expression for 0 to 100 with the decimal point.

^100(\.[0]{1,2})?|([0-9]|[1-9][0-9])(\.[0-9]{1,2})?$

OpenSSL: PEM routines:PEM_read_bio:no start line:pem_lib.c:703:Expecting: TRUSTED CERTIFICATE

I had the same issue using Windows, got if fixed by opening it in Notepad++ and changing the encoding from "UCS-2 LE BOM" to "UTF-8".

Submit form after calling e.preventDefault()

Binding to the button would not resolve for submissions outside of pressing the button e.g. pressing enter

Warning - Build path specifies execution environment J2SE-1.4

If you have Java 1.8 then

You need this xml part in pom.xml and update project.

 <properties>
    <maven.compiler.target>1.8</maven.compiler.target>
  </properties>

What's the difference between ".equals" and "=="?

Lets say that "==" operator returns true if both both operands belong to same object but when it will return true as we can't assign a single object multiple values

public static void main(String [] args){
    String s1 = "Hello";
    String s1 = "Hello";  // This is not possible to assign multiple values to single object
    if(s1 == s1){
      // Now this retruns true
   }
}

Now when this happens practically speaking, If its not happen then why this is == compares functionality....

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

I solved this problem by removing --deploy-mode cluster from spark-submit code. By default , spark submit takes client mode which has following advantage :

1. It opens up Netty HTTP server and distributes all jars to the worker nodes.
2. Driver program runs on master node , which means dedicated resources to driver process.

While in cluster mode :

 1.  It runs on worker node.
 2. All the jars need to be placed in a common folder of the cluster so that it is accessible to all the worker nodes or in folder of each worker node.

Here it's not able to access hive metastore due to unavailability of hive jar to any of the nodes in cluster. enter image description here

how to refresh page in angular 2

Just in case someone else encounters this problem. You need to call

window.location.reload()

And you cannot call this from a expression. If you want to call this from a click event you need to put this on a function:

(click)="realodPage()"

And simply define the function:

reloadPage() {
   window.location.reload();
}

If you are changing the route, it might not work because the click event seems to happen before the route changes. A very dirty solution is just to add a small delay

reloadPage() {
    setTimeout(()=>{
      window.location.reload();
    }, 100);
}

How to install python3 version of package via pip on Ubuntu?

  1. You should install ALL dependencies:

    sudo apt-get install build-essential python3-dev python3-setuptools python3-numpy python3-scipy libatlas-dev libatlas3gf-base

  2. Install pip3(if you have installed, please look step 3):

    sudo apt-get install python3-pip

  3. Iinstall scikit-learn by pip3

    pip3 install -U scikit-learn

  4. Open your terminal and entry python3 environment, type import sklearn to check it.

Gook Luck!

CSS: Set Div height to 100% - Pixels

Now with css3 you could try to use calc()

.main{
  height: calc(100% - 111px);
}

have a look at this answer: Div width 100% minus fixed amount of pixels

remove item from stored array in angular 2

You can't use delete to remove an item from an array. This is only used to remove a property from an object.

You should use splice to remove an element from an array:

deleteMsg(msg:string) {
    const index: number = this.data.indexOf(msg);
    if (index !== -1) {
        this.data.splice(index, 1);
    }        
}

What is reflection and why is it useful?

Uses of Reflection

Reflection is commonly used by programs which require the ability to examine or modify the runtime behavior of applications running in the Java virtual machine. This is a relatively advanced feature and should be used only by developers who have a strong grasp of the fundamentals of the language. With that caveat in mind, reflection is a powerful technique and can enable applications to perform operations which would otherwise be impossible.

Extensibility Features

An application may make use of external, user-defined classes by creating instances of extensibility objects using their fully-qualified names. Class Browsers and Visual Development Environments A class browser needs to be able to enumerate the members of classes. Visual development environments can benefit from making use of type information available in reflection to aid the developer in writing correct code. Debuggers and Test Tools Debuggers need to be able to examine private members in classes. Test harnesses can make use of reflection to systematically call a discoverable set APIs defined on a class, to ensure a high level of code coverage in a test suite.

Drawbacks of Reflection

Reflection is powerful, but should not be used indiscriminately. If it is possible to perform an operation without using reflection, then it is preferable to avoid using it. The following concerns should be kept in mind when accessing code via reflection.

  • Performance Overhead

Because reflection involves types that are dynamically resolved, certain Java virtual machine optimizations cannot be performed. Consequently, reflective operations have slower performance than their non-reflective counterparts and should be avoided in sections of code which are called frequently in performance-sensitive applications.

  • Security Restrictions

Reflection requires a runtime permission which may not be present when running under a security manager. This is in an important consideration for code which has to run in a restricted security context, such as in an Applet.

  • Exposure of Internals

Since reflection allows code to perform operations that would be illegal in non-reflective code, such as accessing private fields and methods, the use of reflection can result in unexpected side-effects, which may render code dysfunctional and may destroy portability. Reflective code breaks abstractions and therefore may change behavior with upgrades of the platform.

source: The Reflection API

How to call stopservice() method of Service class from the calling activity class

@Juri

If you add IntentFilters for your service, you are saying you want to expose your service to other applications, then it may be stopped unexpectedly by other applications.

How can I check if a date is the same day as datetime.today()?

You can set the hours, minutes, seconds and microseconds to whatever you like

datetime.datetime.today().replace(hour=0, minute=0, second=0, microsecond=0)

but trutheality's answer is probably best when they are all to be zero and you can just compare the .date()s of the times

Maybe it is faster though if you have to compare hundreds of datetimes because you only need to do the replace() once vs hundreds of calls to date()

The following sections have been defined but have not been rendered for the layout page "~/Views/Shared/_Layout.cshtml": "Scripts"

I searched for the error in the web and came to this page. I am using Visual Studio 2015 and this is my first MVC project.

If you miss the @ symbol before the render section you will get the same error. I would like to share this for future beginners.

 @RenderSection("headscripts", required: false)

SQL Server principal "dbo" does not exist,

Go to the Properties - Files. The owner name must be blank. Just put "sa" in the user name and the issue will be resolved.

Enum ToString with user friendly strings

That other post is Java. You can't put methods in Enums in C#.

just do something like this:

PublishStatusses status = ...
String s = status.ToString();

If you want to use different display values for your enum values, you could use Attributes and Reflection.

java.lang.OutOfMemoryError: Java heap space

  1. In most of the cases, the code is not optimized. Release those objects which you think shall not be needed further. Avoid creation of objects in your loop each time. Try to use caches. I don't know how your application is doing. But In programming, one rule of normal life applies as well

    Prevention is better than cure. "Don't create unnecessary objects"

Java: Static vs inner class

Discussing nested classes...

The difference is that a nested class declaration that is also static can be instantiated outside of the enclosing class.

When you have a nested class declaration that is not static, Java won't let you instantiate it except via the enclosing class. The object created out of the inner class is linked to the object created from the outer class, so the inner class can reference the fields of the outer.

But if it's static, then the link does not exist, the outer fields cannot be accessed (except via an ordinary reference like any other object) and you can therefore instantiate the nested class by itself.

Converting a byte array to PNG/JPG

You should be able to do something like this:

byte[] bitmap = GetYourImage();

using(Image image = Image.FromStream(new MemoryStream(bitmap)))
{
    image.Save("output.jpg", ImageFormat.Jpeg);  // Or Png
}

Look here for more info.

Hopefully this helps.

Sending "User-agent" using Requests library in Python

It's more convenient to use a session, this way you don't have to remember to set headers each time:

session = requests.Session()
session.headers.update({'User-Agent': 'Custom user agent'})

session.get('https://httpbin.org/headers')

By default, session also manages cookies for you. In case you want to disable that, see this question.

C# DateTime to "YYYYMMDDHHMMSS" format

Get the date as a DateTime object instead of a String. Then you can format it as you want.

  • MM/dd/yyyy 08/22/2006
  • dddd, dd MMMM yyyy Tuesday, 22 August 2006
  • dddd, dd MMMM yyyy HH:mm Tuesday, 22 August 2006 06:30
  • dddd, dd MMMM yyyy hh:mm tt Tuesday, 22 August 2006 06:30 AM
  • dddd, dd MMMM yyyy H:mm Tuesday, 22 August 2006 6:30
  • dddd, dd MMMM yyyy h:mm tt Tuesday, 22 August 2006 6:30 AM
  • dddd, dd MMMM yyyy HH:mm:ss Tuesday, 22 August 2006 06:30:07
  • MM/dd/yyyy HH:mm 08/22/2006 06:30
  • MM/dd/yyyy hh:mm tt 08/22/2006 06:30 AM
  • MM/dd/yyyy H:mm 08/22/2006 6:30
  • MM/dd/yyyy h:mm tt 08/22/2006 6:30 AM
  • MM/dd/yyyy HH:mm:ss 08/22/2006 06:30:07

Click here for more patterns

"code ." Not working in Command Line for Visual Studio Code on OSX/Mac

For Mac OSX: There is a way to install Visual Studio Code through Brew-Cask.

  1. First, install 'Homebrew' from here.
  2. Now run following command and it will install latest Visual Studio Code on your Mac.

    $> brew cask install visual-studio-code

Above command should install Visual Studio Code and also set up the command-line calling of Visual Studio Code.

If above steps don't work then you can do it manually. By following Microsoft Visual Studio Code documentation given here.

NTFS performance and large volumes of files and directories

There are also performance problems with short file name creation slowing things down. Microsoft recommends turning off short filename creation if you have more than 300k files in a folder [1]. The less unique the first 6 characters are, the more of a problem this is.

[1] How NTFS Works from http://technet.microsoft.com, search for "300,000"

How to allow users to check for the latest app version from inside the app?

Here's how to find the current and latest available versions:

       try {
            String curVersion = getPackageManager().getPackageInfo(getPackageName(), 0).versionName;
            String newVersion = curVersion;
            newVersion = Jsoup.connect("https://play.google.com/store/apps/details?id=" + getPackageName() + "&hl=en")
                    .timeout(30000)
                    .userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6")
                    .referrer("http://www.google.com")
                    .get()
                    .select("div.hAyfc:nth-child(4) .IQ1z0d .htlgb")
                    .first()
                    .ownText();
            Log.d("Curr Version" , curVersion);
            Log.d("New Version" , newVersion);

        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

Gradle: Execution failed for task ':processDebugManifest'

Maybe you have some duplicated Activities

Like this:

<activity android:name=".register.RegisterStepsActivity" />

....

<activity android:name=".register.RegisterStepsActivity" />

just comment one of them

Spring MVC Controller redirect using URL parameters instead of in response

You can have processForm() return a View object instead, and have it return the concrete type RedirectView which has a parameter for setExposeModelAttributes().

When you return a view name prefixed with "redirect:", Spring MVC transforms this to a RedirectView object anyway, it just does so with setExposeModelAttributes to true (which I think is an odd value to default to).

Add Text on Image using PIL

Even more minimal example (draws "Hello world!" in black and with the default font in the top-left of the image):

...
from PIL import ImageDraw
...
ImageDraw.Draw(
    image  # Image
).text(
    (0, 0),  # Coordinates
    'Hello world!',  # Text
    (0, 0, 0)  # Color
)

SQL conditional SELECT

@selectField1 AS bit
@selectField2 AS bit

SELECT
CASE 
    WHEN @selectField1 THEN Field1
    WHEN @selectField2 THEN Field2
    ELSE someDefaultField
END
FROM Table

Is this what you're looking for?

How to clear the JTextField by clicking JButton

Looking for EventHandling, ActionListener?

or code?

JButton b = new JButton("Clear");
b.addActionListener(new ActionListener(){
    public void actionPerformed(ActionEvent e){
        textfield.setText("");
        //textfield.setText(null); //or use this
    }
});

Also See
How to Use Buttons

How to convert a Scikit-learn dataset to a Pandas dataset?

Here's another integrated method example maybe helpful.

from sklearn.datasets import load_iris
iris_X, iris_y = load_iris(return_X_y=True, as_frame=True)
type(iris_X), type(iris_y)

The data iris_X are imported as pandas DataFrame and the target iris_y are imported as pandas Series.

Web Application Problems (web.config errors) HTTP 500.19 with IIS7.5 and ASP.NET v2

I got this error by putting the <customErrors> tag inside of <system.webServer> instead of <system.web> where it belongs. There was a little squiggle under the <customErrors> tag but I didn't notice it right away.

How can I parse JSON with C#?

Try the following code:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("URL");
JArray array = new JArray();
using (var twitpicResponse = (HttpWebResponse)request.GetResponse())
using (var reader = new StreamReader(twitpicResponse.GetResponseStream()))
{
    JavaScriptSerializer js = new JavaScriptSerializer();
    var objText = reader.ReadToEnd();

    JObject joResponse = JObject.Parse(objText);
    JObject result = (JObject)joResponse["result"];
    array = (JArray)result["Detail"];
    string statu = array[0]["dlrStat"].ToString();
}

How can I use the $index inside a ng-repeat to enable a class and show a DIV?

The issue here is that ng-repeat creates its own scope, so when you do selected=$index it creates a new a selected property in that scope rather than altering the existing one. To fix this you have two options:

Change the selected property to a non-primitive (ie object or array, which makes javascript look up the prototype chain) then set a value on that:

$scope.selected = {value: 0};

<a ng-click="selected.value = $index">A{{$index}}</a>

See plunker

or

Use the $parent variable to access the correct property. Though less recommended as it increases coupling between scopes

<a ng-click="$parent.selected = $index">A{{$index}}</a>

See plunker

Scp command syntax for copying a folder from local machine to a remote server

scp -r C:/site user@server_ip:path

path is the place, where site will be copied into the remote server


EDIT: As I said in my comment, try pscp, as you want to use scp using PuTTY.

The other option is WinSCP

Get Value From Select Option in Angular 4

    //in html file
    <div class="row">
                <div class="col-md-6">
                    <div class="form-group">
                        <label for="name">Country</label>
                        <select class="form-control" formControlName="country" (change)="onCountryChange($event.target.value)">
                            <option disabled selected value [ngValue]="null"> -- Select Country  -- </option>
                            <option *ngFor="let country of countries" [value]="country.id">{{country.name}}</option>
                            <div *ngIf="isEdit">
                                <option></option>
                            </div>
                        </select>
                      </div>   
                </div>
            </div>
            <div class="help-block" *ngIf="studentForm.get('country').invalid && studentForm.get('country').touched">
                <div *ngIf="studentForm.get('country').errors.required">*country is required</div>
            </div>
            <div class="row">
                <div class="col-md-6">
                    <div class="form-group">
                        <label for="name">State</label>
                        <select class="form-control" formControlName="state" (change)="onStateChange($event.target.value)">
                            <option disabled selected value [ngValue]="null"> -- Select State -- </option>
                            <option *ngFor="let state of states" [value]="state.id">{{state.state_name}}</option>
                        </select>
                      </div>   
                </div>
            </div>
            <div class="help-block" *ngIf="studentForm.get('state').invalid && studentForm.get('state').touched">
                <div *ngIf="studentForm.get('state').errors.required">*state is enter code hererequired</div>
            </div>
            <div class="row">
                <div class="col-md-6">
                    <div class="form-group">
                        <label for="name">City</label>
                        <select class="form-control" formControlName="city">
                            <option disabled selected value [ngValue]="null"> -- Select City -- </option>
                            <option *ngFor="let city of cities" [value]="city.id" >{{city.city_name}}</option>
                        </select>
                      </div>   
                </div>
            </div>
            <div class="help-block" *ngIf="studentForm.get('city').invalid && studentForm.get('city').touched">
                <div *ngIf="studentForm.get('city').errors.required">*city is required</div>
            </div>
    //then in component
    onCountryChange(countryId:number){
   this.studentServive.getSelectedState(countryId).subscribe(resData=>{
    this.states = resData;
   });
  }
  onStateChange(stateId:number){
    this.studentServive.getSelectedCity(stateId).subscribe(resData=>{
     this.cities = resData;
    });
   }`enter code here`

List of tuples to dictionary

Functional decision for @pegah answer:

from itertools import groupby

mylist = [('a', 1), ('b', 3), ('a', 2), ('b', 4)]
#mylist = iter([('a', 1), ('b', 3), ('a', 2), ('b', 4)])

result = { k : [*map(lambda v: v[1], values)]
    for k, values in groupby(sorted(mylist, key=lambda x: x[0]), lambda x: x[0])
    }

print(result)
# {'a': [1, 2], 'b': [3, 4]}

How to clear the Entry widget after a button is pressed in Tkinter?

Simply define a function and set the value of your Combobox to empty/null or whatever you want. Try the following.

def Reset():
    cmb.set("")

here, cmb is a variable in which you have assigned the Combobox. Now call that function in a button such as,

btn2 = ttk.Button(root, text="Reset",command=Reset)

How to edit my Excel dropdown list?

Attribute_Brands is a named range.

On any worksheet (tab) press F5 and type Attribute_Brands into the reference box and click on the OK button.

This will take you to the named range.

The data in it can be updated by typing new values into the cells.

The named range can be altered via the 'Insert - Name - Define' menu.

How to make external HTTP requests with Node.js

You can use the built-in http module to do an http.request().

However if you want to simplify the API you can use a module such as superagent

Get user location by IP address

    public static string GetLocationIPAPI(string ipaddress)
    {
        try
        {
            IPDataIPAPI ipInfo = new IPDataIPAPI();
            string strResponse = new WebClient().DownloadString("http://ip-api.com/json/" + ipaddress);
            if (strResponse == null || strResponse == "") return "";
            ipInfo = JsonConvert.DeserializeObject<IPDataIPAPI>(strResponse);
            if (ipInfo == null || ipInfo.status.ToLower().Trim() == "fail") return "";
            else return ipInfo.city + "; " + ipInfo.regionName + "; " + ipInfo.country + "; " + ipInfo.countryCode;
        }
        catch (Exception)
        {
            return "";
        }
    }

public class IPDataIPINFO
{
    public string ip { get; set; }
    public string city { get; set; }
    public string region { get; set; }
    public string country { get; set; }
    public string loc { get; set; }
    public string postal { get; set; }
    public int org { get; set; }

}

==========================

    public static string GetLocationIPINFO(string ipaddress)
    {            
        try
        {
            IPDataIPINFO ipInfo = new IPDataIPINFO();
            string strResponse = new WebClient().DownloadString("http://ipinfo.io/" + ipaddress);
            if (strResponse == null || strResponse == "") return "";
            ipInfo = JsonConvert.DeserializeObject<IPDataIPINFO>(strResponse);
            if (ipInfo == null || ipInfo.ip == null || ipInfo.ip == "") return "";
            else return ipInfo.city + "; " + ipInfo.region + "; " + ipInfo.country + "; " + ipInfo.postal;
        }
        catch (Exception)
        {
            return "";
        }
    }

public class IPDataIPAPI
{
    public string status { get; set; }
    public string country { get; set; }
    public string countryCode { get; set; }
    public string region { get; set; }
    public string regionName { get; set; }
    public string city { get; set; }
    public string zip { get; set; }
    public string lat { get; set; }
    public string lon { get; set; }
    public string timezone { get; set; }
    public string isp { get; set; }
    public string org { get; set; }
    public string @as { get; set; }
    public string query { get; set; }
}

==============================

    private static string GetLocationIPSTACK(string ipaddress)
    {
        try
        {
            IPDataIPSTACK ipInfo = new IPDataIPSTACK();
            string strResponse = new WebClient().DownloadString("http://api.ipstack.com/" + ipaddress + "?access_key=XX384X1XX028XX1X66XXX4X04XXXX98X");
            if (strResponse == null || strResponse == "") return "";
            ipInfo = JsonConvert.DeserializeObject<IPDataIPSTACK>(strResponse);
            if (ipInfo == null || ipInfo.ip == null || ipInfo.ip == "") return "";
            else return ipInfo.city + "; " + ipInfo.region_name + "; " + ipInfo.country_name + "; " + ipInfo.zip;
        }
        catch (Exception)
        {
            return "";
        }
    }

public class IPDataIPSTACK
{
    public string ip { get; set; }
    public int city { get; set; }
    public string region_code { get; set; }
    public string region_name { get; set; }
    public string country_code { get; set; }
    public string country_name { get; set; }
    public string zip { get; set; }


}

how to view the contents of a .pem certificate

Use the -printcert command like this:

keytool -printcert -file certificate.pem

How to use SearchView in Toolbar Android

If you would like to setup the search facility inside your Fragment, just add these few lines:

Step 1 - Add the search field to you toolbar:

<item
    android:id="@+id/action_search"
    android:icon="@android:drawable/ic_menu_search"
    app:showAsAction="always|collapseActionView"
    app:actionViewClass="android.support.v7.widget.SearchView"
    android:title="Search"/>

Step 2 - Add the logic to your onCreateOptionsMenu()

import android.support.v7.widget.SearchView; // not the default !

@Override
public boolean onCreateOptionsMenu( Menu menu) {
    getMenuInflater().inflate( R.menu.main, menu);

    MenuItem myActionMenuItem = menu.findItem( R.id.action_search);
    searchView = (SearchView) myActionMenuItem.getActionView();
    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            // Toast like print
            UserFeedback.show( "SearchOnQueryTextSubmit: " + query);
            if( ! searchView.isIconified()) {
                searchView.setIconified(true);
            }
            myActionMenuItem.collapseActionView();
            return false;
        }
        @Override
        public boolean onQueryTextChange(String s) {
            // UserFeedback.show( "SearchOnQueryTextChanged: " + s);
            return false;
        }
    });
    return true;
}

When to use DataContract and DataMember attributes?

  1. Data contract: It specifies that your entity class is ready for Serialization process.

  2. Data members: It specifies that the particular field is part of the data contract and it can be serialized.

Convert Decimal to Varchar

Hope this will help you

Cast(columnName as Numeric(10,2)) 
        or

Cast(@s as decimal(10,2))

I am not getting why you want to cast to varchar?.If you cast to varchar again convert back to decimail for two decimal points

IOException: Too many open files

Don't know the nature of your app, but I have seen this error manifested multiple times because of a connection pool leak, so that would be worth checking out. On Linux, socket connections consume file descriptors as well as file system files. Just a thought.

include antiforgerytoken in ajax post ASP.NET MVC



        function DeletePersonel(id) {

                var data = new FormData();
                data.append("__RequestVerificationToken", "@HtmlHelper.GetAntiForgeryToken()");

                $.ajax({
                    type: 'POST',
                    url: '/Personel/Delete/' + id,
                    data: data,
                    cache: false,
                    processData: false,
                    contentType: false,
                    success: function (result) {

                    }
                });

        }
    

        public static class HtmlHelper
        {
            public static string GetAntiForgeryToken()
            {
                System.Text.RegularExpressions.Match value = System.Text.RegularExpressions.Regex.Match(System.Web.Helpers.AntiForgery.GetHtml().ToString(), "(?:value=\")(.*)(?:\")");
                if (value.Success)
                {
                    return value.Groups[1].Value;
                }
                return "";
            }
        }

Regex (grep) for multi-line search needed

I am not very good in grep. But your problem can be solved using AWK command. Just see

awk '/select/,/from/' *.sql

The above code will result from first occurence of select till first sequence of from. Now you need to verify whether returned statements are having customername or not. For this you can pipe the result. And can use awk or grep again.

Initialize a byte array to a certain value, other than the default null?

This function is way faster than a for loop for filling an array.

The Array.Copy command is a very fast memory copy function. This function takes advantage of that by repeatedly calling the Array.Copy command and doubling the size of what we copy until the array is full.

I discuss this on my blog at https://grax32.com/2013/06/fast-array-fill-function-revisited.html (Link updated 12/16/2019). Also see Nuget package that provides this extension method. http://sites.grax32.com/ArrayExtensions/

Note that this would be easy to make into an extension method by just adding the word "this" to the method declarations i.e. public static void ArrayFill<T>(this T[] arrayToFill ...

public static void ArrayFill<T>(T[] arrayToFill, T fillValue)
{
    // if called with a single value, wrap the value in an array and call the main function
    ArrayFill(arrayToFill, new T[] { fillValue });
}

public static void ArrayFill<T>(T[] arrayToFill, T[] fillValue)
{
    if (fillValue.Length >= arrayToFill.Length)
    {
        throw new ArgumentException("fillValue array length must be smaller than length of arrayToFill");
    }

    // set the initial array value
    Array.Copy(fillValue, arrayToFill, fillValue.Length);

    int arrayToFillHalfLength = arrayToFill.Length / 2;

    for (int i = fillValue.Length; i < arrayToFill.Length; i *= 2)
    {
        int copyLength = i;
        if (i > arrayToFillHalfLength)
        {
            copyLength = arrayToFill.Length - i;
        }

        Array.Copy(arrayToFill, 0, arrayToFill, i, copyLength);
    }
}

iterating and filtering two lists using java 8

@DSchmdit answer worked for me. I would like to add on that. So my requirement was to filter a file based on some configurations stored in the table. The file is first retrieved and collected as list of dtos. I receive the configurations from the db and store it as another list. This is how I made the filtering work with streams

    List<FPRSDeferralModel> modelList = Files
            .lines(Paths.get("src/main/resources/rootFiles/XXXXX.txt")).parallel().parallel()
            .map(line -> {
                FileModel fileModel= new FileModel();
                line = line.trim();
                if (line != null && !line.isEmpty()) {
                    System.out.println("line" + line);
                    fileModel.setPlanId(Long.parseLong(line.substring(0, 5)));
                    fileModel.setDivisionList(line.substring(15, 30));
                    fileModel.setRegionList(line.substring(31, 50));
                    Map<String, String> newMap = new HashedMap<>();
                    newMap.put("other", line.substring(51, 80));
                    fileModel.setOtherDetailsMap(newMap);

                }
                return fileModel;
            }).collect(Collectors.toList());

    for (FileModel model : modelList) {
        System.out.println("model:" + model);
    }

    DbConfigModelList respList = populate();
    System.out.println("after populate");
    List<DbConfig> respModelList = respList.getFeedbackResponseList();


    Predicate<FileModel> somePre = s -> respModelList.stream().anyMatch(respitem -> {

        System.out.println("sinde respitem:"+respitem.getPrimaryConfig().getPlanId());
        System.out.println("s.getPlanid()"+s.getPlanId());
        System.out.println("s.getPlanId() == respitem.getPrimaryConfig().getPlanId():"+
        (s.getPlanId().compareTo(respitem.getPrimaryConfig().getPlanId())));
        return s.getPlanId().compareTo(respitem.getPrimaryConfig().getPlanId()) == 0
                && (s.getSsnId() != null);
    });



 final List<FileModel> finalList =  modelList.stream().parallel().filter(somePre).collect(Collectors.toList());

 finalList.stream().forEach(item -> {
     System.out.println("filtered item is:"+item);
 });

The details are in the implementation of filter predicates. This proves much more perfomant over iterating over loops and filtering out

Cannot GET / Nodejs Error

Have you checked your folder structure? It seems to me like Express can't find your root directory, which should be a a folder named "site" right under your default directory. Here is how it should look like, according to the tutorial:

node_modules/
  .bin/
  express/
  mongoose/
  path/
site/
  css/
  img/
  js/
  index.html
package.json

For example on my machine, I started getting the same error as you when I renamed my "site" folder as something else. So I would suggest you check that you have the index.html page inside a "site" folder that sits on the same path as your server.js file.

Hope that helps!

Using cut command to remove multiple columns

You are able to cut all odd/even columns by using seq:

This would print all odd columns

echo 1,2,3,4,5,6,7,8,9,10 | cut -d, -f$(seq -s, 1 2 10)

To print all even columns you could use

echo 1,2,3,4,5,6,7,8,9,10 | cut -d, -f$(seq -s, 2 2 10)

By changing the second number of seq you can specify which columns to be printed.

If the specification which columns to print is more complex you could also use a "one-liner-if-clause" like

echo 1,2,3,4,5,6,7,8,9,10 | cut -d, -f$(for i in $(seq 1 10); do if [[ $i -lt 10 && $i -lt 5 ]];then echo -n $i,; else echo -n $i;fi;done)

This would print all columns from 1 to 5 - you can simply modify the conditions to create more complex conditions to specify weather a column shall be printed.

How to find out if a file exists in C# / .NET?

Give full path as input. Avoid relative paths.

 return File.Exists(FinalPath);

How do I indent multiple lines at once in Notepad++?

The problem was with the QuickText plugin. After removing it, indent worked as normal.

Downloading a picture via urllib and python

All the above codes, do not allow to preserve the original image name, which sometimes is required. This will help in saving the images to your local drive, preserving the original image name

    IMAGE = URL.rsplit('/',1)[1]
    urllib.urlretrieve(URL, IMAGE)

Try this for more details.

What does it mean to "program to an interface"?

If you program in Java, JDBC is a good example. JDBC defines a set of interfaces but says nothing about the implementation. Your applications can be written against this set of interfaces. In theory, you pick some JDBC driver and your application would just work. If you discover there's a faster or "better" or cheaper JDBC driver or for whatever reason, you can again in theory re-configure your property file, and without having to make any change in your application, your application would still work.

How to update a record using sequelize for node?

This solution is deprecated

failure|fail|error() is deprecated and will be removed in 2.1, please use promise-style instead.

so you have to use

Project.update(

    // Set Attribute values 
    {
        title: 'a very different title now'
    },

    // Where clause / criteria 
    {
        _id: 1
    }

).then(function() {

    console.log("Project with id =1 updated successfully!");

}).catch(function(e) {
    console.log("Project update failed !");
})

And you can use .complete() as well

Regards

How to fix: /usr/lib/libstdc++.so.6: version `GLIBCXX_3.4.15' not found

this problem can be solved by installing the latest libstdc++.

$ sudo add-apt-repository ppa:ubuntu-toolchain-r/test
$ sudo apt-get update
$ sudo apt-get install libstdc++6-7-dbg

How to center an unordered list?

_x000D_
_x000D_
ul {_x000D_
  display: table;_x000D_
  margin: 0 auto;_x000D_
}
_x000D_
<html>_x000D_
_x000D_
<body>_x000D_
  <ul>_x000D_
    <li>56456456</li>_x000D_
    <li>4564564564564649999999999999999999999999999996</li>_x000D_
    <li>45645</li>_x000D_
  </ul>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

How do I shutdown, restart, or log off Windows via a bat file?

Original answer: Oct. 2008

You also got all the "rundll32.exe shell32.dll" serie:

(see update below)

  • rundll32.exe user.exe,**ExitWindows** [Fast Shutdown of Windows]
  • rundll32.exe user.exe,**ExitWindowsExec** [Restart Windows]

    rundll32.exe shell32.dll,SHExitWindowsEx n
    

where n stands for:

  • 0 - LOGOFF
  • 1 - SHUTDOWN
  • 2 - REBOOT
  • 4 - FORCE
  • 8 - POWEROFF

(can be combined -> 6 = 2+4 FORCE REBOOT)


Update April 2015 (6+ years later):

1800 INFORMATION kindly points out in the comments:

Don't use rundll32.exe for this purpose. It expects that the function you passed on the command line has a very specific method signature - it doesn't match the method signature of ExitWindows.

Raymond CHEN wrote:

The function signature required for functions called by rundll32.exe is:

void CALLBACK ExitWindowsEx(HWND hwnd, HINSTANCE hinst,
       LPSTR pszCmdLine, int nCmdShow);

That hasn't stopped people from using rundll32 to call random functions that weren't designed to be called by rundll32, like user32 LockWorkStation or user32 ExitWindowsEx.

(oops)

The actual function signature for ExitWindowsEx is:

BOOL WINAPI ExitWindowsEx(UINT uFlags, DWORD dwReserved);

And to make it crystal-clear:

Rundll32 is a leftover from Windows 95, and it has been deprecated since at least Windows Vista because it violates a lot of modern engineering guidelines.

Convert float to std::string in C++

You can define a template which will work not only just with doubles, but with other types as well.

template <typename T> string tostr(const T& t) { 
   ostringstream os; 
   os<<t; 
   return os.str(); 
} 

Then you can use it for other types.

double x = 14.4;
int y = 21;

string sx = tostr(x);
string sy = tostr(y);

Generic Property in C#

Okay, I'll bite. You want something like this: If you declare a "property" like this:

Update: I'm now pretty sure that Fredrik Mörk answered your question and gave a solution. I'm not really happy with the idea, but it seems to answer exactly what I understood from your question.

public class PropertyFoo {
  public MyProp<String> Name;
}

this ends up as

public class PropertyFoo {
  public string Name {
    get { /* do predefined stuff here */ }
    set { /*other predefined stuff here */ }
  }
}

No. Not possible and not a property, really. Look for template/snippet support in your IDE.

Detect if the app was launched/opened from a push notification

If you are running iOS 13 or above use this code in your SceneDelegate:

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
    
    guard let notificationResponse = connectionOptions.notificationResponse else { return }
    
    let pushTitle = notificationResponse.notification.request.content.title
    let pushSubtitle = notificationResponse.notification.request.content.subtitle
    let pushBody = notificationResponse.notification.request.content.body
    
    // do your staff here
}

QLabel: set color of text and background

You can use QPalette, however you must set setAutoFillBackground(true); to enable background color

QPalette sample_palette;
sample_palette.setColor(QPalette::Window, Qt::white);
sample_palette.setColor(QPalette::WindowText, Qt::blue);

sample_label->setAutoFillBackground(true);
sample_label->setPalette(sample_palette);
sample_label->setText("What ever text");

It works fine on Windows and Ubuntu, I haven't played with any other OS.

Note: Please see QPalette, color role section for more details

How to sort a data frame by date

The only way I found to work with hours, through an US format in source (mm-dd-yyyy HH-MM-SS PM/AM)...

df_dataSet$time <- as.POSIXct( df_dataSet$time , format = "%m/%d/%Y %I:%M:%S %p" , tz = "GMT")
class(df_dataSet$time)
df_dataSet <- df_dataSet[do.call(order, df_dataSet), ] 

What's the difference between a null pointer and a void pointer?

Usually a null pointer (which can be of any type, including a void pointer !) points to:

  • the address 0, against which most CPU instructions sets can do a very fast compare-and-branch (to check for uninitialized or invalid pointers, for instance) with optimal code size/performance for the ISA.

  • an address that's illegal for user code to access (such as 0x00000000 in many cases), so that if a code actually tries to access data at or near this address, the OS or debugger can easily stop or trap a program with this bug.

A void pointer is usually a method of cheating or turning-off compiler type checking, for instance if you want to return a pointer to one type, or an unknown type, to use as another type. For instance malloc() returns a void pointer to a type-less chunk of memory, the type of which you can cast to later use as a pointer to bytes, short ints, double floats, typePotato's, or whatever.

How to disable input conditionally in vue.js

To toggle the input's disabled attribute was surprisingly complex. The issue for me was twofold:

(1) Remember: the input's "disabled" attribute is NOT a Boolean attribute.
The mere presence of the attribute means that the input is disabled.

However, the Vue.js creators have prepared this... https://vuejs.org/v2/guide/syntax.html#Attributes

(Thanks to @connexo for this... How to add disabled attribute in input text in vuejs?)

(2) In addition, there was a DOM timing re-rendering issue that I was having. The DOM was not updating when I tried to toggle back.

Upon certain situations, "the component will not re-render immediately. It will update in the next 'tick.'"

From Vue.js docs: https://vuejs.org/v2/guide/reactivity.html

The solution was to use:

this.$nextTick(()=>{
    this.disableInputBool = true
})

Fuller example workflow:

<div @click="allowInputOverwrite">
    <input
        type="text"
        :disabled="disableInputBool">
</div>

<button @click="disallowInputOverwrite">
    press me (do stuff in method, then disable input bool again)
</button>

<script>

export default {
  data() {
    return {
      disableInputBool: true
    }
  },
  methods: {
    allowInputOverwrite(){
      this.disableInputBool = false
    },
    disallowInputOverwrite(){
      // accomplish other stuff here.
      this.$nextTick(()=>{
        this.disableInputBool = true
      })
    }
  }

}
</script>

Finding element in XDocument?

My experience when working with large & complicated XML files is that sometimes neither Elements nor Descendants seem to work in retrieving a specific Element (and I still do not know why).

In such cases, I found that a much safer option is to manually search for the Element, as described by the following MSDN post:

https://social.msdn.microsoft.com/Forums/vstudio/en-US/3d457c3b-292c-49e1-9fd4-9b6a950f9010/how-to-get-tag-name-of-xml-by-using-xdocument?forum=csharpgeneral

In short, you can create a GetElement function:

private XElement GetElement(XDocument doc,string elementName)
{
    foreach (XNode node in doc.DescendantNodes())
    {
        if (node is XElement)
        {
            XElement element = (XElement)node;
            if (element.Name.LocalName.Equals(elementName))
                return element;
        }
    }
    return null;
}

Which you can then call like this:

XElement element = GetElement(doc,"Band");

Note that this will return null if no matching element is found.

cannot convert 'std::basic_string<char>' to 'const char*' for argument '1' to 'int system(const char*)'

The system function requires const char *, and your expression is of the type std::string. You should write

string name = "john";
string system_str = " quickscan.exe resolution 300 selectscanner jpg showui showprogress filename '"+name+".jpg'";
system(system_str.c_str ());

How to change context root of a dynamic web project in Eclipse?

Apache tomcat keeps the project context path in server.xml path. For each web project on Eclipse, there is tag from there you can change it.
Suppose, there are two or three project deployed on server. For each one context path is stored in . This tag is located on server.xml file within Server created on eclipse.

I have one project for there on context root path in server is:

<Context docBase="Test" path="/test" reloadable="true" source="org.eclipse.jst.jee.server:Test1"/>

This path represents context path of your web application. By changing this path, your web app context path will change.

Apple Cover-flow effect using jQuery or other library?

jCoverflip was just released and is very customizable.

How do I install the ext-curl extension with PHP 7?

I tried the above solutions but it didn't work for me, just incase there any other person in the same shoes, this is what I did. I updated apt-get with the following command

sudo add-apt-repository ppa:ondrej/php

this i installed with php curl for the version of php that i was using, mine was

sudo apt-get install php7.1-curl

What is special about /dev/tty?

/dev/tty is a synonym for the controlling terminal (if any) of the current process. As jtl999 says, it's a character special file; that's what the c in the ls -l output means.

man 4 tty or man -s 4 tty should give you more information, or you can read the man page online here.

Incidentally, pwd > /dev/tty doesn't necessarily print to the shell's stdout (though it is the pwd command's standard output). If the shell's standard output has been redirected to something other than the terminal, /dev/tty still refers to the terminal.

You can also read from /dev/tty, which will normally read from the keyboard.

Bootstrap Navbar toggle button not working

Your code looks great, the only thing i see is that you did not include the collapsed class in your button selector. http://www.bootply.com/cpHugxg2f8 Note: Requires JavaScript plugin If JavaScript is disabled and the viewport is narrow enough that the navbar collapses, it will be impossible to expand the navbar and view the content within the .navbar-collapse.

The responsive navbar requires the collapse plugin to be included in your version of Bootstrap.

<div class="navbar-wrapper">
      <div class="container">

        <nav class="navbar navbar-inverse navbar-static-top">
          <div class="container">
            <div class="navbar-header">
              <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
                <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="#">Project name</a>
            </div>
            <div id="navbar" class="navbar-collapse collapse">
              <ul class="nav navbar-nav">
                    <li><a href="">Page 1</a>
                    </li>
                    <li><a href="">Page 2</a>
                    </li>
                    <li><a href="">Page 3</a>
                    </li>

              </ul>
            </div>
          </div>
        </nav>

      </div>
    </div>

How to delete specific characters from a string in Ruby?

If you just want to remove the first two characters and the last two, then you can use negative indexes on the string:

s = "((String1))"
s = s[2...-2]
p s # => "String1"

If you want to remove all parentheses from the string you can use the delete method on the string class:

s = "((String1))"
s.delete! '()'
p s #  => "String1"

How to remove all the occurrences of a char in c++ string

This code removes repetition of characters i.e, if the input is aaabbcc then the output will be abc. (the array must be sorted for this code to work)

cin >> s;
ans = "";
ans += s[0];
for(int i = 1;i < s.length();++i)
if(s[i] != s[i-1])
    ans += s[i];
cout << ans << endl;

How do you Programmatically Download a Webpage in Java

Well, you could go with the built-in libraries such as URL and URLConnection, but they don't give very much control.

Personally I'd go with the Apache HTTPClient library.
Edit: HTTPClient has been set to end of life by Apache. The replacement is: HTTP Components

Why declare unicode by string in python?

That doesn't set the format of the string; it sets the format of the file. Even with that header, "hello" is a byte string, not a Unicode string. To make it Unicode, you're going to have to use u"hello" everywhere. The header is just a hint of what format to use when reading the .py file.

How to check command line parameter in ".bat" file?

You are comparing strings. If an arguments are omitted, %1 expands to a blank so the commands become IF =="-b" GOTO SPECIFIC for example (which is a syntax error). Wrap your strings in quotes (or square brackets).

REM this is ok
IF [%1]==[/?] GOTO BLANK

REM I'd recommend using quotes exclusively
IF "%1"=="-b" GOTO SPECIFIC

IF NOT "%1"=="-b" GOTO UNKNOWN

Xcode stops working after set "xcode-select -switch"

You should be pointing it towards the Developer directory, not the Xcode application bundle. Run this:

sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer

With recent versions of Xcode, you can go to Xcode ? Preferences… ? Locations and pick one of the options for Command Line Tools to set the location.

Need help rounding to 2 decimal places

The problem will be that you cannot represent 0.575 exactly as a binary floating point number (eg a double). Though I don't know exactly it seems that the representation closest is probably just a bit lower and so when rounding it uses the true representation and rounds down.

If you want to avoid this problem then use a more appropriate data type. decimal will do what you want:

Math.Round(0.575M, 2, MidpointRounding.AwayFromZero)

Result: 0.58

The reason that 0.75 does the right thing is that it is easy to represent in binary floating point since it is simple 1/2 + 1/4 (ie 2^-1 +2^-2). In general any finite sum of powers of two can be represented in binary floating point. Exceptions are when your powers of 2 span too great a range (eg 2^100+2 is not exactly representable).

Edit to add:

Formatting doubles for output in C# might be of interest in terms of understanding why its so hard to understand that 0.575 is not really 0.575. The DoubleConverter in the accepted answer will show that 0.575 as an Exact String is 0.5749999999999999555910790149937383830547332763671875 You can see from this why rounding give 0.57.

Is it possible to wait until all javascript files are loaded before executing javascript code?

You can use .getScript() and run your code after it loads:

 $.getScript("my_lovely_script.js", function(){

    alert("Script loaded and executed.");
    // here you can use anything you defined in the loaded script

 });

You can see a better explanation here: How do I include a JavaScript file in another JavaScript file?

How to Set Focus on Input Field using JQuery

If the input happens to be in a bootstrap modal dialog, the answer is different. Copying from How to Set focus to first text input in a bootstrap modal after shown this is what is required:

$('#myModal').on('shown.bs.modal', function () {
  $('#textareaID').focus();
})  

How to copy files between two nodes using ansible

A simple way to used copy module to transfer the file from one server to another

Here is playbook

---
- hosts: machine1 {from here file will be transferred to another remote machine}
  tasks:
  - name: transfer data from machine1 to machine2

    copy:
     src=/path/of/machine1

     dest=/path/of/machine2

    delegate_to: machine2 {file/data receiver machine}

Find the last element of an array while using a foreach loop in PHP

Another way to go is to remember the previous loop cycle result and use that as the end result:

    $result = $where = "";
    foreach ($conditions as $col => $val) {
        $result = $where .= $this->getAdapter()->quoteInto($col.' = ?', $val);
        $where .=  " AND ";
    }
    return $this->delete($result);

Calling Member Functions within Main C++

From your question it is unclear if you want to be able use the class without an identity or if calling the method requires you to create an instance of the class. This depends on whether you want the printInformation member to write some general information or more specific about the object identity.

Case 1: You want to use the class without creating an instance. The members of that class should be static, using this keyword you tell the compiler that you want to be able to call the method without having to create a new instance of the class.

class MyClass
{
public:
    static void printInformation();
};

Case 2: You want the class to have an instance, you first need to create an object so that the class has an identity, once that is done you can use the object his methods.

Myclass m;
m.printInformation();

// Or, in the case that you want to use pointers:
Myclass * m = new Myclass();
m->printInformation();

If you don't know when to use pointers, read Pukku's summary in this Stack Overflow question.
Please note that in the current case you would not need a pointer. :-)

Why does 'git commit' not save my changes?

I had a very similar issue with the same error message. "Changes not staged for commit", yet when I do a diff it shows differences. I finally figured out that a while back I had changed a directories case. ex. "PostgeSQL" to "postgresql". As I remember now sometimes git will leave a file or two behind in the old case directory. Then you will commit a new version to the new case.

Thus git doesn't know which one to rely on. So to resolve it, I had to go onto the github's website. Then you're able to view both cases. And you must delete all the files in the incorrect cased directory. Be sure that you have the correct version saved off or in the correct cased directory.

Once you have deleted all the files in the old case directory, that whole directory will disappear. Then do a commit.

At this point you should be able to do a Pull on your local computer and not see the conflicts any more. Thus being able to commit again. :)

How can I copy a conditional formatting from one document to another?

You can also copy a cell which contains the conditional formatting and then select the range (of destination document -or page-) where you want the conditional format to be applied and select "paste special" > "paste only conditional formatting"

How do we count rows using older versions of Hibernate (~2009)?

It's very easy, just run the following JPQL query:

int count = (
(Number)
    entityManager
    .createQuery(
        "select count(b) " +
        "from Book b")
    .getSingleResult()
).intValue();

The reason we are casting to Number is that some databases will return Long while others will return BigInteger, so for portability sake you are better off casting to a Number and getting an int or a long, depending on how many rows you are expecting to be counted.

TypeError: module.__init__() takes at most 2 arguments (3 given)

In my case where I had the problem I was referring to a module when I tried extending the class.

import logging
class UserdefinedLogging(logging):

If you look at the Documentation Info, you'll see "logging" displayed as module.

In this specific case I had to simply inherit the logging module to create an extra class for the logging.

Select row and element in awk

To print the columns with a specific string, you use the // search pattern. For example, if you are looking for second columns that contains abc:

awk '$2 ~ /abc/'

... and if you want to print only a particular column:

awk '$2 ~ /abc/ { print $3 }'

... and for a particular line number:

awk '$2 ~ /abc/ && FNR == 5 { print $3 }'

How to join entries in a set into one string?

You have the join statement backwards try:

print ', '.join(set_3)

Difference between iCalendar (.ics) and the vCalendar (.vcs)

The newer iCalendar format, with more data attached, includes information about the person who created the event, so that when it is imported into Outlook (for example), changes to that event are communicated via email to the creator. This can be helpful when you need to inform others of any changes.

However, when I am just exporting an event from one of my calendars to another, I prefer to use vCalendar, since this does not require sending an email message to the creator (usually myself) if I make a change or delete something.

align textbox and text/labels in html?

Using a table would be one (and easy) option.

Other options are all about setting fixed width on the and making it text-aligned to the right:

label {
   width: 200px;
   display: inline-block;
   text-align: right;
}

or, as was pointed out, make them all float instead of inline.

Positioning the colorbar

The best way to get good control over the colorbar position is to give it its own axis. Like so:

# What I imagine your plotting looks like so far
fig = plt.figure()
ax1 = fig.add_subplot(111)
ax1.plot(your_data)

# Now adding the colorbar
cbaxes = fig.add_axes([0.8, 0.1, 0.03, 0.8]) 
cb = plt.colorbar(ax1, cax = cbaxes)  

The numbers in the square brackets of add_axes refer to [left, bottom, width, height], where the coordinates are just fractions that go from 0 to 1 of the plotting area.

How to zip a whole folder using PHP

There is a useful undocumented method in the ZipArchive class: addGlob();

$zipFile = "./testZip.zip";
$zipArchive = new ZipArchive();

if ($zipArchive->open($zipFile, (ZipArchive::CREATE | ZipArchive::OVERWRITE)) !== true)
    die("Failed to create archive\n");

$zipArchive->addGlob("./*.txt");
if ($zipArchive->status != ZIPARCHIVE::ER_OK)
    echo "Failed to write files to zip\n";

$zipArchive->close();

Now documented at: www.php.net/manual/en/ziparchive.addglob.php

postgresql: INSERT INTO ... (SELECT * ...)

If you want insert into specify column:

INSERT INTO table (time)
(SELECT time FROM 
    dblink('dbname=dbtest', 'SELECT time FROM tblB') AS t(time integer) 
    WHERE time > 1000
);

Javascript Debugging line by line using Google Chrome

Assuming you're running on a Windows machine...

  1. Hit the F12 key
  2. Select the Scripts, or Sources, tab in the developer tools
  3. Click the little folder icon in the top level
  4. Select your JavaScript file
  5. Add a breakpoint by clicking on the line number on the left (adds a little blue marker)
  6. Execute your JavaScript

Then during execution debugging you can do a handful of stepping motions...

  • F8 Continue: Will continue until the next breakpoint
  • F10 Step over: Steps over next function call (won't enter the library)
  • F11 Step into: Steps into the next function call (will enter the library)
  • Shift + F11 Step out: Steps out of the current function

Update

After reading your updated post; to debug your code I would recommend temporarily using the jQuery Development Source Code. Although this doesn't directly solve your problem, it will allow you to debug more easily. For what you're trying to achieve I believe you'll need to step-in to the library, so hopefully the production code should help you decipher what's happening.

Execute command on all files in a directory

How about this:

find /some/directory -maxdepth 1 -type f -exec cmd option {} \; > results.out
  • -maxdepth 1 argument prevents find from recursively descending into any subdirectories. (If you want such nested directories to get processed, you can omit this.)
  • -type -f specifies that only plain files will be processed.
  • -exec cmd option {} tells it to run cmd with the specified option for each file found, with the filename substituted for {}
  • \; denotes the end of the command.
  • Finally, the output from all the individual cmd executions is redirected to results.out

However, if you care about the order in which the files are processed, you might be better off writing a loop. I think find processes the files in inode order (though I could be wrong about that), which may not be what you want.

Google drive limit number of download

It looks like that this limitation can be avoided if you use the following URL pattern:

https://googledrive.com/host/file-id

For your case the download URL will look like this - https://googledrive.com/host/0ByvXJAlpPqQPYWNqY0V3MGs0Ujg

Please keep in mind that this method works only if file is shared with "Public on the web" option.

Python basics printing 1 to 100

consider the following:

def gukan(count):
    while count < 100:
      print(count)
      count=count+3;
gukan(0) #prints ..., 93, 96, 99


def gukan(count):
    while count < 100:
      print(count)
      count=count+9;
gukan(0) # prints ..., 81, 90, 99

you should use count < 100 because count will never reach the exact number 100 if you use 3 or 9 as the increment, thus creating an infinite loop.

Good luck!~ :)

How to change font size in a textbox in html

Here are some ways to edit the text and the size of the box:

rows="insertNumber"
cols="insertNumber"
style="font-size:12pt"

Example:

<textarea rows="5" cols="30" style="font-size: 12pt" id="myText">Enter 
Text Here</textarea>

Set markers for individual points on a line in Matplotlib

A simple trick to change a particular point marker shape, size... is to first plot it with all the other data then plot one more plot only with that point (or set of points if you want to change the style of multiple points). Suppose we want to change the marker shape of second point:

x = [1,2,3,4,5]
y = [2,1,3,6,7]

plt.plot(x, y, "-o")
x0 = [2]
y0 = [1]
plt.plot(x0, y0, "s")

plt.show()

Result is: Plot with multiple markers

enter image description here

How to set a parameter in a HttpServletRequest?

The most upvoted solution generally works but for Spring and/or Spring Boot, the values will not wire to parameters in controller methods annotated with @RequestParam unless you specifically implemented getParameterValues(). I combined the solution(s) here and from this blog:

import java.util.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

public class MutableHttpRequest extends HttpServletRequestWrapper {

    private final Map<String, String[]> mutableParams = new HashMap<>();

    public MutableHttpRequest(final HttpServletRequest request) {
        super(request);
    }

    public MutableHttpRequest addParameter(String name, String value) {
        if (value != null)
            mutableParams.put(name, new String[] { value });

        return this;
    }

    @Override
    public String getParameter(final String name) {
        String[] values = getParameterMap().get(name);

        return Arrays.stream(values)
                .findFirst()
                .orElse(super.getParameter(name));
    }

    @Override
    public Map<String, String[]> getParameterMap() {
        Map<String, String[]> allParameters = new HashMap<>();
        allParameters.putAll(super.getParameterMap());
        allParameters.putAll(mutableParams);

        return Collections.unmodifiableMap(allParameters);
    }

    @Override
    public Enumeration<String> getParameterNames() {
        return Collections.enumeration(getParameterMap().keySet());
    }

    @Override
    public String[] getParameterValues(final String name) {
        return getParameterMap().get(name);
    }
}

note that this code is not super-optimized but it works.

When do I use the PHP constant "PHP_EOL"?

I found PHP_EOL very useful for file handling, specially if you are writing multiple lines of content into a file.

For example, you have a long string that you want to break into the multiple lines while writing into plain file. Using \r\n might not work so simply put PHP_EOL into your script and the result is awesome.

Check out this simple example below:

<?php

$output = 'This is line 1' . PHP_EOL .
          'This is line 2' . PHP_EOL .
          'This is line 3';

$file = "filename.txt";

if (is_writable($file)) {
    // In our example we're opening $file in append mode.
    // The file pointer is at the bottom of the file hence
    // that's where $output will go when we fwrite() it.
    if (!$handle = fopen($file, 'a')) {
         echo "Cannot open file ($file)";
         exit;
    }
    // Write $output to our opened file.
    if (fwrite($handle, $output) === FALSE) {
        echo "Cannot write to file ($file)";
        exit;
    }
    echo "Success, content ($output) wrote to file ($file)";
    fclose($handle);
} else {
    echo "The file $file is not writable";
}
?>

numpy max vs amax vs maximum

np.max is just an alias for np.amax. This function only works on a single input array and finds the value of maximum element in that entire array (returning a scalar). Alternatively, it takes an axis argument and will find the maximum value along an axis of the input array (returning a new array).

>>> a = np.array([[0, 1, 6],
                  [2, 4, 1]])
>>> np.max(a)
6
>>> np.max(a, axis=0) # max of each column
array([2, 4, 6])

The default behaviour of np.maximum is to take two arrays and compute their element-wise maximum. Here, 'compatible' means that one array can be broadcast to the other. For example:

>>> b = np.array([3, 6, 1])
>>> c = np.array([4, 2, 9])
>>> np.maximum(b, c)
array([4, 6, 9])

But np.maximum is also a universal function which means that it has other features and methods which come in useful when working with multidimensional arrays. For example you can compute the cumulative maximum over an array (or a particular axis of the array):

>>> d = np.array([2, 0, 3, -4, -2, 7, 9])
>>> np.maximum.accumulate(d)
array([2, 2, 3, 3, 3, 7, 9])

This is not possible with np.max.

You can make np.maximum imitate np.max to a certain extent when using np.maximum.reduce:

>>> np.maximum.reduce(d)
9
>>> np.max(d)
9

Basic testing suggests the two approaches are comparable in performance; and they should be, as np.max() actually calls np.maximum.reduce to do the computation.

Trigger change event of dropdown

I don't know that much JQuery but I've heard it allows to fire native events with this syntax.

$(document).ready(function(){

    $('#countrylist').change(function(e){
       // Your event handler
    });

    // And now fire change event when the DOM is ready
    $('#countrylist').trigger('change');
});

You must declare the change event handler before calling trigger() or change() otherwise it won't be fired. Thanks for the mention @LenielMacaferi.

More information here.

Comparing object properties in c#

here is revised one to treat null = null as equal

 private bool PublicInstancePropertiesEqual<T>(T self, T to, params string[] ignore) where T : class
        {
            if (self != null && to != null)
            {
                Type type = typeof(T);
                List<string> ignoreList = new List<string>(ignore);
                foreach (PropertyInfo pi in type.GetProperties(BindingFlags.Public | BindingFlags.Instance))
                {
                    if (!ignoreList.Contains(pi.Name))
                    {
                        object selfValue = type.GetProperty(pi.Name).GetValue(self, null);
                        object toValue = type.GetProperty(pi.Name).GetValue(to, null);
                        if (selfValue != null)
                        {
                            if (!selfValue.Equals(toValue))
                                return false;
                        }
                        else if (toValue != null)
                            return false;
                    }
                }
                return true;
            }
            return self == to;
        }

Python get current time in right timezone

To get the current time in the local timezone as a naive datetime object:

from datetime import datetime
naive_dt = datetime.now()

If it doesn't return the expected time then it means that your computer is misconfigured. You should fix it first (it is unrelated to Python).

To get the current time in UTC as a naive datetime object:

naive_utc_dt = datetime.utcnow()

To get the current time as an aware datetime object in Python 3.3+:

from datetime import datetime, timezone

utc_dt = datetime.now(timezone.utc) # UTC time
dt = utc_dt.astimezone() # local time

To get the current time in the given time zone from the tz database:

import pytz

tz = pytz.timezone('Europe/Berlin')
berlin_now = datetime.now(tz)

It works during DST transitions. It works if the timezone had different UTC offset in the past i.e., it works even if the timezone corresponds to multiple tzinfo objects at different times.

Design Documents (High Level and Low Level Design Documents)

High-Level Design (HLD) involves decomposing a system into modules, and representing the interfaces & invocation relationships among modules. An HLD is referred to as software architecture.

LLD, also known as a detailed design, is used to design internals of the individual modules identified during HLD i.e. data structures and algorithms of the modules are designed and documented.

Now, HLD and LLD are actually used in traditional Approach (Function-Oriented Software Design) whereas, in OOAD, the system is seen as a set of objects interacting with each other.

As per the above definitions, a high-level design document will usually include a high-level architecture diagram depicting the components, interfaces, and networks that need to be further specified or developed. The document may also depict or otherwise refer to work flows and/or data flows between component systems.

Class diagrams with all the methods and relations between classes come under LLD. Program specs are covered under LLD. LLD describes each and every module in an elaborate manner so that the programmer can directly code the program based on it. There will be at least 1 document for each module. The LLD will contain - a detailed functional logic of the module in pseudo code - database tables with all elements including their type and size - all interface details with complete API references(both requests and responses) - all dependency issues - error message listings - complete inputs and outputs for a module.

Can not deserialize instance of java.util.ArrayList out of VALUE_STRING

This is the solution for my old question:

I implemented my own ContextResolver in order to enable the DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY feature.

package org.lig.hadas.services.mapper;

import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.ext.ContextResolver;
import javax.ws.rs.ext.Provider;

import org.codehaus.jackson.map.DeserializationConfig;
import org.codehaus.jackson.map.ObjectMapper;

@Produces(MediaType.APPLICATION_JSON)
@Provider
public class ObjectMapperProvider implements ContextResolver<ObjectMapper>
{
   ObjectMapper mapper;

   public ObjectMapperProvider(){
       mapper = new ObjectMapper();
       mapper.configure(DeserializationConfig.Feature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true);
   }
   @Override
   public ObjectMapper getContext(Class<?> type) {
       return mapper;
   }
}

And in the web.xml I registered my package into the servlet definition...

<servlet>
    <servlet-name>...</servlet-name>
    <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
    <init-param>
        <param-name>com.sun.jersey.config.property.packages</param-name>
        <param-value>...;org.lig.hadas.services.mapper</param-value>        
    </init-param>
    ...
</servlet>

... all the rest is transparently done by jersey/jackson.

jQuery - If element has class do this

First, you're missing some parentheses in your conditional:

if ($("#about").hasClass("opened")) {
  $("#about").animate({right: "-700px"}, 2000);
}

But you can also simplify this to:

$('#about.opened').animate(...);

If #about doesn't have the opened class, it won't animate.

If the problem is with the animation itself, we'd need to know more about your element positioning (absolute? absolute inside relative parent? does the parent have layout?)

Round number to nearest integer

I use and may advise the following solution (python3.6):

y = int(x + (x % (1 if x >= 0 else -1)))

It works fine for half-numbers (positives and negatives) and works even faster than int(round(x)):

round_methods = [lambda x: int(round(x)), 
                 lambda x: int(x + (x % (1 if x >= 0 else -1))),
                 lambda x: np.rint(x).astype(int),
                 lambda x: int(proper_round(x))]

for rm in round_methods:
    %timeit rm(112.5)
Out:
201 ns ± 3.96 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
159 ns ± 0.646 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)
925 ns ± 7.66 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
1.18 µs ± 8.66 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)

for rm in round_methods:
    print(rm(112.4), rm(112.5), rm(112.6))
    print(rm(-12.4), rm(-12.5), rm(-12.6))
    print('=' * 11)

Out:
112 112 113
-12 -12 -13
===========
112 113 113
-12 -13 -13
===========
112 112 113
-12 -12 -13
===========
112 113 113
-12 -13 -13
===========