Programs & Examples On #Xmlbeans

XMLBeans is a technology for accessing XML by binding it to Java types.

Apache POI error loading XSSFWorkbook class

If you have downloaded pio-3.17 On eclipse: right click on the project folder -> build path -> configure build path -> libraries -> add external jars -> add all the commons jar file from the "lib". It's worked for me.

org.apache.poi.POIXMLException: org.apache.poi.openxml4j.exceptions.InvalidFormatException:

You are trying to access an XLS file. However, you are using XSSFWorkbook and XSSFSheet class objects. These classes are mainly used for XLSX files.

For XLS file: HSSFWorkbook & HSSFSheet
For XLSX file: XSSFSheet & XSSFSheet

So in place of XSSFWorkbook use HSSFWorkbook and in place of XSSFSheet use HSSFSheet.

So your code should look like this after the changes are made:

HSSFWorkbook workbook = new HSSFWorkbook(file);

HSSFSheet sheet = workbook.getSheetAt(0);

java.lang.ClassNotFoundException: org.apache.xmlbeans.XmlObject Error

When trying to translate Excel file with .xlsx suffix, you need to add additional jar, xmlbeansxxx.jar. xxxx is version, such as xmlbeans-2.3.0.jar

Maven: how to override the dependency added by a library

Simply specify the version in your current pom. The version specified here will override other.

Forcing a version
A version will always be honoured if it is declared in the current POM with a particular version - however, it should be noted that this will also affect other poms downstream if it is itself depended on using transitive dependencies.


Resources :

Java Webservice Client (Best way)

I have had good success using Spring WS for the client end of a web service app - see http://static.springsource.org/spring-ws/sites/1.5/reference/html/client.html

My project uses a combination of:

  • XMLBeans (generated from a simple Maven job using the xmlbeans-maven-plugin)

  • Spring WS - using marshalSendAndReceive() reduces the code down to one line for sending and receiving

  • some Dozer - mapping the complex XMLBeans to simple beans for the client GUI

Set mouse focus and move cursor to end of input using jQuery

    function focusCampo(id){
        var inputField = document.getElementById(id);
        if (inputField != null && inputField.value.length != 0){
            if (inputField.createTextRange){
                var FieldRange = inputField.createTextRange();
                FieldRange.moveStart('character',inputField.value.length);
                FieldRange.collapse();
                FieldRange.select();
            }else if (inputField.selectionStart || inputField.selectionStart == '0') {
                var elemLen = inputField.value.length;
                inputField.selectionStart = elemLen;
                inputField.selectionEnd = elemLen;
                inputField.focus();
            }
        }else{
            inputField.focus();
        }
    }

$('#urlCompany').focus(focusCampo('urlCompany'));

works for all ie browsers..

Omitting one Setter/Getter in Lombok

If you have setter and getter as private it will come up in PMD checks.

How can I open two pages from a single click without using JavaScript?

it is working perfectly by only using html

<p><a href="#"onclick="window.open('http://google.com');window.open('http://yahoo.com');">Click to open Google and Yahoo</a></p>

calling server side event from html button control

On your aspx page define the HTML Button element with the usual suspects: runat, class, title, etc.

If this element is part of a data bound control (i.e.: grid view, etc.) you may want to use CommandName and possibly CommandArgument as attributes. Add your button's content and closing tag.

<button id="cmdAction" 
    runat="server" onserverclick="cmdAction_Click()" 
    class="Button Styles" 
    title="Does something on the server" 
    <!-- for databound controls -->
    CommandName="cmdname"> 
    CommandArgument="args..."
    >
    <!-- content -->
    <span class="ui-icon ..."></span>
    <span class="push">Click Me</span>
</button>

On the code behind page the element would call the handler that would be defined as the element's ID_Click event function.

protected void cmdAction_Click(object sender, EventArgs e)
{
: do something.
}

There are other solutions as in using custom controls, etc. Also note that I am using this live on projects in VS2K8.

Hoping this helps. Enjoy!

Get pandas.read_csv to read empty values as empty string instead of nan

We have a simple argument in Pandas read_csv for this:

Use:

df = pd.read_csv('test.csv', na_filter= False)

Pandas documentation clearly explains how the above argument works.

Link

convert string into array of integers

The point against parseInt-approach:

There's no need to use lambdas and/or give radix parameter to parseInt, just use parseFloat or Number instead.


Reasons:

  1. It's working:

    var src = "1,2,5,4,3";
    var ids = src.split(',').map(parseFloat); // [1, 2, 5, 4, 3]
    
    var obj = {1: ..., 3: ..., 4: ..., 7: ...};
    var keys= Object.keys(obj); // ["1", "3", "4", "7"]
    var ids = keys.map(parseFloat); // [1, 3, 4, 7]
    
    var arr = ["1", 5, "7", 11];
    var ints= arr.map(parseFloat); // [1, 5, 7, 11]
    ints[1] === "5" // false
    ints[1] === 5   // true
    ints[2] === "7" // false
    ints[2] === 7   // true
    
  2. It's shorter.

  3. It's a tiny bit quickier and takes advantage of cache, when parseInt-approach - doesn't:

      // execution time measure function
      // keep it simple, yeah?
    > var f = (function (arr, c, n, m) {
          var i,t,m,s=n();
          for(i=0;i++<c;)t=arr.map(m);
          return n()-s
      }).bind(null, "2,4,6,8,0,9,7,5,3,1".split(','), 1000000, Date.now);
    
    > f(Number) // first launch, just warming-up cache
    > 3971 // nice =)
    
    > f(Number)
    > 3964 // still the same
    
    > f(function(e){return+e})
    > 5132 // yup, just little bit slower
    
    > f(function(e){return+e})
    > 5112 // second run... and ok.
    
    > f(parseFloat)
    > 3727 // little bit quicker than .map(Number)
    
    > f(parseFloat)
    > 3737 // all ok
    
    > f(function(e){return parseInt(e,10)})
    > 21852 // awww, how adorable...
    
    > f(function(e){return parseInt(e)})
    > 22928 // maybe, without '10'?.. nope.
    
    > f(function(e){return parseInt(e)})
    > 22769 // second run... and nothing changes.
    
    > f(Number)
    > 3873 // and again
    > f(parseFloat)
    > 3583 // and again
    > f(function(e){return+e})
    > 4967 // and again
    
    > f(function(e){return parseInt(e,10)})
    > 21649 // dammit 'parseInt'! >_<
    

Notice: In Firefox parseInt works about 4 times faster, but still slower than others. In total: +e < Number < parseFloat < parseInt

disabling spring security in spring boot app

Since security.disable option is banned from usage there is still a way to achieve it from pure config without touching any class flies (for me it creates convenience with environments manipulation and possibility to activate it with ENV variable) if you use Boot

spring.autoconfigure.exclude: org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration

Programmatically go back to the previous fragment in the backstack

By adding fragment_tran.addToBackStack(null) on last fragment, I am able to do come back on last fragment.

adding new fragment:

view.findViewById(R.id.changepass).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            FragmentTransaction transaction = getActivity().getSupportFragmentManager().beginTransaction();
            transaction.replace(R.id.container, new ChangePassword());
            transaction.addToBackStack(null);
            transaction.commit();
        }
    });

Remove "whitespace" between div element

You may use line-height on div1 as below:

<div id="div1" style="line-height:0px;">
    <div></div><div></div><div></div><br/><div></div><div></div><div></div>
</div>

See this: http://jsfiddle.net/wCpU8/

Bootstrap 3 Navbar Collapse

If the problem you face is the menu breaking into multiple lines, you can try one of the following:

1) Try to reduce the number of menu items or their length, like removing menu items or shortening the words.

2) Reducing the padding between the menu items, like this:

.navbar .nav > li > a {
padding: 10px 15px 10px; /* Change here the second value for padding-left and padding right */
}

Default padding is 15px both sides (left and right).

If you prefer to change each individual side use:

padding-left: 7px; 
padding-right: 8px;

This setting affects the dropdown list too.

This doesn't answer the question but it could help others who don't want to mess with the CSS or using LESS variables. The two common approaches to solve this problem.

Returning multiple values from a C++ function

Boost tuple would be my preferred choice for a generalized system of returning more than one value from a function.

Possible example:

include "boost/tuple/tuple.hpp"

tuple <int,int> divide( int dividend,int divisor ) 

{
  return make_tuple(dividend / divisor,dividend % divisor )
}

How to compare two files in Notepad++ v6.6.8

There is the "Compare" plugin. You can install it via Plugins > Plugin Manager.

Alternatively you can install a specialized file compare software like WinMerge.

How to return rows from left table not found in right table?

select * from left table where key field not in (select key field from right table)

What is the difference between atan and atan2 in C++?

Consider a right angled triangle. We label the hypotenuse r, the horizontal side y and the vertical side x. The angle of interest α is the angle between x and r.

C++ atan2(y, x) will give us the value of angle α in radians. atan is used if we only know or are interested in y/x not y and x individually. So if p = y/x then to get α we'd use atan(p).

You cannot use atan2 to determine the quadrant, you can use atan2 only if you already know which quadrant your in! In particular positive x and y imply the first quadrant, positive y and negative x, the second and so on. atan or atan2 themselves simply return a positive or a negative number, nothing more.

TimePicker Dialog from clicking EditText

public class **Your java Class** extends ActionBarActivity implements  View.OnClickListener{
date = (EditText) findViewById(R.id.date);
date.setInputType(InputType.TYPE_NULL);
        date.requestFocus();
        date.setOnClickListener(this);
        dateFormatter = new SimpleDateFormat("yyyy-MM-dd", Locale.US);

        setDateTimeField();

private void setDateTimeField() {
        Calendar newCalendar = Calendar.getInstance();
        fromDatePickerDialog = new DatePickerDialog(this, new DatePickerDialog.OnDateSetListener() {

            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                Calendar newDate = Calendar.getInstance();
                newDate.set(year, monthOfYear, dayOfMonth);
                date.setText(dateFormatter.format(newDate.getTime()));
            }

        }, newCalendar.get(Calendar.YEAR), newCalendar.get(Calendar.MONTH), newCalendar.get(Calendar.DAY_OF_MONTH));

    }
@Override
    public void onClick(View v) {
        fromDatePickerDialog.show();
    }
}

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

On many devices (such as the iPhone), it prevents the user from using the browser's zoom. If you have a map and the browser does the zooming, then the user will see a big ol' pixelated image with huge pixelated labels. The idea is that the user should use the zooming provided by Google Maps. Not sure about any interaction with your plugin, but that's what it's there for.

More recently, as @ehfeng notes in his answer, Chrome for Android (and perhaps others) have taken advantage of the fact that there's no native browser zooming on pages with a viewport tag set like that. This allows them to get rid of the dreaded 300ms delay on touch events that the browser takes to wait and see if your single touch will end up being a double touch. (Think "single click" and "double click".) However, when this question was originally asked (in 2011), this wasn't true in any mobile browser. It's just added awesomeness that fortuitously arose more recently.

Java program to connect to Sql Server and running the sample query From Eclipse

Just Change the query like this:

SELECT TOP 1 * FROM [HumanResources].[Employee]

where Employee is your table name and HumanResources is your Schema name if I am not wrong.

Hope your problem will be resolved. :)

How would I check a string for a certain letter in Python?

Use the in keyword without is.

if "x" in dog:
    print "Yes!"

If you'd like to check for the non-existence of a character, use not in:

if "x" not in dog:
    print "No!"

The iOS Simulator deployment targets is set to 7.0, but the range of supported deployment target version for this platform is 8.0 to 12.1

If your are come from react-native and facing this error just do this

  1. Open Podfile(your project > ios>Podfile)
  2. comment flipper functions in podfile as below
#use_flipper!
 #post_install do |installer|
   #flipper_post_install(installer)
 #end
  1. In terminal inside IOS folder enter this command pod install

yep, that is it hope it works to you

Javascript - User input through HTML input tag to set a Javascript variable?

I tried to send/add input tag's values into JavaScript variable which worked well for me, here is the code:

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript">
            function changef()
            {
            var ctext=document.getElementById("c").value;

            document.writeln(ctext);
            }

        </script>
    </head>
    <body>
        <input type="text" id="c" onchange="changef"();>

        <button type="button" onclick="changef()">click</button>
    </body> 
</html>

Responsive dropdown navbar with angular-ui bootstrap (done in the correct angular kind of way)

My solotion for responsive/dropdown navbar with angular-ui bootstrap (when update to angular 1.5 and, ui-bootrap 1.2.1)
index.html

     ...    
    <link rel="stylesheet" href="/css/app.css">
</head>
<body>


<nav class="navbar navbar-inverse navbar-fixed-top">
        <div class="container">
            <input type="checkbox" id="navbar-toggle-cbox">
            <div class="navbar-header">
                <label for="navbar-toggle-cbox" class="navbar-toggle" 
                       ng-init="navCollapsed = true" 
                       ng-click="navCollapsed = !navCollapsed"  
                       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>
                </label>
                <a class="navbar-brand" href="#">Project name</a>
                 <div id="navbar" class="collapse navbar-collapse"  ng-class="{'in':!navCollapsed}">
                    <ul class="nav navbar-nav">
                        <li class="active"><a href="/view1">Home</a></li>
                        <li><a href="/view2">About</a></li>
                        <li><a href="#">Contact</a></li>
                        <li uib-dropdown>
                            <a href="#" uib-dropdown-toggle>Dropdown <b class="caret"></b></a>
                            <ul uib-dropdown-menu role="menu" aria-labelledby="split-button">
                                <li role="menuitem"><a href="#">Action</a></li>
                                <li role="menuitem"><a href="#">Another action</a></li>                                   
                            </ul>
                        </li>

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

app.css

/* show the collapse when navbar toggle is checked */
#navbar-toggle-cbox:checked ~ .collapse {
    display: block;
}

