Programs & Examples On #Cgpdfdictionaryref

How can I convert a cv::Mat to a gray scale in OpenCv?

Using the C++ API, the function name has slightly changed and it writes now:

#include <opencv2/imgproc/imgproc.hpp>

cv::Mat greyMat, colorMat;
cv::cvtColor(colorMat, greyMat, CV_BGR2GRAY);

The main difficulties are that the function is in the imgproc module (not in the core), and by default cv::Mat are in the Blue Green Red (BGR) order instead of the more common RGB.

OpenCV 3

Starting with OpenCV 3.0, there is yet another convention. Conversion codes are embedded in the namespace cv:: and are prefixed with COLOR. So, the example becomes then:

#include <opencv2/imgproc/imgproc.hpp>

cv::Mat greyMat, colorMat;
cv::cvtColor(colorMat, greyMat, cv::COLOR_BGR2GRAY);

As far as I have seen, the included file path hasn't changed (this is not a typo).

The network path was not found

On my end, the problem was an unsuccessful connection to the VPN (while working from home). And yeah, the connectionString was using a context from remote server. Which resulted in the following error:

<Error>
  <Message>An error has occurred.</Message>
  <ExceptionMessage>The network path was not found</ExceptionMessage>
  <ExceptionType>System.ComponentModel.Win32Exception</ExceptionType>
  <StackTrace/>
</Error>

Reading a binary input stream into a single byte array in Java

You can use Apache commons-io for this task:

Refer to this method:

public static byte[] readFileToByteArray(File file) throws IOException

Update:

Java 7 way:

byte[] bytes = Files.readAllBytes(Paths.get(filename));

and if it is a text file and you want to convert it to String (change encoding as needed):

StandardCharsets.UTF_8.decode(ByteBuffer.wrap(bytes)).toString()

How do I script a "yes" response for installing programs?

The 'yes' command will echo 'y' (or whatever you ask it to) indefinitely. Use it as:

yes | command-that-asks-for-input

or, if a capital 'Y' is required:

yes Y | command-that-asks-for-input

How do I handle a click anywhere in the page, even when a certain element stops the propagation?

Events in modern DOM implementations have two phases, capturing and bubbling. The capturing phase is the first phase, flowing from the defaultView of the document to the event target, followed by the bubbling phase, flowing from the event target back to the defaultView. For more information, see http://www.w3.org/TR/DOM-Level-3-Events/#event-flow.

To handle the capturing phase of an event, you need to set the third argument for addEventListener to true:

document.body.addEventListener('click', fn, true); 

Sadly, as Wesley mentioned, the capturing phase of an event cannot be handled reliably, or at all, in older browsers.

One possible solution is to handle the mouseup event instead, since event order for clicks is:

  1. mousedown
  2. mouseup
  3. click

If you can be sure you have no handlers cancelling the mouseup event, then this is one way (and, arguably, a better way) to go. Another thing to note is that many, if not most (if not all), UI menus disappear on mouse down.

Python lookup hostname from IP with 1 second timeout

What you're trying to accomplish is called Reverse DNS lookup.

socket.gethostbyaddr("IP") 
# => (hostname, alias-list, IP)

http://docs.python.org/library/socket.html?highlight=gethostbyaddr#socket.gethostbyaddr

However, for the timeout part I have read about people running into problems with this. I would check out PyDNS or this solution for more advanced treatment.

JS - window.history - Delete a state

There is no way to delete or read the past history.

You could try going around it by emulating history in your own memory and calling history.pushState everytime window popstate event is emitted (which is proposed by the currently accepted Mike's answer), but it has a lot of disadvantages that will result in even worse UX than not supporting the browser history at all in your dynamic web app, because:

  • popstate event can happen when user goes back ~2-3 states to the past
  • popstate event can happen when user goes forward

So even if you try going around it by building virtual history, it's very likely that it can also lead into a situation where you have blank history states (to which going back/forward does nothing), or where that going back/forward skips some of your history states totally.

POST unchecked HTML checkboxes

When the checkbox is unchecked on submit, update the checkbox value to 'NO' and set checked = 'TRUE'

https://jsfiddle.net/pommyk/8d9jLrvo/26/

$(document).ready(function() 
{
  function save() 
  {
    if (document.getElementById('AgeVerification').checked == false) 
    {
      document.getElementById('AgeVerification').value = 'no';
      document.getElementById('AgeVerification').checked = true;     
    }
  }
  document.getElementById("submit").onclick = save;
})

SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed

Then, as this blog post suggests,

"How to Cure Net::HTTP’s Risky Default HTTPS Behavior"

you might want to install the always_verify_ssl_certificates gem that allow you to set a default value for ca_file.

JavaScript Adding an ID attribute to another created Element

Since id is an attribute don't create an id element, just do this:

myPara.setAttribute("id", "id_you_like");

How to get user name using Windows authentication in asp.net?

These are the different variables you have access to and their values, depending on the IIS configuration.

Scenario 1: Anonymous Authentication in IIS with impersonation off.

HttpContext.Current.Request.LogonUserIdentity.Name    SERVER1\IUSR_SERVER1 
HttpContext.Current.Request.IsAuthenticated           False                    
HttpContext.Current.User.Identity.Name                –                        
System.Environment.UserName                           ASPNET                   
Security.Principal.WindowsIdentity.GetCurrent().Name  SERVER1\ASPNET

Scenario 2: Windows Authentication in IIS, impersonation off.

HttpContext.Current.Request.LogonUserIdentity.Name    MYDOMAIN\USER1   
HttpContext.Current.Request.IsAuthenticated           True             
HttpContext.Current.User.Identity.Name                MYDOMAIN\USER1   
System.Environment.UserName                           ASPNET           
Security.Principal.WindowsIdentity.GetCurrent().Name  SERVER1\ASPNET

Scenario 3: Anonymous Authentication in IIS, impersonation on

HttpContext.Current.Request.LogonUserIdentity.Name    SERVER1\IUSR_SERVER1 
HttpContext.Current.Request.IsAuthenticated           False                    
HttpContext.Current.User.Identity.Name                –                        
System.Environment.UserName                           IUSR_SERVER1           
Security.Principal.WindowsIdentity.GetCurrent().Name  SERVER1\IUSR_SERVER1 

Scenario 4: Windows Authentication in IIS, impersonation on

HttpContext.Current.Request.LogonUserIdentity.Name    MYDOMAIN\USER1
HttpContext.Current.Request.IsAuthenticated           True          
HttpContext.Current.User.Identity.Name                MYDOMAIN\USER1
System.Environment.UserName                           USER1         
Security.Principal.WindowsIdentity.GetCurrent().Name  MYDOMAIN\USER1

Legend
SERVER1\ASPNET: Identity of the running process on server.
SERVER1\IUSR_SERVER1: Anonymous guest user defined in IIS.
MYDOMAIN\USER1: The user of the remote client.

Source

Converting a character code to char (VB.NET)

You could use the Chr(int) function

What is an IIS application pool?

An application pool is a group of one or more URLs that are served by a worker process or set of worker processes. Any Web directory or virtual directory can be assigned to an application pool.

Every application within an application pool shares the same worker process.

Visual Studio Code open tab in new window

This is a very highly upvoted issue request in Github for Floating Windows.

Until they support it, you can try the following workarounds:

1. Duplicate Workspace in New Window [1]

The Duplicate Workspace in new Window Command was added in v1.24 (May 2018) to sort of address this.

  1. Open up Keyboard Shortcuts Ctrl + K, Ctrl + S
  2. Map workbench.action.duplicateWorkspaceInNewWindow to Ctrl + Shift + N or whatever you'd like

Duplicate Workspace in New Window

2. Open Active File in New Window [2]

Rather than manually open a new window and dragging the file, you can do it all with a single command.

  1. Open Active File in New Window Ctrl + K, O

Open Active File in New Window

3. New Window with Same File [3]

As AllenBooTung also pointed out, you can open/drag any file in a separate blank instance.

  1. Open New Window Ctrl + Shift + N
  2. Drag tab into new window

4. Open Workspace and Folder Simultaneously [4]

VS Code will not allow you to open the same folder in two different instances, but you can use Workspaces to open the same directory of files in a side by side instance.

  1. Open Folder Ctrl + K,Ctrl + O
  2. Save Current Project As a Workspace
  3. Open Folder Ctrl + K,Ctrl + O

For any workaround, also consider setting setting up auto save so the documents are kept in sync by updating the files.autoSave setting to afterDelay, onFocusChange, or onWindowChange

AutoSave

#define in Java

Simplest Answer is "No Direct method of getting it because there is no pre-compiler" But you can do it by yourself. Use classes and then define variables as final so that it can be assumed as constant throughout the program
Don't forget to use final and variable as public or protected not private otherwise you won't be able to access it from outside that class

How to get sp_executesql result into a variable?

Return values are generally not used to "return" a result but to return success (0) or an error number (1-65K). The above all seem to indicate that sp_executesql does not return a value, which is not correct. sp_executesql will return 0 for success and any other number for failure.

In the below, @i will return 2727

DECLARE @s NVARCHAR(500)
DECLARE @i INT;
SET @s = 'USE [Blah]; UPDATE STATISTICS [dbo].[TableName] [NonExistantStatisticsName];';
EXEC @i = sys.sp_executesql @s
SELECT @i AS 'Blah'

SSMS will show this Msg 2727, Level 11, State 1, Line 1 Cannot find index 'NonExistantStaticsName'.

Sending email from Azure

Sending from a third party SMTP isn't restricted by or specific to Azure. Using System.Net.Mail, create your message, configure your SMTP client, send the email:

// create the message
var msg = new MailMessage();
msg.From = new MailAddress("[email protected]"); 
msg.To.Add(strTo); 
msg.Subject = strSubject; 
msg.IsBodyHtml = true; 
msg.Body = strMessage;

// configure the smtp server
var smtp = new SmtpClient("YourSMTPServer"); 
var = new System.Net.NetworkCredential("YourSMTPServerUserName", "YourSMTPServerPassword");

// send the message
smtp.Send(msg); 

UPDATE: I added a post on Medium about how to do this with an Azure Function - https://medium.com/@viperguynaz/building-a-serverless-contact-form-f8f0bff46ba9

Use of REPLACE in SQL Query for newline/ carriage return characters

There are probably embedded tabs (CHAR(9)) etc. as well. You can find out what other characters you need to replace (we have no idea what your goal is) with something like this:

DECLARE @var NVARCHAR(255), @i INT;

SET @i = 1;

SELECT @var = AccountType FROM dbo.Account
  WHERE AccountNumber = 200
  AND AccountType LIKE '%Daily%';

CREATE TABLE #x(i INT PRIMARY KEY, c NCHAR(1), a NCHAR(1));

WHILE @i <= LEN(@var)
BEGIN
  INSERT #x 
    SELECT SUBSTRING(@var, @i, 1), ASCII(SUBSTRING(@var, @i, 1));

  SET @i = @i + 1;
END

SELECT i,c,a FROM #x ORDER BY i;

You might also consider doing better cleansing of this data before it gets into your database. Cleaning it every time you need to search or display is not the best approach.

Unable to run Java code with Intellij IDEA

Sometimes, patience is key.

I had the same problem with a java project with big node_modules / .m2 directories.
The indexing was very long so I paused it and it prevented me from using Run Configurations.

So I waited for the indexing to finish and only then I was able to run my main class.

How to return a custom object from a Spring Data JPA GROUP BY query

This SQL query return List< Object[] > would.

You can do it this way:

 @RestController
 @RequestMapping("/survey")
 public class SurveyController {

   @Autowired
   private SurveyRepository surveyRepository;

     @RequestMapping(value = "/find", method =  RequestMethod.GET)
     public Map<Long,String> findSurvey(){
       List<Object[]> result = surveyRepository.findSurveyCount();
       Map<Long,String> map = null;
       if(result != null && !result.isEmpty()){
          map = new HashMap<Long,String>();
          for (Object[] object : result) {
            map.put(((Long)object[0]),object[1]);
          }
       }
     return map;
     }
 }

How to get ° character in a string in python?

You can also use chr(176) to print the degree sign. Here is an example using python 3.6.5 interactive shell:

https://i.stack.imgur.com/spoWL.png

Get the last element of a std::string

*(myString.end() - 1) maybe? That's not exactly elegant either.

A python-esque myString.at(-1) would be asking too much of an already-bloated class.

How do I download the Android SDK without downloading Android Studio?

Command line only without sdkmanager (for advanced users / CI):

You can find the download links for all individual packages, including various revisions, in the repository XML file: https://dl.google.com/android/repository/repository-12.xml

(where 12 is the version of the repository index and will increase in the future).

All <sdk:url> values are relative to https://dl.google.com/android/repository, so

<sdk:url>platform-27_r03.zip</sdk:url>

can be downloaded at https://dl.google.com/android/repository/platform-27_r03.zip

Similar summary XML files exist for system images as well:

How to clear browsing history using JavaScript?

You cannot clear the browser history. It belongs to the user, not the developer. Also have a look at the MDN documentation.

Update: The link you were posting all over does not actually clear your browser history. It just prevents using the back button.

Android: How to add R.raw to project?

If you have a res/raw folder, be sure to add a file with a valid filename, otherwise the entire folder won't show up in the R class. If there's an error with a filename, it will appear in red in the console.

Could not load type 'System.ServiceModel.Activation.HttpModule' from assembly 'System.ServiceModel

I am late, hope it will help someone ....This is a known issue with IIS 8.0

The solution is to delete the 3.x module and handler from IIS manager. You could delete them at the application or site level if you want to keep them in applicationHost.config. But I wanted to delete them from applicationHost.config. do the following steps:

In IIS manager, click the machine name node. In “Features View”, double-click “Modules”. Find “ServiceModel” and remove it. Image 1 for Solve IIS 8 Error: Could not load type ‘System.ServiceModel.Activation.HttpModule’

Go back to the machine name node’s “Features View”, double-click “Handler Mappings”. Find “svc-Integrated” and remove it. Image 2 for Solve IIS 8 Error: Could not load type ‘System.ServiceModel.Activation.HttpModule’

Postgresql: error "must be owner of relation" when changing a owner object

This solved my problem : Sample alter table statement to change the ownership.

ALTER TABLE databasechangelog OWNER TO arwin_ash;
ALTER TABLE databasechangeloglock OWNER TO arwin_ash;

Best method to download image from url in Android

Try this code to download an image from a URL on Android:

DownloadManager downloadManager = (DownloadManager)getSystemService(Context.DOWNLOAD_SERVICE);
Uri uri = Uri.parse(imageName);
DownloadManager.Request request = new DownloadManager.Request(uri);
request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);
Long reference = downloadManager.enqueue(request);