/* the checkbox used only internally; don't display it */
#navbar-toggle-cbox {
  display:none
}

Differences between Octave and MATLAB?

MATLAB is, first and foremost, a commercial offering. Therefore, everything in MATLAB pretty much works out of the box. All the core functionality is solid, and if you're working on a special project then MATLAB probably has an add-on they can sell you that adds a lot of additional domain-specific .m files for you. It ain't cheap, but it works and it will get the job done without complaint.

Octave always shows its open-source, information-wants-to-be-free roots. It's free, and it will remind you that it's free at every opportunity. It's developed by volunteers who hate Windows with a passion. Therefore Octave runs on Windows grudgingly. It's quite surprising that as many MATLAB features exist as they do.

But here's the rub. Anytime you try to do something more than trivially complex, Octave suddenly breaks in subtle and hard to understand ways. Oops -- the terminal driver had an overflow somewhere deep in the OpenGL layer. You can't print. Oops -- the figure plots do strange things with their fonts. Good luck figuring out why. Oops -- there's some hidden dependency between Octave and some other obscure bit of free software, so it won't compile. Good luck figuring out which it is.

And the Octave response is hey! It's free software! You have all the source code, you can fix all those bugs yourself! Maybe if I had infinite time and resources on my hands, I could spend all my time fixing bugs in free software, but I personally don't. If I worked in academia, I might.

So at the core, the issue of whether to choose MATLAB or Octave comes down to one question. Interestingly, that question is always the same, when choosing between commercial vs. free software variants.

And the question is:

Do you have more money than time?

How to set up a squid Proxy with basic username and password authentication?

Here's what I had to do to setup basic auth on Ubuntu 14.04 (didn't find a guide anywhere else)

Basic squid conf

/etc/squid3/squid.conf instead of the super bloated default config file

auth_param basic program /usr/lib/squid3/basic_ncsa_auth /etc/squid3/passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated

# Choose the port you want. Below we set it to default 3128.
http_port 3128

Please note the basic_ncsa_auth program instead of the old ncsa_auth

squid 2.x

For squid 2.x you need to edit /etc/squid/squid.conf file and place:

auth_param basic program /usr/lib/squid/digest_pw_auth /etc/squid/passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated

Setting up a user

sudo htpasswd -c /etc/squid3/passwords username_you_like

and enter a password twice for the chosen username then

sudo service squid3 restart

squid 2.x

sudo htpasswd -c /etc/squid/passwords username_you_like

and enter a password twice for the chosen username then

sudo service squid restart

htdigest vs htpasswd

For the many people that asked me: the 2 tools produce different file formats:

  • htdigest stores the password in plain text.
  • htpasswd stores the password hashed (various hashing algos are available)

Despite this difference in format basic_ncsa_auth will still be able to parse a password file generated with htdigest. Hence you can alternatively use:

sudo htdigest -c /etc/squid3/passwords realm_you_like username_you_like

Beware that this approach is empirical, undocumented and may not be supported by future versions of Squid.

On Ubuntu 14.04 htdigest and htpasswd are both available in the [apache2-utils][1] package.

MacOS

Similar as above applies, but file paths are different.

Install squid

brew install squid

Start squid service

brew services start squid

Squid config file is stored at /usr/local/etc/squid.conf.

Comment or remove following line:

http_access allow localnet

Then similar to linux config (but with updated paths) add this:

auth_param basic program /usr/local/Cellar/squid/4.8/libexec/basic_ncsa_auth /usr/local/etc/squid_passwords
auth_param basic realm proxy
acl authenticated proxy_auth REQUIRED
http_access allow authenticated

Note that path to basic_ncsa_auth may be different since it depends on installed version when using brew, you can verify this with ls /usr/local/Cellar/squid/. Also note that you should add the above just bellow the following section:

#
# INSERT YOUR OWN RULE(S) HERE TO ALLOW ACCESS FROM YOUR CLIENTS
#

Now generate yourself a user:password basic auth credential (note: htpasswd and htdigest are also both available on MacOS)

htpasswd -c /usr/local/etc/squid_passwords username_you_like

Restart the squid service

brew services restart squid

Why is there no Constant feature in Java?

You can use static final to create something that works similar to Const, I have used this in the past.

protected static final int cOTHER = 0;
protected static final int cRPM = 1;
protected static final int cSPEED = 2;
protected static final int cTPS = 3;
protected int DataItemEnum = 0;

public static final int INVALID_PIN = -1;
public static final int LED_PIN = 0;

Notification bar icon turns white in Android 5 Lollipop

Another option is to take advantage of version-specific drawable (mipmap) directories to supply different graphics for Lollipop and above.

In my app, the "v21" directories contain icons with transparent text while the other directories contain non-transparent version (for versions of Android older than Lollipop).

File system

Which should look something like this:

Android Studio

This way, you don't need to check for version numbers in code, e.g.

PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,
            PendingIntent.FLAG_ONE_SHOT);

Uri defaultSoundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)
        .setSmallIcon(R.mipmap.ic_notification)
        .setContentTitle(title)
        .setContentText(message)
        .setAutoCancel(true)
        .setSound(defaultSoundUri)
            .setContentIntent(pendingIntent);

Likewise, you can reference "ic_notification" (or whatever you choose to call it) in your GCM payload if you use the "icon" attribute.

https://developers.google.com/cloud-messaging/http-server-ref#notification-payload-support

Wrapping a react-router Link in an html button

You can use useHistory hook since react-router v5.1.0.

The useHistory hook gives you access to the history instance that you may use to navigate.

import React from 'react'
import { useHistory } from 'react-router-dom'

export default function SomeComponent() {
  const { push } = useHistory()
  ...
  <button
    type="button"
    onClick={() => push('/some-link')}
  >
    Some link
  </button>
  ...
}

Inline CSS styles in React: how to implement a:hover?

In regards to styled-components and react-router v4 you can do this:

import {NavLink} from 'react-router-dom'

const Link = styled(NavLink)`     
  background: blue;

  &:hover {
    color: white;
  }
`

...
<Clickable><Link to="/somewhere">somewhere</Link></Clickable>

Why do I get "MismatchSenderId" from GCM server side?

Check google-services.json file in app folder of your Android project. Generate a new one from Firebase console if you are unsure. I got this error in two cases.

  1. I used a test Firebase project with test application (that contained right google-services.json file). Then I tried to send push notification to another application and got this error ('"error": "MismatchSenderId"'). I understood that the second application was bound to another Firebase project with different google-services.json. Because server keys are different, the request should be rewritten.

  2. I changed google-services.json in the application, because I wanted to replace test Firebase project with an actual. I generated right google-services.json file, changed request, but kept receiving this error. On the next day it fixed itself. I suspect Firebase doesn't update synchronously.

To get a server key for the request, open https://console.firebase.google.com and select an appropriate project.

enter image description here

Then paste it in the request.

enter image description here

SQL WHERE condition is not equal to?

I was just solving this problem. If you use <> or is not in on a variable, that is null, it will result in false. So instead of <> 1, you must check it like this:

 AND (isdelete is NULL or isdelete = 0)

How to convert a time string to seconds?

without imports

time = "01:34:11"
sum(x * int(t) for x, t in zip([3600, 60, 1], time.split(":"))) 

mysqli_select_db() expects parameter 1 to be mysqli, string given

Your arguments are in the wrong order. The connection comes first according to the docs

<?php
require("constants.php");

// 1. Create a database connection
$connection = mysqli_connect(DB_SERVER,DB_USER,DB_PASS);

if (!$connection) {
    error_log("Failed to connect to MySQL: " . mysqli_error($connection));
    die('Internal server error');
}

// 2. Select a database to use 
$db_select = mysqli_select_db($connection, DB_NAME);
if (!$db_select) {
    error_log("Database selection failed: " . mysqli_error($connection));
    die('Internal server error');
}

?>

SQL Query - SUM(CASE WHEN x THEN 1 ELSE 0) for multiple columns

I would change the query in the following ways:

  1. Do the aggregation in subqueries. This can take advantage of more information about the table for optimizing the group by.
  2. Combine the second and third subqueries. They are aggregating on the same column. This requires using a left outer join to ensure that all data is available.
  3. By using count(<fieldname>) you can eliminate the comparisons to is null. This is important for the second and third calculated values.
  4. To combine the second and third queries, it needs to count an id from the mde table. These use mde.mdeid.

The following version follows your example by using union all:

SELECT CAST(Detail.ReceiptDate AS DATE) AS "Date",
       SUM(TOTALMAILED) as TotalMailed,
       SUM(TOTALUNDELINOTICESRECEIVED) as TOTALUNDELINOTICESRECEIVED,
       SUM(TRACEUNDELNOTICESRECEIVED) as TRACEUNDELNOTICESRECEIVED
FROM ((select SentDate AS "ReceiptDate", COUNT(*) as TotalMailed,
              NULL as TOTALUNDELINOTICESRECEIVED, NULL as TRACEUNDELNOTICESRECEIVED
       from MailDataExtract
       where SentDate is not null
       group by SentDate
      ) union all
      (select MDE.ReturnMailDate AS ReceiptDate, 0,
              COUNT(distinct mde.mdeid) as TOTALUNDELINOTICESRECEIVED,
              SUM(case when sd.ReturnMailTypeId = 1 then 1 else 0 end) as TRACEUNDELNOTICESRECEIVED
       from MailDataExtract MDE left outer join
            DTSharedData.dbo.ScanData SD
            ON SD.ScanDataID = MDE.ReturnScanDataID
       group by MDE.ReturnMailDate;
      )
     ) detail
GROUP BY CAST(Detail.ReceiptDate AS DATE)
ORDER BY 1;

The following does something similar using full outer join:

SELECT coalesce(sd.ReceiptDate, mde.ReceiptDate) AS "Date",
       sd.TotalMailed, mde.TOTALUNDELINOTICESRECEIVED,
       mde.TRACEUNDELNOTICESRECEIVED
FROM (select cast(SentDate as date) AS "ReceiptDate", COUNT(*) as TotalMailed
      from MailDataExtract
      where SentDate is not null
      group by cast(SentDate as date)
     ) sd full outer join
    (select cast(MDE.ReturnMailDate as date) AS ReceiptDate,
            COUNT(distinct mde.mdeID) as TOTALUNDELINOTICESRECEIVED,
            SUM(case when sd.ReturnMailTypeId = 1 then 1 else 0 end) as TRACEUNDELNOTICESRECEIVED
     from MailDataExtract MDE left outer join
          DTSharedData.dbo.ScanData SD
          ON SD.ScanDataID = MDE.ReturnScanDataID
     group by cast(MDE.ReturnMailDate as date)
    ) mde
    on sd.ReceiptDate = mde.ReceiptDate
ORDER BY 1;

How to select multiple files with <input type="file">?

There is also HTML5 <input type="file[]" multiple /> (specification).

Browser support is quite good on desktop (just not supported by IE 9 and prior), less good on mobile, I guess because it's harder to implement correctly depending on the platform and version.

Importing a long list of constants to a Python file

If you really want constants, not just variables looking like constants, the standard way to do it is to use immutable dictionaries. Unfortunately it's not built-in yet, so you have to use third party recipes (like this one or that one).

How can I dynamically set the position of view in Android?

Use RelativeLayout, place your view in it, get RelativeLayout.LayoutParams object from your view and set margins as you need. Then call requestLayout() on your view. This is the only way I know.

ERROR: permission denied for relation tablename on Postgres while trying a SELECT as a readonly user

make sure your user has attributes on its role. for example:

postgres=# \du
                             List of roles
 Role name |                   Attributes                   | Member of 
-----------+------------------------------------------------+-----------
 flux      |                                                | {}
 postgres  | Superuser, Create role, Create DB, Replication | {}

after performing the following command:

postgres=# ALTER ROLE flux WITH Superuser;
ALTER ROLE
postgres=# \du
                             List of roles
 Role name |                   Attributes                   | Member of 
-----------+------------------------------------------------+-----------
 flux      | Superuser                                      | {}
postgres  | Superuser, Create role, Create DB, Replication | {}

it fixed the problem.

see tutorial for roles and stuff here: https://www.digitalocean.com/community/tutorials/how-to-use-roles-and-manage-grant-permissions-in-postgresql-on-a-vps--2

How to display alt text for an image in chrome

I use this, it works with php...

<span><?php
if (file_exists("image/".$data['img_name'])) {
  ?>
  <img src="image/<?php echo $data['img_name']; ?>" width="100" height="100">
  <?php
}else{
  echo "Image Not Found";
}>?
</span>

Essentially what the code is doing, is checking for the File. The $data variable will be used with our array then actually make the desired change. If it isn't found, it will throw an Exception.

Best practices with STDIN in Ruby?

Following are some things I found in my collection of obscure Ruby.

So, in Ruby, a simple no-bells implementation of the Unix command cat would be:

#!/usr/bin/env ruby
puts ARGF.read

ARGF is your friend when it comes to input; it is a virtual file that gets all input from named files or all from STDIN.

ARGF.each_with_index do |line, idx|
    print ARGF.filename, ":", idx, ";", line
end

# print all the lines in every file passed via command line that contains login
ARGF.each do |line|
    puts line if line =~ /login/
end

Thank goodness we didn’t get the diamond operator in Ruby, but we did get ARGF as a replacement. Though obscure, it actually turns out to be useful. Consider this program, which prepends copyright headers in-place (thanks to another Perlism, -i) to every file mentioned on the command-line:

#!/usr/bin/env ruby -i

Header = DATA.read

ARGF.each_line do |e|
  puts Header if ARGF.pos - e.length == 0
  puts e
end

__END__
#--
# Copyright (C) 2007 Fancypants, Inc.
#++

Credit to:

Nested routes with react router v4 / v5

You can try something like Routes.js

import React, { Component } from 'react'
import { BrowserRouter as Router, Route } from 'react-router-dom';
import FrontPage from './FrontPage';
import Dashboard from './Dashboard';
import AboutPage from './AboutPage';
import Backend from './Backend';
import Homepage from './Homepage';
import UserPage from './UserPage';
class Routes extends Component {
    render() {
        return (
            <div>
                <Route exact path="/" component={FrontPage} />
                <Route exact path="/home" component={Homepage} />
                <Route exact path="/about" component={AboutPage} />
                <Route exact path="/admin" component={Backend} />
                <Route exact path="/admin/home" component={Dashboard} />
                <Route exact path="/users" component={UserPage} />    
            </div>
        )
    }
}

export default Routes

App.js

import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import { BrowserRouter as Router, Route } from 'react-router-dom'
import Routes from './Routes';

class App extends Component {
  render() {
    return (
      <div className="App">
      <Router>
        <Routes/>
      </Router>
      </div>
    );
  }
}

export default App;

I think you can achieve the same from here also.

Deploying just HTML, CSS webpage to Tomcat

If you want to create a .war file you can deploy to a Tomcat instance using the Manager app, create a folder, put all your files in that folder (including an index.html file) move your terminal window into that folder, and execute the following command:

zip -r <AppName>.war *

I've tested it with Tomcat 8 on the Mac, but it should work anywhere

Getting session value in javascript

<script>
var someSession = '<%= Session["SessionName"].ToString() %>';
alert(someSession)
</script>

This code you can write in Aspx. If you want this in some js.file, you have two ways:

  1. Make aspx file which writes complete JS code, and set source of this file as Script src
  2. Make handler, to process JS file as aspx.

Laravel stylesheets and javascript don't load for non-base routes

in Laravel 5,
there are 2 ways to load a js file in your view
first is using html helper, second is using asset helpers.
to use html helper you have to first install this package via commandline:

composer require illuminate/html

then you need to reqister it, so go to config/app.php, and add this line to the providers array

'Illuminate\Html\HtmlServiceProvider'

then you have to define aliases for your html package so go to aliases array in config/app.php and add this

'Html'     => 'Illuminate\Html\HtmlFacade'

now your html helper is installed so in your blade view files you can write this:

{!! Html::script('js/test.js') !!}

this will look for your test.js file in your project_root/public/js/test.js.
//////////////////////////////////////////////////////////////
to use asset helpers instead of html helper, you have to write sth like this in your view files:

<script src="{{ URL::asset('test.js') }}"></script>

this will look for test.js file in project_root/resources/assets/test.js

What is the difference between declarative and imperative paradigm in programming?

The difference has mostly to do with the overall level of abstraction. With declarative, at some point, you're so far away from the individual steps that the program has a lot of latitude regarding how to get your result.


You could look at every piece of instruction as falling somewhere on a continuum:

Degree of abstraction:

Declarative <<=====|==================>> Imperative

Declarative Real World Example:

  1. Librarian, please check me out a copy of Moby Dick. (Librarian, at their discretion chooses the best method for performing the request)

Imperative Real World Example:

  1. Go into Library
  2. Find Book Organization System (Card Catalog - Old school)
  3. Research how to use Card Catalogs (You forgot too, right)
  4. Figure out how shelves are labeled and organized.
  5. Figure out how books are organized on a shelf.
  6. Cross-reference book location from card catalog with organization system to find said book.
  7. Take book to check-out system.
  8. Check out book.

Is Constructor Overriding Possible?

No it is not possible to override a constructor. If we try to do this then compiler error will come. And it is never possible in Java. Lets see the example. It will ask please write a return type o the method. means it will treat that overriden constructor as a method not as a constructor.

package com.sample.test;

class Animal{

    public static void showMessage()
    {
        System.out.println("we are in Animal class");
    }
}

class Dog extends Animal{

    public void DogShow() 
    {
        System.out.println("we are in Dog show class");
    } 

    public static void showMessage()
    {
        System.out.println("we are in overriddn method of dog class");
    }
}

public class AnimalTest { 

    public static void main(String [] args)
    {
        Animal animal = new Animal();
        animal.showMessage();

        Dog dog = new Dog();
        dog.DogShow();

        Animal animal2 = new Dog();
        animal2.showMessage();
    }

}

How to add multiple columns to pandas dataframe in one assignment?

use of list comprehension, pd.DataFrame and pd.concat

pd.concat(
    [
        df,
        pd.DataFrame(
            [[np.nan, 'dogs', 3] for _ in range(df.shape[0])],
            df.index, ['column_new_1', 'column_new_2','column_new_3']
        )
    ], axis=1)

enter image description here

Comparing boxed Long values 127 and 128

TL;DR

Java caches boxed Integer instances from -128 to 127. Since you are using == to compare objects references instead of values, only cached objects will match. Either work with long unboxed primitive values or use .equals() to compare your Long objects.

Long (pun intended) version

Why there is problem in comparing Long variable with value greater than 127? If the data type of above variable is primitive (long) then code work for all values.

Java caches Integer objects instances from the range -128 to 127. That said:

  • If you set to N Long variables the value 127 (cached), the same object instance will be pointed by all references. (N variables, 1 instance)
  • If you set to N Long variables the value 128 (not cached), you will have an object instance pointed by every reference. (N variables, N instances)

That's why this:

Long val1 = 127L;
Long val2 = 127L;

System.out.println(val1 == val2);

Long val3 = 128L;
Long val4 = 128L;

System.out.println(val3 == val4);

Outputs this:

true
false

For the 127L value, since both references (val1 and val2) point to the same object instance in memory (cached), it returns true.

On the other hand, for the 128 value, since there is no instance for it cached in memory, a new one is created for any new assignments for boxed values, resulting in two different instances (pointed by val3 and val4) and returning false on the comparison between them.

That happens solely because you are comparing two Long object references, not long primitive values, with the == operator. If it wasn't for this Cache mechanism, these comparisons would always fail, so the real problem here is comparing boxed values with == operator.

Changing these variables to primitive long types will prevent this from happening, but in case you need to keep your code using Long objects, you can safely make these comparisons with the following approaches:

System.out.println(val3.equals(val4));                     // true
System.out.println(val3.longValue() == val4.longValue());  // true
System.out.println((long)val3 == (long)val4);              // true

(Proper null checking is necessary, even for castings)

IMO, it's always a good idea to stick with .equals() methods when dealing with Object comparisons.

Reference links:

Superscript in CSS only?

Related or maybe not related, using superscript as a HTML element or as a span+css in text might cause problem with localization - in localization programs.

For example let's say "3rd party software":

3<sup>rd</sup> party software
3<span class="superscript">rd</span> party software

How can translators translate "rd"? They can leave it empty for several cyrrilic languages, but what about of other exotic or RTL languages?

In this case it is better to avoid using superscripts and use a full wording like "third-party software". Or, as mentioned here in other comments, adding plus signs in superscript via jQuery.

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

SELECT P.*
FROM primary_table P
LEFT JOIN secondary_table S on P.id = S.p_id
WHERE S.p_id IS NULL

How can I run specific migration in laravel

use this command php artisan migrate --path=/database/migrations/my_migration.php it worked for me..

How to set default vim colorscheme

Your .vimrc file goes in your $HOME directory. In *nix, cd ~; vim .vimrc. The commands in the .vimrc are the same as you type in ex-mode in vim, only without the leading colon, so colo evening would suffice. Comments in the .vimrc are indicated with a leading double-quote.

To see an example vimrc, open $VIMRUNTIME/vimrc_example.vim from within vim

:e $VIMRUNTIME/vimrc_example.vim

Plotting a 3d cube, a sphere and a vector in Matplotlib

For drawing just the arrow, there is an easier method:-

from mpl_toolkits.mplot3d import Axes3D
import matplotlib.pyplot as plt
fig = plt.figure()
ax = fig.gca(projection='3d')
ax.set_aspect("equal")

#draw the arrow
ax.quiver(0,0,0,1,1,1,length=1.0)

plt.show()

quiver can actually be used to plot multiple vectors at one go. The usage is as follows:- [ from http://matplotlib.org/mpl_toolkits/mplot3d/tutorial.html?highlight=quiver#mpl_toolkits.mplot3d.Axes3D.quiver]

quiver(X, Y, Z, U, V, W, **kwargs)

Arguments:

X, Y, Z: The x, y and z coordinates of the arrow locations

U, V, W: The x, y and z components of the arrow vectors

The arguments could be array-like or scalars.

Keyword arguments:

length: [1.0 | float] The length of each quiver, default to 1.0, the unit is the same with the axes

arrow_length_ratio: [0.3 | float] The ratio of the arrow head with respect to the quiver, default to 0.3

pivot: [ ‘tail’ | ‘middle’ | ‘tip’ ] The part of the arrow that is at the grid point; the arrow rotates about this point, hence the name pivot. Default is ‘tail’

normalize: [False | True] When True, all of the arrows will be the same length. This defaults to False, where the arrows will be different lengths depending on the values of u,v,w.

Example of a strong and weak entity types

After browsing search engines for a few hours I came across a site with a great ERD example here: http://www.exploredatabase.com/2016/07/description-about-weak-entity-sets-in-DBMS.html

I've recreated the ERD. Unfortunately they did not specify the primary key of the weak entity.

enter image description here

If the building could only have one and only one apartment, then it seems the partial discriminator room number would not be created (i.e. discarded).

Can functions be passed as parameters?

This is the simplest way I can come with.

package main

import "fmt"

func main() {
    g := greeting
    getFunc(g)
}

func getFunc(f func()) {
    f()
}

func greeting() {
    fmt.Println("Hello")
}

Turn on IncludeExceptionDetailInFaults (either from ServiceBehaviorAttribute or from the <serviceDebug> configuration behavior) on the server

If you want to do this by code, you can add the behavior like this:

serviceHost.Description.Behaviors.Remove(
    typeof(ServiceDebugBehavior));
serviceHost.Description.Behaviors.Add(
    new ServiceDebugBehavior { IncludeExceptionDetailInFaults = true });

Showing line numbers in IPython/Jupyter Notebooks

To turn line numbers on by default in all cells at startup I recommend this link. I quote:

  1. Navigate to your jupyter config directory, which you can find by typing the following at the command line:

    jupyter --config-dir
    
  2. From there, open or create the custom folder.

  3. In that folder, you should find a custom.js file. If there isn’t one, you should be able to create one. Open it in a text editor and add this code:

    define([
        'base/js/namespace',
        'base/js/events'
        ],
        function(IPython, events) {
            events.on("app_initialized.NotebookApp",
                function () {
                    IPython.Cell.options_default.cm_config.lineNumbers = true;
                }
            );
        }
    );
    

javascript: get a function's variable's value within another function

nameContent only exists within the first() function, as you defined it within the first() function.

To make its scope broader, define it outside of the functions:

var nameContent;

function first(){
    nameContent=document.getElementById('full_name').value;
}

function second() {
    first();
    y=nameContent; alert(y);
}
second();

A slightly better approach would be to return the value, as global variables get messy very quickly:

function getFullName() {
  return document.getElementById('full_name').value;
}

function doStuff() {
  var name = getFullName();

  alert(name);
}

doStuff();

checking if number entered is a digit in jquery

$(document).ready(function () {



    $("#cust_zip").keypress(function (e) {
        //var z = document.createUserForm.cust_mobile1.value;
        //alert(z);
        if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) {

            $("#errmsgzip").html("Digits Only.").show().fadeOut(3000);
            return false;
        }
    });
});

Regex match entire words only

Use word boundaries:

/\b($word)\b/i

Or if you're searching for "S.P.E.C.T.R.E." like in Sinan Ünür's example:

/(?:\W|^)(\Q$word\E)(?:\W|$)/i

Promise Error: Objects are not valid as a React child

You can't just return an array of objects because there's nothing telling React how to render that. You'll need to return an array of components or elements like:

render: function() {
  return (
    <span>
      // This will go through all the elements in arrayFromJson and
      // render each one as a <SomeComponent /> with data from the object
      {this.state.arrayFromJson.map(function(object) {
        return (
          <SomeComponent key={object.id} data={object} />
        );
      })}
    </span>
  );
}

How do I replace a double-quote with an escape-char double-quote in a string using JavaScript?

You need to use a global regular expression for this. Try it this way:

str.replace(/"/g, '\\"');

Check out regex syntax and options for the replace function in Using Regular Expressions with JavaScript.

how to display progress while loading a url to webview in android?

Check out the sample code. It help you.

 private ProgressBar progressBar;
 progressBar=(ProgressBar)findViewById(R.id.webloadProgressBar);
 WebView urlWebView= new WebView(Context);
    urlWebView.setWebViewClient(new AppWebViewClients(progressBar));
                        urlWebView.getSettings().setJavaScriptEnabled(true);
                        urlWebView.loadUrl(detailView.getUrl());

public class AppWebViewClients extends WebViewClient {
     private ProgressBar progressBar;

    public AppWebViewClients(ProgressBar progressBar) {
        this.progressBar=progressBar;
        progressBar.setVisibility(View.VISIBLE);
    }
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        // TODO Auto-generated method stub
        view.loadUrl(url);
        return true;
    }

    @Override
    public void onPageFinished(WebView view, String url) {
        // TODO Auto-generated method stub
        super.onPageFinished(view, url);
        progressBar.setVisibility(View.GONE);
    }
}

Thanks.

How to a convert a date to a number and back again in MATLAB

Use DATESTR

>> datestr(40189)
ans =
12-Jan-0110

Unfortunately, Excel starts counting at 1-Jan-1900. Find out how to convert serial dates from Matlab to Excel by using DATENUM

>> datenum(2010,1,11)
ans =
      734149
>> datenum(2010,1,11)-40189
ans =
      693960
>> datestr(40189+693960)
ans =
11-Jan-2010

In other words, to convert any serial Excel date, call

datestr(excelSerialDate + 693960)