Convert and format a Date in JSP

You can do that using the SimpleDateFormat class.

SimpleDateFormat formatter=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

String dates=formatter.format(mydate);
//mydate is your date object

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

I'm not familiar with the package WriteXLS; I generally use XLConnect:

library(XLConnect)
##
newWB <- loadWorkbook(
  filename="F:/TempDir/tempwb.xlsx",
  create=TRUE)
##
for(i in 1:10){
  wsName <- paste0("newsheet",i)
  createSheet(
    newWB,
    name=wsName)
  ##
  writeWorksheet(
    newWB,
    data=data.frame(
      X=1:10,
      Dataframe=paste0("DF ",i)),
    sheet=wsName,
    header=TRUE,
    rownames=NULL)
}
saveWorkbook(newWB)

This can certainly be vectorized, as @joran noted above, but just for the sake of generating dynamic sheet names quickly, I used a for loop to demonstrate.

I used the create=TRUE argument in loadWorkbook since I was creating a new .xlsx file, but if your file already exists then you don't have to specify this, as the default value is FALSE.

Here are a few screenshots of the created workbook:

enter image description here

enter image description here

enter image description here

How to stop EditText from gaining focus at Activity startup in Android

It can be achieved by inheriting EditText and overriding onTouchEvent.

class NonFocusableEditText: EditText {

    constructor(context: Context): super(context)
    constructor(context: Context, attrs: AttributeSet?): super(context, attrs)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int): super(context, attrs, defStyleAttr)

    override fun onTouchEvent(event: MotionEvent?): Boolean {
        return if (isFocusable) super.onTouchEvent(event) else false
    }
}

Then you can use it in the layouts like normal EditText:

<com.yourpackage.NonFocusableEditText
        android:id="@+id/editText"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"    
        android:hint="@string/your_hint"
        android:imeOptions="actionDone"
        android:inputType="textNoSuggestions" />

Format date in a specific timezone

You can Try this ,

Here you can get the date based on the Client Timezone (Browser).

moment(new Date().getTime()).zone(new Date().toString().match(/([-\+][0-9]+)\s/)[1]).format('YYYY-MM-DD HH:mm:ss')

The regex basically gets you the offset value.

Cheers!!

Send email from localhost running XAMMP in PHP using GMAIL mail server

[sendmail]

smtp_server=smtp.gmail.com  
smtp_port=25  
error_logfile=error.log  
debug_logfile=debug.log  
[email protected] 
auth_password=gmailpassword  
[email protected]

need authenticate username and password of mail then only once can successfully send mail from localhost

python selenium click on button

try this:

download firefox, add the plugin "firebug" and "firepath"; after install them go to your webpage, start firebug and find the xpath of the element, it unique in the page so you can't make any mistake.

See picture: instruction

browser.find_element_by_xpath('just copy and paste the Xpath').click()

How do I remove all HTML tags from a string without knowing which tags are in it?

You can parse the string using Html Agility pack and get the InnerText.

    HtmlDocument htmlDoc = new HtmlDocument();
    htmlDoc.LoadHtml(@"<b> Hulk Hogan's Celebrity Championship Wrestling &nbsp;&nbsp;&nbsp;<font color=\"#228b22\">[Proj # 206010]</font></b>&nbsp;&nbsp;&nbsp; (Reality Series, &nbsp;)");
    string result = htmlDoc.DocumentNode.InnerText;

Print directly from browser without print popup window

For IE browsers, the "VBScript solution" works.

But as mentioned by @purefusion at Bypass Printdialog in IE9, Use Print() rather than window.print()

Should I use @EJB or @Inject

Injection already existed in Java EE 5 with the @Resource, @PersistentUnit or @EJB annotations, for example. But it was limited to certain resources (datasource, EJB . . .) and into certain components (Servlets, EJBs, JSF backing bean . . .). With CDI you can inject nearly anything anywhere thanks to the @Inject annotation.

Python : List of dict, if exists increment a dict value, if not append a new dict

Use defaultdict:

from collections import defaultdict

urls = defaultdict(int)

for url in list_of_urls:
    urls[url] += 1

Remove row lines in twitter bootstrap