EDIT

To get the date in mm/dd/yyyy format, call datestr with the specified format

excelSerialDate = 40189;
datestr(excelSerialDate + 693960,'mm/dd/yyyy')
ans =
01/11/2010

Also, if you want to get rid of the leading zero for the month, you can use REGEXPREP to fix things

excelSerialDate = 40189;
regexprep(datestr(excelSerialDate + 693960,'mm/dd/yyyy'),'^0','')
ans =
1/11/2010

How to force cp to overwrite without confirmation

You probably have an alias somewhere, mapping cp to cp -i; because with the default settings, cp won't ask to overwrite. Check your .bashrc, your .profile etc.

See cp manpage: Only when -i parameter is specified will cp actually prompt before overwriting.

You can check this via the alias command:

$ alias
alias cp='cp -i'
alias diff='diff -u'
....

To undefine the alias, use:

$ unalias cp

How to pass a variable to the SelectCommand of a SqlDataSource?

try with this.

Protected Sub SqlDataSource_Selecting(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.SqlDataSourceSelectingEventArgs) Handles SqlDataSource.Selecting

    e.Command.CommandText = "SELECT [ImageID],[ImagePath] FROM [TblImage] where IsActive = 1"

    End Sub

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

The idle shortcut is an "Advertised Shortcut" which breaks certain features like the "find target" button. Google for more info.

You can view the link with a hex editor or download LNK Parser to see where it points to.

In my case it runs:
..\..\..\..\..\Python27\pythonw.exe "C:\Python27\Lib\idlelib\idle.pyw"

How to run Gradle from the command line on Mac bash

./gradlew

Your directory with gradlew is not included in the PATH, so you must specify path to the gradlew. . means "current directory".

Why would Oracle.ManagedDataAccess not work when Oracle.DataAccess does?

I received the same error message. To resolve this I just replaced the Oracle.ManagedDataAccess assembly with the older Oracle.DataAccess assembly. This solution may not work if you require new features found in the new assembly. In my case I have many more higher priority issues then trying to configure the new Oracle assembly.

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

This works for me

public string[] GetGroupNames(string domainName, string userName)
    {
        List<string> result = new List<string>();

        using (PrincipalContext principalContext = new PrincipalContext(ContextType.Domain, domainName))
        {
            using (PrincipalSearchResult<Principal> src = UserPrincipal.FindByIdentity(principalContext, userName).GetGroups())
            {
                src.ToList().ForEach(sr => result.Add(sr.SamAccountName));
            }
        }

        return result.ToArray();
    }

Spring - download response as a file

I have written comments below to understand code sample. Some one if using, they can follow it , as I named the files accordingly.

  1. IF server is sending blob in the response, then our client should be able to produce it.

  2. As my purpose is solved by using these. I can able to download files, as I have used type: 'application/*' for all files.

  3. Created "downloadLink" variable is just technique used in response so that, it would fill like some clicked on link, then response comes and then its href would be triggered.

_x000D_
_x000D_
controller.js_x000D_
//this function is in controller, which will be trigered on download button hit. _x000D_
_x000D_
  $scope.downloadSampleFile = function() {_x000D_
//create sample hidden link in document, to accept Blob returned in the response from back end_x000D_
    _x000D_
  var downloadLink = document.createElement("a");_x000D_
_x000D_
  document.body.appendChild(downloadLink);_x000D_
  downloadLink.style = "display: none";_x000D_
_x000D_
//This service is written Below how does it work, by aceepting necessary params_x000D_
  downloadFile.downloadfile(data).then(function (result) {_x000D_
_x000D_
   var fName = result.filename;_x000D_
   var file = new Blob([result.data], {type: 'application/*'});_x000D_
   var fileURL = (window.URL || window.webkitURL).createObjectURL(file);_x000D_
_x000D_
          _x000D_
//Blob, client side object created to with holding browser specific download popup, on the URL created with the help of window obj._x000D_
          _x000D_
   downloadLink.href = fileURL;_x000D_
   downloadLink.download = fName;_x000D_
   downloadLink.click();_x000D_
  });_x000D_
 };_x000D_
_x000D_
_x000D_
_x000D_
_x000D_
services.js_x000D_
_x000D_
.factory('downloadFile', ["$http", function ($http) {_x000D_
 return {_x000D_
  downloadfile : function () {_x000D_
   return $http.get(//here server endpoint to which you want to hit the request_x000D_
              , {_x000D_
    responseType: 'arraybuffer',_x000D_
    params: {_x000D_
     //Required params_x000D_
    },_x000D_
   }).then(function (response, status, headers, config) {_x000D_
    return response;_x000D_
   });_x000D_
  },_x000D_
 };_x000D_
}])
_x000D_
_x000D_
_x000D_

Get class labels from Keras functional model

In addition to @Emilia Apostolova answer to get the ground truth labels, from

generator = train_datagen.flow_from_directory("train", batch_size=batch_size)

just call

y_true_labels = generator.classes

MySQL Nested Select Query?

You just need to write the first query as a subquery (derived table), inside parentheses, pick an alias for it (t below) and alias the columns as well.

The DISTINCT can also be safely removed as the internal GROUP BY makes it redundant:

SELECT DATE(`date`) AS `date` , COUNT(`player_name`) AS `player_count`
FROM (
    SELECT MIN(`date`) AS `date`, `player_name`
    FROM `player_playtime`
    GROUP BY `player_name`
) AS t
GROUP BY DATE( `date`) DESC LIMIT 60 ;

Since the COUNT is now obvious that is only counting rows of the derived table, you can replace it with COUNT(*) and further simplify the query:

SELECT t.date , COUNT(*) AS player_count
FROM (
    SELECT DATE(MIN(`date`)) AS date
    FROM player_playtime
    GROUP BY player_name
) AS t
GROUP BY t.date DESC LIMIT 60 ;

Date format in the json output using spring boot

If you want to change the format for all dates you can add a builder customizer. Here is an example of a bean that converts dates to ISO 8601:

@Bean
public Jackson2ObjectMapperBuilderCustomizer jsonCustomizer() {
    return new Jackson2ObjectMapperBuilderCustomizer() {
        @Override
        public void customize(Jackson2ObjectMapperBuilder builder) {
            builder.dateFormat(new ISO8601DateFormat());        
        }           
    };
}

Moment.js with Vuejs

If your project is a single page application, (eg project created by vue init webpack myproject), I found this way is most intuitive and simple:

In main.js

import moment from 'moment'

Vue.prototype.moment = moment

Then in your template, simply use

<span>{{moment(date).format('YYYY-MM-DD')}}</span>

What is the Sign Off feature in Git for?

There are some nice answers on this question. I’ll try to add a more broad answer, namely about what these kinds of lines/headers/trailers are about in current practice. Not so much about the sign-off header in particular (it’s not the only one).

Headers or trailers (?1) like “sign-off” (?2) is, in current practice in projects like Git and Linux, effectively structured metadata for the commit. These are all appended to the end of the commit message, after the “free form” (unstructured) part of the body of the message. These are token–value (or key–value) pairs typically delimited by a colon and a space (:?).