The other way around, if you have problems ADDING the lines to your panel dont forget to add the to your TABLE. By default (http://getbootstrap.com/components/#panels), it is suppose to add the line but It helped me to add the tag so now the row lines are shown.

The following example "probably" wont display the lines between rows:

<div class="panel panel-default">
    <!-- Default panel contents -->
    <div class="panel-heading">Panel heading</div>
    <!-- Table -->
    <table class="table">
        <tr><td> Hi 1! </td></tr>
        <tr><td> Hi 2! </td></tr>
    </table>
</div>

The following example WILL display the lines between rows:

<div class="panel panel-default">
    <!-- Default panel contents -->
    <div class="panel-heading">Panel heading</div>
    <!-- Table -->
    <table class="table">
        <thead></thead>
        <tr><td> Hi 1! </td></tr>
        <tr><td> Hi 2! </td></tr>
    </table>
</div>

Sticky and NON-Sticky sessions

I've made an answer with some more details here : https://stackoverflow.com/a/11045462/592477

Or you can read it there ==>

When you use loadbalancing it means you have several instances of tomcat and you need to divide loads.

  • If you're using session replication without sticky session : Imagine you have only one user using your web app, and you have 3 tomcat instances. This user sends several requests to your app, then the loadbalancer will send some of these requests to the first tomcat instance, and send some other of these requests to the secondth instance, and other to the third.
  • If you're using sticky session without replication : Imagine you have only one user using your web app, and you have 3 tomcat instances. This user sends several requests to your app, then the loadbalancer will send the first user request to one of the three tomcat instances, and all the other requests that are sent by this user during his session will be sent to the same tomcat instance. During these requests, if you shutdown or restart this tomcat instance (tomcat instance which is used) the loadbalancer sends the remaining requests to one other tomcat instance that is still running, BUT as you don't use session replication, the instance tomcat which receives the remaining requests doesn't have a copy of the user session then for this tomcat the user begin a session : the user loose his session and is disconnected from the web app although the web app is still running.
  • If you're using sticky session WITH session replication : Imagine you have only one user using your web app, and you have 3 tomcat instances. This user sends several requests to your app, then the loadbalancer will send the first user request to one of the three tomcat instances, and all the other requests that are sent by this user during his session will be sent to the same tomcat instance. During these requests, if you shutdown or restart this tomcat instance (tomcat instance which is used) the loadbalancer sends the remaining requests to one other tomcat instance that is still running, as you use session replication, the instance tomcat which receives the remaining requests has a copy of the user session then the user keeps on his session : the user continue to browse your web app without being disconnected, the shutdown of the tomcat instance doesn't impact the user navigation.

How to get named excel sheets while exporting from SSRS

You could use -sed- and -grep- to replace or write to the xml header of each file specifying your desired sheet name, e.g., sheetname1, between any occurrence of the tags:

<Sheetnames>?sheetname1?</Sheetnames>

How to kill a while loop with a keystroke?

For Python 3.7, I copied and changed the very nice answer by user297171 so it works in all scenarios in Python 3.7 that I tested.

import threading as th

keep_going = True
def key_capture_thread():
    global keep_going
    input()
    keep_going = False

def do_stuff():
    th.Thread(target=key_capture_thread, args=(), name='key_capture_thread', daemon=True).start()
    while keep_going:
        print('still going...')

do_stuff()

What is the difference between C# and .NET?

C# does not have a seperate runtime library. It uses .NET as a runtime library.

json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

json.loads() takes a JSON encoded string, not a filename. You want to use json.load() (no s) instead and pass in an open file object:

with open('/Users/JoshuaHawley/clean1.txt') as jsonfile:
    data = json.load(jsonfile)

The open() command produces a file object that json.load() can then read from, to produce the decoded Python object for you. The with statement ensures that the file is closed again when done.

The alternative is to read the data yourself and then pass it into json.loads().

How to change the default encoding to UTF-8 for Apache?

In my case add to .htaccess

AddDefaultCharset off
AddDefaultCharset windows-1252

Encrypt and Decrypt text with RSA in PHP

Security warning: This code snippet is vulnerable to Bleichenbacher's 1998 padding oracle attack. See this answer for better security.

class MyEncryption
{

    public $pubkey = '...public key here...';
    public $privkey = '...private key here...';

    public function encrypt($data)
    {
        if (openssl_public_encrypt($data, $encrypted, $this->pubkey))
            $data = base64_encode($encrypted);
        else
            throw new Exception('Unable to encrypt data. Perhaps it is bigger than the key size?');

        return $data;
    }

    public function decrypt($data)
    {
        if (openssl_private_decrypt(base64_decode($data), $decrypted, $this->privkey))
            $data = $decrypted;
        else
            $data = '';

        return $data;
    }
}

How to print an exception in Python 3?

Try

try:
    print undefined_var
except Exception as e:
    print(e)

this will print the representation given by e.__str__():

"name 'undefined_var' is not defined"

you can also use:

print(repr(e))

which will include the Exception class name:

"NameError("name 'undefined_var' is not defined",)"

How to access Session variables and set them in javascript?

i used my .php file to put required into sessions

$_SESSION['name'] = $phparray["name"]; $ajaxoutput['name'] =$phparray["name"];

in my .js file i used

sessionStorage.setItem("name", ajaxreturnedarray["name"]);

and i retrieved this using

var myName= sessionStorage.getItem("name");

in other .js files or in same .js files

if i keep it as it is , it will return same at all times even you loggedout. so while logging out i made

sessionStorage.setItem("name", "");

using this i emptied local variable. i used this process in single page website login/logout sessions. i hope this way will work for you because it worked for me. plz let me know your experiences.

How do I remove  from the beginning of a file?

Same problem, different solution.

One line in the PHP file was printing out XML headers (which use the same begin/end tags as PHP). Looks like the code within these tags set the encoding, and was executed within PHP which resulted in the strange characters. Either way here's the solution:

# Original
$xml_string = "&lt;?xml version=\"1.0\" encoding=\"UTF-8\"?&gt;";

# fixed
$xml_string = "<" . "?xml version=\"1.0\" encoding=\"UTF-8\"?" . ">";

Center a column using Twitter Bootstrap 3

You can use text-center for the row and can make sure the internal divs have display:inline-block (with not float).

As:

<div class="container">
    <div class="row text-center" style="background-color : black;">
        <div class="redBlock">A red block</div>
        <div class="whiteBlock">A white block</div>
        <div class="yellowBlock">A yellow block</div>
    </div>
</div>

And CSS:

.redBlock {
    width: 100px;
    height: 100px;
    background-color: aqua;
    display: inline-block
}
.whiteBlock {
    width: 100px;
    height: 100px;
    background-color: white;
    display: inline-block
}
.yellowBlock {
    width: 100px;
    height: 100px;
    background-color: yellow;
    display: inline-block
}

The fiddle: http://jsfiddle.net/DTcHh/3177/

Create a git patch from the uncommitted changes in the current working directory

git diff for unstaged changes.

git diff --cached for staged changes.

git diff HEAD for both staged and unstaged changes.

Could not find com.android.tools.build:gradle:3.0.0-alpha1 in circle ci

My problem was that I forgot that I added a proxy in gradle.properties in C:\Users\(current user)\.gradle like:

systemProp.http.proxyHost=****
systemProp.http.proxyPort=8850

How to get cookie's expire time

To get cookies expire time, use this simple method.

<?php

//#############PART 1#############
//expiration time (a*b*c*d) <- change D corresponding to number of days for cookie expiration
$time = time()+(60*60*24*365);
$timeMemo = (string)$time;

//sets cookie with expiration time defined above
setcookie("testCookie", "" . $timeMemo . "", $time);

//#############PART 2#############
//this function will convert seconds to days.
function secToDays($sec){

    return ($sec / 60 / 60 / 24);

}
//checks if cookie is set and prints out expiration time in days
if(isset($_COOKIE['testCookie'])){

    echo "Cookie is set<br />";
    if(round(secToDays((intval($_COOKIE['testCookie']) - time())),1) < 1){
        echo "Cookie will expire today.";
    }else{
        echo "Cookie will expire in " . round(secToDays((intval($_COOKIE['testCookie']) - time())),1) . " day(s)";
    }

}else{
    echo "not set...";
}

?>

You need to keep Part 1 and Part 2 in different files, otherwise you will get the same expire date everytime.

Android: How to use webcam in emulator?

Follow the below steps in Eclipse.

  1. Goto -> AVD Manager
  2. Create/Edit the AVD.
  3. Hardware > New:
  4. Configures camera facing back
  5. Click on the property value and choose = "webcam0".
  6. Once done all the above the webcam should be connected. If it doesnt then you need to check your WebCam drivers.

Check here for more information : How to use web camera in android emulator to capture a live image?

enter image description here

How to read file binary in C#?

Generally, I don't really see a possible way to do this. I've exhausted all of the options that the earlier comments gave you, and they don't seem to work. You could try this:

        `private void button1_Click(object sender, EventArgs e)
    {
        Stream myStream = null;
        OpenFileDialog openFileDialog1 = new OpenFileDialog();
        openFileDialog1.InitialDirectory = "This PC\\Documents";
        openFileDialog1.Filter = "All Files (*.*)|*.*";
        openFileDialog1.FilterIndex = 1;
        openFileDialog1.RestoreDirectory = true;
        openFileDialog1.Title = "Open a file with code";

        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {
            string exeCode = string.Empty;
            using (BinaryReader br = new BinaryReader(File.OpenRead(openFileDialog1.FileName))) //Sets a new integer to the BinaryReader
            {
                br.BaseStream.Seek(0x4D, SeekOrigin.Begin); //The seek is starting from 0x4D
                exeCode = Encoding.UTF8.GetString(br.ReadBytes(1000000000)); //Reads as many bytes as it can from the beginning of the .exe file
            }
            using (BinaryReader br = new BinaryReader(File.OpenRead(openFileDialog1.FileName)))
                br.Close(); //Closes the BinaryReader. Without it, opening the file with any other command will result the error "This file is being used by another process".

            richTextBox1.Text = exeCode;
        }
    }`
  • That's the code for the "Open..." button, but here's the code for the "Save..." button:

    ` private void button2_Click(object sender, EventArgs e) { SaveFileDialog save = new SaveFileDialog();

        save.Filter = "All Files (*.*)|*.*";
        save.Title = "Save Your Changes";
        save.InitialDirectory = "This PC\\Documents";
        save.FilterIndex = 1;
    
        if (save.ShowDialog() == DialogResult.OK)
        {
    
            using (BinaryWriter bw = new BinaryWriter(File.OpenWrite(save.FileName))) //Sets a new integer to the BinaryReader
            {
                bw.BaseStream.Seek(0x4D, SeekOrigin.Begin); //The seek is starting from 0x4D
                bw.Write(richTextBox1.Text);
            }
        }
    }`
    
    • That's the save button. This works fine, but only shows the '!This cannot be run in DOS-Mode!' - Otherwise, if you can fix this, I don't know what to do.

    • My Site

Detecting value change of input[type=text] in jQuery

This combination of events worked for me:

$("#myTextBox").on("input paste", function() {
   alert($(this).val()); 
});

Get the difference between two dates both In Months and days in sql

I think that your question is not defined well enough, for the following reason.

Answers relying on months_between have to deal with the following issue: that the function reports exactly one month between 2013-02-28 and 2013-03-31, and between 2013-01-28 and 2013-02-28, and between 2013-01-31 and 2013-02-28 (I suspect that some answerers have not used these functions in practice, or are now going to have to review some production code!)

This is documented behaviour, in which dates that are both the last in their respective months or which fall on the same day of the month are judged to be an integer number of months apart.

So, you get the same result of "1" when comparing 2013-02-28 with 2013-01-28 or with 2013-01-31, but comparing it with 2013-01-29 or 2013-01-30 gives 0.967741935484 and 0.935483870968 respectively -- so as one date approaches the other the difference reported by this function can increase.

If this is not an acceptable situation then you'll have to write a more complex function, or just rely on a calculation that assumes 30 (for example) days per month. In the latter case, how will you deal with 2013-02-28 and 2013-03-31?

How can I remove all files in my git repo and update/push from my local git repo?

Do a git add -A from the top of the working copy, take a look at git status and/or git diff --cached to review what you're about to do, then git commit the result.

@Media min-width & max-width

If website on small devices behavior like desktop screen then you have to put this meta tag into header before

<meta name="viewport" content="width=device-width, initial-scale=1">

For media queries you can set this as

this will cover your all mobile/cellphone widths

 @media only screen and (min-width: 200px) and (max-width: 767px)  {
    //Put your CSS here for 200px to 767px width devices (cover all width between 200px to 767px //
   
    }

For iPad and iPad pro you have to use

  @media only screen and (min-width: 768px) and (max-width: 1024px)  {
        //Put your CSS here for 768px to 1024px width devices(covers all width between 768px to 1024px //   
  }

If you want to add css for Landscape mode you can add this

and (orientation : landscape)

  @media only screen and (min-width: 200px) and (max-width: 767px) and (orientation : portrait) {
        //Put your CSS here for 200px to 767px width devices (cover all mobile portrait width //        
  }

How to set Spinner default value to null?

I assume that you want to have a Spinner with first empty invisible item (that is a strange feature of Spinner that cannot show a list without selecting an item). You should add a class that will contain data:

data class YourData(val id: Int, val name: String?)

This is the adapter.

class YourAdapter(
    context: Context,
    private val textViewResourceId: Int,
    private var items: ArrayList<YourData>
) : ArrayAdapter<YourData>(context, textViewResourceId, items) {

    private var inflater: LayoutInflater = context.getSystemService(
        Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater

    override fun getCount(): Int = items.size + 1

    override fun getItem(position: Int): YourData? =
        if (position == 0) YourData(0, "") else items[position - 1]

    override fun getItemId(position: Int): Long = position.toLong()

    override fun getView(position: Int, convertView: View?, parent: ViewGroup): View =
        if (position == 0) {
            getFirstTextView(convertView)
        } else {
            getTextView(convertView, parent, position - 1)
        }

    override fun getDropDownView(position: Int, convertView: View?, parent: ViewGroup): View =
        getView(position, convertView, parent)

    private fun getFirstTextView(convertView: View?): View {
        // Just simple TextView as initial selection.
        var textView: TextView? = convertView as? TextView
        val holder: FirstViewHolder
        if (textView?.tag !is FirstViewHolder) {
            textView = TextView(context) // inflater.inflate(R.layout.your_text, parent, false) as TextView
            textView.height = 0 // Hide first item.
            holder = FirstViewHolder()
            holder.textView = textView
            textView.tag = holder
        }
        return textView
    }

    private fun getTextView(
        convertView: View?,
        parent: ViewGroup,
        position: Int
    ): TextView {
        var textView: TextView? = convertView as? TextView
        val holder: ViewHolder
        if (textView?.tag is ViewHolder) {
            holder = textView.tag as ViewHolder
        } else {
            textView = inflater.inflate(textViewResourceId, parent, false) as TextView
            holder = ViewHolder()
            holder.textView = textView
            textView.tag = holder
        }
        holder.textView.text = items[position].name

        return textView
    }

    private class FirstViewHolder {
        lateinit var textView: TextView
    }

    private class ViewHolder {
        lateinit var textView: TextView
    }
}

To create:

YourAdapter(context!!, R.layout.text_item, ArrayList())

To add items:

private fun fill(items: List<YourData>, adapter: YourAdapter) {
    adapter.run {
        clear()
        addAll(items)
        notifyDataSetChanged()
    }
}

When you load items to your Spinner with that fill() command, you should know, that indices are also incremented. So if you wish to select 3rd item, you should now select 4th: spinner?.setSelection(index + 1)

Using Lato fonts in my css (@font-face)

Font Squirrel has a wonderful web font generator.

I think you should find what you need here to generate OTF fonts and the needed CSS to use them. It will even support older IE versions.

Python class returning value

I think you are very confused about what is occurring.

In Python, everything is an object:

  • [] (a list) is an object
  • 'abcde' (a string) is an object
  • 1 (an integer) is an object
  • MyClass() (an instance) is an object
  • MyClass (a class) is also an object
  • list (a type--much like a class) is also an object

They are all "values" in the sense that they are a thing and not a name which refers to a thing. (Variables are names which refer to values.) A value is not something different from an object in Python.

When you call a class object (like MyClass() or list()), it returns an instance of that class. (list is really a type and not a class, but I am simplifying a bit here.)

When you print an object (i.e. get a string representation of an object), that object's __str__ or __repr__ magic method is called and the returned value printed.

For example:

>>> class MyClass(object):
...     def __str__(self):
...             return "MyClass([])"
...     def __repr__(self):
...             return "I am an instance of MyClass at address "+hex(id(self))
... 
>>> m = MyClass()
>>> print m
MyClass([])
>>> m
I am an instance of MyClass at address 0x108ed5a10
>>> 

So what you are asking for, "I need that MyClass return a list, like list(), not the instance info," does not make any sense. list() returns a list instance. MyClass() returns a MyClass instance. If you want a list instance, just get a list instance. If the issue instead is what do these objects look like when you print them or look at them in the console, then create a __str__ and __repr__ method which represents them as you want them to be represented.

Update for new question about equality

Once again, __str__ and __repr__ are only for printing, and do not affect the object in any other way. Just because two objects have the same __repr__ value does not mean they are equal!

MyClass() != MyClass() because your class does not define how these would be equal, so it falls back to the default behavior (of the object type), which is that objects are only equal to themselves:

>>> m = MyClass()
>>> m1 = m
>>> m2 = m
>>> m1 == m2
True
>>> m3 = MyClass()
>>> m1 == m3
False

If you want to change this, use one of the comparison magic methods

For example, you can have an object that is equal to everything:

>>> class MyClass(object):
...     def __eq__(self, other):
...             return True
... 
>>> m1 = MyClass()
>>> m2 = MyClass()
>>> m1 == m2
True
>>> m1 == m1
True
>>> m1 == 1
True
>>> m1 == None
True
>>> m1 == []
True

I think you should do two things:

  1. Take a look at this guide to magic method use in Python.
  2. Justify why you are not subclassing list if what you want is very list-like. If subclassing is not appropriate, you can delegate to a wrapped list instance instead:

    class MyClass(object):
        def __init__(self):
            self._list = []
        def __getattr__(self, name):
            return getattr(self._list, name)
    
        # __repr__ and __str__ methods are automatically created
        # for every class, so if we want to delegate these we must
        # do so explicitly
        def __repr__(self):
            return "MyClass(%s)" % repr(self._list)
        def __str__(self):
            return "MyClass(%s)" % str(self._list)
    

    This will now act like a list without being a list (i.e., without subclassing list).

    >>> c = MyClass()
    >>> c.append(1)
    >>> c
    MyClass([1])
    

Python loop that also accesses previous and next values

I think this works and not complicated

array= [1,5,6,6,3,2]
for i in range(0,len(array)):
    Current = array[i]
    Next = array[i+1]
    Prev = array[i-1]

Failed to resolve: com.google.android.gms:play-services in IntelliJ Idea with gradle

I had the same problem and it resolved by disabling Gradle's offline mode although I could not remember when I did disable it!

Here's the solution:

How to disable Gradle 'offline mode' in android studio? [duplicate]

Wrap long lines in Python

def fun():
    print(('{0} Here is a really long '
           'sentence with {1}').format(3, 5))

Adjacent string literals are concatenated at compile time, just as in C. http://docs.python.org/reference/lexical_analysis.html#string-literal-concatenation is a good place to start for more info.

How to get last key in an array?

$arr = array('key1'=>'value1','key2'=>'value2','key3'=>'value3');
list($last_key) = each(array_reverse($arr));
print $last_key;
// key3

What is the difference between match_parent and fill_parent?

FILL_PARENT is deprecated from the API level 8 and higher and it is renamed for the upper versions as MATCH_PARENT

Both are same FILL_PARENT and MATCH_PARENT,FILL_PARENT was used in the lower version less than API level 8 and MATCH_PATENT are used in higher API level greater than 8.

FILL_PARENT (renamed MATCH_PARENT in API Level 8 and higher), which means that the view wants to be as big as its parent (minus padding)

fill_parent: The view should be as big as its parent (minus padding). This constant is deprecated starting from API Level 8 and is replaced by match_parent.

For more details please visit this page

Get the current URL with JavaScript?

Use window.location for read and write access to the location object associated with the current frame. If you just want to get the address as a read-only string, you may use document.URL, which should contain the same value as window.location.href.

How to Set Focus on Input Field using JQuery

Justin's answer did not work for me (Chromium 18, Firefox 43.0.1). jQuery's .focus() creates visual highlight, but text cursor does not appear in the field (jquery 3.1.0).

Inspired by https://www.sitepoint.com/jqueryhtml5-input-focus-cursor-positions/ , I added autofocus attribute to the input field and voila!

function addfield() {
    n=$('table tr').length;
    $('table').append('<tr><td><input name=field'+n+' autofocus></td><td><input name=value'+n+'></td></tr>');
    $('input[name="aa"'+n+']').focus();
}

MySQL, Concatenate two columns

$crud->set_relation('id','students','{first_name} {last_name}');
$crud->display_as('student_id','Students Name');

Load CSV data into MySQL in Python

If you do not have the pandas and sqlalchemy libraries, import using pip

pip install pandas
pip install sqlalchemy

We can use pandas and sqlalchemy to directly insert into the database

import csv
import pandas as pd
from sqlalchemy import create_engine, types

engine = create_engine('mysql://root:*Enter password here*@localhost/*Enter Databse name here*') # enter your password and database names here

df = pd.read_csv("Excel_file_name.csv",sep=',',quotechar='\'',encoding='utf8') # Replace Excel_file_name with your excel sheet name
df.to_sql('Table_name',con=engine,index=False,if_exists='append') # Replace Table_name with your sql table name

Eliminating NAs from a ggplot

Not sure if you have solved the problem. For this issue, you can use the "filter" function in the dplyr package. The idea is to filter the observations/rows whose values of the variable of your interest is not NA. Next, you make the graph with these filtered observations. You can find my codes below, and note that all the name of the data frame and variable is copied from the prompt of your question. Also, I assume you know the pipe operators.

library(tidyverse) 

MyDate %>%
   filter(!is.na(the_variable)) %>%
     ggplot(aes(x= the_variable, fill=the_variable)) + 
        geom_bar(stat="bin") 

You should be able to remove the annoying NAs on your plot. Hope this works :)

How to calculate the sum of all columns of a 2D numpy array (efficiently)

a.sum(0)

should solve the problem. It is a 2d np.array and you will get the sum of all column. axis=0 is the dimension that points downwards and axis=1 the one that points to the right.

Heroku "psql: FATAL: remaining connection slots are reserved for non-replication superuser connections"

I actually tried to implement connection pooling on the django end using:

https://github.com/gmcguire/django-db-pool

but I still received this error, despite lowering the number of connections available to below the standard development DB quota of 20 open connections.

There is an article here about how to move your postgresql database to the free/cheap tier of Amazon RDS. This would allow you to set max_connections higher. This will also allow you to pool connections at the database level using PGBouncer.

https://www.lewagon.com/blog/how-to-migrate-heroku-postgres-database-to-amazon-rds

UPDATE:

Heroku responded to my open ticket and stated that my database was improperly load balanced in their network. They said that improvements to their system should prevent similar problems in the future. Nonetheless, support manually relocated my database and performance is noticeably improved.

Ruby convert Object to Hash

If you need nested objects to be converted as well.

# @fn       to_hash obj {{{
# @brief    Convert object to hash
#
# @return   [Hash] Hash representing converted object
#
def to_hash obj
  Hash[obj.instance_variables.map { |key|
    variable = obj.instance_variable_get key
    [key.to_s[1..-1].to_sym,
      if variable.respond_to? <:some_method> then
        hashify variable
      else
        variable
      end
    ]
  }]
end # }}}

Visual Studio Expand/Collapse keyboard shortcuts

Collapse to definitions

CTRL + M, O

Expand all outlining

CTRL + M, X

Expand or collapse everything

CTRL + M, L

This also works with other languages like TypeScript and JavaScript

What is correct media query for IPad Pro?

I can't guarantee that this will work for every new iPad Pro which will be released but this works pretty well as of 2019:

@media only screen and (min-width: 1024px) and (max-height: 1366px)
    and (-webkit-min-device-pixel-ratio: 1.5) and (hover: none) {
    /* ... */
}

Finding the mode of a list

If you want a clear approach, useful for classroom and only using lists and dictionaries by comprehension, you can do:

def mode(my_list):
    # Form a new list with the unique elements
    unique_list = sorted(list(set(my_list)))
    # Create a comprehensive dictionary with the uniques and their count
    appearance = {a:my_list.count(a) for a in unique_list} 
    # Calculate max number of appearances
    max_app = max(appearance.values())
    # Return the elements of the dictionary that appear that # of times
    return {k: v for k, v in appearance.items() if v == max_app}

When to use pthread_exit() and when to use pthread_join() in Linux?

pthread_exit() will terminate the calling thread and exit from that(but resources used by calling thread is not released to operating system if it is not detached from main thread.)

pthrade_join() will wait or block the calling thread until target thread is not terminated. In simple word it will wait for to exit the target thread.

In your code, if you put sleep(or delay) in PrintHello function before pthread_exit(), then main thread may be exit and terminate full process, Although your PrintHello function is not completed it will terminate. If you use pthrade_join() function in main before calling pthread_exit() from main it will block main thread and wait to complete your calling thread (PrintHello).

How to query GROUP BY Month in a Year

I am doing like this in MSSQL

Getting Monthly Data:

 SELECT YEAR(DATE_CREATED) [Year], MONTH(DATE_CREATED) [Month], 
     DATENAME(MONTH,DATE_CREATED) [Month Name], SUM(Num_of_Pictures) [Pictures Count]
    FROM pictures_table
    GROUP BY YEAR(DATE_CREATED), MONTH(DATE_CREATED), 
     DATENAME(MONTH, DATE_CREATED)
    ORDER BY 1,2

Getting Monthly Data using PIVOT:

SELECT *
FROM (SELECT YEAR(DATE_CREATED) [Year], 
       DATENAME(MONTH, DATE_CREATED) [Month], 
       SUM(Num_of_Pictures) [Pictures Count]
      FROM pictures_table
      GROUP BY YEAR(DATE_CREATED), 
      DATENAME(MONTH, DATE_CREATED)) AS MontlySalesData
PIVOT( SUM([Pictures Count])   
    FOR Month IN ([January],[February],[March],[April],[May],
    [June],[July],[August],[September],[October],[November],
    [December])) AS MNamePivot

How do I make a newline after a twitter bootstrap element?

I believe Twitter Bootstrap has a class called clearfix that you can use to clear the floating.

<ul class="nav nav-tabs span2 clearfix">

Django DateField default options

This should do the trick:

models.DateTimeField(_("Date"), auto_now_add = True)

Check if a specific tab page is selected (active)

For whatever reason the above would not work for me. This is what did:

if (tabControl.SelectedTab.Name == "tabName" )
{
     .. do stuff
}

where tabControl.SelectedTab.Name is the name attribute assigned to the page in the tabcontrol itself.

How to align content of a div to the bottom

2015 solution

<div style='width:200px; height:60px; border:1px solid red;'>

    <table width=100% height=100% cellspacing=0 cellpadding=0 border=0>
        <tr><td valign=bottom>{$This_text_at_bottom}</td></tr>
    </table>

</div>

http://codepen.io/anon/pen/qERMdx

your welcome

How do I create a Python function with optional arguments?

Just use the *args parameter, which allows you to pass as many arguments as you want after your a,b,c. You would have to add some logic to map args->c,d,e,f but its a "way" of overloading.

def myfunc(a,b, *args, **kwargs):
   for ar in args:
      print ar
myfunc(a,b,c,d,e,f)

And it will print values of c,d,e,f


Similarly you could use the kwargs argument and then you could name your parameters.

def myfunc(a,b, *args, **kwargs):
      c = kwargs.get('c', None)
      d = kwargs.get('d', None)
      #etc
myfunc(a,b, c='nick', d='dog', ...)

And then kwargs would have a dictionary of all the parameters that are key valued after a,b

Why does git say "Pull is not possible because you have unmerged files"?

If you want to pull down a remote branch to run locally (say for reviewing or testing purposes), and when you $ git pull you get local merge conflicts:

$ git checkout REMOTE-BRANCH
$ git pull  (you get local merge conflicts)
$ git reset --hard HEAD (discards local conflicts, and resets to remote branch HEAD)
$ git pull (now get remote branch updates without local conflicts)

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

Q: - ... "Could you use any class that implements an interface?"
A: - Yes.

Q: - ... "When would you need to do that?"
A: - Each time you need a class(es) that implements interface(s).

Note: We couldn't instantiate an interface not implemented by a class - True.

  • Why?
  • Because the interface has only method prototypes, not definitions (just functions names, not their logic)

AnIntf anInst = new Aclass();
// we could do this only if Aclass implements AnIntf.
// anInst will have Aclass reference.


Note: Now we could understand what happened if Bclass and Cclass implemented same Dintf.

Dintf bInst = new Bclass();  
// now we could call all Dintf functions implemented (defined) in Bclass.

Dintf cInst = new Cclass();  
// now we could call all Dintf functions implemented (defined) in Cclass.

What we have: Same interface prototypes (functions names in interface), and call different implementations.

Bibliography: Prototypes - wikipedia

Arduino Tools > Serial Port greyed out

Same comment as Philip Kirkbride. It wasn't a permission issue, but using the Arduino IDE downloaded from their website solved my problem. Thanks! Michael

Clearing a text field on button click

If you want to reset it, then simple use:

<input type="reset" value="Reset" />

But beware, it will not clear out textboxes that have default value. For example, if we have the following textboxes and by default, they have the following values:

<input id="textfield1" type="text" value="sample value 1" />
<input id="textfield2" type="text" value="sample value 2" />

So, to clear it out, compliment it with javascript:

function clearText()  
{
    document.getElementById('textfield1').value = "";
    document.getElementById('textfield2').value = "";
}  

And attach it to onclick of the reset button:
<input type="reset" value="Reset" onclick="clearText()" />

SSL certificate is not trusted - on mobile only

Put your domain name here: https://www.ssllabs.com/ssltest/analyze.html You should be able to see if there are any issues with your ssl certificate chain. I am guessing that you have SSL chain issues. A short description of the problem is that there's actually a list of certificates on your server (and not only one) and these need to be in the correct order. If they are there but not in the correct order, the website will be fine on desktop browsers (an iOs as well I think), but android is more strict about the order of certificates, and will give an error if the order is incorrect. To fix this you just need to re-order the certificates.

javascript - Create Simple Dynamic Array

updated = > june 2020

if are you using node js you can create or append a string value with " ," operator then inside the loop you can

for (var j = 0; j <= data.legth -1; j++) {
                    lang += data.lang  +", " ;

                }

 var langs = lang.split(',')
 console.log("Languages =>",  lang, typeof(lang), typeof(langs), langs) 
 console.log(lang[0]) // here access arrary by index value
            

you can see the type of string and object

How to Apply Corner Radius to LinearLayout

You would use a Shape Drawable as the layout's background and set its cornerRadius. Check this blog for a detailed tutorial

How to get images in Bootstrap's card to be the same height/width?

I found the below works for my setup using cards and grid system. I set the flex-grow property of card-image-top class to 1 and the object fit on the same to contain and the flex-grow property of the body to 0.

HTML

<div class="container-fluid">
    <div class="row row-cols-2 row-cols-md-4">
        <div class="col mb-4">
            <div class="card h-100">
                <img src="https://i0.wp.com/www.impact-media.be/wp-content/uploads/2019/09/placeholder-1-e1533569576673-960x960.png" class="card-img-top">
                <div class="card-body">
                    <p class="card-text">Test</p>
                </div>
            </div>
        </div>
        <div class="col mb-4">
            <div class="card h-100">
                <img src="http://www.nebero.com/wp-content/uploads/2014/05/placeholder.jpg" class="card-img-top">
                <div class="card-body">
                    <p class="card-text">Test</p>
                </div>
            </div>
        </div>
        <div class="col mb-4">
            <div class="card h-100">
                <img src="http://www.nebero.com/wp-content/uploads/2014/05/placeholder.jpg" class="card-img-top">
                <div class="card-body">
                    <p class="card-text">Test</p>
                </div>
            </div>
        </div>
        <div class="col mb-4">
            <div class="card h-100">
                <img src="https://i0.wp.com/www.impact-media.be/wp-content/uploads/2019/09/placeholder-1-e1533569576673-960x960.png" class="card-img-top">
                <div class="card-body">
                    <p class="card-text">Test</p>
                </div>
            </div>
        </div>
    </div>
</div>

CSS

.card-img-top {
    flex-grow: 1;
    object-fit:contain;
}
.card-body{
    flex-grow:0;
}

Specific Time Range Query in SQL Server

you can try this (I don't have sql server here today so I can't verify syntax, sorry)

select attributeName
  from tableName
 where CONVERT(varchar,attributeName,101) BETWEEN '03/01/2009' AND '03/31/2009'
   and CONVERT(varchar, attributeName,108) BETWEEN '06:00:00' AND '22:00:00'
   and DATEPART(day,attributeName) BETWEEN 2 AND 4

How can I rename a single column in a table at select?

select t1.Column as Price, t2.Column as Other_Price
from table1 as t1 INNER JOIN table2 as t2 
ON t1.Key = t2.Key 

like this ?

How to avoid warning when introducing NAs by coercion

Use suppressWarnings():

suppressWarnings(as.numeric(c("1", "2", "X")))
[1]  1  2 NA

This suppresses warnings.

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

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

img-src 'self' data:;

What does the DOCKER_HOST variable do?

Upon investigation, it's also worth noting that when you want to start using docker in a new terminal window, the correct command is:

$(boot2docker shellinit)

I had tested these commands:

>>  docker info
Get http:///var/run/docker.sock/v1.15/info: dial unix /var/run/docker.sock: no such file or directory
>>  boot2docker shellinit
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/ca.pem
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/cert.pem
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/key.pem
    export DOCKER_HOST=tcp://192.168.59.103:2376
    export DOCKER_CERT_PATH=/Users/ddavison/.boot2docker/certs/boot2docker-vm
    export DOCKER_TLS_VERIFY=1
>> docker info
Get http:///var/run/docker.sock/v1.15/info: dial unix /var/run/docker.sock: no such file or directory

Notice that docker info returned that same error. however.. when using $(boot2docker shellinit)...

>>  $(boot2docker init)
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/ca.pem
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/cert.pem
Writing /Users/ddavison/.boot2docker/certs/boot2docker-vm/key.pem
>>  docker info
Containers: 3
...

How to get Top 5 records in SqLite?

select price from mobile_sales_details order by price desc limit 5

Note: i have mobile_sales_details table

syntax

select column_name from table_name order by column_name desc limit size.  

if you need top low price just remove the keyword desc from order by

Is there an equivalent to the SUBSTRING function in MS Access SQL?

I have worked alot with msaccess vba. I think you are looking for MID function

example

    dim myReturn as string
    myreturn = mid("bonjour tout le monde",9,4)

will give you back the value "tout"

C++ -- expected primary-expression before ' '

Change

int wordLength = wordLengthFunction(string word);

to

int wordLength = wordLengthFunction(word);

Combining INSERT INTO and WITH/CTE

Yep:

WITH tab (
  bla bla
)

INSERT INTO dbo.prf_BatchItemAdditionalAPartyNos (  BatchID,                                                        AccountNo,
APartyNo,
SourceRowID)    

SELECT * FROM tab

Note that this is for SQL Server, which supports multiple CTEs:

WITH x AS (), y AS () INSERT INTO z (a, b, c) SELECT a, b, c FROM y

Teradata allows only one CTE and the syntax is as your example.

Calculate text width with JavaScript

var textWidth = (function (el) {
    el.style.position = 'absolute';
    el.style.top = '-1000px';
    document.body.appendChild(el);

    return function (text) {
        el.innerHTML = text;
        return el.clientWidth;
    };
})(document.createElement('div'));

Opening popup windows in HTML

I feel like this is the simplest way. (Feel free to change the width and height values).

<a href="http://www.google.com" 
target="popup" 
onclick="window.open('http://www.google.com','popup','width=600,height=600'); return false;">
Link Text goes here...
</a>

Setting max width for body using Bootstrap

You don't have to modify bootstrap-responsive by removing @media (max-width:1200px) ...

My application has a max-width of 1600px. Here's how it worked for me:

  1. Create bootstrap-custom.css - As much as possible, I don't want to override my original bootstrap css.

  2. Inside bootstrap-custom.css, override the container-fluid by including this code:

Like this:

/* set a max-width for horizontal fluid layout and make it centered */
.container-fluid {
  margin-right: auto;
  margin-left: auto;
  max-width: 1600px; /* or 950px */
}

How to set variables in HIVE scripts

One thing to be mindful of is setting strings then referring back to them. You have to make sure the quotes aren't colliding.

 set start_date = '2019-01-21';
 select ${hiveconf:start_date}; 

When setting dates then referring to them in code as the strings can conflict. This wouldn't work with the start_date set above.

 '${hiveconf:start_date}'

We have to be mindful of not setting twice single or double quotes for strings when referring back to them in the query.

How to break out of a loop from inside a switch?

It amazes me how simple this is considering the depth of explanations... Here's all you need...

bool imLoopin = true;

while(imLoopin) {

    switch(msg->state) {

        case MSGTYPE: // ... 
            break;

        // ... more stuff ...

        case DONE:
            imLoopin = false;
            break;

    }

}

LOL!! Really! That's all you need! One extra variable!

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

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

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

select num_rows from all_tables where table_name = 'MY_TABLE'

This query counts the current number of rows in MY_TABLE

select count(*) from my_table

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

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

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

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

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

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

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

laravel 5.4 upload image

You can use it by easy way, through store method in your controller

like the below

First, we must create a form with file input to let us upload our file.

{{Form::open(['route' => 'user.store', 'files' => true])}}

{{Form::label('user_photo', 'User Photo',['class' => 'control-label'])}}
{{Form::file('user_photo')}}
{{Form::submit('Save', ['class' => 'btn btn-success'])}}

{{Form::close()}}

Here is how we can handle file in our controller.

<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class UserController extends Controller
{

  public function store(Request $request)
  {

  // get current time and append the upload file extension to it,
  // then put that name to $photoName variable.
  $photoName = time().'.'.$request->user_photo->getClientOriginalExtension();

  /*
  talk the select file and move it public directory and make avatars
  folder if doesn't exsit then give it that unique name.
  */
  $request->user_photo->move(public_path('avatars'), $photoName);

  }
}

That’s it. Now you can save the $photoName to the database as a user_photo field value. You can use asset(‘avatars’) function in your view and access the photos.

Java: Get last element after split

String str = "www.anywebsite.com/folder/subfolder/directory";
int index = str.lastIndexOf('/');
String lastString = str.substring(index +1);

Now lastString has the value "directory"

How can I compare strings in C using a `switch` statement?

To add to Phimueme's answer above, if your string is always two characters, then you can build a 16-bit int out of the two 8-bit characters - and switch on that (to avoid nested switch/case statements).

How to write the code for the back button?

Basically my code sends data to the next page like so:

**Referring Page**
$this = $_SERVER['PHP_SELF'];
echo "<a href='next_page.php?prev=$this'>Next Page</a>";

**Page with button**
$prev = $_GET['prev'];
echo "<a href='$prev'><button id='back'>Back</button></a>";

How do I convert from a money datatype in SQL server?

I found this approach direct and useful.

CONVERT(VARCHAR(10), CONVERT(MONEY, fieldname)) AS PRICE

Using intents to pass data between activities

Main Activity

public class MainActivity extends Activity {

    EditText user, password;
    Button login;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        user = (EditText) findViewById(R.id.username_edit);
        password = (EditText) findViewById(R.id.edit_password);
        login = (Button) findViewById(R.id.btnSubmit);
        login.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this,Second.class);

                String uservalue = user.getText().toString();
                String name_value = password.getText().toString();
                String password_value = password.getText().toString();

                intent.putExtra("username", uservalue);
                intent.putExtra("password", password_value);
                startActivity(intent);
            }
        });
    }
}

Second Activity in which you want to receive Data

public class Second extends Activity{

    EditText name, pass;
    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.second_activity);

        name = (EditText) findViewById(R.id.editText1);
        pass = (EditText) findViewById(R.id.editText2);

        String value = getIntent().getStringExtra("username");
        String pass_val = getIntent().getStringExtra("password");
        name.setText(value);
        pass.setText(pass_val);
    }
}

What's the difference between a 302 and a 307 redirect?

Originally there was just 302

Response What browsers should do
302 Found Redo request with new url

The idea is that:

  • if you were doing a GET at some location, you would redo your GET to the new URL
  • if you were doing a POST at some location, you would redo your POST to the new URL
  • if you were doing a PUT at some location, you would redo your PUT to the new URL
  • if you were doing a DELETE at some location, you would redo your DELETE to the new URL
  • etc

Unfortunately every browser did it wrong. When getting a 302, they would always switch to GET at the new URL, rather than retrying the request with the same verb (e.g., POST):

  • Mosaic did it wrong
  • Netscape copied the bugs in Mosaic; so they got it wrong
  • Internet Explorer copied the bugs in Netscape; so they got it wrong

It became de-facto wrong.

All browsers got 302 wrong. So 303 and 307 were created.

Response What browsers should do What browsers actually do
302 Found Redo request with new url GET with new url
303 See Other GET with new url GET with new url
307 Temporary Redirect Redo request with new url Redo request with new url