Like I mentioned, “sign-off” is not the only trailer in current practice. See for example this commit, which has to do with “Dirty Cow”:

 mm: remove gup_flags FOLL_WRITE games from __get_user_pages()
 This is an ancient bug that was actually attempted to be fixed once
 (badly) by me eleven years ago in commit 4ceb5db9757a ("Fix
 get_user_pages() race for write access") but that was then undone due to
 problems on s390 by commit f33ea7f404e5 ("fix get_user_pages bug").

 In the meantime, the s390 situation has long been fixed, and we can now
 fix it by checking the pte_dirty() bit properly (and do it better).  The
 s390 dirty bit was implemented in abf09bed3cce ("s390/mm: implement
 software dirty bits") which made it into v3.9.  Earlier kernels will
 have to look at the page state itself.

 Also, the VM has become more scalable, and what used a purely
 theoretical race back then has become easier to trigger.

 To fix it, we introduce a new internal FOLL_COW flag to mark the "yes,
 we already did a COW" rather than play racy games with FOLL_WRITE that
 is very fundamental, and then use the pte dirty flag to validate that
 the FOLL_COW flag is still valid.

 Reported-and-tested-by: Phil "not Paul" Oester <[email protected]>
 Acked-by: Hugh Dickins <[email protected]>
 Reviewed-by: Michal Hocko <[email protected]>
 Cc: Andy Lutomirski <[email protected]>
 Cc: Kees Cook <[email protected]>
 Cc: Oleg Nesterov <[email protected]>
 Cc: Willy Tarreau <[email protected]>
 Cc: Nick Piggin <[email protected]>
 Cc: Greg Thelen <[email protected]>
 Cc: [email protected]
 Signed-off-by: Linus Torvalds <[email protected]>

In addition to the “sign-off” trailer in the above, there is:

  • “Cc” (was notified about the patch)
  • “Acked-by” (acknowledged by the owner of the code, “looks good to me”)
  • “Reviewed-by” (reviewed)
  • “Reported-and-tested-by” (reported and tested the issue (I assume))

Other projects, like for example Gerrit, have their own headers and associated meaning for them.

See: https://git.wiki.kernel.org/index.php/CommitMessageConventions

Moral of the story

It is my impression that, although the initial motivation for this particular metadata was some legal issues (judging by the other answers), the practice of such metadata has progressed beyond just dealing with the case of forming a chain of authorship.

[?1]: man git-interpret-trailers
[?2]: These are also sometimes called “s-o-b” (initials), it seems.

Determine the process pid listening on a certain port

The -p flag of netstat gives you PID of the process:

netstat -l -p

Edit: The command that is needed to get PIDs of socket users in FreeBSD is sockstat. As we worked out during the discussion with @Cyclone, the line that does the job is:

sockstat -4 -l | grep :80 | awk '{print $3}' | head -1

Change language of Visual Studio 2017 RC

  1. Go to Tools -> Options
  2. Select International Settings in Environment and on the right side of a screen you should see a combo with the list of installed language packages. (so in my case Czech, English and same as on MS Windows )
  3. Click on Ok

You have to restart Visual Studio to see the change...

If you are polish (and got polish language settings)

  1. Narzedzia -> Opcje
  2. Ustawienia miedzynarodowe in Srodowisko

Hope this helps! Have a great time in Poland!

How to clear all input fields in bootstrap modal when clicking data-dismiss button?

The following worked for me:

$(':input').val('');

However, it is submitting the form, so it might not be what you are looking for.

Check if object value exists within a Javascript array of objects and if not add a new object to array

I think that, this is the shortest way of addressing this problem. Here I have used ES6 arrow function with .filter to check the existence of newly adding username.

var arr = [{
    id: 1,
    username: 'fred'
}, {
    id: 2,
    username: 'bill'
}, {
    id: 3,
    username: 'ted'
}];

function add(name) {
    var id = arr.length + 1;        
            if (arr.filter(item=> item.username == name).length == 0){
            arr.push({ id: id, username: name });
        }
}

add('ted');
console.log(arr);

Link to Fiddle

Database development mistakes made by application developers

  • Not taking a backup before fixing some issue inside production database.

  • Using DDL commands on stored objects(like tables, views) in stored procedures.

  • Fear of using stored proc or fear of using ORM queries wherever the one is more efficient/appropriate to use.

  • Ignoring the use of a database profiler, which can tell you exactly what your ORM query is being converted into finally and hence verify the logic or even for debugging when not using ORM.

How do I compile C++ with Clang?

I've had a similar problem when building Clang from source (but not with sudo apt-get install. This might depend on the version of Ubuntu which you're running).

It might be worth checking if clang++ can find the correct locations of your C++ libraries:

Compare the results of g++ -v <filename.cpp> and clang++ -v <filename.cpp>, under "#include < ... > search starts here:".

How do I use installed packages in PyCharm?

On Project Explorer, you can right click on the folder where the module is contained and set as 'Source'.

It will be parsed in the Index for code completion as well as other items.

Is it possible to use global variables in Rust?

I am new to Rust, but this solution seems to work:

#[macro_use]
extern crate lazy_static;

use std::sync::{Arc, Mutex};

lazy_static! {
    static ref GLOBAL: Arc<Mutex<GlobalType> =
        Arc::new(Mutex::new(GlobalType::new()));
}

Another solution is to declare a crossbeam channel tx/rx pair as an immutable global variable. The channel should be bounded and can only hold 1 element. When you initialize the global variable, push the global instance into the channel. When using the global variable, pop the channel to acquire it and push it back when done using it.

Both solutions should provide a safe approach to using global variables.

A simple command line to download a remote maven2 artifact to the local repository?

Give them a trivial pom with these jars listed as dependencies and instructions to run:

mvn dependency:go-offline

This will pull the dependencies to the local repo.

A more direct solution is dependency:get, but it's a lot of arguments to type:

mvn dependency:get -DrepoUrl=something -Dartifact=group:artifact:version

How do I detect if I am in release or debug mode?

Alternatively, you could differentiate using BuildConfig.BUILD_TYPE;

If you're running debug build BuildConfig.BUILD_TYPE.equals("debug"); returns true. And for release build BuildConfig.BUILD_TYPE.equals("release"); returns true.

What is the reason for java.lang.IllegalArgumentException: No enum const class even though iterating through values() works just fine?

Enum.valueOf() only checks the constant name, so you need to pass it "COLUMN_HEADINGS" instead of "columnHeadings". Your name property has nothing to do with Enum internals.


To address the questions/concerns in the comments:

The enum's "builtin" (implicitly declared) valueOf(String name) method will look up an enum constant with that exact name. If your input is "columnHeadings", you have (at least) three choices:

  1. Forget about the naming conventions for a bit and just name your constants as it makes most sense: enum PropName { contents, columnHeadings, ...}. This is obviously the most convenient.
  2. Convert your camelCase input into UPPER_SNAKE_CASE before calling valueOf, if you're really fond of naming conventions.
  3. Implement your own lookup method instead of the builtin valueOf to find the corresponding constant for an input. This makes most sense if there are multiple possible mappings for the same set of constants.

Failed to fetch URL https://dl-ssl.google.com/android/repository/addons_list-1.xml, reason: Connection to https://dl-ssl.google.com refused

If you are on Windows 7, simply run Eclipse with Admin privilege will solve this issue.

Just tried this on my Windows 7 64bits OS.

Could not load file or assembly 'Microsoft.ReportViewer.WebForms'

I've solved the problem by copying both

  • Microsoft.ReportViewer.WebForms.dll from C:\Program Files (x86)\Microsoft Visual Studio 12.0\ReportViewer
  • and Microsoft.reportviewer.common.dll from C:\Program Files\Microsoft Office\Office15\ADDINS\PowerPivot Excel Add-in

into bin folder (website).

Of course web.config must have:

    <httpHandlers>
        <add path="Reserved.ReportViewerWebControl.axd" verb="*" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" validate="false" />
    </httpHandlers>

    <assemblies>

        <add assembly="Microsoft.ReportViewer.WebForms, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845DCD8080CC91" />
        <add assembly="Microsoft.ReportViewer.Common, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845DCD8080CC91" />
    </assemblies>

    <buildProviders>
        <add extension=".rdlc" type="Microsoft.Reporting.RdlBuildProvider, Microsoft.ReportViewer.WebForms, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" />
    </buildProviders>

    <system.webServer>
        <validation validateIntegratedModeConfiguration="false" />
        <handlers>
            <add name="ReportViewerWebControlHandler" preCondition="integratedMode" verb="*" path="Reserved.ReportViewerWebControl.axd" type="Microsoft.Reporting.WebForms.HttpHandler, Microsoft.ReportViewer.WebForms, Version=11.0.0.0, Culture=neutral, PublicKeyToken=89845dcd8080cc91" />
        </handlers>
    </system.webServer>

And that's all. For me is ok.

Hope this helps.

How to find what code is run by a button or element in Chrome using Developer Tools

You can use findHandlersJS

You can find the handler by doing in the chrome console:

findEventHandlers("click", "img.envio")

You'll get the following information printed in chrome's console:

  • element
    The actual element where the event handler was registered in
  • events
    Array with information about the jquery event handlers for the event type that we are interested in (e.g. click, change, etc)
  • handler
    Actual event handler method that you can see by right clicking it and selecting Show function definition
  • selector
    The selector provided for delegated events. It will be empty for direct events.
  • targets
    List with the elements that this event handler targets. For example, for a delegated event handler that is registered in the document object and targets all buttons in a page, this property will list all buttons in the page. You can hover them and see them highlighted in chrome.

More info here and you can try it in this example site here.

How to achieve ripple animation using support library?

Sometimes you have a custom background, in that cases a better solution is use android:foreground="?selectableItemBackground"

Update

If you want ripple effect with rounded corners and custom background you can use this:

background_ripple.xml

<?xml version="1.0" encoding="utf-8"?>
<ripple xmlns:android="http://schemas.android.com/apk/res/android" android:color="@color/ripple_color">
<item android:id="@android:id/mask">
    <shape android:shape="rectangle">
        <solid android:color="@android:color/white" />
        <corners android:radius="5dp" />
    </shape>
</item>

<item android:id="@android:id/background">
    <shape android:shape="rectangle">
        <solid android:color="@android:color/white" />
        <corners android:radius="5dp" />
    </shape>
</item>

layout.xml

<Button
    android:id="@+id/btn_play"
    android:background="@drawable/background_ripple"
    app:backgroundTint="@color/colorPrimary"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="@string/play_now" />

I used this on API >= 21

cast class into another class or convert class to another

By using following code you can copy any class object to another class object for same name and same type of properties.

public class CopyClass
{
    /// <summary>
    /// Copy an object to destination object, only matching fields will be copied
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="sourceObject">An object with matching fields of the destination object</param>
    /// <param name="destObject">Destination object, must already be created</param>
    public static void CopyObject<T>(object sourceObject, ref T destObject)
    {
        //  If either the source, or destination is null, return
        if (sourceObject == null || destObject == null)
            return;

        //  Get the type of each object
        Type sourceType = sourceObject.GetType();
        Type targetType = destObject.GetType();

        //  Loop through the source properties
        foreach (PropertyInfo p in sourceType.GetProperties())
        {
            //  Get the matching property in the destination object
            PropertyInfo targetObj = targetType.GetProperty(p.Name);
            //  If there is none, skip
            if (targetObj == null)
                continue;

            //  Set the value in the destination
            targetObj.SetValue(destObject, p.GetValue(sourceObject, null), null);
        }
    }
}

Call Method Like,

ClassA objA = new ClassA();
ClassB objB = new ClassB();

CopyClass.CopyObject(objOfferMast, ref objB);

It will copy objA into objB.

Procedure or function !!! has too many arguments specified

In addition to all the answers provided so far, another reason for causing this exception can happen when you are saving data from list to database using ADO.Net.

Many developers will mistakenly use for loop or foreach and leave the SqlCommand to execute outside the loop, to avoid that make sure that you have like this code sample for example:

public static void Save(List<myClass> listMyClass)
    {
        using (var Scope = new System.Transactions.TransactionScope())
        {
            if (listMyClass.Count > 0)
            {
                for (int i = 0; i < listMyClass.Count; i++)
                {
                    SqlCommand cmd = new SqlCommand("dbo.SP_SaveChanges", myConnection);
                    cmd.CommandType = CommandType.StoredProcedure;
                    cmd.Parameters.Clear();

                    cmd.Parameters.AddWithValue("@ID", listMyClass[i].ID);
                    cmd.Parameters.AddWithValue("@FirstName", listMyClass[i].FirstName);
                    cmd.Parameters.AddWithValue("@LastName", listMyClass[i].LastName);

                    try
                    {
                        myConnection.Open();
                        cmd.ExecuteNonQuery();
                    }
                    catch (SqlException sqe)
                    {
                        throw new Exception(sqe.Message);
                    }
                    catch (Exception ex)
                    {
                        throw new Exception(ex.Message);
                    }
                    finally
                    {
                        myConnection.Close();
                    }
                }
            }
            else
            {
                throw new Exception("List is empty");
            }

            Scope.Complete();
        }
    }

I ran into a merge conflict. How can I abort the merge?

git merge --abort

Abort the current conflict resolution process, and try to reconstruct the pre-merge state.

If there were uncommitted worktree changes present when the merge started, git merge --abort will in some cases be unable to reconstruct these changes. It is therefore recommended to always commit or stash your changes before running git merge.

git merge --abort is equivalent to git reset --merge when MERGE_HEAD is present.

http://www.git-scm.com/docs/git-merge

How to pass parameters or arguments into a gradle task

Its nothing more easy.

run command: ./gradlew clean -PjobId=9999

and

in gradle use: println(project.gradle.startParameter.projectProperties)

You will get clue.

Convert CString to const char*

I had a similar problem. I had a char* buffer with the .so name in it.
I could not convert the char* variable to LPCTSTR. Here's how I got around it...

char *fNam;
...
LPCSTR nam = fNam;
dll = LoadLibraryA(nam);

Removing fields from struct or hiding them in JSON Response

I created this function to convert struct to JSON string by ignoring some fields. Hope it will help.

func GetJSONString(obj interface{}, ignoreFields ...string) (string, error) {
    toJson, err := json.Marshal(obj)
    if err != nil {
        return "", err
    }

    if len(ignoreFields) == 0 {
        return string(toJson), nil
    }

    toMap := map[string]interface{}{}
    json.Unmarshal([]byte(string(toJson)), &toMap)

    for _, field := range ignoreFields {
        delete(toMap, field)
    }

    toJson, err = json.Marshal(toMap)
    if err != nil {
        return "", err
    }
    return string(toJson), nil
}

Example: https://play.golang.org/p/nmq7MFF47Gp

What is a race condition?

A race condition is a kind of bug, that happens only with certain temporal conditions.

Example: Imagine you have two threads, A and B.

In Thread A:

if( object.a != 0 )
    object.avg = total / object.a

In Thread B:

object.a = 0

If thread A is preempted just after having check that object.a is not null, B will do a = 0, and when thread A will gain the processor, it will do a "divide by zero".

This bug only happen when thread A is preempted just after the if statement, it's very rare, but it can happen.

how to set the query timeout from SQL connection string

you can set Timeout in connection string (time for Establish connection between client and sql). commandTimeout is set per command but its default time is 30 secend

How to reset (clear) form through JavaScript?

Use JavaScript function reset():

document.forms["frm_id"].reset();

Difference between app.use and app.get in express.js

app.get is called when the HTTP method is set to GET, whereas app.use is called regardless of the HTTP method, and therefore defines a layer which is on top of all the other RESTful types which the express packages gives you access to.

MVC 4 Razor File Upload

you just have to change the name of your input filed because same name is required in parameter and input field name just replace this line Your code working fine

 <input type="file" name="file" />

List(of String) or Array or ArrayList

List(Of String) will handle that, mostly - though you need to either use AddRange to add a collection of items, or Add to add one at a time:

lstOfString.Add(String1)
lstOfString.Add(String2)
lstOfString.Add(String3)
lstOfString.Add(String4)

If you're adding known values, as you show, a good option is to use something like:

Dim inputs() As String = { "some value", _
                              "some value2", _
                              "some value3", _
                              "some value4" }

Dim lstOfString as List(Of String) = new List(Of String)(inputs)

' ...
Dim s3 = lstOfStrings(3)

This will still allow you to add items later as desired, but also get your initial values in quickly.


Edit:

In your code, you need to fix the declaration. Change:

Dim lstWriteBits() As List(Of String) 

To:

Dim lstWriteBits As List(Of String) 

Currently, you're declaring an Array of List(Of String) objects.

Excel VBA function to print an array to the workbook

On the same theme as other answers, keeping it simple

Sub PrintArray(Data As Variant, Cl As Range)
    Cl.Resize(UBound(Data, 1), UBound(Data, 2)) = Data
End Sub


Sub Test()
    Dim MyArray() As Variant

    ReDim MyArray(1 To 3, 1 To 3) ' make it flexible

    ' Fill array
    '  ...

    PrintArray MyArray, ActiveWorkbook.Worksheets("Sheet1").[A1]
End Sub

How do I compare strings in Java?

You can also use the compareTo() method to compare two Strings. If the compareTo result is 0, then the two strings are equal, otherwise the strings being compared are not equal.

The == compares the references and does not compare the actual strings. If you did create every string using new String(somestring).intern() then you can use the == operator to compare two strings, otherwise equals() or compareTo methods can only be used.

WPF checkbox binding

Hello this is my first time posting so please be patient: my answer was to create a simple property:

public bool Checked { get; set; }

Then to set the data context of the Checkbox (called cb1):

cb1.DataContext = this;

Then to bind the IsChecked proerty of it in the xaml

IsChecked="{Binding Checked}"

The code is like this:

XAML

<CheckBox x:Name="cb1"
          HorizontalAlignment="Left"
          Margin="439,81,0,0"
          VerticalAlignment="Top"
          Height="35" Width="96"
          IsChecked="{Binding Checked}"/>

Code behind

public partial class MainWindow : Window
{
    public bool Checked { get; set; }

    public MainWindow()
    {
        InitializeComponent();

        cb1.DataContext = this;
    }

    private void myyButton_Click(object sender, RoutedEventArgs e)
    {
        MessageBox.Show(Checked.ToString());
    }
}

How do I get the backtrace for all the threads in GDB?

Is there a command that does?

thread apply all where

How do I POST with multipart form data using fetch?

I was recently working with IPFS and worked this out. A curl example for IPFS to upload a file looks like this:

curl -i -H "Content-Type: multipart/form-data; boundary=CUSTOM" -d $'--CUSTOM\r\nContent-Type: multipart/octet-stream\r\nContent-Disposition: file; filename="test"\r\n\r\nHello World!\n--CUSTOM--' "http://localhost:5001/api/v0/add"

The basic idea is that each part (split by string in boundary with --) has it's own headers (Content-Type in the second part, for example.) The FormData object manages all this for you, so it's a better way to accomplish our goals.

This translates to fetch API like this:

const formData = new FormData()
formData.append('blob', new Blob(['Hello World!\n']), 'test')

fetch('http://localhost:5001/api/v0/add', {
  method: 'POST',
  body: formData
})
.then(r => r.json())
.then(data => {
  console.log(data)
})

Is it possible to put CSS @media rules inline?

Media Queries in style-Attributes are not possible right now. But if you have to set this dynamically via Javascript. You could insert that rule via JS aswell.

document.styleSheets[0].insertRule("@media only screen and (max-width : 300px) { span { background-image:particular_ad_small.png; } }","");

This is as if the style was there in the stylesheet. So be aware of specificity.

NodeJS / Express: what is "app.use"?

In short app.use() supports all type of requests [eg:get,post,...] so its mostly used to setup middelware. or can be used for when the routes and functions seperated

example:

app.use("/test",functionName)

and functionName is located in different file

Shell Script: Execute a python program from within a shell script

Since the other posts say everything (and I stumbled upon this post while looking for the following).
Here is a way how to execute a python script from another python script:

Python 2:

execfile("somefile.py", global_vars, local_vars)

Python 3:

with open("somefile.py") as f:
    code = compile(f.read(), "somefile.py", 'exec')
    exec(code, global_vars, local_vars)

and you can supply args by providing some other sys.argv

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 23: ordinal not in range(128)

When you get a UnicodeEncodeError, it means that somewhere in your code you convert directly a byte string to a unicode one. By default in Python 2 it uses ascii encoding, and utf8 encoding in Python3 (both may fail because not every byte is valid in either encoding)

To avoid that, you must use explicit decoding.

If you may have 2 different encoding in your input file, one of them accepts any byte (say UTF8 and Latin1), you can try to first convert a string with first and use the second one if a UnicodeDecodeError occurs.

def robust_decode(bs):
    '''Takes a byte string as param and convert it into a unicode one.
First tries UTF8, and fallback to Latin1 if it fails'''
    cr = None
    try:
        cr = bs.decode('utf8')
    except UnicodeDecodeError:
        cr = bs.decode('latin1')
    return cr

If you do not know original encoding and do not care for non ascii character, you can set the optional errors parameter of the decode method to replace. Any offending byte will be replaced (from the standard library documentation):

Replace with a suitable replacement character; Python will use the official U+FFFD REPLACEMENT CHARACTER for the built-in Unicode codecs on decoding and ‘?’ on encoding.

bs.decode(errors='replace')

Why does integer division in C# return an integer and not a float?

See C# specification. There are three types of division operators

  • Integer division
  • Floating-point division
  • Decimal division

In your case we have Integer division, with following rules applied:

The division rounds the result towards zero, and the absolute value of the result is the largest possible integer that is less than the absolute value of the quotient of the two operands. The result is zero or positive when the two operands have the same sign and zero or negative when the two operands have opposite signs.

I think the reason why C# use this type of division for integers (some languages return floating result) is hardware - integers division is faster and simpler.

How do I assign ls to an array in Linux Bash?

Whenever possible, you should avoid parsing the output of ls (see Greg's wiki on the subject). Basically, the output of ls will be ambiguous if there are funny characters in any of the filenames. It's also usually a waste of time. In this case, when you execute ls -d */, what happens is that the shell expands */ to a list of subdirectories (which is already exactly what you want), passes that list as arguments to ls -d, which looks at each one, says "yep, that's a directory all right" and prints it (in an inconsistent and sometimes ambiguous format). The ls command isn't doing anything useful!

Well, ok, it is doing one thing that's useful: if there are no subdirectories, */ will get left as is, ls will look for a subdirectory named "*", not find it, print an error message that it doesn't exist (to stderr), and not print the "*/" (to stdout).

The cleaner way to make an array of subdirectory names is to use the glob (*/) without passing it to ls. But in order to avoid putting "*/" in the array if there are no actual subdirectories, you should set nullglob first (again, see Greg's wiki):

shopt -s nullglob
array=(*/)
shopt -u nullglob # Turn off nullglob to make sure it doesn't interfere with anything later
echo "${array[@]}"  # Note double-quotes to avoid extra parsing of funny characters in filenames

If you want to print an error message if there are no subdirectories, you're better off doing it yourself:

if (( ${#array[@]} == 0 )); then
    echo "No subdirectories found" >&2
fi

Doctrine and LIKE query

This is not possible with the magic find methods. Try using the query builder:

$result = $em->getRepository("Orders")->createQueryBuilder('o')
   ->where('o.OrderEmail = :email')
   ->andWhere('o.Product LIKE :product')
   ->setParameter('email', '[email protected]')
   ->setParameter('product', 'My Products%')
   ->getQuery()
   ->getResult();

Create view with primary key?

I got the error "The table/view 'dbo.vMyView' does not have a primary key defined" after I created a view in SQL server query designer. I solved the problem by using ISNULL on a column to force entity framework to use it as a primary key. You might have to restart visual studio to get the warnings to go away.

CREATE VIEW [dbo].[vMyView]
AS
SELECT ISNULL(Id, -1) AS IdPrimaryKey, Name
FROM  dbo.MyTable

Prevent linebreak after </div>

The div elements are block elements, so by default they take upp the full available width.

One way is to turn them into inline elements:

.label, .text { display: inline; }

This will have the same effect as using span elements instead of div elements.

Another way is to float the elements:

.label, .text { float: left; }

This will change how the width of the elements is decided, so that thwy will only be as wide as their content. It will also make the elements float beside each other, similar to how images flow beside each other.

You can also consider changing the elements. The div element is intended for document divisions, I usually use a label and a span element for a construct like this:

<label>My Label:</label>
<span>My text</span>

sorting a vector of structs

Yes: you can sort using a custom comparison function:

std::sort(info.begin(), info.end(), my_custom_comparison);

my_custom_comparison needs to be a function or a class with an operator() overload (a functor) that takes two data objects and returns a bool indicating whether the first is ordered prior to the second (i.e., first < second). Alternatively, you can overload operator< for your class type data; operator< is the default ordering used by std::sort.

Either way, the comparison function must yield a strict weak ordering of the elements.

How to embed image or picture in jupyter notebook, either from a local machine or from a web resource?

Agreed, i had the same issues and this is what worked and what did not:

WORKED: <img src="Docs/pinoutDOIT32devkitv1.png" width="800"/>
*DOES NOT WORK: <img src="/Docs/pinoutDOIT32devkitv1.png" width="800"/>
DOES NOT WORK: <img src="./Docs/pinoutDOIT32devkitv1.png" width="800"/>*

Val and Var in Kotlin

You can easily think it as:

var is used for setter (value will change).

val is used for getter (read-only, value won't change).

How do I tell whether my IE is 64-bit? (For that matter, Java too?)

Rob Heiser suggested checking out your java version by using 'java -version'.

That will identify the Java version that will be commonly found and used. Doing dev work, you can often have more than one version installed (I currently have 2 JREs - 6 and 7 - and may soon have 8).

http://www.coderanch.com/t/453224/java/java/java-version-work-setting-path

java -version will look for java.exe in the System32 directory in Windows. That's where a JRE will install it.

I'm assuming that IE either simply looks for java and that automatically starts checking in System32 or it'll use the path and hit whichever java.exe comes first in your path (if you tamper with the path to point to another JRE).

Also from what SLaks said, I would disagree with one thing. There is likely slightly better performance out of 64-it IE in 64-bit environments. So there is some reason for using it.

How to create an array from a CSV file using PHP and the fgetcsv function

If you want each line to be in an array, and each cell in the line in array:

$file = fopen('csvFile.csv', 'r');              // Open the file                     
while (($line = fgetcsv($file)) !== FALSE) {    // Read one line
    $array[] =$line;                            // Add the line in the main array
}
echo '<pre>';
print_r($array);   //print it out
echo '</pre>'; 
fclose($file);

What is [Serializable] and when should I use it?

Serialization is the process of converting an object into a stream of bytes to store the object or transmit it to memory, a database, or a file.

How serialization works

This illustration shows the overall process of serialization:

enter image description here

The object is serialized to a stream that carries the data. The stream may also have information about the object's type, such as its version, culture, and assembly name. From that stream, the object can be stored in a database, a file, or memory.

Details in Microsoft Docs.

POST string to ASP.NET Web Api application - returns null

([FromBody] IDictionary<string,object> data)

Getting MAC Address

For Linux let me introduce a shell script that will show the mac address and allows to change it (MAC sniffing).

 ifconfig eth0 | grep HWaddr |cut -dH -f2|cut -d\  -f2
 00:26:6c:df:c3:95

Cut arguements may dffer (I am not an expert) try:

ifconfig etho | grep HWaddr
eth0      Link encap:Ethernet  HWaddr 00:26:6c:df:c3:95  

To change MAC we may do:

ifconfig eth0 down
ifconfig eth0 hw ether 00:80:48:BA:d1:30
ifconfig eth0 up

will change mac address to 00:80:48:BA:d1:30 (temporarily, will restore to actual one upon reboot).

How to break nested loops in JavaScript?

Use function for multilevel loops - this is good way:

function find_dup () {
    for (;;) {
        for(;;) {
            if (done) return;
        }
    }
}

Unable to execute dex: Multiple dex files define Lcom/myapp/R$array;

If you use 'com.google.android.gms:play-services' You can add what you really need to look at the following list:

Google+ com.google.android.gms:play-services-plus:10.0.1

Google Account Login com.google.android.gms:play-services-auth:10.0.1

Google Actions, Base Client Library com.google.android.gms:play-services-base:10.0.1

Google Address API com.google.android.gms:play-services-identity:10.0.1

Firebase App Indexing com.google.firebase:firebase-appindexing:10.0.1 Google Analytics com.google.android.gms:play-services-analytics:10.0.1

Google Awareness com.google.android.gms:play-services-awareness:10.0.1

Google Cast com.google.android.gms:play-services-cast:10.0.1

Google Cloud Messaging com.google.android.gms:play-services-gcm:10.0.1

Google Drive com.google.android.gms:play-services-drive:10.0.1

Google Fit com.google.android.gms:play-services-fitness:10.0.1

Google Location and Activity Recognition com.google.android.gms:play-services-location:10.0.1

Google Maps com.google.android.gms:play-services-maps:10.0.1

Google Mobile Ads com.google.android.gms:play-services-ads:10.0.1

Google Places com.google.android.gms:play-services-places:10.0.1

Mobile Vision com.google.android.gms:play-services-vision:10.0.1

Google Nearby com.google.android.gms:play-services-nearby:10.0.1

Google Panorama Viewer com.google.android.gms:play-services-panorama:10.0.1

Google Play Game services com.google.android.gms:play-services-games:10.0.1

SafetyNet com.google.android.gms:play-services-safetynet:10.0.1

Android Pay com.google.android.gms:play-services-wallet:10.0.1

Android Wear com.google.android.gms:play-services-wearable:10.0.1

How to see query history in SQL Server Management Studio

SELECT deqs.last_execution_time AS [Time], dest.text AS [Query], dest.*
FROM sys.dm_exec_query_stats AS deqs
CROSS APPLY sys.dm_exec_sql_text(deqs.sql_handle) AS dest
WHERE dest.dbid = DB_ID('msdb')
ORDER BY deqs.last_execution_time DESC

This should show you the time and date of when a query was ran

How can I send emails through SSL SMTP with the .NET Framework?

For gmail these settings worked for me, the ServicePointManager.SecurityProtocol line was necessary. Because I has setup 2 step verification I needed get a App Password from google app password generator.

SmtpClient mailer = new SmtpClient();
mailer.Host = "smtp.gmail.com";
mailer.Port = 587;
mailer.EnableSsl = true;
ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls;

iPhone UILabel text soft shadow

This answer to this similar question provides code for drawing a blurred shadow behind a UILabel. The author uses CGContextSetShadow() to generate the shadow for the drawn text.

ASP.NET DateTime Picker

Basic Date Picker Lite

This is the free version of their flagship product, but it contains a date and time picker native for asp.net.

How to exclude file only from root folder in Git

From the documentation:

If the pattern does not contain a slash /, git treats it as a shell glob pattern and checks for a match against the pathname relative to the location of the .gitignore file (relative to the toplevel of the work tree if not from a .gitignore file).

A leading slash matches the beginning of the pathname. For example, "/*.c" matches "cat-file.c" but not "mozilla-sha1/sha1.c".

So you should add the following line to your root .gitignore:

/config.php

How to create a jQuery function (a new jQuery method or plugin)?

From the Docs:

(function( $ ){
   $.fn.myfunction = function() {
      alert('hello world');
      return this;
   }; 
})( jQuery );

Then you do

$('#my_div').myfunction();

Creating a class object in c++

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

a) pointer

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

delete example;

b) Simple declaration

Example example;

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

2) Singleton C++

This SO question may helps you

How do I set the background color of Excel cells using VBA?

or alternatively you could not bother coding for it and use the 'conditional formatting' function in Excel which will set the background colour and font colour based on cell value.

There are only two variables here so set the default to yellow and then overwrite when the value is greater than or less than your threshold values.

How To Get Selected Value From UIPickerView

       NSInteger SelectedRow;
                   SelectedRow = [yourPickerView selectedRowInComponent:0];
                   selectedPickerString = [YourPickerArray objectAtIndex:SelectedRow];
                   self.YourTextField.text= selectedPickerString;

    // if  you want to move pickerview to selected row then 
 for (int i = 0; I<YourPickerArray.count; i++) {
  if ([[YourPickerArray objectAtIndex:i] isEqualToString:self.YourTextField.text]) { 
[yourPickerView selectRow:i inComponent:0 animated:NO];
 }
}

What are the use cases for selecting CHAR over VARCHAR in SQL?

There is a difference between early performance optimization and using a best practice type of rule. If you are creating new tables where you will always have a fixed length field, it makes sense to use CHAR, you should be using it in that case. This isn't early optimization, but rather implementing a rule of thumb (or best practice).

i.e. - If you have a 2 letter state field, use CHAR(2). If you have a field with the actual state names, use VARCHAR.

Where and how is the _ViewStart.cshtml layout file linked?

From ScottGu's blog:

Starting with the ASP.NET MVC 3 Beta release, you can now add a file called _ViewStart.cshtml (or _ViewStart.vbhtml for VB) underneath the \Views folder of your project:

The _ViewStart file can be used to define common view code that you want to execute at the start of each View’s rendering. For example, we could write code within our _ViewStart.cshtml file to programmatically set the Layout property for each View to be the SiteLayout.cshtml file by default:

Because this code executes at the start of each View, we no longer need to explicitly set the Layout in any of our individual view files (except if we wanted to override the default value above).

Important: Because the _ViewStart.cshtml allows us to write code, we can optionally make our Layout selection logic richer than just a basic property set. For example: we could vary the Layout template that we use depending on what type of device is accessing the site – and have a phone or tablet optimized layout for those devices, and a desktop optimized layout for PCs/Laptops. Or if we were building a CMS system or common shared app that is used across multiple customers we could select different layouts to use depending on the customer (or their role) when accessing the site.

This enables a lot of UI flexibility. It also allows you to more easily write view logic once, and avoid repeating it in multiple places.

Also see this.


In a more general sense this ability of MVC framework to "know" about _Viewstart.cshtml is called "Coding by convention".

Convention over configuration (also known as coding by convention) is a software design paradigm which seeks to decrease the number of decisions that developers need to make, gaining simplicity, but not necessarily losing flexibility. The phrase essentially means a developer only needs to specify unconventional aspects of the application. For example, if there's a class Sale in the model, the corresponding table in the database is called “sales” by default. It is only if one deviates from this convention, such as calling the table “products_sold”, that one needs to write code regarding these names.

Wikipedia

There's no magic to it. Its just been written into the core codebase of the MVC framework and is therefore something that MVC "knows" about. That why you don't find it in the .config files or elsewhere; it's actually in the MVC code. You can however override to alter or null out these conventions.

Meaning of = delete after function declaration

= delete is a feature introduce in C++11. As per =delete it will not allowed to call that function.

In detail.

Suppose in a class.

Class ABC{
 Int d;
 Public:
  ABC& operator= (const ABC& obj) =delete
  {

  }
};

While calling this function for obj assignment it will not allowed. Means assignment operator is going to restrict to copy from one object to another.

Returning Month Name in SQL Server Query

Select SUBSTRING (convert(varchar,S0.OrderDateTime,100),1,3) from your Table Name

Strtotime() doesn't work with dd/mm/YYYY format

Here is the simplified solution:

$date = '25/05/2010';
$date = str_replace('/', '-', $date);
echo date('Y-m-d', strtotime($date));

Result:

2010-05-25

The strtotime documentation reads:

Dates in the m/d/y or d-m-y formats are disambiguated by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed.

Convenient C++ struct initialisation

I know this question is old, but there is a way to solve this until C++20 finally brings this feature from C to C++. What you can do to solve this is use preprocessor macros with static_asserts to check your initialization is valid. (I know macros are generally bad, but here I don't see another way.) See example code below:

#define INVALID_STRUCT_ERROR "Instantiation of struct failed: Type, order or number of attributes is wrong."

#define CREATE_STRUCT_1(type, identifier, m_1, p_1) \
{ p_1 };\
static_assert(offsetof(type, m_1) == 0, INVALID_STRUCT_ERROR);\

#define CREATE_STRUCT_2(type, identifier, m_1, p_1, m_2, p_2) \
{ p_1, p_2 };\
static_assert(offsetof(type, m_1) == 0, INVALID_STRUCT_ERROR);\
static_assert(offsetof(type, m_2) >= sizeof(identifier.m_1), INVALID_STRUCT_ERROR);\

#define CREATE_STRUCT_3(type, identifier, m_1, p_1, m_2, p_2, m_3, p_3) \
{ p_1, p_2, p_3 };\
static_assert(offsetof(type, m_1) == 0, INVALID_STRUCT_ERROR);\
static_assert(offsetof(type, m_2) >= sizeof(identifier.m_1), INVALID_STRUCT_ERROR);\
static_assert(offsetof(type, m_3) >= (offsetof(type, m_2) + sizeof(identifier.m_2)), INVALID_STRUCT_ERROR);\

#define CREATE_STRUCT_4(type, identifier, m_1, p_1, m_2, p_2, m_3, p_3, m_4, p_4) \
{ p_1, p_2, p_3, p_4 };\
static_assert(offsetof(type, m_1) == 0, INVALID_STRUCT_ERROR);\
static_assert(offsetof(type, m_2) >= sizeof(identifier.m_1), INVALID_STRUCT_ERROR);\
static_assert(offsetof(type, m_3) >= (offsetof(type, m_2) + sizeof(identifier.m_2)), INVALID_STRUCT_ERROR);\
static_assert(offsetof(type, m_4) >= (offsetof(type, m_3) + sizeof(identifier.m_3)), INVALID_STRUCT_ERROR);\

// Create more macros for structs with more attributes...

Then when you have a struct with const attributes, you can do this:

struct MyStruct
{
    const int attr1;
    const float attr2;
    const double attr3;
};

const MyStruct test = CREATE_STRUCT_3(MyStruct, test, attr1, 1, attr2, 2.f, attr3, 3.);

It's a bit inconvenient, because you need macros for every possible number of attributes and you need to repeat the type and name of your instance in the macro call. Also you cannot use the macro in a return statement, because the asserts come after the initialization.

But it does solve your problem: When you change the struct, the call will fail at compile-time.

If you use C++17, you can even make these macros more strict by forcing the same types, e.g.:

#define CREATE_STRUCT_3(type, identifier, m_1, p_1, m_2, p_2, m_3, p_3) \
{ p_1, p_2, p_3 };\
static_assert(offsetof(type, m_1) == 0, INVALID_STRUCT_ERROR);\
static_assert(offsetof(type, m_2) >= sizeof(identifier.m_1), INVALID_STRUCT_ERROR);\
static_assert(offsetof(type, m_3) >= (offsetof(type, m_2) + sizeof(identifier.m_2)), INVALID_STRUCT_ERROR);\
static_assert(typeid(p_1) == typeid(identifier.m_1), INVALID_STRUCT_ERROR);\
static_assert(typeid(p_2) == typeid(identifier.m_2), INVALID_STRUCT_ERROR);\
static_assert(typeid(p_3) == typeid(identifier.m_3), INVALID_STRUCT_ERROR);\

excel plot against a date time x series

Try using an X-Y Scatter graph with datetime formatted as YYYY-MM-DD HH:MM.

This provides a reasonable graph for me (using Excel 2010).

Excel Datetime XY Scatter

Ubuntu says "bash: ./program Permission denied"

Try this:

sudo chmod +x program_name
./program_name 

Laravel 5.2 - Use a String as a Custom Primary Key for Eloquent Table becomes 0

This was added to the upgrade documentation on Dec 29, 2015, so if you upgraded before then you probably missed it.

When fetching any attribute from the model it checks if that column should be cast as an integer, string, etc.

By default, for auto-incrementing tables, the ID is assumed to be an integer in this method:

https://github.com/laravel/framework/blob/5.2/src/Illuminate/Database/Eloquent/Model.php#L2790

So the solution is:

class UserVerification extends Model
{
    protected $primaryKey = 'your_key_name'; // or null

    public $incrementing = false;

    // In Laravel 6.0+ make sure to also set $keyType
    protected $keyType = 'string';
}

Simple CSS: Text won't center in a button

make sure:

box-sizing : content-box;

react-router - pass props to handler component

If you'd rather not write wrappers, I guess you could do this:

class Index extends React.Component { 

  constructor(props) {
    super(props);
  }
  render() {
    return (
      <h1>
        Index - {this.props.route.foo}
      </h1>
    );
  }
}

var routes = (
  <Route path="/" foo="bar" component={Index}/>
);

How to copy std::string into std::vector<char>?

You need a back inserter to copy into vectors:

std::copy(str.c_str(), str.c_str()+str.length(), back_inserter(data));

JPA With Hibernate Error: [PersistenceUnit: JPA] Unable to build EntityManagerFactory

It worked for me after adding the following dependency in pom,

<dependency>
 <groupId>org.hibernate</groupId>
 <artifactId>hibernate-validator</artifactId>
 <version>4.3.0.Final</version>
</dependency>

npm install gives error "can't find a package.json file"

node comes with npm installed so you should have a version of npm, however npm gets updated more frequently than node does, so you'll want to make sure it's the latest version.

sudo npm install npm -g

Test: Run npm -v. The version should be higher than 2.1.8.

npm install

THAT'S IT!

https://www.youtube.com/watch?v=wREima9e6vk

How to create strings containing double quotes in Excel formulas?

Concatenate " as a ceparate cell:

    A |   B   | C | D
1   " | text  | " | =CONCATENATE(A1; B1; C1);

D1 displays "text"

When do you use the "this" keyword?

Never. Ever. If you have variable shadowing, your naming conventions are on crack. I mean, really, no distinguishing naming for member variables? Facepalm

Angular 2 - innerHTML styling

We pull in content frequently from our CMS as [innerHTML]="content.title". We place the necessary classes in the application's root styles.scss file rather than in the component's scss file. Our CMS purposely strips out in-line styles so we must have prepared classes that the author can use in their content. Remember using {{content.title}} in the template will not render html from the content.

How would I run an async Task<T> method synchronously?

Tested in .Net 4.6. It can also avoid deadlock.

For async method returning Task.

Task DoSomeWork();
Task.Run(async () => await DoSomeWork()).Wait();

For async method returning Task<T>

Task<T> GetSomeValue();
var result = Task.Run(() => GetSomeValue()).Result;

Edit:

If the caller is running in the thread pool thread (or the caller is also in a task), it may still cause a deadlock in some situation.

div hover background-color change?

div hover background color change

Try like this:

.class_name:hover{
    background-color:#FF0000;
}

How to disable mouse right click on a web page?

Firstly, if you are doing this just to prevent people viewing the source of your page - it won't work, because they can always use a keyboard shortcut to view it.

Secondly, you will have to use JavaScript to accomplish this. If the user has JS disabled, you cannot prevent the right click.

That said, add this to your body tag to disable right clicks.

<body oncontextmenu="return false;">

Connecting to SQL Server with Visual Studio Express Editions

The only way I was able to get C# Express 2008 to work was to move the database file. So, I opened up SQL Server Management Studio and after dropping the database, I copied the file to my project folder. Then I reattached the database to management studio. Now, when I try to attach to the local copy it works. Apparently, you can not use the same database file more than once.

Array to String PHP?

One of the Best way:

echo print_r($array, true);

Calculate RSA key fingerprint

$ ssh-add -l 

will also work on Mac OS X v10.8 (Mountain Lion) - v10.10 (Yosemite).

It also supports the option -E to specify the fingerprint format so in case MD5 is needed (it's often used, e.g. by GitHub), just add -E md5 to the command.

How do I clear all variables in the middle of a Python script?

The globals() function returns a dictionary, where keys are names of objects you can name (and values, by the way, are ids of these objects) The exec() function takes a string and executes it as if you just type it in a python console. So, the code is

for i in list(globals().keys()):
    if(i[0] != '_'):
        exec('del {}'.format(i))

DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss") is returning AM time instead of PM time?

With C#6.0 you also have a new way of formatting date when using string interpolation e.g.

$"{DateTime.Now:yyyy-MM-dd HH:mm:ss}"

Can't say its any better, but it is slightly cleaner if including the formatted DateTime in a longer string.

More about string interpolation.

log4j:WARN No appenders could be found for logger (running jar file, not web app)

You will find de log4j.properties in solr/examples/resources.

If you don't find the file, i put it here:

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

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

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

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

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

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

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

Regards

Replacing a fragment with another fragment inside activity group

In kotlin you can do:

// instantiate the new fragment
val fragment: Fragment = ExampleFragment()

val transaction = supportFragmentManager.beginTransaction()
transaction.replace(R.id.book_description_fragment, fragment)
transaction.addToBackStack("transaction_name")
// Commit the transaction
transaction.commit()

Run JavaScript when an element loses focus

You're looking for the onblur event. Look here, for more details.

Regex any ASCII character

Try using .+ instead of [(\w)(\W)(\s)]+.

Note that this actually includes more than you need - ASCII only defines the first 128 characters.

How to convert unsigned long to string

The standard approach is to use sprintf(buffer, "%lu", value); to write a string rep of value to buffer. However, overflow is a potential problem, as sprintf will happily (and unknowingly) write over the end of your buffer.

This is actually a big weakness of sprintf, partially fixed in C++ by using streams rather than buffers. The usual "answer" is to allocate a very generous buffer unlikely to overflow, let sprintf output to that, and then use strlen to determine the actual string length produced, calloc a buffer of (that size + 1) and copy the string to that.

This site discusses this and related problems at some length.

Some libraries offer snprintf as an alternative which lets you specify a maximum buffer size.

How to check if a std::thread is still running?

Create a mutex that the running thread and the calling thread both have access to. When the running thread starts it locks the mutex, and when it ends it unlocks the mutex. To check if the thread is still running, the calling thread calls mutex.try_lock(). The return value of that is the status of the thread. (Just make sure to unlock the mutex if the try_lock worked)

One small problem with this, mutex.try_lock() will return false between the time the thread is created, and when it locks the mutex, but this can be avoided using a slightly more complex method.

/etc/apt/sources.list" E212: Can't open file for writing

change user to root

sodu su -

browse to etc

vi sudoers

look for root user in user priviledge section. you will get it like

root ALL=(ALL:ALL) ALL 

make same entry for your user name. if you username is 'myuser' then add

myuser ALL=(ALL:ALL) ALL

it will look like

root ALL=(ALL:ALL) ALL 

myuser ALL=(ALL:ALL) ALL 

save it. change root user to your user. now try the same where you were getting the sudoers issue

Command line: search and replace in all filenames matched by grep

The answer already given of using find and sed

find -name '*.html' -print -exec sed -i.bak 's/foo/bar/g' {} \;

is probably the standard answer. Or you could use perl -pi -e s/foo/bar/g' instead of the sed command.

For most quick uses, you may find the command rpl is easier to remember. Here is replacement (foo -> bar), recursively on all files in the current directory:

rpl -R foo bar .

It's not available by default on most Linux distros but is quick to install (apt-get install rpl or similar).

However, for tougher jobs that involve regular expressions and back substitution, or file renames as well as search-and-replace, the most general and powerful tool I'm aware of is repren, a small Python script I wrote a while back for some thornier renaming and refactoring tasks. The reasons you might prefer it are:

  • Support renaming of files as well as search-and-replace on file contents (including moving files between directories and creating new parent directories).
  • See changes before you commit to performing the search and replace.
  • Support regular expressions with back substitution, whole words, case insensitive, and case preserving (replace foo -> bar, Foo -> Bar, FOO -> BAR) modes.
  • Works with multiple replacements, including swaps (foo -> bar and bar -> foo) or sets of non-unique replacements (foo -> bar, f -> x).

Check the README for examples.

Android - Activity vs FragmentActivity?

FragmentActivity gives you all of the functionality of Activity plus the ability to use Fragments which are very useful in many cases, particularly when working with the ActionBar, which is the best way to use Tabs in Android.

If you are only targeting Honeycomb (v11) or greater devices, then you can use Activity and use the native Fragments introduced in v11 without issue. FragmentActivity was built specifically as part of the Support Library to back port some of those useful features (such as Fragments) back to older devices.

I should also note that you'll probably find the Backward Compatibility - Implementing Tabs training very helpful going forward.

PHP display image BLOB from MySQL

Try Like this.

For Inserting into DB

$db = mysqli_connect("localhost","root","","DbName"); //keep your db name
$image = addslashes(file_get_contents($_FILES['images']['tmp_name']));
//you keep your column name setting for insertion. I keep image type Blob.
$query = "INSERT INTO products (id,image) VALUES('','$image')";  
$qry = mysqli_query($db, $query);

For Accessing image From Blob

$db = mysqli_connect("localhost","root","","DbName"); //keep your db name
$sql = "SELECT * FROM products WHERE id = $id";
$sth = $db->query($sql);
$result=mysqli_fetch_array($sth);
echo '<img src="data:image/jpeg;base64,'.base64_encode( $result['image'] ).'"/>';

Hope It will help you.

Thanks.

How to use Global Variables in C#?

There's no such thing as a global variable in C#. Period.

You can have static members if you want:

public static class MyStaticValues
{
   public static bool MyStaticBool {get;set;}
}

AngularJS - Any way for $http.post to send request parameters instead of JSON?

From AngularJS documentation:

params – {Object.} – Map of strings or objects which will be turned to ?key1=value1&key2=value2 after the url. If the value is not a string, it will be JSONified.

So, provide string as parameters. If you don't want that, then use transformations. Again, from the documentation:

To override these transformation locally, specify transform functions as transformRequest and/or transformResponse properties of the config object. To globally override the default transforms, override the $httpProvider.defaults.transformRequest and $httpProvider.defaults.transformResponse properties of the $httpProvider.

Refer to documentation for more details.

Comparing two hashmaps for equal values and same key sets?

Simply use :

mapA.equals(mapB);

Compares the specified object with this map for equality. Returns true if the given object is also a map and the two maps represent the same mappings

Java out.println() how is this possible?

out is a PrintStream type of static variable(object) of System class and println() is function of the PrintStream class.

class PrintStream
{
    public void println(){}    //member function
    ...
}

class System
{
    public static final PrintStream out;   //data member
    ...
}

That is why the static variable(object) out is accessed with the class name System which further invokes the method println() of it's type PrintStream (which is a class).

How to fix the height of a <div> element?

change the div to display block

.topbar{
    display:block;
    width:100%;
    height:70px;
    background-color:#475;
    overflow:scroll;
    }

i made a jsfiddle example here please check

http://jsfiddle.net/TgPRM/

How to force composer to reinstall a library?

As user @aaracrr pointed out in a comment on another answer probably the best answer is to re-require the package with the same version constraint.

ie.

composer require vendor/package

or specifying a version constraint

composer require vendor/package:^1.0.0

currently unable to handle this request HTTP ERROR 500

Your site is serving a 500 Internal Server Error. This can be caused by a number of things, such as:

  • File Permissions
  • Fatal Code Errors
  • Web Server Issues

EDIT

As you have highlighted it is a permission issue. You need to ensure that your files are executable by the web server user

Please see below article for some guidance on proper file permissions. https://www.digitalocean.com/community/questions/proper-permissions-for-web-server-s-directory

findAll() in yii

Try:

$id =101;
$comments = EmailArchive::model()->findAll(
array("condition"=>"email_id =  $id","order"=>"id"));

OR

$id =101;
$criteria = new CDbCriteria();
$criteria->addCondition("email_id=:email_id");
$criteria->params = array(':email_id' => $id);
$comments = EmailArchive::model()->findAll($criteria);

OR

$Criteria = new CDbCriteria();
$Criteria->condition = "email_id = $id";
$Products = Product::model()->findAll($Criteria);

How to search a string in String array

Well, something is going to have to look, and looping is more efficient than recursion (since tail-end recursion isn't fully implemented)... so if you just don't want to loop yourself, then either of:

bool has = arr.Contains(var); // .NET 3.5

or

bool has = Array.IndexOf(arr, var) >= 0;

For info: avoid names like var - this is a keyword in C# 3.0.

TypeError: 'str' object is not callable (Python)

It is important to note (in case you came here by Google) that "TypeError: 'str' object is not callable" means only that a variable that was declared as String-type earlier is attempted to be used as a function (e.g. by adding parantheses in the end.)

You can get the exact same error message also, if you use any other built-in method as variable name.

Deleting Objects in JavaScript

This work for me, although its not a good practice. It simply delete all the the associated element with which the object belong.

 for (element in homeService) {
          delete homeService[element];
  }

Reset Windows Activation/Remove license key

  1. Open a command prompt as an Administrator.

  2. Enter slmgr /upk and wait for this to complete. This will uninstall the current product key from Windows and put it into an unlicensed state.

  3. Enter slmgr /cpky and wait for this to complete. This will remove the product key from the registry if it's still there.

  4. Enter slmgr /rearm and wait for this to complete. This is to reset the Windows activation timers so the new users will be prompted to activate Windows when they put in the key.

This should put the system back to a pre-key state.

Hope this helps you out!

Get public/external IP address?

Using a great similar service

private string GetPublicIpAddress()
{
    var request = (HttpWebRequest)WebRequest.Create("http://ifconfig.me");

    request.UserAgent = "curl"; // this will tell the server to return the information as if the request was made by the linux "curl" command

    string publicIPAddress;

    request.Method = "GET";
    using (WebResponse response = request.GetResponse())
    {
        using (var reader = new StreamReader(response.GetResponseStream()))
        {
            publicIPAddress = reader.ReadToEnd();
        }
    }

    return publicIPAddress.Replace("\n", "");
}

How can I update my ADT in Eclipse?

I viewed the Eclipse ADT documentation and found out the way to get around this issue. I was able to Update My SDK Tool to 22.0.4 (Latest Version).

Solution is: First Update ADT to 22.0.4 and then Update SDK Tool to 22.0.4

The above link says,

ADT 22.0.4 is designed for use with SDK Tools r22.0.4. If you haven't already installed SDK Tools r22.0.4 into your SDK, use the Android SDK Manager to do so

What I had to do was update my ADT to 22.0.4 (Latest Version) and then I was able to update SDK tool to 22.0.4. I thought only SDK Tool has been updated not ADT, so I was updating the SDK Tool with Older ADT Version (22.0.1).

How to Update your ADT to Latest Version

  1. In Eclipse go to Help

  2. Install New Software ---> Add

  3. inside Add Repository write the Name: ADT (or whatever you want)

  4. Location: https://dl-ssl.google.com/android/eclipse/

  5. after loading you should get Developer Tools and NDK Plugins

  6. check both if you want to use the Native Developer Kit (NDK) in the future or check

  7. Developer Tool only

  8. click Next

  9. Finish

How to getText on an input in protractor

getText() function won't work like the way it used to be for webdriver, in order to get it work for protractor you will need to wrap it in a function and return the text something like we did for our protractor framework we have kept it in a common function like -

getText : function(element, callback) {
        element.getText().then (function(text){             
            callback(text);
         });        

    },

By this you can have the text of an element.

Let me know if it is still unclear.

What is the main difference between Collection and Collections in Java?

Collection is an interface from which other class forms like List, Set are derived. Collections (with "S") is a utility class having static methods to simplify work on collection. Ex : Collections.sort()

How to specify different Debug/Release output directories in QMake .pro file

The short answer is: you don't.

You should run qmake followed by make in whatever build directory you want to build in. So, run it once in a debug directory, once in a release directory.

That's how anyone building your project would expect it to work, and that's how Qt itself is set up to build, that's also how Qt Creator expects your .pro file to behave: it simply starts qmake and then make in the build folder for your target's chosen configuration.

If you wish to create these folders and perform the two (or more) builds in them, you'll need a top-level makefile, possibly created from a top-level project file via qmake.

It's not uncommon to have more than two build configurations, so you're unnecessarily committing yourself to only differentiating between a build and a release; you might have builds with different optimization levels, etc. The debug/release dichotomy is best left to rest in peace.

Lotus Notes email as an attachment to another email

You can slecet sent item /email and drag to desktop , it will automatic created new file on desktop. Then you can attach and send it in to new emails.

Bootstrap Modal sitting behind backdrop

In my case, I could fix it by adding css for the .modal-backdrop

.modal-backdrop {
  z-index: -1;
}

Although this works, form controls still seem to appear above the backdrop, clicking anywhere dismisses the modal, but it doesn't look great.

A better workaround for me is to bind to the shown event (once the page is loaded) and to correct the z-index property.

$('.modal').on('shown.bs.modal', function() {
  $(this).css("z-index", parseInt($('.modal-backdrop').css('z-index')) + 1);
});

In this case, if you are OK with changing the DOM on modal shown:

$('.modal').on('shown.bs.modal', function() {
  //Make sure the modal and backdrop are siblings (changes the DOM)
  $(this).before($('.modal-backdrop'));
  //Make sure the z-index is higher than the backdrop
  $(this).css("z-index", parseInt($('.modal-backdrop').css('z-index')) + 1);
});

onchange event on input type=range is not triggering in firefox while dragging

Apparently Chrome and Safari are wrong: onchange should only be triggered when the user releases the mouse. To get continuous updates, you should use the oninput event, which will capture live updates in Firefox, Safari and Chrome, both from the mouse and the keyboard.

However, oninput is not supported in IE10, so your best bet is to combine the two event handlers, like this:

<span id="valBox"></span>
<input type="range" min="5" max="10" step="1" 
   oninput="showVal(this.value)" onchange="showVal(this.value)">

Check out this Bugzilla thread for more information.

Create Directory When Writing To File In Node.js

Shameless plug alert!

You will have to check for each directory in the path structure you want and create it manually if it doesn't exist. All the tools to do so are already there in Node's fs module, but you can do all of that simply with my mkpath module: https://github.com/jrajav/mkpath

How do I view the list of functions a Linux shared library is exporting?

Among other already mentioned tools you can use also readelf (manual). It is similar to objdump but goes more into detail. See this for the difference explanation.

$ readelf -sW /lib/liblzma.so.5 |head -n10

Symbol table '.dynsym' contains 128 entries:
   Num:    Value  Size Type    Bind   Vis      Ndx Name
     0: 00000000     0 NOTYPE  LOCAL  DEFAULT  UND
     1: 00000000     0 FUNC    GLOBAL DEFAULT  UND pthread_mutex_unlock@GLIBC_2.0 (4)
     2: 00000000     0 FUNC    GLOBAL DEFAULT  UND pthread_mutex_destroy@GLIBC_2.0 (4)
     3: 00000000     0 NOTYPE  WEAK   DEFAULT  UND _ITM_deregisterTMCloneTable
     4: 00000000     0 FUNC    GLOBAL DEFAULT  UND memmove@GLIBC_2.0 (5)
     5: 00000000     0 FUNC    GLOBAL DEFAULT  UND free@GLIBC_2.0 (5)
     6: 00000000     0 FUNC    GLOBAL DEFAULT  UND memcpy@GLIBC_2.0 (5)

Run a PHP file in a cron job using CPanel

For domain specific Multi PHP Cron Job, do like this,

/usr/local/bin/ea-php56 /home/username/domain_path/path/to/cron/script

In the above example, replace “ea-php56” with the PHP version assigned to the domain you wish to use.

Hope this helps someone.

Regular cast vs. static_cast vs. dynamic_cast

dynamic_cast has runtime type checking and only works with references and pointers, whereas static_cast does not offer runtime type checking. For complete information, see the MSDN article static_cast Operator.

Converting an integer to a hexadecimal string in Ruby

How about using %/sprintf:

i = 20
"%x" % i  #=> "14"

How to create custom exceptions in Java?

To define a checked exception you create a subclass (or hierarchy of subclasses) of java.lang.Exception. For example:

public class FooException extends Exception {
  public FooException() { super(); }
  public FooException(String message) { super(message); }
  public FooException(String message, Throwable cause) { super(message, cause); }
  public FooException(Throwable cause) { super(cause); }
}

Methods that can potentially throw or propagate this exception must declare it:

public void calculate(int i) throws FooException, IOException;

... and code calling this method must either handle or propagate this exception (or both):

try {
  int i = 5;
  myObject.calculate(5);
} catch(FooException ex) {
  // Print error and terminate application.
  ex.printStackTrace();
  System.exit(1);
} catch(IOException ex) {
  // Rethrow as FooException.
  throw new FooException(ex);
}

You'll notice in the above example that IOException is caught and rethrown as FooException. This is a common technique used to encapsulate exceptions (typically when implementing an API).

Sometimes there will be situations where you don't want to force every method to declare your exception implementation in its throws clause. In this case you can create an unchecked exception. An unchecked exception is any exception that extends java.lang.RuntimeException (which itself is a subclass of java.lang.Exception):

public class FooRuntimeException extends RuntimeException {
  ...
}

Methods can throw or propagate FooRuntimeException exception without declaring it; e.g.

public void calculate(int i) {
  if (i < 0) {
    throw new FooRuntimeException("i < 0: " + i);
  }
}

Unchecked exceptions are typically used to denote a programmer error, for example passing an invalid argument to a method or attempting to breach an array index bounds.

The java.lang.Throwable class is the root of all errors and exceptions that can be thrown within Java. java.lang.Exception and java.lang.Error are both subclasses of Throwable. Anything that subclasses Throwable may be thrown or caught. However, it is typically bad practice to catch or throw Error as this is used to denote errors internal to the JVM that cannot usually be "handled" by the programmer (e.g. OutOfMemoryError). Likewise you should avoid catching Throwable, which could result in you catching Errors in addition to Exceptions.