In chart form

The 5 different kinds of redirects:

+------------------------------------------------------------+
¦           ¦                Switch to GET?                  ¦
¦           ¦------------------------------------------------¦
¦ Temporary ¦          No            ¦         Yes           ¦
¦-----------+------------------------+-----------------------¦
¦ No        ¦ 308 Permanent Redirect ¦ 301 Moved Permanently ¦
¦-----------+------------------------+-----------------------¦
¦ Yes       ¦ 307 Temporary Redirect ¦ 303 See Other         ¦
¦           ¦ 302 Found (intended)   ¦ 302 Found (actual)    ¦
+------------------------------------------------------------+

Alternatively:

Response Switch to get? Temporary?
301 Moved Permanently No No
302 Found (intended) No Yes
302 Found (actual) Yes Yes
303 See Other Yes Yes
307 Temporary Redirect No Yes
308 Permanent Redirect No No

Change Placeholder Text using jQuery

$(document).ready(function(){ 
  $('form').find("input[type=search]").each(function(ev)
  {
     $(this).attr("placeholder", "Search Whatever you want");
  });
});

incompatible character encodings: ASCII-8BIT and UTF-8

Just for the record: for me it turned out that it was the gem called 'mysql' ... obviously this is working with US-ASCII 8 bit by default. So changing it to the gem called mysql2 (the 2 is the important point here) solved all of my issues.

I looked @ the gem list posted above - Michael Koper has obviously mysql2 installed but I posted this in case someone has this issue as well .. (took me some time to figure out).

If you dislike this answer please comment and I will delete it.

P.S: German umlauts (ä,ö and ü) screwed it out with mysql

How to build a DataTable from a DataGridView?

I don't know anything provided by the Framework (beyond what you want to avoid) that would do what you want but (as I suspect you know) it would be pretty easy to create something simple yourself:

private DataTable GetDataTableFromDGV(DataGridView dgv) {
    var dt = new DataTable();
    foreach (DataGridViewColumn column in dgv.Columns) {
        if (column.Visible) {
            // You could potentially name the column based on the DGV column name (beware of dupes)
            // or assign a type based on the data type of the data bound to this DGV column.
            dt.Columns.Add();
        }
    }

    object[] cellValues = new object[dgv.Columns.Count];
    foreach (DataGridViewRow row in dgv.Rows) {
        for (int i = 0; i < row.Cells.Count; i++) {
            cellValues[i] = row.Cells[i].Value;
        }
        dt.Rows.Add(cellValues);
    }

    return dt;
}

How to use BOOLEAN type in SELECT statement

You can definitely get Boolean value from a SELECT query, you just can't use a Boolean data-type.

You can represent a Boolean with 1/0.

CASE WHEN (10 > 0) THEN 1  ELSE 0 END (It can be used in SELECT QUERY)

SELECT CASE WHEN (10 > 0) THEN 1  ELSE 0 END AS MY_BOOLEAN_COLUMN
  FROM DUAL

Returns, 1 (in Hibernate/Mybatis/etc 1 is true). Otherwise, you can get printable Boolean values from a SELECT.

SELECT CASE WHEN (10 > 0) THEN 'true' ELSE 'false' END AS MY_BOOLEAN_COLUMN
 FROM DUAL

This returns the string 'true'.

Setting active profile and config location from command line in spring boot

When setting the profile via the Maven plugin you must do it via run.jvmArguments

mvn spring-boot:run -Drun.jvmArguments="-Dspring.profiles.active=production"

With debug option:

mvn spring-boot:run -Drun.jvmArguments="-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=5005 -Dspring.profiles.active=jpa"

I've seen this trip a lot of people up..hope it helps

Adding click event handler to iframe

iframe doesn't have onclick event but we can implement this by using iframe's onload event and javascript like this...

function iframeclick() {
document.getElementById("theiframe").contentWindow.document.body.onclick = function() {
        document.getElementById("theiframe").contentWindow.location.reload();
    }
}


<iframe id="theiframe" src="youriframe.html" style="width: 100px; height: 100px;" onload="iframeclick()"></iframe>

I hope it will helpful to you....

How to align flexbox columns left and right?

There are different ways but simplest would be to use the space-between see the example at the end

#container {    
    border: solid 1px #000;
    display: flex;    
    flex-direction: row;
    justify-content: space-between;
    padding: 10px;
    height: 50px;
}

.item {
    width: 20%;
    border: solid 1px #000;
    text-align: center;
}

see the example

upstream sent too big header while reading response header from upstream

Plesk instructions

I combined the top two answers here

In Plesk 12, I had nginx running as a reverse proxy (which I think is the default). So the current top answer doesn't work as nginx is also being run as a proxy.

I went to Subscriptions | [subscription domain] | Websites & Domains (tab) | [Virtual Host domain] | Web Server Settings.

Then at the bottom of that page you can set the Additional nginx directives which I set to be a combination of the top two answers here:

fastcgi_buffers         16  16k;
fastcgi_buffer_size         32k;
proxy_buffer_size          128k;
proxy_buffers            4 256k;
proxy_busy_buffers_size    256k;

Null & empty string comparison in Bash

First of all, note you are not using the variable correctly:

if [ "pass_tc11" != "" ]; then
#     ^
#     missing $

Anyway, to check if a variable is empty or not you can use -z --> the string is empty:

if [ ! -z "$pass_tc11" ]; then
   echo "hi, I am not empty"
fi

or -n --> the length is non-zero:

if [ -n "$pass_tc11" ]; then
   echo "hi, I am not empty"
fi

From man test:

-z STRING

the length of STRING is zero

-n STRING

the length of STRING is nonzero

Samples:

$ [ ! -z "$var" ] && echo "yes"
$

$ var=""
$ [ ! -z "$var" ] && echo "yes"
$

$ var="a"
$ [ ! -z "$var" ] && echo "yes"
yes

$ var="a"
$ [ -n "$var" ] && echo "yes"
yes

how do I strip white space when grabbing text with jQuery?

Actually, jQuery has a built in trim function:

 var emailAdd = jQuery.trim($(this).text());

See here for details.

Simple IEnumerator use (with example)

I'd do something like:

private IEnumerable<string> DoWork(IEnumerable<string> data)
{
    List<string> newData = new List<string>();
    foreach(string item in data)
    {
        newData.Add(item + "roxxors");
    }
    return newData;
}

Simple stuff :)

.attr('checked','checked') does not work

It works, but

$('input[name="myname"][checked]').val()

will return the value of the first element with attribute checked. And the a radio button still has this attribute (and it comes before the b button). Selecting b does not remove the checked attribute from a.

You can use jQuery's :checked:

$('input[name="myname"]:checked').val()

DEMO


Further notes:

  • Using $('b').attr('checked',true); is enough.
  • As others mentioned, don't use inline event handlers, use jQuery to add the event handler.

What is a thread exit code?

what happened to me is that I have multiple projects in my solution. I meant to debug project 1, however, the project 2 was set as the default starting project. I fixed this by, right click on the project and select "Set as startup project", then running debugging is fine.

Jquery button click() function is not working

You need to use the event delegation syntax of .on() here. Change:

$("#add").click(function() {

to

$("#buildyourform").on('click', '#add', function () {

jsFiddle example

In what cases do I use malloc and/or new?

The new and delete operators can operate on classes and structures, whereas malloc and free only work with blocks of memory that need to be cast.

Using new/delete will help to improve your code as you will not need to cast allocated memory to the required data structure.

How to remove all callbacks from a Handler?

For any specific Runnable instance, call Handler.removeCallbacks(). Note that it uses the Runnable instance itself to determine which callbacks to unregister, so if you are creating a new instance each time a post is made, you need to make sure you have references to the exact Runnable to cancel. Example:

Handler myHandler = new Handler();
Runnable myRunnable = new Runnable() {
    public void run() {
        //Some interesting task
    }
};

You can call myHandler.postDelayed(myRunnable, x) to post another callback to the message queue at other places in your code, and remove all pending callbacks with myHandler.removeCallbacks(myRunnable)

Unfortunately, you cannot simply "clear" the entire MessageQueue for a Handler, even if you make a request for the MessageQueue object associated with it because the methods for adding and removing items are package protected (only classes within the android.os package can call them). You may have to create a thin Handler subclass to manage a list of Runnables as they are posted/executed...or look at another paradigm for passing your messages between each Activity

Hope that Helps!

Finding the direction of scrolling in a UIScrollView?

Here is my solution for behavior like in @followben answer, but without loss with slow start (when dy is 0)

@property (assign, nonatomic) BOOL isFinding;
@property (assign, nonatomic) CGFloat previousOffset;

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {
    self.isFinding = YES;
}
- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    if (self.isFinding) {
        if (self.previousOffset == 0) {
            self.previousOffset = self.tableView.contentOffset.y;

        } else {
            CGFloat diff = self.tableView.contentOffset.y - self.previousOffset;
            if (diff != 0) {
                self.previousOffset = 0;
                self.isFinding = NO;

                if (diff > 0) {
                    // moved up
                } else {
                    // moved down
                }
            }
        }
    }
}

Retrieve only the queried element in an object array in MongoDB collection

Another interesing way is to use $redact, which is one of the new aggregation features of MongoDB 2.6. If you are using 2.6, you don't need an $unwind which might cause you performance problems if you have large arrays.

db.test.aggregate([
    { $match: { 
         shapes: { $elemMatch: {color: "red"} } 
    }},
    { $redact : {
         $cond: {
             if: { $or : [{ $eq: ["$color","red"] }, { $not : "$color" }]},
             then: "$$DESCEND",
             else: "$$PRUNE"
         }
    }}]);

$redact "restricts the contents of the documents based on information stored in the documents themselves". So it will run only inside of the document. It basically scans your document top to the bottom, and checks if it matches with your if condition which is in $cond, if there is match it will either keep the content($$DESCEND) or remove($$PRUNE).

In the example above, first $match returns the whole shapes array, and $redact strips it down to the expected result.

Note that {$not:"$color"} is necessary, because it will scan the top document as well, and if $redact does not find a color field on the top level this will return false that might strip the whole document which we don't want.

Convert JsonNode into POJO

In Jackson 2.4, you can convert as follows:

MyClass newJsonNode = jsonObjectMapper.treeToValue(someJsonNode, MyClass.class);

where jsonObjectMapper is a Jackson ObjectMapper.


In older versions of Jackson, it would be

MyClass newJsonNode = jsonObjectMapper.readValue(someJsonNode, MyClass.class);

How to install an APK file on an Android phone?

Directly connect your Android device and select the USB debugging option in the device. Eclipse will itself find your device, and then just run the code.

Or alternatively, paste your APK file in the Android SDK platform-tools folder and from the command prompt install it like this:

D:......../platform-tools> adb install yourfile.apk.

Combine two or more columns in a dataframe into a new column with a new name

Using dplyr::mutate:

library(dplyr)
df <- mutate(df, x = paste(n, s)) 

df 
> df
  n  s     b    x
1 2 aa  TRUE 2 aa
2 3 bb FALSE 3 bb
3 5 cc  TRUE 5 cc

Comments in .gitignore?

Do git help gitignore

You will get the help page with following line:

A line starting with # serves as a comment.

How to automatically add user account AND password with a Bash script?

The code below worked in Ubuntu 14.04. Try before you use it in other versions/linux variants.

# quietly add a user without password
adduser --quiet --disabled-password --shell /bin/bash --home /home/newuser --gecos "User" newuser

# set password
echo "newuser:newpassword" | chpasswd

Explain the concept of a stack frame in a nutshell

If you understand stack very well then you will understand how memory works in program and if you understand how memory works in program you will understand how function store in program and if you understand how function store in program you will understand how recursive function works and if you understand how recursive function works you will understand how compiler works and if you understand how compiler works your mind will works as compiler and you will debug any program very easily

Let me explain how stack works:

First you have to know how functions are represented in stack :

Heap stores dynamically allocated values.
Stack stores automatic allocation and deletion values.

enter image description here

Let's understand with example :

def hello(x):
    if x==1:
        return "op"
    else:
        u=1
        e=12
        s=hello(x-1)
        e+=1
        print(s)
        print(x)
        u+=1
    return e

hello(4)

Now understand parts of this program :

enter image description here

Now let's see what is stack and what are stack parts:

enter image description here

Allocation of the stack :

Remember one thing: if any function's return condition gets satisfied, no matter it has loaded the local variables or not, it will immediately return from stack with it's stack frame. It means that whenever any recursive function get base condition satisfied and we put a return after base condition, the base condition will not wait to load local variables which are located in the “else” part of program. It will immediately return the current frame from the stack following which the next frame is now in the activation record.

See this in practice:

enter image description here

Deallocation of the block:

So now whenever a function encounters return statement, it delete the current frame from the stack.

While returning from the stack, values will returned in reverse of the original order in which they were allocated in stack.

enter image description here

how to get bounding box for div element in jquery

using JQuery:

myelement=$("#myelement")
[myelement.offset().left, myelement.offset().top,  myelement.width(), myelement.height()]

NavigationBar bar, tint, and title text color in iOS 8

I like Alex's answer. If you want something quick to try out in a ViewController make sure you use

viewWillAppear()
override func viewWillAppear(animated: Bool) {
    super.viewWillAppear(animated)
    var nav = self.navigationController?.navigationBar
    nav?.barStyle = UIBarStyle.Black
    nav?.tintColor = UIColor.white
    nav?.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.orange]
    //nav?.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.orange] // swift 4.2
}

enter image description here

Build not visible in itunes connect

When you upload your build from Application loader or directly from your xcode to App Store and it is not showing even on multiple uploads with different build version then

  1. Open your .plist file and check whether there is any key string starting with "Privacy - ........."
  2. If that key string value is empty, then Add some string.
    example, for me i was using camera, photo Library, Microphone and Location.
    For my project i added the string as follows
    a. This app requires access to the Camera.
    b. This app requires access to the Photo Library.
    c. This app requires access to Microphone of your device.
    d. This app requires access to your Location.
    e. This app requires access to the Bluetooth.
  3. Now upload the build it will get Accepted.

Note: This permission string is mandatory from iOS 10.

How to list all properties of a PowerShell object

If you want to know what properties (and methods) there are:

Get-WmiObject -Class "Win32_computersystem" | Get-Member

jQuery - If element has class do this

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

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

But you can also simplify this to:

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

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

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

Nodejs convert string into UTF-8

I'd recommend using the Buffer class:

var someEncodedString = Buffer.from('someString', 'utf-8');

This avoids any unnecessary dependencies that other answers require, since Buffer is included with node.js, and is already defined in the global scope.

Adding subscribers to a list using Mailchimp's API v3

BATCH LOAD - OK, so after having my previous reply deleted for just using links I have updated with the code I managed to get working. Appreciate anyone to simplify / correct / refine / put in function etc as I'm still learning this stuff, but I got batch member list add working :)

$apikey = "whatever-us99";                            
$list_id = "12ab34dc56";

$email1 = "[email protected]";
$fname1 = "Jack";
$lname1 = "Black";

$email2 = "[email protected]";
$fname2 = "Jill";
$lname2 = "Hill";

$auth = base64_encode( 'user:'.$apikey );

$data1 = array(
    "apikey"        => $apikey,
    "email_address" => $email1,
    "status"        => "subscribed",
    "merge_fields"  => array(                
            'FNAME' => $fname1,
            'LNAME' => $lname1,
    )
);

$data2 = array(
    "apikey"        => $apikey,
    "email_address" => $email2,
    "status"        => "subscribed",                
    "merge_fields"  => array(                
            'FNAME' => $fname2,
            'LNAME' => $lname2,
    )
);

$json_data1 = json_encode($data1);
$json_data2 = json_encode($data2);

$array = array(
    "operations" => array(
        array(
            "method" => "POST",
            "path" => "/lists/$list_id/members/",
            "body" => $json_data1
        ),
        array(
            "method" => "POST",
            "path" => "/lists/$list_id/members/",
            "body" => $json_data2
        )
    )
);

$json_post = json_encode($array);

$ch = curl_init();

$curlopt_url = "https://us99.api.mailchimp.com/3.0/batches";
curl_setopt($ch, CURLOPT_URL, $curlopt_url);

curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json',
'Authorization: Basic '.$auth));
curl_setopt($ch, CURLOPT_USERAGENT, 'PHP-MCAPI/3.0');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_POSTFIELDS, $json_post);

print_r($json_post . "\n");
$result = curl_exec($ch);

var_dump($result . "\n");
print_r ($result . "\n");

How to capture the android device screen content?

if you want to do screen capture from Java code in Android app AFAIK you must have Root provileges.

How to fill the whole canvas with specific color?

We don't need to access the canvas context.

Implementing hednek in pure JS you would get canvas.setAttribute('style', 'background-color:#00F8'). But my preferred method requires converting the kabab-case to camelCase.

canvas.style.backgroundColor = '#00F8'

Apache: "AuthType not set!" 500 Error

The problem here can be formulated another way: how do I make a config that works both in apache 2.2 and 2.4?

Require all granted is only in 2.4, but Allow all ... stops working in 2.4, and we want to be able to rollout a config that works in both.

The only solution I found, which I am not sure is the proper one, is to use:

# backwards compatibility with apache 2.2
Order allow,deny
Allow from all

# forward compatibility with apache 2.4
Require all granted
Satisfy Any

This should resolve your problem, or at least did for me. Now the problem will probably be much harder to solve if you have more complex access rules...

See also this fairly similar question. The Debian wiki also has useful instructions for supporting both 2.2 and 2.4.

How to install a Notepad++ plugin offline?

If the plugin you want to install is not listed in the Plugins Admin, you may still install it manually. The plugin (in the DLL form) should be placed in the plugins subfolder of the Notepad++ Install Folder, under the subfolder with the same name of plugin binary name without file extension.

For example, if the plugin you want to install named myAwesomePlugin.dll, you should install it with the following path:

%PROGRAMFILES(x86)%\Notepad++\plugins\myAwesomePlugin\myAwesomePlugin.dll

or

%PROGRAMFILES%\Notepad++\plugins\myAwesomePlugin\myAwesomePlugin.dll

Once you installed the plugin, you can use (and you may configure) it via the menu “Plugins”.

Restart the Notepad++ after putting the plugin

Source : https://npp-user-manual.org/docs/plugins/

Find in Files: Search all code in Team Foundation Server

Another solution is to use "ctrl+shift+F". You can change the search location to a local directory rather than a solution or project. This will just take the place of the desktop search and you'll still need to get the latest code, but it will allow you to remain within Visual Studio to do your searching.

Where is the .NET Framework 4.5 directory?

The webpage is incorrect and I have pointed this out to MS and they will get it changed.

As already stated above .NET 4.5 is an in-place upgrade of 4.0 so you will only have Microsoft.NET\Framework\v4.0.30319.

The ToolVersion for MSBuild remains at "4.0".

How to return string value from the stored procedure

You are placing your result in the RETURN value instead of in the passed @rvalue.

From MSDN

(RETURN) Is the integer value that is returned. Stored procedures can return an integer value to a calling procedure or an application.

Changing your procedure.

ALTER procedure S_Comp(@str1 varchar(20),@r varchar(100) out) as 

    declare @str2 varchar(100) 
    set @str2 ='welcome to sql server. Sql server is a product of Microsoft' 
    if(PATINDEX('%'+@str1 +'%',@str2)>0) 
        SELECT @r =  @str1+' present in the string' 
    else 
        SELECT @r = @str1+' not present'

Calling the procedure

  DECLARE @r VARCHAR(100)
  EXEC S_Comp 'Test', @r OUTPUT
  SELECT @r

ASP.NET MVC - Getting QueryString values

I recommend using the ValueProvider property of the controller, much in the way that UpdateModel/TryUpdateModel do to extract the route, query, and form parameters required. This will keep your method signatures from potentially growing very large and being subject to frequent change. It also makes it a little easier to test since you can supply a ValueProvider to the controller during unit tests.

What is the difference between const and readonly in C#?

The key difference is that Const is the C equivalent of #DEFINE. The number literally gets substituted a-la precompiler. Readonly is actually treated as a variable.

This distinction is especially relevant when you have Project A depending on a Public constant from Project B. Suppose the public constant changes. Now your choice of const/readonly will impact the behavior on project A:

Const: project A does not catch the new value (unless it is recompiled with the new const, of course) because it was compiled with the constants subtituted in.

ReadOnly: Project A will always ask project B for it's variable value, so it will pick up the new value of the public constant in B.

Honestly, I would recommend you use readonly for nearly everything except truly universal constants ( e.g. Pi, Inches_To_Centimeters). For anything that could possibly change, I say use readonly.

Hope this helps, Alan.

Progress Bar with HTML and CSS

2014 answer: Since 2014 HTML now 5 includes a <progress> element that does not need JavaScript. The percent value moves with the progress using inline content. Tested only in webkit. Hope it helps:

jsFiddle

CSS:

_x000D_
_x000D_
progress {_x000D_
 display:inline-block;_x000D_
 width:190px;_x000D_
 height:20px;_x000D_
 padding:15px 0 0 0;_x000D_
 margin:0;_x000D_
 background:none;_x000D_
 border: 0;_x000D_
 border-radius: 15px;_x000D_
 text-align: left;_x000D_
 position:relative;_x000D_
 font-family: Arial, Helvetica, sans-serif;_x000D_
 font-size: 0.8em;_x000D_
}_x000D_
progress::-webkit-progress-bar {_x000D_
 height:11px;_x000D_
 width:150px;_x000D_
 margin:0 auto;_x000D_
 background-color: #CCC;_x000D_
 border-radius: 15px;_x000D_
 box-shadow:0px 0px 6px #777 inset;_x000D_
}_x000D_
progress::-webkit-progress-value {_x000D_
 display:inline-block;_x000D_
 float:left;_x000D_
 height:11px;_x000D_
 margin:0px -10px 0 0;_x000D_
 background: #F70;_x000D_
 border-radius: 15px;_x000D_
 box-shadow:0px 0px 6px #777 inset;_x000D_
}_x000D_
progress:after {_x000D_
 margin:-26px 0 0 -7px;_x000D_
 padding:0;_x000D_
 display:inline-block;_x000D_
 float:left;_x000D_
 content: attr(value) '%';_x000D_
}
_x000D_
<progress id="progressBar" max="100" value="77"></progress>
_x000D_
_x000D_
_x000D_

How to change font-color for disabled input?

Replace disabled with readonly="readonly". I think it is the same function.

<input type="text" class="details-dialog" readonly="readonly" style="color: ur color;">

npm - how to show the latest version of a package

You can see all the version of a module with npm view. eg: To list all versions of bootstrap including beta.

npm view bootstrap versions

But if the version list is very big it will truncate. An --json option will print all version including beta versions as well.

npm view bootstrap versions --json

If you want to list only the stable versions not the beta then use singular version

npm view bootstrap@* versions

Or

npm view bootstrap@* versions --json

And, if you want to see only latest version then here you go.

npm view bootstrap version

JBoss vs Tomcat again

I'd certainly look to TomEE since the idea behind is to keep Tomcat bringing all the JavaEE 6 integration missing by default. That's a kind of very good compromise

How to use workbook.saveas with automatic Overwrite

I recommend that before executing SaveAs, delete the file it exists.

If Dir("f:ull\path\with\filename.xls") <> "" Then
    Kill "f:ull\path\with\filename.xls"
End If

It's easier than setting DisplayAlerts off and on, plus if DisplayAlerts remains off due to code crash, it can cause problems if you work with Excel in the same session.

Preventing twitter bootstrap carousel from auto sliding on page load

if you're using bootstrap 3 set data-interval="false" on the HTML structure of carousel

example:

<div id="carousel-example-generic" class="carousel slide" data-ride="carousel" data-interval="false">

How to do Base64 encoding in node.js?

You can do base64 encoding and decoding with simple javascript.

    $("input").keyup(function () {
     var value = $(this).val(),
         hash = Base64.encode(value);
     $(".test").html(hash);

     var decode = Base64.decode(hash);

     $(".decode").html(decode);
 });

var Base64={_keyStr:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",encode:function(e){var t="";var n,r,i,s,o,u,a;var f=0;e=Base64._utf8_encode(e);while(f<e.length){n=e.charCodeAt(f++);r=e.charCodeAt(f++);i=e.charCodeAt(f++);s=n>>2;o=(n&3)<<4|r>>4;u=(r&15)<<2|i>>6;a=i&63;if(isNaN(r)){u=a=64}else if(isNaN(i)){a=64}t=t+this._keyStr.charAt(s)+this._keyStr.charAt(o)+this._keyStr.charAt(u)+this._keyStr.charAt(a)}return t},decode:function(e){var t="";var n,r,i;var s,o,u,a;var f=0;e=e.replace(/[^A-Za-z0-9+/=]/g,"");while(f<e.length){s=this._keyStr.indexOf(e.charAt(f++));o=this._keyStr.indexOf(e.charAt(f++));u=this._keyStr.indexOf(e.charAt(f++));a=this._keyStr.indexOf(e.charAt(f++));n=s<<2|o>>4;r=(o&15)<<4|u>>2;i=(u&3)<<6|a;t=t+String.fromCharCode(n);if(u!=64){t=t+String.fromCharCode(r)}if(a!=64){t=t+String.fromCharCode(i)}}t=Base64._utf8_decode(t);return t},_utf8_encode:function(e){e=e.replace(/rn/g,"n");var t="";for(var n=0;n<e.length;n++){var r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r)}else if(r>127&&r<2048){t+=String.fromCharCode(r>>6|192);t+=String.fromCharCode(r&63|128)}else{t+=String.fromCharCode(r>>12|224);t+=String.fromCharCode(r>>6&63|128);t+=String.fromCharCode(r&63|128)}}return t},_utf8_decode:function(e){var t="";var n=0;var r=c1=c2=0;while(n<e.length){r=e.charCodeAt(n);if(r<128){t+=String.fromCharCode(r);n++}else if(r>191&&r<224){c2=e.charCodeAt(n+1);t+=String.fromCharCode((r&31)<<6|c2&63);n+=2}else{c2=e.charCodeAt(n+1);c3=e.charCodeAt(n+2);t+=String.fromCharCode((r&15)<<12|(c2&63)<<6|c3&63);n+=3}}return t}}

// Define the string
var string = 'Hello World!';

// Encode the String
var encodedString = Base64.encode(string);
console.log(encodedString); // Outputs: "SGVsbG8gV29ybGQh"

// Decode the String
var decodedString = Base64.decode(encodedString);
console.log(decodedString); // Outputs: "Hello World!"</script></div>

This is implemented in this Base64 encoder decoder

Bold black cursor in Eclipse deletes code, and I don't know how to get rid of it

It sounds like you hit the "Insert" key .. in most applications this results in a fat (solid rectangle) cursor being displayed, as your screenshot suggests. This indicates that you are in overwrite mode rather than the default insert mode.

Just hit the "insert" key on your keyboard once more... it's usually near the 'delete' (not backspace), scroll lock and 'Print Screen' (often above the cursor keys in a full size keyboard.) This will switch back to insert mode and turn your cursor into a vertical line rather than a rectangle.

How can I exclude $(this) from a jQuery selector?

You can use the not function rather than the :not selector:

$(".content a").not(this).hide("slow")

How can I cast int to enum?

The following is a slightly better extension method:

public static string ToEnumString<TEnum>(this int enumValue)
{
    var enumString = enumValue.ToString();
    if (Enum.IsDefined(typeof(TEnum), enumValue))
    {
        enumString = ((TEnum) Enum.ToObject(typeof (TEnum), enumValue)).ToString();
    }
    return enumString;
}

Alternative to deprecated getCellType

Use getCellType()

switch (cell.getCellType()) {
   case BOOLEAN :
                 //To-do
                 break;
   case NUMERIC:
                 //To-do
                 break;
   case STRING:
                 //To-do
                 break;
}

Converting String to Double in Android

  kw=(EditText)findViewById(R.id.kw);
    btn=(Button)findViewById(R.id.btn);
    cost=(TextView )findViewById(R.id.cost);


            btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) { cst =  Double.valueOf(kw.getText().toString());
            cst = cst*0.551;
            cost.setText(cst.toString());
        }
    });

Converting a char to ASCII?

A char is an integral type. When you write

char ch = 'A';

you're setting the value of ch to whatever number your compiler uses to represent the character 'A'. That's usually the ASCII code for 'A' these days, but that's not required. You're almost certainly using a system that uses ASCII.

Like any numeric type, you can initialize it with an ordinary number:

char ch = 13;

If you want do do arithmetic on a char value, just do it: ch = ch + 1; etc.

However, in order to display the value you have to get around the assumption in the iostreams library that you want to display char values as characters rather than numbers. There are a couple of ways to do that.

std::cout << +ch << '\n';
std::cout << int(ch) << '\n'

Easy way to make a confirmation dialog in Angular?

Method 1

One simple way to confirm is to use the native browser confirm alert. The template can have a button or link.

<button type=button class="btn btn-primary"  (click)="clickMethod('name')">Delete me</button>

And the component method can be something like below.

clickMethod(name: string) {
  if(confirm("Are you sure to delete "+name)) {
    console.log("Implement delete functionality here");
  }
}

Method 2

Another way to get a simple confirmation dialog is to use the angular bootstrap components like ng-bootstrap or ngx-bootstrap. You can simply install the component and use the modal component.

  1. Examples of modals using ng-bootstrap
  2. Examples of modals using ngx-bootstrap.

Method 3

Provided below is another way to implement a simple confirmation popup using angular2/material that I implemented in my project.

app.module.ts

import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { ConfirmationDialog } from './confirm-dialog/confirmation-dialog';

@NgModule({
  imports: [
    ...
    FormsModule,
    ReactiveFormsModule
  ],
  declarations: [
    ...
    ConfirmationDialog
  ],
  providers: [ ... ],
  bootstrap: [ AppComponent ],
  entryComponents: [ConfirmationDialog]
})
export class AppModule { }

confirmation-dialog.ts

import { Component, Input } from '@angular/core';
import { MdDialog, MdDialogRef } from '@angular/material';

@Component({
  selector: 'confirm-dialog',
  templateUrl: '/app/confirm-dialog/confirmation-dialog.html',
})
export class ConfirmationDialog {
  constructor(public dialogRef: MdDialogRef<ConfirmationDialog>) {}

  public confirmMessage:string;
}

confirmation-dialog.html

<h1 md-dialog-title>Confirm</h1>
<div md-dialog-content>{{confirmMessage}}</div>
<div md-dialog-actions>
  <button md-button style="color: #fff;background-color: #153961;" (click)="dialogRef.close(true)">Confirm</button>
  <button md-button (click)="dialogRef.close(false)">Cancel</button>
</div>

app.component.html

<button (click)="openConfirmationDialog()">Delete me</button>

app.component.ts

import { MdDialog, MdDialogRef } from '@angular/material';
import { ConfirmationDialog } from './confirm-dialog/confirmation-dialog';

@Component({
  moduleId: module.id,
  templateUrl: '/app/app.component.html',
  styleUrls: ['/app/main.css']
})

export class AppComponent implements AfterViewInit {
  dialogRef: MdDialogRef<ConfirmationDialog>;

  constructor(public dialog: MdDialog) {}

  openConfirmationDialog() {
    this.dialogRef = this.dialog.open(ConfirmationDialog, {
      disableClose: false
    });
    this.dialogRef.componentInstance.confirmMessage = "Are you sure you want to delete?"

    this.dialogRef.afterClosed().subscribe(result => {
      if(result) {
        // do confirmation actions
      }
      this.dialogRef = null;
    });
  }
}

index.html => added following stylesheet

<link rel="stylesheet" href="node_modules/@angular/material/core/theming/prebuilt/indigo-pink.css">

insert password into database in md5 format?

You can use MD5() in mysql or md5() in php. To use salt add it to password before running md5, f.e.:

$salt ='my_string';
$hash = md5($salt . $password);

It's better to use different salt for every password. For this you have to save your salt in db (and also hash). While authentication user will send his login and pass. You will find his hash and salt in db and find out:

if ($hash == md5($salt . $_POST['password'])) {}

Convert String to Integer in XSLT 1.0

Adding to jelovirt's answer, you can use number() to convert the value to a number, then round(), floor(), or ceiling() to get a whole integer.

Example

<xsl:variable name="MyValAsText" select="'5.14'"/>
<xsl:value-of select="number($MyValAsText) * 2"/> <!-- This outputs 10.28 -->
<xsl:value-of select="floor($MyValAsText)"/> <!-- outputs 5 -->
<xsl:value-of select="ceiling($MyValAsText)"/> <!-- outputs 6 -->
<xsl:value-of select="round($MyValAsText)"/> <!-- outputs 5 -->

Set a form's action attribute when submitting?

You can do that on javascript side .

<input type="submit" value="Send It!" onClick="return ActionDeterminator();">

When clicked, the JavaScript function ActionDeterminator() determines the alternate action URL. Example code.

function ActionDeterminator() {
  if(document.myform.reason[0].checked == true) {
    document.myform.action = 'http://google.com';
  }
  if(document.myform.reason[1].checked == true) {
    document.myform.action = 'http://microsoft.com';
    document.myform.method = 'get';
  }
  if(document.myform.reason[2].checked == true) {
    document.myform.action = 'http://yahoo.com';
  }
  return true;
}

How to convert an xml string to a dictionary?

Disclaimer: This modified XML parser was inspired by Adam Clark The original XML parser works for most of simple cases. However, it didn't work for some complicated XML files. I debugged the code line by line and finally fixed some issues. If you find some bugs, please let me know. I am glad to fix it.

class XmlDictConfig(dict):  
    '''   
    Note: need to add a root into if no exising    
    Example usage:
    >>> tree = ElementTree.parse('your_file.xml')
    >>> root = tree.getroot()
    >>> xmldict = XmlDictConfig(root)
    Or, if you want to use an XML string:
    >>> root = ElementTree.XML(xml_string)
    >>> xmldict = XmlDictConfig(root)
    And then use xmldict for what it is... a dict.
    '''
    def __init__(self, parent_element):
        if parent_element.items():
            self.updateShim( dict(parent_element.items()) )
        for element in parent_element:
            if len(element):
                aDict = XmlDictConfig(element)
            #   if element.items():
            #   aDict.updateShim(dict(element.items()))
                self.updateShim({element.tag: aDict})
            elif element.items():    # items() is specialy for attribtes
                elementattrib= element.items()
                if element.text:           
                    elementattrib.append((element.tag,element.text ))     # add tag:text if there exist
                self.updateShim({element.tag: dict(elementattrib)})
            else:
                self.updateShim({element.tag: element.text})

    def updateShim (self, aDict ):
        for key in aDict.keys():   # keys() includes tag and attributes
            if key in self:
                value = self.pop(key)
                if type(value) is not list:
                    listOfDicts = []
                    listOfDicts.append(value)
                    listOfDicts.append(aDict[key])
                    self.update({key: listOfDicts})
                else:
                    value.append(aDict[key])
                    self.update({key: value})
            else:
                self.update({key:aDict[key]})  # it was self.update(aDict)    

'readline/readline.h' file not found

You reference a Linux distribution, so you need to install the readline development libraries

On Debian based platforms, like Ubuntu, you can run:

sudo apt-get install libreadline-dev 

and that should install the correct headers in the correct places,.

If you use a platform with yum, like SUSE, then the command should be:

yum install readline-devel

How to test my servlet using JUnit

You can do this using Mockito to have the mock return the correct params, verify they were indeed called (optionally specify number of times), write the 'result' and verify it's correct.

import static org.junit.Assert.*;
import static org.mockito.Mockito.*;
import java.io.*;
import javax.servlet.http.*;
import org.apache.commons.io.FileUtils;
import org.junit.Test;

public class TestMyServlet extends Mockito{

    @Test
    public void testServlet() throws Exception {
        HttpServletRequest request = mock(HttpServletRequest.class);       
        HttpServletResponse response = mock(HttpServletResponse.class);    

        when(request.getParameter("username")).thenReturn("me");
        when(request.getParameter("password")).thenReturn("secret");

        StringWriter stringWriter = new StringWriter();
        PrintWriter writer = new PrintWriter(stringWriter);
        when(response.getWriter()).thenReturn(writer);

        new MyServlet().doPost(request, response);

        verify(request, atLeast(1)).getParameter("username"); // only if you want to verify username was called...
        writer.flush(); // it may not have been flushed yet...
        assertTrue(stringWriter.toString().contains("My expected string"));
    }
}

Rename all files in a folder with a prefix in a single command

With rnm (you will need to install it):

rnm -ns 'Unix_/fn/' *

Or

rnm -rs '/^/Unix_/' *

P.S : I am the author of this tool.

How to restore default perspective settings in Eclipse IDE

Go Windows -> Perspective -> Reset Perspective definetly this one help you.

Unix command to check the filesize

I hope ls -lah will do the job. Also if you are new to unix environment please go to http://www.tutorialspoint.com/unix/unix-useful-commands.htm

sh: 0: getcwd() failed: No such file or directory on cited drive

if some directory/folder does not exist but somehow you navigated to that directory in that case you can see this Error,

for example:

  • currently, you are in "mno" directory (path = abc/def/ghi/jkl/mno
  • run "sudo su" and delete mno
  • goto the "ghi" directory and delete "jkl" directory
  • now you are in "ghi" directory (path abc/def/ghi)
  • run "exit"
  • after running the "exit", you will get that Error
  • now you will be in "mno"(path = abc/def/ghi/jkl/mno) folder. that does not exist.

so, Generally this Error will show when Directory doesn't exist.

to fix this, simply run "cd;" or you can move to any other directory which exists.

wget/curl large file from google drive

ggID='put_googleID_here'  
ggURL='https://drive.google.com/uc?export=download'  
filename="$(curl -sc /tmp/gcokie "${ggURL}&id=${ggID}" | grep -o '="uc-name.*</span>' | sed 's/.*">//;s/<.a> .*//')"  
getcode="$(awk '/_warning_/ {print $NF}' /tmp/gcokie)"  
curl -Lb /tmp/gcokie "${ggURL}&confirm=${getcode}&id=${ggID}" -o "${filename}"  

How does it work?
Get cookie file and html code with curl.
Pipe html to grep and sed and search for file name.
Get confirm code from cookie file with awk.
Finally download file with cookie enabled, confirm code and filename.

curl -Lb /tmp/gcokie "https://drive.google.com/uc?export=download&confirm=Uq6r&id=0B5IRsLTwEO6CVXFURmpQZ1Jxc0U" -o "SomeBigFile.zip"

If you dont need filename variable curl can guess it
-L Follow redirects
-O Remote-name
-J Remote-header-name

curl -sc /tmp/gcokie "${ggURL}&id=${ggID}" >/dev/null  
getcode="$(awk '/_warning_/ {print $NF}' /tmp/gcokie)"  
curl -LOJb /tmp/gcokie "${ggURL}&confirm=${getcode}&id=${ggID}" 

To extract google file ID from URL you can use:

echo "gURL" | egrep -o '(\w|-){26,}'  
# match more than 26 word characters  

OR

echo "gURL" | sed 's/[^A-Za-z0-9_-]/\n/g' | sed -rn '/.{26}/p'  
# replace non-word characters with new line,   
# print only line with more than 26 word characters 

How to install Google Play Services in a Genymotion VM (with no drag and drop support)?

Drag and Drop did not work on my system...

I found a blogpost which describes how you install it with adb:

adb push Genymotion-ARM-Translation_v1.1.zip /sdcard/Download/Genymotion-ARM-Translation_v1.1.zip

adb push gapps-jb-yyyymmdd-signed.zip /sdcard/Download/gapps.zip

adb shell flash-archive.sh /sdcard/Download/Genymotion-ARM-Translation_v1.1.zip

adb reboot

adb shell flash-archive.sh /sdcard/Download/gapps.zip

adb reboot

How can I parse a string with a comma thousand separator to a number?

On modern browsers you can use the built in Intl.NumberFormat to detect the browser's number formatting and normalize the input to match.

_x000D_
_x000D_
function parseNumber(value, locales = navigator.languages) {
  const example = Intl.NumberFormat(locales).format('1.1');
  const cleanPattern = new RegExp(`[^-+0-9${ example.charAt( 1 ) }]`, 'g');
  const cleaned = value.replace(cleanPattern, '');
  const normalized = cleaned.replace(example.charAt(1), '.');

  return parseFloat(normalized);
}

const corpus = {
  '1.123': {
    expected: 1.123,
    locale: 'en-US'
  },
  '1,123': {
    expected: 1123,
    locale: 'en-US'
  },
  '2.123': {
    expected: 2123,
    locale: 'fr-FR'
  },
  '2,123': {
    expected: 2.123,
    locale: 'fr-FR'
  },
}


for (const candidate in corpus) {
  const {
    locale,
    expected
  } = corpus[candidate];
  const parsed = parseNumber(candidate, locale);

  console.log(`${ candidate } in ${ corpus[ candidate ].locale } == ${ expected }? ${ parsed === expected }`);
}
_x000D_
_x000D_
_x000D_

Their's obviously room for some optimization and caching but this works reliably in all languages.

What is the preferred Bash shebang?

/bin/sh is usually a link to the system's default shell, which is often bash but on, e.g., Debian systems is the lighter weight dash. Either way, the original Bourne shell is sh, so if your script uses some bash (2nd generation, "Bourne Again sh") specific features ([[ ]] tests, arrays, various sugary things, etc.), then you should be more specific and use the later. This way, on systems where bash is not installed, your script won't run. I understand there may be an exciting trilogy of films about this evolution...but that could be hearsay.

Also note that when evoked as sh, bash to some extent behaves as POSIX standard sh (see also the GNU docs about this).

Find difference between timestamps in seconds in PostgreSQL

Try: 

SELECT EXTRACT(EPOCH FROM (timestamp_B - timestamp_A))
FROM TableA

Details here: EXTRACT.

Change bootstrap navbar collapse breakpoint without using LESS

In bootstrap 4, if you want to over-ride when navbar-expand-*, expands and collapses and shows and hides the hamburger (navbar-toggler) you have to find that style/definition in bootstrap.css, and redefine it in your own customstyle.css (or directly in bootstrap.css if you are so inclined).

Eg. I wanted the navbar-expand-lg to collapses and shows the navbar-toggler at 950px. In bootstrap.css I find:

@media (max-width: 991.98px) {
  .navbar-expand-lg > .container,
  .navbar-expand-lg > .container-fluid {
    padding-right: 0;
    padding-left: 0;
  }
}

And below that ...

@media (min-width:992px) { 
    ... lots of styling ...
}

I copied both @media queries and stuck them in my style.css, then modified the size to fit my needs. I my case I wanted it to collapse at 950px. The @media queries must need to be different sizes (I'm guessing), so I set container max-width to 949.98px and used the 950px for the other @media query and so the following code was appended to my style.css. This was not easy to detangle from twisted solutions I found on Stackoverflow and elsewhere. Hope this helps.

@media (max-width: 949.98px) {
    .navbar-expand-lg > .container,
    .navbar-expand-lg > .container-fluid {
        padding-right: 0;
        padding-left: 0;
    }
}

@media (min-width: 950px) {
    .navbar-expand-lg {
        -webkit-box-orient: horizontal;
        -webkit-box-direction: normal;
        -ms-flex-flow: row nowrap;
        flex-flow: row nowrap;
        -webkit-box-pack: start;
        -ms-flex-pack: start;
        justify-content: flex-start;
    }
    .navbar-expand-lg .navbar-nav {
        -webkit-box-orient: horizontal;
        -webkit-box-direction: normal;
        -ms-flex-direction: row;
        flex-direction: row;
    }
    .navbar-expand-lg .navbar-nav .dropdown-menu {
        position: absolute;
    }
    .navbar-expand-lg .navbar-nav .dropdown-menu-right {
        right: 0;
        left: auto;
    }
    .navbar-expand-lg .navbar-nav .nav-link {
        padding-right: 0.5rem;
        padding-left: 0.5rem;
    }
    .navbar-expand-lg > .container,
    .navbar-expand-lg > .container-fluid {
        -ms-flex-wrap: nowrap;
        flex-wrap: nowrap;
    }
    .navbar-expand-lg .navbar-collapse {
        display: -webkit-box !important;
        display: -ms-flexbox !important;
        display: flex !important;
        -ms-flex-preferred-size: auto;
        flex-basis: auto;
    }
    .navbar-expand-lg .navbar-toggler {
        display: none;
    }
    .navbar-expand-lg .dropup .dropdown-menu {
        top: auto;
        bottom: 100%;
    }
}

Can you overload controller methods in ASP.NET MVC?

Create the base method as virtual

public virtual ActionResult Index()

Create the overridden method as override

public override ActionResult Index()

Edit: This obviously applies only if the override method is in a derived class which appears not to have been the OP's intention.

How to search file text for a pattern and replace it with a given value

In my case I am using tty-gem ruby gem for that.

I also needed appending, prepending (on a given text/regex inside the file), diffs, and others. The gem includes all that and a fairly clear documentation.

HTTP 401 - what's an appropriate WWW-Authenticate header value?

When indicating HTTP Basic Authentication we return something like:

WWW-Authenticate: Basic realm="myRealm"

Whereas Basic is the scheme and the remainder is very much dependent on that scheme. In this case realm just provides the browser a literal that can be displayed to the user when prompting for the user id and password.

You're obviously not using Basic however since there is no point having session expiry when Basic Auth is used. I assume you're using some form of Forms based authentication.

From recollection, Windows Challenge Response uses a different scheme and different arguments.

The trick is that it's up to the browser to determine what schemes it supports and how it responds to them.

My gut feel if you are using forms based authentication is to stay with the 200 + relogin page but add a custom header that the browser will ignore but your AJAX can identify.

For a really good User + AJAX experience, get the script to hang on to the AJAX request that found the session expired, fire off a relogin request via a popup, and on success, resubmit the original AJAX request and carry on as normal.

Avoid the cheat that just gets the script to hit the site every 5 mins to keep the session alive cause that just defeats the point of session expiry.

The other alternative is burn the AJAX request but that's a poor user experience.

How do I install an R package from source?

Download the source package, open Terminal.app, navigate to the directory where you currently have the file, and then execute:

R CMD INSTALL RJSONIO_0.2-3.tar.gz

Do note that this will only succeed when either: a) the package does not need compilation or b) the needed system tools for compilation are present. See: https://cran.r-project.org/bin/macosx/tools/

What does "Fatal error: Unexpectedly found nil while unwrapping an Optional value" mean?

I had this error once when I was trying to set my Outlets values from the prepare for segue method as follows:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let destination = segue.destination as? DestinationVC{

        if let item = sender as? DataItem{
            // This line pops up the error
            destination.nameLabel.text = item.name
        }
    }
}

Then I found out that I can't set the values of the destination controller outlets because the controller hasn't been loaded or initialized yet.

So I solved it this way:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let destination = segue.destination as? DestinationVC{

        if let item = sender as? DataItem{
            // Created this method in the destination Controller to update its outlets after it's being initialized and loaded
            destination.updateView(itemData:  item)
        }
    }
}

Destination Controller:

// This variable to hold the data received to update the Label text after the VIEW DID LOAD
var name = ""

// Outlets
@IBOutlet weak var nameLabel: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view.
    nameLabel.text = name
}

func updateView(itemDate: ObjectModel) {
    name = itemDate.name
}

I hope this answer helps anyone out there with the same issue as I found the marked answer is great resource to the understanding of optionals and how they work but hasn't addressed the issue itself directly.

What does the ^ (XOR) operator do?

The (^) XOR operator generates 1 when it is applied on two different bits (0 and 1). It generates 0 when it is applied on two same bits (0 and 0 or 1 and 1).

Make sure that the controller has a parameterless public constructor error

In my case, it was because of exception inside the constructor of my injected dependency (in your example - inside DashboardRepository constructor). The exception was caught somewhere inside MVC infrastructure. I found this after I added logs in relevant places.

Java SSLException: hostname in certificate didn't match

The certificate verification process will always verify the DNS name of the certificate presented by the server, with the hostname of the server in the URL used by the client.

The following code

HttpPost post = new HttpPost("https://74.125.236.52/accounts/ClientLogin");

will result in the certificate verification process verifying whether the common name of the certificate issued by the server, i.e. www.google.com matches the hostname i.e. 74.125.236.52. Obviously, this is bound to result in failure (you could have verified this by browsing to the URL https://74.125.236.52/accounts/ClientLogin with a browser, and seen the resulting error yourself).

Supposedly, for the sake of security, you are hesitant to write your own TrustManager (and you musn't unless you understand how to write a secure one), you ought to look at establishing DNS records in your datacenter to ensure that all lookups to www.google.com will resolve to 74.125.236.52; this ought to be done either in your local DNS servers or in the hosts file of your OS; you might need to add entries to other domains as well. Needless to say, you will need to ensure that this is consistent with the records returned by your ISP.

A server with the specified hostname could not be found

I received A server with the specified hostname could not be found.. I figured out my MacOS app had turned on App Sandboxing. The easiest way to avoid problem is to turn off Sandbox.