Programs & Examples On #Custom build step

How do I hide a menu item in the actionbar?

Initially set the menu item visibility to false in the menu layout file as follows :

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto">
    <item
        android:visible="false"
        android:id="@+id/action_do_something"
        android:title="@string/txt_do_something"
        app:showAsAction="always|withText"
        android:icon="@drawable/ic_done"/>
</menu>

You can then simply set the visibility of the menu item to false in your onCreateOptionsMenu() after inflating the menu.

@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    inflater.inflate(menu,R.menu.menu);
    MenuItem item = menu.findItem(R.id.menuItemId);
    if (item != null){
        item.setVisible(false);
    }
}

jQuery remove selected option from this

$('#some_select_box option:selected').remove();

Angularjs action on click of button

The calculation occurs immediately since the calculation call is bound in the template, which displays its result when quantity changes.

Instead you could try the following approach. Change your markup to the following:

<div ng-controller="myAppController" style="text-align:center">
  <p style="font-size:28px;">Enter Quantity:
      <input type="text" ng-model="quantity"/>
  </p>
  <button ng-click="calculateQuantity()">Calculate</button>
  <h2>Total Cost: Rs.{{quantityResult}}</h2>
</div>

Next, update your controller:

myAppModule.controller('myAppController', function($scope,calculateService) {
  $scope.quantity=1;
  $scope.quantityResult = 0;

  $scope.calculateQuantity = function() {
    $scope.quantityResult = calculateService.calculate($scope.quantity, 10);
  };
});

Here's a JSBin example that demonstrates the above approach.

The problem with this approach is the calculated result remains visible with the old value till the button is clicked. To address this, you could hide the result whenever the quantity changes.

This would involve updating the template to add an ng-change on the input, and an ng-if on the result:

<input type="text" ng-change="hideQuantityResult()" ng-model="quantity"/>

and

<h2 ng-if="showQuantityResult">Total Cost: Rs.{{quantityResult}}</h2>

In the controller add:

$scope.showQuantityResult = false;

$scope.calculateQuantity = function() {
  $scope.quantityResult = calculateService.calculate($scope.quantity, 10);
  $scope.showQuantityResult = true;
};

$scope.hideQuantityResult = function() {
  $scope.showQuantityResult = false;
}; 

These updates can be seen in this JSBin demo.

Displaying Image in Java

import java.awt.FlowLayout;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

public class DisplayImage {

    public static void main(String avg[]) throws IOException
    {
        DisplayImage abc=new DisplayImage();
    }

    public DisplayImage() throws IOException
    {
        BufferedImage img=ImageIO.read(new File("f://images.jpg"));
        ImageIcon icon=new ImageIcon(img);
        JFrame frame=new JFrame();
        frame.setLayout(new FlowLayout());
        frame.setSize(200,300);
        JLabel lbl=new JLabel();
        lbl.setIcon(icon);
        frame.add(lbl);
        frame.setVisible(true);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}

How to hide scrollbar in Firefox?

For more recent version of Firefox the old solutions don't work anymore, but I did succesfully used in v66.0.3 the scrollbar-color property which you can set to transparent transparent and which will make the scrollbar in Firefox on the desktop at least invisible (still takes place in the viewport and on mobile doesn't work, but there the scrollbar is a fine line that is placed over the content on the right).

overflow-y: auto; //or hidden if you don't want horizontal scrolling
overflow-y: auto;
scrollbar-color: transparent transparent;

Bash: Strip trailing linebreak from output

One way:

wc -l < log.txt | xargs echo -n

Does Python have a ternary conditional operator?

Vinko Vrsalovic's answer is good enough. There is only one more thing:

Note that conditionals are an expression, not a statement. This means you can't use assignment statements or pass or other statements within a conditional expression

Walrus operator in Python 3.8

After that walrus operator was introduced in Python 3.8, there is something changed.

(a := 3) if True else (b := 5)

gives a = 3 and b is not defined,

(a := 3) if False else (b := 5)

gives a is not defined and b = 5, and

c = (a := 3) if False else (b := 5)

gives c = 5, a is not defined and b = 5.

Even if this may be ugly, assignments can be done inside conditional expressions after Python 3.8. Anyway, it is still better to use normal if statement instead in this case.

How can I convert an image into Base64 string using JavaScript?

_x000D_
_x000D_
document.querySelector('input').onchange = e => {
  const fr = new FileReader()
  fr.onloadend = () => document.write(fr.result)
  fr.readAsDataURL(e.target.files[0])
}
_x000D_
<input type="file">
_x000D_
_x000D_
_x000D_

Gmail Error :The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.5.1 Authentication Required

try changing the host, this is the new one, I got this configuring mozilla thunderbird

Host = "smtp.googlemail.com"

that work for me

Declare a variable as Decimal

The best way is to declare the variable as a Single or a Double depending on the precision you need. The data type Single utilizes 4 Bytes and has the range of -3.402823E38 to 1.401298E45. Double uses 8 Bytes.

You can declare as follows:

Dim decAsdf as Single

or

Dim decAsdf as Double

Here is an example which displays a message box with the value of the variable after calculation. All you have to do is put it in a module and run it.

Sub doubleDataTypeExample()
Dim doubleTest As Double


doubleTest = 0.0000045 * 0.005 * 0.01

MsgBox "doubleTest = " & doubleTest
End Sub

How can I change the remote/target repository URL on Windows?

One more way to do this is:

git config remote.origin.url https://github.com/abc/abc.git

To see the existing URL just do:

git config remote.origin.url

web-api POST body object always null

If the any of values of the request's JSON object are not the same type as expected by the service then the [FromBody] argument will be null.

For example, if the age property in the json had a float value:

"age":18.0

but the API service expects it to be an int

"age":18

then student will be null. (No error messages will be sent in the response unless no null reference check).

How to display list items on console window in C#

Assume that we need to view some data in command prompt which are coming from a database table. First we create a list. Team_Details is my property class.

    List<Team_Details> teamDetails = new List<Team_Details>();

Then you can connect to the database and do the data retrieving part and save it to the list as follows.

            string connetionString = "Data Source=.;Initial Catalog=your DB name;Integrated Security=True;MultipleActiveResultSets=True";
            using (SqlConnection conn = new SqlConnection(connetionString)){
            string getTeamDetailsQuery = "select * from Team";
            conn.Open();
            using (SqlCommand cmd = new SqlCommand(getTeamDetailsQuery, conn))
                    {
                        SqlDataReader rdr = cmd.ExecuteReader();
                    {
                        teamDetails.Add(new Team_Details
                        {
                            Team_Name = rdr.GetString(rdr.GetOrdinal("Team_Name")),
                            Team_Lead = rdr.GetString(rdr.GetOrdinal("Team_Lead")),
                        });
                    }

Then you can print this list in command prompt as follows.

foreach (Team_Details i in teamDetails)
                        {
                            Console.WriteLine(i.Team_Name);
                            Console.WriteLine(i.Team_Lead);
                        }

Insert new item in array on any position in PHP

if unsure, then DONT USE THESE:

$arr1 = $arr1 + $arr2;

OR

$arr1 += $arr2;

because with + original array will be overwritten. (see source)

Delete topic in Kafka 0.8.1.1

bin/kafka-topics.sh –delete –zookeeper localhost:2181 –topic <topic-name>

What is difference between sjlj vs dwarf vs seh?

There's a short overview at MinGW-w64 Wiki:

Why doesn't mingw-w64 gcc support Dwarf-2 Exception Handling?

The Dwarf-2 EH implementation for Windows is not designed at all to work under 64-bit Windows applications. In win32 mode, the exception unwind handler cannot propagate through non-dw2 aware code, this means that any exception going through any non-dw2 aware "foreign frames" code will fail, including Windows system DLLs and DLLs built with Visual Studio. Dwarf-2 unwinding code in gcc inspects the x86 unwinding assembly and is unable to proceed without other dwarf-2 unwind information.

The SetJump LongJump method of exception handling works for most cases on both win32 and win64, except for general protection faults. Structured exception handling support in gcc is being developed to overcome the weaknesses of dw2 and sjlj. On win64, the unwind-information are placed in xdata-section and there is the .pdata (function descriptor table) instead of the stack. For win32, the chain of handlers are on stack and need to be saved/restored by real executed code.

GCC GNU about Exception Handling:

GCC supports two methods for exception handling (EH):

  • DWARF-2 (DW2) EH, which requires the use of DWARF-2 (or DWARF-3) debugging information. DW-2 EH can cause executables to be slightly bloated because large call stack unwinding tables have to be included in th executables.
  • A method based on setjmp/longjmp (SJLJ). SJLJ-based EH is much slower than DW2 EH (penalising even normal execution when no exceptions are thrown), but can work across code that has not been compiled with GCC or that does not have call-stack unwinding information.

[...]

Structured Exception Handling (SEH)

Windows uses its own exception handling mechanism known as Structured Exception Handling (SEH). [...] Unfortunately, GCC does not support SEH yet. [...]

See also:

Which keycode for escape key with jQuery

To explain where other answers haven't; the problem is your use of keypress.

Perhaps the event is just mis-named but keypress is defined to fire when when an actualcharacteris being inserted. I.e. text.
Whereas what you want is keydown/keyup, which fires whenever (before or after, respectively) the user depresses akey. I.e. those things on the keyboard.

The difference appears here because esc is a control character (literally 'non-printing character') and so doesn't write any text, thus not even firing keypress.
enter is weird, because even though you are using it as a control character (i.e. to control the UI), it is still inserting a new-line character, which will fire keypress.

Source: quirksmode

Python: List vs Dict for look up table

set() is exactly what you want. O(1) lookups, and smaller than a dict.

PHP Warning: include_once() Failed opening '' for inclusion (include_path='.;C:\xampp\php\PEAR')

The include path is set against the server configuration (PHP.ini) but the include path you specify is relative to that path so in your case the include path is (actual path in windows):

C:\xampp\php\PEAR\initcontrols\header_myworks.php

providing the path you pasted in the subject is correct. Make sure your file is located there.

For more info you can get and set the include path programmatically.

Getting Current time to display in Label. VB.net

Use Date.Now instead of DateTime.Now

Equivalent of SQL ISNULL in LINQ?

Looks like the type is boolean and therefore can never be null and should be false by default.

Where are environment variables stored in the Windows Registry?

CMD:

reg query "HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"
reg query HKEY_CURRENT_USER\Environment

PowerShell:

Get-Item "HKLM:\SYSTEM\CurrentControlSet\Control\Session Manager\Environment"
Get-Item HKCU:\Environment

Powershell/.NET: (see EnvironmentVariableTarget Enum)

[System.Environment]::GetEnvironmentVariables([System.EnvironmentVariableTarget]::Machine)
[System.Environment]::GetEnvironmentVariables([System.EnvironmentVariableTarget]::User)

Difference between database and schema

A database is the main container, it contains the data and log files, and all the schemas within it. You always back up a database, it is a discrete unit on its own.

Schemas are like folders within a database, and are mainly used to group logical objects together, which leads to ease of setting permissions by schema.

EDIT for additional question

drop schema test1

Msg 3729, Level 16, State 1, Line 1
Cannot drop schema 'test1' because it is being referenced by object 'copyme'.

You cannot drop a schema when it is in use. You have to first remove all objects from the schema.

Related reading:

  1. What good are SQL Server schemas?
  2. MSDN: User-Schema Separation

Syntax for a single-line Bash infinite while loop

If I can give two practical examples (with a bit of "emotion").

This writes the name of all files ended with ".jpg" in the folder "img":

for f in *; do if [ "${f#*.}" == 'jpg' ]; then echo $f; fi; done

This deletes them:

for f in *; do if [ "${f#*.}" == 'jpg' ]; then rm -r $f; fi; done

Just trying to contribute.

Is there a way to detach matplotlib plots so that the computation can continue?

Use plt.show(block=False), and at the end of your script call plt.show().

This will ensure that the window won't be closed when the script is finished.

RE error: illegal byte sequence on Mac OS X

Add the following lines to your ~/.bash_profile or ~/.zshrc file(s).

export LC_CTYPE=C 
export LANG=C

Javascript: convert 24-hour time-of-day string to 12-hour time with AM/PM and no timezone

Make sure that your time is in this format HH:MM:SS(PM/AM)

function timeConversion(s) {

    s = s.split(':');
    var time = s[2];
    if(time.charAt(2) === 'A' && parseInt(s[0]) == 12) s[0] = '00';
    if(time.charAt(2) === 'P' && parseInt(s[0]) <12) s[0] = parseInt(s[0])+12;
    if(s[0] >=24) s[0]-=24;
    var x = time.split('').slice(0,2);
    s[2] = x.join('');
    console.log(s.join(':'));
}

Unable to launch the IIS Express Web server, Failed to register URL, Access is denied

When using Visual Studio 2015 the solution can be a bit different to the previous answers. VS2015 creates a hidden folder .vs under the same folder as your solution file. Under this is a config folder containing applicationhost.config. Deleting this file (or the entire .vs folder) then starting VS2015 to recreate it can fix this error.

How do I Geocode 20 addresses without receiving an OVER_QUERY_LIMIT response?

Unfortunately this is a restriction of the Google maps service.

I am currently working on an application using the geocoding feature, and I'm saving each unique address on a per-user basis. I generate the address information (city, street, state, etc) based on the information returned by Google maps, and then save the lat/long information in the database as well. This prevents you from having to re-code things, and gives you nicely formatted addresses.

Another reason you want to do this is because there is a daily limit on the number of addresses that can be geocoded from a particular IP address. You don't want your application to fail for a person for that reason.

Windows batch files: .bat vs .cmd?

I believe if you change the value of the ComSpec environment variable to %SystemRoot%system32\cmd.exe(CMD) then it doesn't matter if the file extension is .BAT or .CMD. I'm not sure, but this may even be the default for WinXP and above.

NSRange from Swift Range?

Possible Solution

Swift provides distance() which measures the distance between start and end that can be used to create an NSRange:

let text = "Long paragraph saying something goes here!"
let textRange = text.startIndex..<text.endIndex
let attributedString = NSMutableAttributedString(string: text)

text.enumerateSubstringsInRange(textRange, options: NSStringEnumerationOptions.ByWords, { (substring, substringRange, enclosingRange, stop) -> () in
    let start = distance(text.startIndex, substringRange.startIndex)
    let length = distance(substringRange.startIndex, substringRange.endIndex)
    let range = NSMakeRange(start, length)

//    println("word: \(substring) - \(d1) to \(d2)")

        if (substring == "saying") {
            attributedString.addAttribute(NSForegroundColorAttributeName, value: NSColor.redColor(), range: range)
        }
})

jQuery: Count number of list elements?

and of course the following:

var count = $("#myList").children().length;

can be condensed down to: (by removing the 'var' which is not necessary to set a variable)

count = $("#myList").children().length;

however this is cleaner:

count = $("#mylist li").size();

Prevent jQuery UI dialog from setting focus to first textbox

jQuery 1.9 is released and there does not appear to be a fix. Attempting to prevent focus of the first text box by some of the suggested methods is not working in 1.9. I think beccause the methods attempt to blur focus or move focus occur AFTER the text box in the dialog has already gained focus and done its dirty work.

I can't see anything in the API documentation that makes me think that anything has changed in terms of expected functionality. Off to add an opener button...

Instantiating a generic type

You basically have two choices:

1.Require an instance:

public Navigation(T t) {     this("", "", t); } 

2.Require a class instance:

public Navigation(Class<T> c) {     this("", "", c.newInstance()); } 

You could use a factory pattern, but ultimately you'll face this same issue, but just push it elsewhere in the code.

An Authentication object was not found in the SecurityContext - Spring 3.2.2

For me, the problem was a ContextRefreshedEvent handler. I was doing some data initilization but at that point in the application the Authentication had not been set. It was a catch 22 since the system needed an authentication to authorize and it needed authorization to get the authentication details :). I ended up loosening the authorization from a class level to a method level.

How to truncate string using SQL server

You can use

LEFT(column, length)

or

SUBSTRING(column, start index, length)

What's the u prefix in a Python string?

I came here because I had funny-char-syndrome on my requests output. I thought response.text would give me a properly decoded string, but in the output I found funny double-chars where German umlauts should have been.

Turns out response.encoding was empty somehow and so response did not know how to properly decode the content and just treated it as ASCII (I guess).

My solution was to get the raw bytes with 'response.content' and manually apply decode('utf_8') to it. The result was schöne Umlaute.

The correctly decoded

für

vs. the improperly decoded

fAzr

How can I set the focus (and display the keyboard) on my EditText programmatically

This worked for me, Thanks to ungalcrys

Show keyboard:

editText = (EditText)findViewById(R.id.myTextViewId);
editText.requestFocus();
InputMethodManager imm = (InputMethodManager)getSystemService(this.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,InputMethodManager.HIDE_IMPLICIT_ONLY);

Hide keyboard:

InputMethodManager imm = (InputMethodManager) getSystemService(this.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);

What are the differences between normal and slim package of jquery?

I could see $.ajax is removed from jQuery slim 3.2.1

From the jQuery docs

You can also use the slim build, which excludes the ajax and effects modules

Below is the comment from the slim version with the features removed

/*! jQuery v3.2.1 -ajax,-ajax/jsonp,-ajax/load,-ajax/parseXML,-ajax/script,-ajax/var/location,-ajax/var/nonce,-ajax/var/rquery,-ajax/xhr,-manipulation/_evalUrl,-event/ajax,-effects,-effects/Tween,-effects/animatedSelector | (c) JS Foundation and other contributors | jquery.org/license */

running php script (php function) in linux bash

From the command line, enter this:

php -f filename.php

Make sure that filename.php both includes and executes the function you want to test. Anything you echo out will appear in the console, including errors.

Be wary that often the php.ini for Apache PHP is different from CLI PHP (command line interface).

Reference: https://secure.php.net/manual/en/features.commandline.usage.php

How do I move to end of line in Vim?

The advantage of the 'End' key is it works in both normal and insert modes.

'$' works in normal/command mode only but it also works in the classic vi editor (good to know when vim is not available).

How to pass all arguments passed to my bash script to a function of mine?

I needed a variation on this, which I expect will be useful to others:

function diffs() {
        diff "${@:3}" <(sort "$1") <(sort "$2")
}

The "${@:3}" part means all the members of the array starting at 3. So this function implements a sorted diff by passing the first two arguments to diff through sort and then passing all other arguments to diff, so you can call it similarly to diff:

diffs file1 file2 [other diff args, e.g. -y]

Spring Data JPA findOne() change to Optional how to use this?

Indeed, in the latest version of Spring Data, findOne returns an optional. If you want to retrieve the object from the Optional, you can simply use get() on the Optional. First of all though, a repository should return the optional to a service, which then handles the case in which the optional is empty. afterwards, the service should return the object to the controller.

How do I check if a Sql server string is null or empty

[Column_name] > ' ' excludes Nulls and empty strings. There is a space between the single quotes.

Is it more efficient to copy a vector by reserving and copying, or by creating and swapping?

Direct answer:

  • Use a = operator

We can use the public member function std::vector::operator= of the container std::vector for assigning values from a vector to another.

  • Use a constructor function

Besides, a constructor function also makes sense. A constructor function with another vector as parameter(e.g. x) constructs a container with a copy of each of the elements in x , in the same order.

Caution:

  • Do not use std::vector::swap

std::vector::swap is not copying a vector to another, it is actually swapping elements of two vectors, just as its name suggests. In other words, the source vector to copy from is modified after std::vector::swap is called, which is probably not what you are expected.

  • Deep or shallow copy?

If the elements in the source vector are pointers to other data, then a deep copy is wanted sometimes.

According to wikipedia:

A deep copy, meaning that fields are dereferenced: rather than references to objects being copied, new copy objects are created for any referenced objects, and references to these placed in B.

Actually, there is no currently a built-in way in C++ to do a deep copy. All of the ways mentioned above are shallow. If a deep copy is necessary, you can traverse a vector and make copy of the references manually. Alternatively, an iterator can be considered for traversing. Discussion on iterator is beyond this question.

References

The page of std::vector on cplusplus.com

Select data between a date/time range

In a simple way it can be queried as

select * from hockey_stats 
where game_date between '2018-01-01' and '2018-01-31';

This works if time is not a concern.

Considering time also follow in the following way:

select * from hockey_stats where (game_date between '2018-02-05 01:20:00' and '2018-02-05 03:50:00');

Note this is for MySQL server.

Select Specific Columns from Spark DataFrame

Problem was to select columns of on dataframe after joining with other dataframe.

I tried below and select the columns of salaryDf from the joined dataframe.

Hope this will help

        val empDf=spark.read.option("header","true").csv("/data/tech.txt")

        val salaryDf=spark.read.option("header","true").csv("/data/salary.txt")

        val joinData= empDf.join(salaryDf,empDf.col("first") === salaryDf.col("first") and  empDf.col("last") === salaryDf.col("last"))

      //**below will select the colums of salaryDf only**

     val finalDF=joinData.select(salaryDf.columns map  salaryDf.col:_*)

//same way we can select the columns of empDf
joinData.select(empDf.columns map  empDf.col:_*)

How to flush output of print function?

Running python -h, I see a command line option:

-u : unbuffered binary stdout and stderr; also PYTHONUNBUFFERED=x see man page for details on internal buffering relating to '-u'

Here is the relevant doc.

How can I add or update a query string parameter?

Yeah I had an issue where my querystring would overflow and duplicate, but this was due to my own sluggishness. so I played a bit and worked up some js jquery(actualy sizzle) and C# magick.

So i just realized that after the server has done with the passed values, the values doesn't matter anymore, there is no reuse, if the client wanted to do the same thing evidently it will always be a new request, even if its the same parameters being passed. And thats all clientside, so some caching/cookies etc could be cool in that regards.

JS:

$(document).ready(function () {
            $('#ser').click(function () {
                SerializeIT();
            });
            function SerializeIT() {
                var baseUrl = "";
                baseUrl = getBaseUrlFromBrowserUrl(window.location.toString());
                var myQueryString = "";
                funkyMethodChangingStuff(); //whatever else before serializing and creating the querystring
                myQueryString = $('#fr2').serialize();
                window.location.replace(baseUrl + "?" + myQueryString);
            }
            function getBaseUrlFromBrowserUrl(szurl) {
                return szurl.split("?")[0];
            } 
            function funkyMethodChangingStuff(){
               //do stuff to whatever is in fr2
            }
        });

HTML:

<div id="fr2">
   <input type="text" name="qURL" value="http://somewhere.com" />
   <input type="text" name="qSPart" value="someSearchPattern" />
</div>
<button id="ser">Serialize! and go play with the server.</button>

C#:

    using System.Web;
    using System.Text;
    using System.Collections.Specialized;

    public partial class SomeCoolWebApp : System.Web.UI.Page
    {
        string weburl = string.Empty;
        string partName = string.Empty;

        protected void Page_Load(object sender, EventArgs e)
        {
            string loadurl = HttpContext.Current.Request.RawUrl;
            string querySZ = null;
            int isQuery = loadurl.IndexOf('?');
            if (isQuery == -1) { 
                //If There Was no Query
            }
            else if (isQuery >= 1) {
                querySZ = (isQuery < loadurl.Length - 1) ? loadurl.Substring(isQuery + 1) : string.Empty;
                string[] getSingleQuery = querySZ.Split('?');
                querySZ = getSingleQuery[0];

                NameValueCollection qs = null;
                qs = HttpUtility.ParseQueryString(querySZ);

                weburl = qs["qURL"];
                partName = qs["qSPart"];
                //call some great method thisPageRocks(weburl,partName); or whatever.
          }
      }
  }

Okay criticism is welcome (this was a nightly concoction so feel free to note adjustments). If this helped at all, thumb it up, Happy Coding.

No duplicates, each request as unique as you modified it, and due to how this is structured,easy to add more queries dynamicaly from wthin the dom.

Equivalent of shell 'cd' command to change the working directory?

cd() is easy to write using a generator and a decorator.

from contextlib import contextmanager
import os

@contextmanager
def cd(newdir):
    prevdir = os.getcwd()
    os.chdir(os.path.expanduser(newdir))
    try:
        yield
    finally:
        os.chdir(prevdir)

Then, the directory is reverted even after an exception is thrown:

os.chdir('/home')

with cd('/tmp'):
    # ...
    raise Exception("There's no place like /home.")
# Directory is now back to '/home'.

How do I make a splash screen?

public class MainActivity extends Activity {

@Override

public void onCreate(Bundle savedInstanceState) {

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

    Thread t=new Thread()
    {

        public void run()
        {   

            try {

                sleep(2000);
                finish();
                Intent cv=new Intent(MainActivity.this,HomeScreen.class/*otherclass*/);
                startActivity(cv);
            } 

            catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    };
    t.start();
}

How to install VS2015 Community Edition offline

If you are a MSDN subscriber follow the steps below:

  1. Go to msdn.microsoft.com and sign in.

  2. Go to Programs->Subscriptions->Overview

  3. Click on Subscriber Access

  4. Click on Product Keys ( Claim key as needed)

  5. Select your Visual Studio Preference.

  6. click the EXE drop down list, and select DVD. This will change it to an .ISO image.By default the web installer is selected,

  7. Click green download button(approximately 7.12Gb)

note: I used a Virtual-CloneDrive-5.5 to mount this ISO and install

Remove directory from remote repository after adding them to .gitignore

Note: This solution works only with Github Desktop GUI.

By using Github Desktop GUI it is very simple.

  1. Move the folder onto another location (to out of the project folder) temporarily.

  2. Edit your .gitignore file and remove the folder entry which would be remove master repository on the github page.

  3. Commit and Sync the project folder.

  4. Re-move the folder into the project folder

  5. Re-edit .gitignore file.

That's all.

How to clear all input fields in a specific div with jQuery?

Just had to delete all inputs within a div & using the colon in front of the input when targeting gets most everything.

$('#divId').find(':input').val('');

Add a new item to recyclerview programmatically?

simply add to your data structure ( mItems ) , and then notify your adapter about dataset change

private void addItem(String item) {
  mItems.add(item);
  mAdapter.notifyDataSetChanged();
}

addItem("New Item");

Posting JSON Data to ASP.NET MVC

I see everyone here "took the long route!". As long as you are using MVC, I strongly recommend you to use the easiest method over all which is Newtonsoft.JSON... Also If you dont wanna use libraries check the answer links below. I took a good research time for this to solve the issue for my self and these are the solutions I found;

First implement the Newtonsoft.Json:

using Newtonsoft.Json;

Prepare your Ajax request:

$.ajax({
    dataType: "json",
    contentType: "application/json",            
    type: 'POST',
    url: '/Controller/Action',
    data: { 'items': JSON.stringify(lineItems), 'id': documentId }
});

Then go for your result class:

public ActionResult SaveData(string incoming, int documentId){
    // DeSerialize into your Model as your Model Array
    LineItem[] jsr = JsonConvert.DeserializeObject<LineItem[]>(Temp);
    foreach(LineItem item in jsr){
        // save some stuff
    }
    return Json(new { success = true, message = "Some message" });
}

See the trick up there? Instead of using JsonResult I used regular ActionResult with a string which includes json string. Then deserialized into my Model so I can use this in any action method I have.

Plus sides of this method is :

  1. Easier to pass between actions,
  2. Lesser and more clear usage of code,
  3. No need to change your model,
  4. Simple implementation with JSON.stringify(Model)
  5. Passing only string

Down sides of this method is :

  1. Passing only string
  2. Deserialization process

Also check these questions and answers which are really helpfull:

https://stackoverflow.com/a/45682516/861019

another method :

https://stackoverflow.com/a/31656160/861019

and another method :

https://stackoverflow.com/a/50787450/861019

How to send email to multiple recipients using python smtplib?

import smtplib
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

def sender(recipients): 

    body = 'Your email content here'
    msg = MIMEMultipart()

    msg['Subject'] = 'Email Subject'
    msg['From'] = '[email protected]'
    msg['To'] = (', ').join(recipients.split(','))

    msg.attach(MIMEText(body,'plain'))

    server = smtplib.SMTP('smtp.gmail.com', 587)
    server.starttls()
    server.login('[email protected]', 'yourpassword')
    server.send_message(msg)
    server.quit()

if __name__ == '__main__':
    sender('[email protected],[email protected]')

It only worked for me with send_message function and using the join function in the list whith recipients, python 3.6.

How do I get the web page contents from a WebView?

I know this is a late answer, but I found this question because I had the same problem. I think I found the answer in this post on lexandera.com. The code below is basically a cut-and-paste from the site. It seems to do the trick.

final Context myApp = this;

/* An instance of this class will be registered as a JavaScript interface */
class MyJavaScriptInterface
{
    @JavascriptInterface
    @SuppressWarnings("unused")
    public void processHTML(String html)
    {
        // process the html as needed by the app
    }
}

final WebView browser = (WebView)findViewById(R.id.browser);
/* JavaScript must be enabled if you want it to work, obviously */
browser.getSettings().setJavaScriptEnabled(true);

/* Register a new JavaScript interface called HTMLOUT */
browser.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT");

/* WebViewClient must be set BEFORE calling loadUrl! */
browser.setWebViewClient(new WebViewClient() {
    @Override
    public void onPageFinished(WebView view, String url)
    {
        /* This call inject JavaScript into the page which just finished loading. */
        browser.loadUrl("javascript:window.HTMLOUT.processHTML('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');");
    }
});

/* load a web page */
browser.loadUrl("http://lexandera.com/files/jsexamples/gethtml.html");

How to save select query results within temporary table?

In Sqlite:

CREATE TABLE T AS
SELECT * FROM ...;
-- Use temporary table `T`
DROP TABLE T;

Convert json to a C# array?

using Newtonsoft.Json;

Install this class in package console This class works fine in all .NET Versions, for example in my project: I have DNX 4.5.1 and DNX CORE 5.0 and everything works.

Firstly before JSON deserialization, you need to declare a class to read normally and store some data somewhere This is my class:

public class ToDoItem
{
    public string text { get; set; }
    public string complete { get; set; }
    public string delete { get; set; }
    public string username { get; set; }
    public string user_password { get; set; }
    public string eventID { get; set; }
}

In HttpContent section where you requesting data by GET request for example:

HttpContent content = response.Content;
string mycontent = await content.ReadAsStringAsync();
//deserialization in items
ToDoItem[] items = JsonConvert.DeserializeObject<ToDoItem[]>(mycontent);

Variable number of arguments in C++?

// spawn: allocate and initialize (a simple function)
template<typename T>
T * spawn(size_t n, ...){
  T * arr = new T[n];
  va_list ap;
  va_start(ap, n);
  for (size_t i = 0; i < n; i++)
    T[i] = va_arg(ap,T);
  return arr;
}

User writes:

auto arr = spawn<float> (3, 0.1,0.2,0.3);

Semantically, this looks and feels exactly like an n-argument function. Under the hood, you might unpack it one way or the other.

Environment variable to control java.io.tmpdir?

If you look in the source code of the JDK, you can see that for unix systems the property is read at compile time from the paths.h or hard coded. For windows the function GetTempPathW from win32 returns the tmpdir name.

For posix systems you might expect the standard TMPDIR to work, but that is not the case. You can confirm that TMPDIR is not used by running TMPDIR=/mytmp java -XshowSettings

Column/Vertical selection with Keyboard in SublimeText 3

Commenting just so people can have a solution to the intended question.

You can do what you are wanting but it isn't quite as nice as Notepad++ but it may work for small solutions decently enough.

In sublime if you hold ctrl, or mac equiv., and select the word/characters you want on a single line with the mouse and still holding ctrl go to another line and select the word/characters you want on that line it will be additive and you will build your selection. I mainly use notepadd++ as my extractor and data cleanup and sublime for actual development.

The other way is if your columns are in perfect alignment you can simply middle click on windows or option + click on mac and this enables you to select text in a square like fashion, Columns, inside the lines of text.

How do I define and use an ENUM in Objective-C?

Apple provides a macro to help provide better code compatibility, including Swift. Using the macro looks like this.

typedef NS_ENUM(NSInteger, PlayerStateType) {
  PlayerStateOff,
  PlayerStatePlaying,
  PlayerStatePaused
};

Documented here

ConnectivityManager getNetworkInfo(int) deprecated

This will work in Android 10 as well. It will return true if connected to the internet else return false.

private fun isOnline(): Boolean {
        val connectivityManager =
                getSystemService(Context.CONNECTIVITY_SERVICE) as ConnectivityManager
        val capabilities =
                connectivityManager.getNetworkCapabilities(connectivityManager.activeNetwork)
        if (capabilities != null) {
            when {
                capabilities.hasTransport(NetworkCapabilities.TRANSPORT_CELLULAR) -> {
                    Log.i("Internet", "NetworkCapabilities.TRANSPORT_CELLULAR")
                    return true
                }
                capabilities.hasTransport(NetworkCapabilities.TRANSPORT_WIFI) -> {
                    Log.i("Internet", "NetworkCapabilities.TRANSPORT_WIFI")
                    return true
                }
                capabilities.hasTransport(NetworkCapabilities.TRANSPORT_ETHERNET) -> {
                    Log.i("Internet", "NetworkCapabilities.TRANSPORT_ETHERNET")
                    return true
                }
            }
        }
        return false
    }

Find out the history of SQL queries

You can use this sql statement to get the history for any date:

SELECT * FROM V$SQL V where  to_date(v.FIRST_LOAD_TIME,'YYYY-MM-DD hh24:mi:ss') > sysdate - 60

Spring Boot Configure and Use Two DataSources

I used mybatis - springboot 2.0 tech stack, solution:

//application.properties - start
    sp.ds1.jdbc-url=jdbc:mysql://localhost:3306/mydb?useSSL=false
    sp.ds1.username=user
    sp.ds1.password=pwd
    sp.ds1.testWhileIdle=true
    sp.ds1.validationQuery=SELECT 1
    sp.ds1.driverClassName=com.mysql.jdbc.Driver


    sp.ds2.jdbc-url=jdbc:mysql://localhost:4586/mydb?useSSL=false
    sp.ds2.username=user
    sp.ds2.password=pwd
    sp.ds2.testWhileIdle=true
    sp.ds2.validationQuery=SELECT 1
    sp.ds2.driverClassName=com.mysql.jdbc.Driver

//application.properties - end

//configuration class

    @Configuration
    @ComponentScan(basePackages = "com.mypkg")
    public class MultipleDBConfig {


        public static final String SQL_SESSION_FACTORY_NAME_1 = "sqlSessionFactory1";
        public static final String SQL_SESSION_FACTORY_NAME_2 = "sqlSessionFactory2";

        public static final String MAPPERS_PACKAGE_NAME_1 = "com.mypg.mymapper1";
        public static final String MAPPERS_PACKAGE_NAME_2 = "com.mypg.mymapper2";


        @Bean(name = "mysqlDb1")
        @Primary
        @ConfigurationProperties(prefix = "sp.ds1")
        public DataSource dataSource1() {
            System.out.println("db1 datasource");
            return DataSourceBuilder.create().build();
        }

        @Bean(name = "mysqlDb2")
        @ConfigurationProperties(prefix = "sp.ds2")
        public DataSource dataSource2() {
            System.out.println("db2 datasource");
            return  DataSourceBuilder.create().build();
        }

        @Bean(name = SQL_SESSION_FACTORY_NAME_1)
        @Primary
        public SqlSessionFactory sqlSessionFactory1(@Qualifier("mysqlDb1") DataSource dataSource1) throws Exception {
            System.out.println("sqlSessionFactory1");
            SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
            sqlSessionFactoryBean.setTypeHandlersPackage(MAPPERS_PACKAGE_NAME_1);
            sqlSessionFactoryBean.setDataSource(dataSource1);
            SqlSessionFactory sqlSessionFactory = sqlSessionFactoryBean.getObject();
            sqlSessionFactory.getConfiguration().setMapUnderscoreToCamelCase(true);
            sqlSessionFactory.getConfiguration().setJdbcTypeForNull(JdbcType.NULL);
            return sqlSessionFactory;
        }

        @Bean(name = SQL_SESSION_FACTORY_NAME_2)
        public SqlSessionFactory sqlSessionFactory2(@Qualifier("mysqlDb2") DataSource dataSource2) throws Exception {
            System.out.println("sqlSessionFactory2");
            SqlSessionFactoryBean diSqlSessionFactoryBean = new SqlSessionFactoryBean();
            diSqlSessionFactoryBean.setTypeHandlersPackage(MAPPERS_PACKAGE_NAME_2);
            diSqlSessionFactoryBean.setDataSource(dataSource2);
            SqlSessionFactory sqlSessionFactory = diSqlSessionFactoryBean.getObject();
            sqlSessionFactory.getConfiguration().setMapUnderscoreToCamelCase(true);
            sqlSessionFactory.getConfiguration().setJdbcTypeForNull(JdbcType.NULL);
            return sqlSessionFactory;
        }

        @Bean
        @Primary
        public MapperScannerConfigurer mapperScannerConfigurer1() {
            System.out.println("mapperScannerConfigurer1");
            MapperScannerConfigurer configurer = new MapperScannerConfigurer();
            configurer.setBasePackage(MAPPERS_PACKAGE_NAME_1);
            configurer.setSqlSessionFactoryBeanName(SQL_SESSION_FACTORY_NAME_1);
            return configurer;
        }

        @Bean
        public MapperScannerConfigurer mapperScannerConfigurer2() {
            System.out.println("mapperScannerConfigurer2");
            MapperScannerConfigurer configurer = new MapperScannerConfigurer();
            configurer.setBasePackage(MAPPERS_PACKAGE_NAME_2);
            configurer.setSqlSessionFactoryBeanName(SQL_SESSION_FACTORY_NAME_2);
            return configurer;
        }



    }

Note : 1)@Primary -> @primary

2)---."jdbc-url" in properties -> After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName

How to convert string to long

Do this:

long l = Long.parseLong(str);

However, always check that str contains digits to prevent throwing exceptions. For instance:

String str="ABCDE";
long l = Long.parseLong(str);

would throw an exception but this

String str="1234567";
long l = Long.parseLong(str);

won't.

How to download dependencies in gradle

There is no task to download dependencies; they are downloaded on demand. To learn how to manage dependencies with Gradle, see "Chapter 8. Dependency Management Basics" in the Gradle User Guide.

programmatically add column & rows to WPF Datagrid

To Bind the DataTable into the DataGridTextColumn in CodeBehind xaml

<DataGrid
  Name="TrkDataGrid"
  AutoGenerateColumns="False"
  ItemsSource="{Binding}">
</DataGrid>

xaml.cs

  foreach (DataColumn col in dt.Columns)
  {
    TrkDataGrid.Columns.Add(
      new DataGridTextColumn
      {
        Header = col.ColumnName,
        Binding = new Binding(string.Format("[{0}]", col.ColumnName))
      });
  }

  TrkDataGrid.ItemsSource= dt.DefaultView;

Python TypeError must be str not int

print("the furnace is now " + str(temperature) + "degrees!")

cast it to str

Split page vertically using CSS

Alternatively, you can also use a special function known as the linear-gradient() function to split browser screen into two equal halves. Check out the following code snippet:

body
{
  background-image:linear-gradient(90deg, lightblue 50%, skyblue 50%);
}

Here, linear-gradient() function accepts three arguments

  1. 90deg for vertical division of screen.( Similarly, you can use 180deg for horizontal division of screen)
  2. lightblue color is used to represent the left half of the screen.
  3. skyblue color has been used to represent the right half of the split screen. Here, 50% has been used for equal division of the browser screen. You can use any other value if you don't want an equal division of the screen. Hope this helps. :) Happy Coding!

Android M - check runtime permission - how to determine if the user checked "Never ask again"?

I have to implement dynamic permission for camera. Where 3 possible cases occurs: 1. Allow, 2. Denied, 3. Don't ask again.

 @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {

    for (String permission : permissions) {
        if (ActivityCompat.shouldShowRequestPermissionRationale(getActivity(), permission)) {
            //denied
            Log.e("denied", permission);
        } else {
            if (ActivityCompat.checkSelfPermission(getActivity(), permission) == PackageManager.PERMISSION_GRANTED) {
                //allowed
                Log.e("allowed", permission);
            } else {
                //set to never ask again
                Log.e("set to never ask again", permission);
                //do something here.
            }
        }
    }
    if (requestCode != MaterialBarcodeScanner.RC_HANDLE_CAMERA_PERM) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        return;
    }
    if (grantResults.length != 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
        mScannerView.setResultHandler(this);
        mScannerView.startCamera(mCameraId);
        mScannerView.setFlash(mFlash);
        mScannerView.setAutoFocus(mAutoFocus);
        return;
    } else {
        //set to never ask again
        Log.e("set to never ask again", permissions[0]);
    }
    DialogInterface.OnClickListener listener = new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            dialog.cancel();
        }
    };
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setTitle("Error")
            .setMessage(R.string.no_camera_permission)
            .setPositiveButton(android.R.string.ok, listener)
            .show();


}

private void insertDummyContactWrapper() {
        int hasWriteContactsPermission = checkSelfPermission(Manifest.permission.CAMERA);
        if (hasWriteContactsPermission != PackageManager.PERMISSION_GRANTED) {
            requestPermissions(new String[]{Manifest.permission.CAMERA},
                    REQUEST_CODE_ASK_PERMISSIONS);
            return;
        }
        mScannerView.setResultHandler(this);
        mScannerView.startCamera(mCameraId);
        mScannerView.setFlash(mFlash);
        mScannerView.setAutoFocus(mAutoFocus);
    }

private int checkSelfPermission(String camera) {
    if (ContextCompat.checkSelfPermission(getActivity(), Manifest.permission.CAMERA)
            != PackageManager.PERMISSION_GRANTED) {
        return REQUEST_CODE_ASK_PERMISSIONS;
    } else {
        return REQUEST_NOT_CODE_ASK_PERMISSIONS;
    }
}

PHP: How to remove specific element from an array?

This question has several answers but I want to add something more because when I used unset or array_diff I had several problems to play with the indexes of the new array when the specific element was removed (because the initial index are saved)

I get back to the example :

$array = array('apple', 'orange', 'strawberry', 'blueberry', 'kiwi');
$array_without_strawberries = array_diff($array, array('strawberry'));

or

$array = array('apple', 'orange', 'strawberry', 'blueberry', 'kiwi');
unset($array[array_search('strawberry', $array)]);

If you print the result you will obtain :

foreach ($array_without_strawberries as $data) {
   print_r($data);
}

Result :

> apple
> orange
> blueberry
> kiwi

But the indexes will be saved and so you will access to your element like :

$array_without_strawberries[0] > apple
$array_without_strawberries[1] > orange
$array_without_strawberries[3] > blueberry
$array_without_strawberries[4] > kiwi

And so the final array are not re-indexed. So you need to add after the unset or array_diff:

$array_without_strawberries = array_values($array);

After that your array will have a normal index :

$array_without_strawberries[0] > apple
$array_without_strawberries[1] > orange
$array_without_strawberries[2] > blueberry
$array_without_strawberries[3] > kiwi

Related to this post : Re-Index Array

enter image description here

Hope it will help

Using Linq to get the last N elements of a collection?

//detailed code for the problem
//suppose we have a enumerable collection 'collection'
var lastIndexOfCollection=collection.Count-1 ;
var nthIndexFromLast= lastIndexOfCollection- N;

var desiredCollection=collection.GetRange(nthIndexFromLast, N);
---------------------------------------------------------------------

// use this one liner
var desiredCollection=collection.GetRange((collection.Count-(1+N)), N);

How to return a result from a VBA function

For non-object return types, you have to assign the value to the name of your function, like this:

Public Function test() As Integer
    test = 1
End Function

Example usage:

Dim i As Integer
i = test()

If the function returns an Object type, then you must use the Set keyword like this:

Public Function testRange() As Range
    Set testRange = Range("A1")
End Function

Example usage:

Dim r As Range
Set r = testRange()

Note that assigning a return value to the function name does not terminate the execution of your function. If you want to exit the function, then you need to explicitly say Exit Function. For example:

Function test(ByVal justReturnOne As Boolean) As Integer
    If justReturnOne Then
        test = 1
        Exit Function
    End If
    'more code...
    test = 2
End Function

Documentation: http://msdn.microsoft.com/en-us/library/office/gg264233%28v=office.14%29.aspx

Can you delete multiple branches in one command with Git?

#deleting branch names  started with 202008*   Tested on centos7

git branch | grep $202008 | xargs git branch -D

you can try

git branch | grep $3.2. | xargs git branch -D

Explanation of polkitd Unregistered Authentication Agent

I found this problem too. Because centos service depend on multi-user.target for none desktop Cenots 7.2. so I delete multi-user.target from my .service file. It had missed.

How do I record audio on iPhone with AVAudioRecorder?

Actually, there are no examples at all. Here is my working code. Recording is triggered by the user pressing a button on the navBar. The recording uses cd quality (44100 samples), stereo (2 channels) linear pcm. Beware: if you want to use a different format, especially an encoded one, make sure you fully understand how to set the AVAudioRecorder settings (read carefully the audio types documentation), otherwise you will never be able to initialize it correctly. One more thing. In the code, I am not showing how to handle metering data, but you can figure it out easily. Finally, note that the AVAudioRecorder method deleteRecording as of this writing crashes your application. This is why I am removing the recorded file through the File Manager. When recording is done, I save the recorded audio as NSData in the currently edited object using KVC.

#define DOCUMENTS_FOLDER [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]


- (void) startRecording{

UIBarButtonItem *stopButton = [[UIBarButtonItem alloc] initWithTitle:@"Stop" style:UIBarButtonItemStyleBordered  target:self action:@selector(stopRecording)];
self.navigationItem.rightBarButtonItem = stopButton;
[stopButton release];

AVAudioSession *audioSession = [AVAudioSession sharedInstance];
NSError *err = nil;
[audioSession setCategory :AVAudioSessionCategoryPlayAndRecord error:&err];
if(err){
    NSLog(@"audioSession: %@ %d %@", [err domain], [err code], [[err userInfo] description]);
    return;
}
[audioSession setActive:YES error:&err];
err = nil;
if(err){
    NSLog(@"audioSession: %@ %d %@", [err domain], [err code], [[err userInfo] description]);
    return;
}

recordSetting = [[NSMutableDictionary alloc] init];

[recordSetting setValue :[NSNumber numberWithInt:kAudioFormatLinearPCM] forKey:AVFormatIDKey];
[recordSetting setValue:[NSNumber numberWithFloat:44100.0] forKey:AVSampleRateKey]; 
[recordSetting setValue:[NSNumber numberWithInt: 2] forKey:AVNumberOfChannelsKey];

[recordSetting setValue :[NSNumber numberWithInt:16] forKey:AVLinearPCMBitDepthKey];
[recordSetting setValue :[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsBigEndianKey];
[recordSetting setValue :[NSNumber numberWithBool:NO] forKey:AVLinearPCMIsFloatKey];



// Create a new dated file
NSDate *now = [NSDate dateWithTimeIntervalSinceNow:0];
NSString *caldate = [now description];
recorderFilePath = [[NSString stringWithFormat:@"%@/%@.caf", DOCUMENTS_FOLDER, caldate] retain];

NSURL *url = [NSURL fileURLWithPath:recorderFilePath];
err = nil;
recorder = [[ AVAudioRecorder alloc] initWithURL:url settings:recordSetting error:&err];
if(!recorder){
    NSLog(@"recorder: %@ %d %@", [err domain], [err code], [[err userInfo] description]);
    UIAlertView *alert =
    [[UIAlertView alloc] initWithTitle: @"Warning"
                               message: [err localizedDescription]
                              delegate: nil
                     cancelButtonTitle:@"OK"
                     otherButtonTitles:nil];
    [alert show];
    [alert release];
    return;
}

//prepare to record
[recorder setDelegate:self];
[recorder prepareToRecord];
recorder.meteringEnabled = YES;

BOOL audioHWAvailable = audioSession.inputIsAvailable;
if (! audioHWAvailable) {
    UIAlertView *cantRecordAlert =
    [[UIAlertView alloc] initWithTitle: @"Warning"
                               message: @"Audio input hardware not available"
                              delegate: nil
                     cancelButtonTitle:@"OK"
                     otherButtonTitles:nil];
    [cantRecordAlert show];
    [cantRecordAlert release]; 
    return;
}

// start recording
[recorder recordForDuration:(NSTimeInterval) 10];

}

- (void) stopRecording{

[recorder stop];

NSURL *url = [NSURL fileURLWithPath: recorderFilePath];
NSError *err = nil;
NSData *audioData = [NSData dataWithContentsOfFile:[url path] options: 0 error:&err];
if(!audioData)
    NSLog(@"audio data: %@ %d %@", [err domain], [err code], [[err userInfo] description]);
[editedObject setValue:[NSData dataWithContentsOfURL:url] forKey:editedFieldKey];   

//[recorder deleteRecording];


NSFileManager *fm = [NSFileManager defaultManager];

err = nil;
[fm removeItemAtPath:[url path] error:&err];
if(err)
    NSLog(@"File Manager: %@ %d %@", [err domain], [err code], [[err userInfo] description]);



UIBarButtonItem *startButton = [[UIBarButtonItem alloc] initWithTitle:@"Record" style:UIBarButtonItemStyleBordered  target:self action:@selector(startRecording)];
self.navigationItem.rightBarButtonItem = startButton;
[startButton release];

}

- (void)audioRecorderDidFinishRecording:(AVAudioRecorder *) aRecorder successfully:(BOOL)flag
{

NSLog (@"audioRecorderDidFinishRecording:successfully:");
// your actions here

}

Redirecting to previous page after login? PHP

When user gets to the login page use this to see where is come from

$_SERVER['HTTP_REFERER']

Then set this value into the session, and when he is authenticated use url from the session to redirect him back. But you should do some checking before, if the url is your site. Maybe he come from another site directly to login :)

How to check Spark Version

According to the Cloudera documentation - What's New in CDH 5.7.0 it includes Spark 1.6.0.

How to correctly link php-fpm and Nginx Docker containers?

I think we also need to give the fpm container the volume, dont we? So =>

fpm:
    image: php:fpm
    volumes:
        - ./:/var/www/test/

If i dont do this, i run into this exception when firing a request, as fpm cannot find requested file:

[error] 6#6: *4 FastCGI sent in stderr: "Primary script unknown" while reading response header from upstream, client: 172.17.42.1, server: localhost, request: "GET / HTTP/1.1", upstream: "fastcgi://172.17.0.81:9000", host: "localhost"

Launch an app on OS X with command line

Why not just set add path to to the bin of the app. For MacVim, I did the following.

export PATH=/Applications/MacVim.app/Contents/bin:$PATH

An alias, is another option I tried.

alias mvim='/Applications/MacVim.app/Contents/bin/mvim'
alias gvim=mvim 

With the export PATH I can call all of the commands in the app. Arguments passed well for my test with MacVim. Whereas the alias, I had to alias each command in the bin.

mvim README.txt
gvim Anotherfile.txt

Enjoy the power of alias and PATH. However, you do need to monitor changes when the OS is upgraded.

In MySQL, can I copy one row to insert into the same table?

Just wanted to post my piece of PHP code, because I think the way I collect the columns is a bit cleaner in code than the previous examples. Also this shows how you could easily alter an field, in this case adding a string. But you could also replace a foreign key field with the newly added record, in case you want to copy some child records as well.

  // Read columns, unset the PK (always the first field in my case)
  $stmt = $conn->prepare('SHOW COLUMNS FROM template');
  $stmt->execute();

  $columns = $stmt->fetchAll();
  $columns = array_map(function ($element) { return $element['Field']; }, $columns);

  unset($columns[0]);

  // Insert record in the database. Add string COPY to the name field.
  $sql = "INSERT INTO `template` (".implode(",", $columns).")";
  if ($key = array_search('name', $columns))
      $columns[$key] = "CONCAT(name, ' COPY')";
  $sql .= " SELECT ".implode(",", $columns)." FROM `template` WHERE `id` = ".$id;

  $stmt = $conn->prepare($sql);
  $stmt->execute();

Can't stop rails server

I have noticed on Windows (Im using 10 but not sure if the same for oler). If you use cmd.exe and ctrl + c the raisl server stops correctly.

However, if you use Git Bash, it doesn't. It says it has but when you look at the tmp pids, its still there.

Maybe a bug with git bash?

PHP: if !empty & empty

For several cases, or even just a few cases involving a lot of criteria, consider using a switch.

switch( true ){

    case ( !empty($youtube) && !empty($link) ):{
        // Nothing is empty...
        break;
    }

    case ( !empty($youtube) && empty($link) ):{
        // One is empty...
        break;
    }

    case ( empty($youtube) && !empty($link) ):{
        // The other is empty...
        break;
    }

    case ( empty($youtube) && empty($link) ):{
        // Everything is empty
        break;
    }

    default:{
        // Even if you don't expect ever to use it, it's a good idea to ALWAYS have a default.
        // That way if you change it, or miss a case, you have some default handler.
        break;
    }

}

If you have multiple cases that require the same action, you can stack them and omit the break; to flowthrough. Just maybe put a comment like /*Flowing through*/ so you're explicit about doing it on purpose.

Note that the { } around the cases aren't required, but they are nice for readability and code folding.

More about switch: http://php.net/manual/en/control-structures.switch.php

On postback, how can I check which control cause postback in Page_Init event

I see that there is already some great advice and methods suggest for how to get the post back control. However I found another web page (Mahesh blog) with a method to retrieve post back control ID.

I will post it here with a little modification, including making it an extension class. Hopefully it is more useful in that way.

/// <summary>
/// Gets the ID of the post back control.
/// 
/// See: http://geekswithblogs.net/mahesh/archive/2006/06/27/83264.aspx
/// </summary>
/// <param name = "page">The page.</param>
/// <returns></returns>
public static string GetPostBackControlId(this Page page)
{
    if (!page.IsPostBack)
        return string.Empty;

    Control control = null;
    // first we will check the "__EVENTTARGET" because if post back made by the controls
    // which used "_doPostBack" function also available in Request.Form collection.
    string controlName = page.Request.Params["__EVENTTARGET"];
    if (!String.IsNullOrEmpty(controlName))
    {
        control = page.FindControl(controlName);
    }
    else
    {
        // if __EVENTTARGET is null, the control is a button type and we need to
        // iterate over the form collection to find it

        // ReSharper disable TooWideLocalVariableScope
        string controlId;
        Control foundControl;
        // ReSharper restore TooWideLocalVariableScope

        foreach (string ctl in page.Request.Form)
        {
            // handle ImageButton they having an additional "quasi-property" 
            // in their Id which identifies mouse x and y coordinates
            if (ctl.EndsWith(".x") || ctl.EndsWith(".y"))
            {
                controlId = ctl.Substring(0, ctl.Length - 2);
                foundControl = page.FindControl(controlId);
            }
            else
            {
                foundControl = page.FindControl(ctl);
            }

            if (!(foundControl is IButtonControl)) continue;

            control = foundControl;
            break;
        }
    }

    return control == null ? String.Empty : control.ID;
}

Update (2016-07-22): Type check for Button and ImageButton changed to look for IButtonControl to allow postbacks from third party controls to be recognized.

C# IPAddress from string

You've probably miss-typed something above that bit of code or created your own class called IPAddress. If you're using the .net one, that function should be available.

Have you tried using System.Net.IPAddress just in case?

System.Net.IPAddress ipaddress = System.Net.IPAddress.Parse("127.0.0.1");  //127.0.0.1 as an example

The docs on Microsoft's site have a complete example which works fine on my machine.

Convert String to equivalent Enum value

I might've over-engineered my own solution without realizing that Type.valueOf("enum string") actually existed.

I guess it gives more granular control but I'm not sure it's really necessary.

public enum Type {
    DEBIT,
    CREDIT;

    public static Map<String, Type> typeMapping = Maps.newHashMap();
    static {
        typeMapping.put(DEBIT.name(), DEBIT);
        typeMapping.put(CREDIT.name(), CREDIT);
    }

    public static Type getType(String typeName) {
        if (typeMapping.get(typeName) == null) {
            throw new RuntimeException(String.format("There is no Type mapping with name (%s)"));
        }
        return typeMapping.get(typeName);
    }
}

I guess you're exchanging IllegalArgumentException for RuntimeException (or whatever exception you wish to throw) which could potentially clean up code.

How to get the current URL within a Django template?

For Django > 3 I do not change settings or anything. I add the below code in the template file.

{{ request.path }}  #  -without GET parameters 
{{ request.get_full_path }}  # - with GET parameters

and in view.py pass request variable to the template file.

view.py:

def view_node_taxon(request, cid):
    showone = get_object_or_404(models.taxon, id = cid)
    context = {'showone':showone,'request':request}
    mytemplate  = loader.get_template('taxon/node.html')
    html = mytemplate.render(context)
    return HttpResponse(html)

How to query as GROUP BY in django?

from django.db.models import Sum
Members.objects.annotate(total=Sum(designation))

first you need to import Sum then ..

INSERT and UPDATE a record using cursors in oracle

This is a highly inefficient way of doing it. You can use the merge statement and then there's no need for cursors, looping or (if you can do without) PL/SQL.

MERGE INTO studLoad l
USING ( SELECT studId, studName FROM student ) s
ON (l.studId = s.studId)
WHEN MATCHED THEN
  UPDATE SET l.studName = s.studName
   WHERE l.studName != s.studName
WHEN NOT MATCHED THEN 
INSERT (l.studID, l.studName)
VALUES (s.studId, s.studName)

Make sure you commit, once completed, in order to be able to see this in the database.


To actually answer your question I would do it something like as follows. This has the benefit of doing most of the work in SQL and only updating based on the rowid, a unique address in the table.

It declares a type, which you place the data within in bulk, 10,000 rows at a time. Then processes these rows individually.

However, as I say this will not be as efficient as merge.

declare

   cursor c_data is
    select b.rowid as rid, a.studId, a.studName
      from student a
      left outer join studLoad b
        on a.studId = b.studId
       and a.studName <> b.studName
           ;

   type t__data is table of c_data%rowtype index by binary_integer;
   t_data t__data;

begin

   open c_data;
   loop
      fetch c_data bulk collect into t_data limit 10000;

      exit when t_data.count = 0;

      for idx in t_data.first .. t_data.last loop
         if t_data(idx).rid is null then
            insert into studLoad (studId, studName)
            values (t_data(idx).studId, t_data(idx).studName);
         else
            update studLoad
               set studName = t_data(idx).studName
             where rowid = t_data(idx).rid
                   ;
         end if;
      end loop;

   end loop;
   close c_data;

end;
/

How to change lowercase chars to uppercase using the 'keyup' event?

$(document).ready(function()
{
    $('#yourtext').keyup(function()
    {
        $(this).val($(this).val().toUpperCase());
    });
});

<textarea id="yourtext" rows="5" cols="20"></textarea>

How to format font style and color in echo

You should also use the style 'color' and not 'font-color'

<?php

foreach($months as $key => $month){
  if(strpos($filename,$month)!==false){
        echo "<style = 'color: #ff0000;'> Movie List for {$key} 2013 </style>";
    }
}

?>

In general, the comments on double and single quotes are correct in other suggestions. $Variables only execute in double quotes.

How to convert a string from uppercase to lowercase in Bash?

If you are using bash 4 you can use the following approach:

x="HELLO"
echo $x  # HELLO

y=${x,,}
echo $y  # hello

z=${y^^}
echo $z  # HELLO

Use only one , or ^ to make the first letter lowercase or uppercase.

VBA ADODB excel - read data from Recordset

I am surprised that the connection string works for you, because it is missing a semi-colon. Set is only used with objects, so you would not say Set strNaam.

Set cn = CreateObject("ADODB.Connection")
With cn
 .Provider = "Microsoft.Jet.OLEDB.4.0"
  .ConnectionString = "Data Source=D:\test.xls " & _
  ";Extended Properties=""Excel 8.0;HDR=Yes;"""
.Open
End With
strQuery = "SELECT * FROM [Sheet1$E36:E38]"
Set rs = cn.Execute(strQuery)
Do While Not rs.EOF
  For i = 0 To rs.Fields.Count - 1
    Debug.Print rs.Fields(i).Name, rs.Fields(i).Value
    strNaam = rs.Fields(0).Value
  Next
  rs.MoveNext
Loop
rs.Close

There are other ways, depending on what you want to do, such as GetString (GetString Method Description).

What are -moz- and -webkit-?

What are -moz- and -webkit-?

CSS properties starting with -webkit-, -moz-, -ms- or -o- are called vendor prefixes.


Why do different browsers add different prefixes for the same effect?

A good explanation of vendor prefixes comes from Peter-Paul Koch of QuirksMode:

Originally, the point of vendor prefixes was to allow browser makers to start supporting experimental CSS declarations.

Let's say a W3C working group is discussing a grid declaration (which, incidentally, wouldn't be such a bad idea). Let's furthermore say that some people create a draft specification, but others disagree with some of the details. As we know, this process may take ages.

Let's furthermore say that Microsoft as an experiment decides to implement the proposed grid. At this point in time, Microsoft cannot be certain that the specification will not change. Therefore, instead of adding the grid to its CSS, it adds -ms-grid.

The vendor prefix kind of says "this is the Microsoft interpretation of an ongoing proposal." Thus, if the final definition of the grid is different, Microsoft can add a new CSS property grid without breaking pages that depend on -ms-grid.


UPDATE AS OF THE YEAR 2016

As this post 3 years old, it's important to mention that now most vendors do understand that these prefixes are just creating un-necessary duplicate code and that the situation where you need to specify 3 different CSS rules to get one effect working in all browser is an unwanted one.

As mentioned in this glossary about Mozilla's view on Vendor Prefix on May 3, 2016,

Browser vendors are now trying to get rid of vendor prefix for experimental features. They noticed that Web developers were using them on production Web sites, polluting the global space and making it more difficult for underdogs to perform well.

For example, just a few years ago, to set a rounded corner on a box you had to write:

-moz-border-radius: 10px 5px;
-webkit-border-top-left-radius: 10px;
-webkit-border-top-right-radius: 5px;
-webkit-border-bottom-right-radius: 10px;
-webkit-border-bottom-left-radius: 5px;
border-radius: 10px 5px;

But now that browsers have come to fully support this feature, you really only need the standardized version:

border-radius: 10px 5px;

Finding the right rules for all browsers

As still there's no standard for common CSS rules that work on all browsers, you can use tools like caniuse.com to check support of a rule across all major browsers.

You can also use pleeease.io/play. Pleeease is a Node.js application that easily processes your CSS. It simplifies the use of preprocessors and combines them with best postprocessors. It helps create clean stylesheets, support older browsers and offers better maintainability.

Input:

a {
  column-count: 3;
  column-gap: 10px;
  column-fill: auto;
}

Output:

a {
  -webkit-column-count: 3;
     -moz-column-count: 3;
          column-count: 3;
  -webkit-column-gap: 10px;
     -moz-column-gap: 10px;
          column-gap: 10px;
  -webkit-column-fill: auto;
     -moz-column-fill: auto;
          column-fill: auto;
}

How do I publish a UDP Port on Docker?

Use the -p flag and add /udp suffix to the port number.

-p 53160:53160/udp

Full command

sudo docker run -p 53160:53160 \
    -p 53160:53160/udp -p 58846:58846 \ 
    -p 8112:8112 -t -i aostanin/deluge /start.sh

If you're running boot2docker on Mac, be sure to forward the same ports on boot2docker to your local machine.

You can also document that your container needs to receive UDP using EXPOSE in The Dockerfile (EXPOSE does not publish the port):

EXPOSE 8285/udp

Here is a link with more Docker Networking info covered in the container docs: https://docs.docker.com/config/containers/container-networking/ (Courtesy of Old Pro in the comments)

HTTP GET in VBS

Dim o
Set o = CreateObject("MSXML2.XMLHTTP")
o.open "GET", "http://www.example.com", False
o.send
' o.responseText now holds the response as a string.

How to count days between two dates in PHP?

Here is the raw way to do it

$startTimeStamp = strtotime("2011/07/01");
$endTimeStamp = strtotime("2011/07/17");

$timeDiff = abs($endTimeStamp - $startTimeStamp);

$numberDays = $timeDiff/86400;  // 86400 seconds in one day

// and you might want to convert to integer
$numberDays = intval($numberDays);

Tomcat: How to find out running tomcat version

Enter 404.jsp or non-existent.jsp.

Get Tomcat/JBoss version number at bottom of page.

Image.open() cannot identify image file - Python?

Seems like a Permissions Issue. I was facing the same error. But when I ran it from the root account, it worked. So either give the read permission to the file using chmod (in linux) or run your script after logging in as a root user.

returning a Void object

It is possible to create instances of Void if you change the security manager, so something like this:

static Void getVoid() throws SecurityException, InstantiationException,
        IllegalAccessException, InvocationTargetException {
    class BadSecurityManager extends SecurityManager {
    
        @Override
        public void checkPermission(Permission perm) { }
    
        @Override
        public void checkPackageAccess(String pkg) { }

    }
    System.setSecurityManager(badManager = new BadSecurityManager());
    Constructor<?> constructor = Void.class.getDeclaredConstructors()[0];
    if(!constructor.isAccessible()) {
        constructor.setAccessible(true);
    }
    return (Void) constructor.newInstance();
}

Obviously this is not all that practical or safe; however, it will return an instance of Void if you are able to change the security manager.

What is the difference between a web API and a web service?

All WebServices is API but all API is not WebServices, API which is exposed on Web is called web services.

What is the difference between task and thread?

Task is like a operation that you wanna perform , Thread helps to manage those operation through multiple process nodes. task is a lightweight option as Threading can lead to a complex code management
I will suggest to read from MSDN(Best in world) always

Task

Thread

Shortcut to Apply a Formula to an Entire Column in Excel

If the formula already exists in a cell you can fill it down as follows:

  • Select the cell containing the formula and press CTRL+SHIFT+DOWN to select the rest of the column (CTRL+SHIFT+END to select up to the last row where there is data)
  • Fill down by pressing CTRL+D
  • Use CTRL+UP to return up

On Mac, use CMD instead of CTRL.

An alternative if the formula is in the first cell of a column:

  • Select the entire column by clicking the column header or selecting any cell in the column and pressing CTRL+SPACE
  • Fill down by pressing CTRL+D

How to measure time in milliseconds using ANSI C?

timespec_get from C11

Returns up to nanoseconds, rounded to the resolution of the implementation.

Looks like an ANSI ripoff from POSIX' clock_gettime.

Example: a printf is done every 100ms on Ubuntu 15.10:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>

static long get_nanos(void) {
    struct timespec ts;
    timespec_get(&ts, TIME_UTC);
    return (long)ts.tv_sec * 1000000000L + ts.tv_nsec;
}

int main(void) {
    long nanos;
    long last_nanos;
    long start;
    nanos = get_nanos();
    last_nanos = nanos;
    start = nanos;
    while (1) {
        nanos = get_nanos();
        if (nanos - last_nanos > 100000000L) {
            printf("current nanos: %ld\n", nanos - start);
            last_nanos = nanos;
        }
    }
    return EXIT_SUCCESS;
}

The C11 N1570 standard draft 7.27.2.5 "The timespec_get function says":

If base is TIME_UTC, the tv_sec member is set to the number of seconds since an implementation defined epoch, truncated to a whole value and the tv_nsec member is set to the integral number of nanoseconds, rounded to the resolution of the system clock. (321)

321) Although a struct timespec object describes times with nanosecond resolution, the available resolution is system dependent and may even be greater than 1 second.

C++11 also got std::chrono::high_resolution_clock: C++ Cross-Platform High-Resolution Timer

glibc 2.21 implementation

Can be found under sysdeps/posix/timespec_get.c as:

int
timespec_get (struct timespec *ts, int base)
{
  switch (base)
    {
    case TIME_UTC:
      if (__clock_gettime (CLOCK_REALTIME, ts) < 0)
        return 0;
      break;

    default:
      return 0;
    }

  return base;
}

so clearly:

  • only TIME_UTC is currently supported

  • it forwards to __clock_gettime (CLOCK_REALTIME, ts), which is a POSIX API: http://pubs.opengroup.org/onlinepubs/9699919799/functions/clock_getres.html

    Linux x86-64 has a clock_gettime system call.

    Note that this is not a fail-proof micro-benchmarking method because:

    • man clock_gettime says that this measure may have discontinuities if you change some system time setting while your program runs. This should be a rare event of course, and you might be able to ignore it.

    • this measures wall time, so if the scheduler decides to forget about your task, it will appear to run for longer.

    For those reasons getrusage() might be a better better POSIX benchmarking tool, despite it's lower microsecond maximum precision.

    More information at: Measure time in Linux - time vs clock vs getrusage vs clock_gettime vs gettimeofday vs timespec_get?

Breaking out of nested loops

If you're able to extract the loop code into a function, a return statement can be used to exit the outermost loop at any time.

def foo():
    for x in range(10):
        for y in range(10):
            print(x*y)
            if x*y > 50:
                return
foo()

If it's hard to extract that function you could use an inner function, as @bjd2385 suggests, e.g.

def your_outer_func():
    ...
    def inner_func():
        for x in range(10):
            for y in range(10):
                print(x*y)
                if x*y > 50:
                    return
    inner_func()
    ...

Trying to start a service on boot on Android

This is what I did

1. I made the Receiver class

public class BootReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        //whatever you want to do on boot
       Intent serviceIntent = new Intent(context, YourService.class);
       context.startService(serviceIntent);
    }
}

2.in the manifest

<manifest...>
    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
    <application...>
        <receiver android:name=".BootReceiver" android:enabled="true" android:exported="false">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>
    ...

3.and after ALL you NEED to "set" the receiver in your MainActivity, it may be inside the onCreate

...
 final ComponentName onBootReceiver = new ComponentName(getApplication().getPackageName(), BootReceiver.class.getName());
        if(getPackageManager().getComponentEnabledSetting(onBootReceiver) != PackageManager.COMPONENT_ENABLED_STATE_ENABLED)
        getPackageManager().setComponentEnabledSetting(onBootReceiver,PackageManager.COMPONENT_ENABLED_STATE_ENABLED,PackageManager.DONT_KILL_APP);
...

the final steap I have learned from ApiDemos

Regex Named Groups in Java

What kind of problem do you get with jregex? It worked well for me under java5 and java6.

Jregex does the job well (even if the last version is from 2002), unless you want to wait for javaSE 7.

LINQ-to-SQL vs stored procedures?

A DBA has no freedom to make changes to the data model without forcing you to change your compiled code. With stored procedures, you can hide these sorts of changes to an extent, since the parameter list and results set(s) returned from a procedure represent its contract, and the innards can be changed around, just so long as that contract is still met.

I really don't see this as being a benefit. Being able to change something in isolation might sound good in theory, but just because the changes fulfil a contract doesn't mean it's returning the correct results. To be able to determine what the correct results are you need context and you get that context from the calling code.

Avoid Adding duplicate elements to a List C#

Use a HashSet along with your List:

List<string> myList = new List<string>();
HashSet<string> myHashSet = new HashSet<string>();

public void addToList(string s) {
    if (myHashSet.Add(s)) {
        myList.Add(s);
    }
}

myHashSet.Add(s) will return true if s is not exist in it.

How can I use pointers in Java?

Java does not have pointers like C has, but it does allow you to create new objects on the heap which are "referenced" by variables. The lack of pointers is to stop Java programs from referencing memory locations illegally, and also enables Garbage Collection to be automatically carried out by the Java Virtual Machine.

Java check if boolean is null

The only thing that can be a null is a non-primivite.

A boolean which can only hold TRUE or FALSE is a primitive. The TRUE/FALSE in memory are actually numbers (0 and 1)

0 = FALSE

1 = TRUE

So when you instantiate an object it will be null String str; // will equal null

On the other hand if you instaniate a primitive it will be assigned to 0 default.

boolean isTrue; // will be 0

int i; // will be 0

How to merge two arrays of objects by ID using lodash?

Create dictionaries for both arrays using _.keyBy(), merge the dictionaries, and convert the result to an array with _.values(). In this way, the order of the arrays doesn't matter. In addition, it can also handle arrays of different length.

_x000D_
_x000D_
const ObjectId = (id) => id; // mock of ObjectId_x000D_
const arr1 = [{"member" : ObjectId("57989cbe54cf5d2ce83ff9d8"),"bank" : ObjectId("575b052ca6f66a5732749ecc"),"country" : ObjectId("575b0523a6f66a5732749ecb")},{"member" : ObjectId("57989cbe54cf5d2ce83ff9d6"),"bank" : ObjectId("575b052ca6f66a5732749ecc"),"country" : ObjectId("575b0523a6f66a5732749ecb")}];_x000D_
const arr2 = [{"member" : ObjectId("57989cbe54cf5d2ce83ff9d6"),"name" : 'xxxxxx',"age" : 25},{"member" : ObjectId("57989cbe54cf5d2ce83ff9d8"),"name" : 'yyyyyyyyyy',"age" : 26}];_x000D_
_x000D_
const merged = _(arr1) // start sequence_x000D_
  .keyBy('member') // create a dictionary of the 1st array_x000D_
  .merge(_.keyBy(arr2, 'member')) // create a dictionary of the 2nd array, and merge it to the 1st_x000D_
  .values() // turn the combined dictionary to array_x000D_
  .value(); // get the value (array) out of the sequence_x000D_
_x000D_
console.log(merged);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.14.0/lodash.min.js"></script>
_x000D_
_x000D_
_x000D_

Using ES6 Map

Concat the arrays, and reduce the combined array to a Map. Use Object#assign to combine objects with the same member to a new object, and store in map. Convert the map to an array with Map#values and spread:

_x000D_
_x000D_
const ObjectId = (id) => id; // mock of ObjectId_x000D_
const arr1 = [{"member" : ObjectId("57989cbe54cf5d2ce83ff9d8"),"bank" : ObjectId("575b052ca6f66a5732749ecc"),"country" : ObjectId("575b0523a6f66a5732749ecb")},{"member" : ObjectId("57989cbe54cf5d2ce83ff9d6"),"bank" : ObjectId("575b052ca6f66a5732749ecc"),"country" : ObjectId("575b0523a6f66a5732749ecb")}];_x000D_
const arr2 = [{"member" : ObjectId("57989cbe54cf5d2ce83ff9d6"),"name" : 'xxxxxx',"age" : 25},{"member" : ObjectId("57989cbe54cf5d2ce83ff9d8"),"name" : 'yyyyyyyyyy',"age" : 26}];_x000D_
_x000D_
const merged = [...arr1.concat(arr2).reduce((m, o) => _x000D_
  m.set(o.member, Object.assign(m.get(o.member) || {}, o))_x000D_
, new Map()).values()];_x000D_
_x000D_
console.log(merged);
_x000D_
_x000D_
_x000D_

Apache is not running from XAMPP Control Panel ( Error: Apache shutdown unexpectedly. This may be due to a blocked port)

Check if you have Skype installed on your machine.

Login and go to Tools - Options - Advanced - Connection and uncheck the box which says use port 80

--

Check if Apache service is already installed by firing up services.msc from run command prompt.

How to delete a service from command prompt? sc delete “serviceName”

Remember serviceName should be replaced by exact name of the Apache service as shown is services list.

Check if IIS is running and taking up port 80. If so, disable it.

--

Check if AVP (Kaspersky) is running and taking up port 80. If so add httpd.exe as an exception to allowed programs.

--

Hope it helps.

If using maven, usually you put log4j.properties under java or resources?

Add the below code from the resources tags in your pom.xml inside build tags. so it means resources tags must be inside of build tags in your pom.xml

<build>
    <resources>
        <resource>
            <directory>src/main/java/resources</directory>
                <filtering>true</filtering> 
         </resource>
     </resources>
<build/>

Java Regex Replace with Capturing Group

Source: java-implementation-of-rubys-gsub

Usage:

// Rewrite an ancient unit of length in SI units.
String result = new Rewriter("([0-9]+(\\.[0-9]+)?)[- ]?(inch(es)?)") {
    public String replacement() {
        float inches = Float.parseFloat(group(1));
        return Float.toString(2.54f * inches) + " cm";
    }
}.rewrite("a 17 inch display");
System.out.println(result);

// The "Searching and Replacing with Non-Constant Values Using a
// Regular Expression" example from the Java Almanac.
result = new Rewriter("([a-zA-Z]+[0-9]+)") {
    public String replacement() {
        return group(1).toUpperCase();
    }
}.rewrite("ab12 cd efg34");
System.out.println(result);

Implementation (redesigned):

import static java.lang.String.format;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public abstract class Rewriter {
    private Pattern pattern;
    private Matcher matcher;

    public Rewriter(String regularExpression) {
        this.pattern = Pattern.compile(regularExpression);
    }

    public String group(int i) {
        return matcher.group(i);
    }

    public abstract String replacement() throws Exception;

    public String rewrite(CharSequence original) {
        return rewrite(original, new StringBuffer(original.length())).toString();
    }

    public StringBuffer rewrite(CharSequence original, StringBuffer destination) {
        try {
            this.matcher = pattern.matcher(original);
            while (matcher.find()) {
                matcher.appendReplacement(destination, "");
                destination.append(replacement());
            }
            matcher.appendTail(destination);
            return destination;
        } catch (Exception e) {
            throw new RuntimeException("Cannot rewrite " + toString(), e);
        }
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append(pattern.pattern());
        for (int i = 0; i <= matcher.groupCount(); i++)
            sb.append(format("\n\t(%s) - %s", i, group(i)));
        return sb.toString();
    }
}

Node.js Port 3000 already in use but it actually isn't?

Open Task Manager (press Ctrl+Alt+Del Select the 'Processes Tab' Search for 'Node.js: Server-side JavaScript' Select it and click on 'End task' button

Creating a fixed sidebar alongside a centered Bootstrap 3 grid

As drew_w said, you can find a good example here.

HTML

<div id="wrapper">
    <div id="sidebar-wrapper">
        <ul class="sidebar-nav">
            <li class="sidebar-brand"><a href="#">Home</a></li>
            <li><a href="#">Another link</a></li>
            <li><a href="#">Next link</a></li>
            <li><a href="#">Last link</a></li>
        </ul>
    </div>
    <div id="page-content-wrapper">
        <div class="page-content">
            <div class="container">
                <div class="row">
                    <div class="col-md-12">
                        <!-- content of page -->
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

CSS

#wrapper {
  padding-left: 250px;
  transition: all 0.4s ease 0s;
}

#sidebar-wrapper {
  margin-left: -250px;
  left: 250px;
  width: 250px;
  background: #CCC;
  position: fixed;
  height: 100%;
  overflow-y: auto;
  z-index: 1000;
  transition: all 0.4s ease 0s;
}

#page-content-wrapper {
  width: 100%;
}

.sidebar-nav {
  position: absolute;
  top: 0;
  width: 250px;
  list-style: none;
  margin: 0;
  padding: 0;
}

@media (max-width:767px) {

    #wrapper {
      padding-left: 0;
    }

    #sidebar-wrapper {
      left: 0;
    }

    #wrapper.active {
      position: relative;
      left: 250px;
    }

    #wrapper.active #sidebar-wrapper {
      left: 250px;
      width: 250px;
      transition: all 0.4s ease 0s;
    }

}

JSFIDDLE

Where are shared preferences stored?

The data is stored on the device, in your application's private data area. It is not in an Eclipse project.

Click button copy to clipboard using jQuery

Even better approach without flash or any other requirements is clipboard.js. All you need to do is add data-clipboard-target="#toCopyElement" on any button, initialize it new Clipboard('.btn'); and it will copy the content of DOM with id toCopyElement to clipboard. This is a snippet that copy the text provided in your question via a link.

One limitation though is that it does not work on safari, but it works on all other browser including mobile browsers as it does not use flash

_x000D_
_x000D_
$(function(){_x000D_
  new Clipboard('.copy-text');_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdn.jsdelivr.net/clipboard.js/1.5.12/clipboard.min.js"></script>_x000D_
_x000D_
<p id="content">Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s</p>_x000D_
_x000D_
<a class="copy-text" data-clipboard-target="#content" href="#">copy Text</a>
_x000D_
_x000D_
_x000D_

How to assign multiple classes to an HTML container?

To assign multiple classes to an html element, include both class names within the quotations of the class attribute and have them separated by a space:

<article class="column wrapper"> 

In the above example, column and wrapper are two separate css classes, and both of their properties will be applied to the article element.

Which characters need to be escaped in HTML?

It depends upon the context. Some possible contexts in HTML:

  • document body
  • inside common attributes
  • inside script tags
  • inside style tags
  • several more!

See OWASP's Cross Site Scripting Prevention Cheat Sheet, especially the "Why Can't I Just HTML Entity Encode Untrusted Data?" and "XSS Prevention Rules" sections. However, it's best to read the whole document.

How do you deploy Angular apps?

If you deploy your application in Apache (Linux server) so you can follow following steps : Follow following steps :

Step 1: ng build --prod --env=prod

Step 2. (Copy dist into server) then dist folder created, copy dist folder and deploy it in root directory of server.

Step 3. Creates .htaccess file in root folder and paste this in the .htaccess

 <IfModule mod_rewrite.c>
  RewriteEngine On
  RewriteBase /
  RewriteRule ^index\.html$ - [L]
  RewriteCond %{REQUEST_FILENAME} !-f
  RewriteCond %{REQUEST_FILENAME} !-d
  RewriteRule . /index.html [L]
</IfModule>

CKEditor automatically strips classes from div

Disabling content filtering

The easiest solution is going to the config.js and setting:

config.allowedContent = true;

(Remember to clear browser's cache). Then CKEditor stops filtering the inputted content at all. However, this will totally disable content filtering which is one of the most important CKEditor features.

Configuring content filtering

You can also configure CKEditor's content filter more precisely to allow only these element, classes, styles and attributes which you need. This solution is much better, because CKEditor will still remove a lot of crappy HTML which browsers produce when copying and pasting content, but it will not strip the content you want.

For example, you can extend the default CKEditor's configuration to accept all div classes:

config.extraAllowedContent = 'div(*)';

Or some Bootstrap stuff:

config.extraAllowedContent = 'div(col-md-*,container-fluid,row)';

Or you can allow description lists with optional dir attributes for dt and dd elements:

config.extraAllowedContent = 'dl; dt dd[dir]';

These were just very basic examples. You can write all kind of rules - requiring attributes, classes or styles, matching only special elements, matching all elements. You can also disallow stuff and totally redefine CKEditor's rules. Read more about:

How to manually send HTTP POST requests from Firefox or Chrome browser?

May not be directly related to browsers but fiddler is another good software.

Fiddler web debugger

Zoom to fit: PDF Embedded in HTML

just in case someone need it, in firefox for me it work like this

<iframe src="filename.pdf#zoom=FitH" style="position:absolute;right:0; top:0; bottom:0; width:100%;"></iframe>

How to import popper.js?

I deleted any existing popper directories, then ran

npm install --save popper.js angular-popper

Git: How to remove remote origin from Git repo

You can rename (changing URL of a remote repository) using :

git remote set-url origin new_URL

new_URL can be like https://github.com/abcdefgh/abcd.git

Too permanently delete the remote repository use :

git remote remove origin

What's the difference between emulation and simulation?

I do not know whether this is the general opinion, but I've always differentiated the two by what they are used for. An emulator is used if you actually want to use the emulated machine for its output. A simulator, on the other hand, is for when you want to study the simulated machine or test its behaviour.

For example, if you want to write some state machine logic in your application (which is running on a general purpose CPU), you write a small state machine emulator. If you want to study the efficiency or viability of a state machine for a particular problem, you write a simulator.

Java Timer vs ExecutorService?

If it's available to you, then it's difficult to think of a reason not to use the Java 5 executor framework. Calling:

ScheduledExecutorService ex = Executors.newSingleThreadScheduledExecutor();

will give you a ScheduledExecutorService with similar functionality to Timer (i.e. it will be single-threaded) but whose access may be slightly more scalable (under the hood, it uses concurrent structures rather than complete synchronization as with the Timer class). Using a ScheduledExecutorService also gives you advantages such as:

  • You can customize it if need be (see the newScheduledThreadPoolExecutor() or the ScheduledThreadPoolExecutor class)
  • The 'one off' executions can return results

About the only reasons for sticking to Timer I can think of are:

  • It is available pre Java 5
  • A similar class is provided in J2ME, which could make porting your application easier (but it wouldn't be terribly difficult to add a common layer of abstraction in this case)

function to return a string in java

Your code is fine. There's no problem with returning Strings in this manner.

In Java, a String is a reference to an immutable object. This, coupled with garbage collection, takes care of much of the potential complexity: you can simply pass a String around without worrying that it would disapper on you, or that someone somewhere would modify it.

If you don't mind me making a couple of stylistic suggestions, I'd modify the code like so:

public String time_to_string(long t) // time in milliseconds
{
    if (t < 0)
    {
        return "-";
    }
    else
    {
        int secs = (int)(t/1000);
        int mins = secs/60;
        secs = secs - (mins * 60);
        return String.format("%d:%02d", mins, secs);
    }
}

As you can see, I've pushed the variable declarations as far down as I could (this is the preferred style in C++ and Java). I've also eliminated ans and have replaced the mix of string concatenation and String.format() with a single call to String.format().

How do I trap ctrl-c (SIGINT) in a C# console app

In my case, I passed an async lambda to Console.CancelKeyPress, which won't work.

Single Line Nested For Loops

First of all, your first code doesn't use a for loop per se, but a list comprehension.

  1. Would be equivalent to

    for j in range(0, width): for i in range(0, height): m[i][j]

  2. Much the same way, it generally nests like for loops, right to left. But list comprehension syntax is more complex.

  3. I'm not sure what this question is asking


  1. Any iterable object that yields iterable objects that yield exactly two objects (what a mouthful - i.e [(1,2),'ab'] would be valid )

  2. The order in which the object yields upon iteration. i goes to the first yield, j the second.

  3. Yes, but not as pretty. I believe it is functionally equivalent to:

    l = list()
    for i,j in object:
        l.append(function(i,j))
    

    or even better use map:

    map(function, object)
    

    But of course function would have to get i, j itself.

  4. Isn't this the same question as 3?

Redirect from a view to another view

Purpose of view is displaying model. You should use controller to redirect request before creating model and passing it to view. Use Controller.RedirectToAction method for this.

Determine on iPhone if user has enabled push notifications

Swift 3+

    if #available(iOS 10.0, *) {
        UNUserNotificationCenter.current().getNotificationSettings(completionHandler: { (settings: UNNotificationSettings) in
            // settings.authorizationStatus == .authorized
        })
    } else {
        return UIApplication.shared.currentUserNotificationSettings?.types.contains(UIUserNotificationType.alert) ?? false
    }

RxSwift Observable Version for iOS10+:

import UserNotifications
extension UNUserNotificationCenter {
    static var isAuthorized: Observable<Bool> {
        return Observable.create { observer in
            DispatchQueue.main.async {
                current().getNotificationSettings(completionHandler: { (settings: UNNotificationSettings) in
                    if settings.authorizationStatus == .authorized {
                        observer.onNext(true)
                        observer.onCompleted()
                    } else {
                        current().requestAuthorization(options: [.badge, .alert, .sound]) { (granted, error) in
                            observer.onNext(granted)
                            observer.onCompleted()
                        }
                    }
                })
            }
            return Disposables.create()
        }
    }
}

Split string in C every white space

Just as an idea of a different style of string manipulation in C, here's an example which does not modify the source string, and does not use malloc. To find spaces I use the libc function strpbrk.

int print_words(const char *string, FILE *f)
{
   static const char space_characters[] = " \t";
   const char *next_space;

   // Find the next space in the string
   //
   while ((next_space = strpbrk(string, space_characters)))
   {
      const char *p;

      // If there are non-space characters between what we found
      // and what we started from, print them.
      //
      if (next_space != string)
      {
         for (p=string; p<next_space; p++)
         {
            if(fputc(*p, f) == EOF)
            {
               return -1;
            }
         }

         // Print a newline
         //
         if (fputc('\n', f) == EOF)
         {
            return -1;
         }
      }

      // Advance next_space until we hit a non-space character
      //
      while (*next_space && strchr(space_characters, *next_space))
      {
         next_space++;
      }

      // Advance the string
      //
      string = next_space;
   }

   // Handle the case where there are no spaces left in the string
   //
   if (*string)
   {
      if (fprintf(f, "%s\n", string) < 0)
      {
         return -1;
      }
   }

   return 0;
}

How to select first and last TD in a row?

You could use the :first-child and :last-child pseudo-selectors:

tr td:first-child,
tr td:last-child {
    /* styles */
}

This should work in all major browsers, but IE7 has some problems when elements are added dynamically (and it won't work in IE6).

Running an executable in Mac Terminal

To run an executable in mac

1). Move to the path of the file:

cd/PATH_OF_THE_FILE

2). Run the following command to set the file's executable bit using the chmod command:

chmod +x ./NAME_OF_THE_FILE

3). Run the following command to execute the file:

./NAME_OF_THE_FILE

Once you have run these commands, going ahead you just have to run command 3, while in the files path.

Using iFrames In ASP.NET

How about:

<asp:HtmlIframe ID="yourIframe" runat="server" />

Is supported since .Net Framework 4.5

If you have Problems using this control, you might take a look here.

How to undo "git commit --amend" done instead of "git commit"

  1. Checkout to temporary branch with last commit

    git branch temp HEAD@{1}

  2. Reset last commit

    git reset temp

  3. Now, you'll have all files your commit as well as previous commit. Check status of all the files.

    git status

  4. Reset your commit files from git stage.

    git reset myfile1.js (so on)

  5. Reattach this commit

    git commit -C HEAD@{1}

  6. Add and commit your files to new commit.

Mixing a PHP variable with a string literal

echo "{$test}y";

You can use braces to remove ambiguity when interpolating variables directly in strings.

Also, this doesn't work with single quotes. So:

echo '{$test}y';

will output

{$test}y

Dynamically load a function from a DLL

In addition to the already posted answer, I thought I should share a handy trick I use to load all the DLL functions into the program through function pointers, without writing a separate GetProcAddress call for each and every function. I also like to call the functions directly as attempted in the OP.

Start by defining a generic function pointer type:

typedef int (__stdcall* func_ptr_t)();

What types that are used aren't really important. Now create an array of that type, which corresponds to the amount of functions you have in the DLL:

func_ptr_t func_ptr [DLL_FUNCTIONS_N];

In this array we can store the actual function pointers that point into the DLL memory space.

Next problem is that GetProcAddress expects the function names as strings. So create a similar array consisting of the function names in the DLL:

const char* DLL_FUNCTION_NAMES [DLL_FUNCTIONS_N] = 
{
  "dll_add",
  "dll_subtract",
  "dll_do_stuff",
  ...
};

Now we can easily call GetProcAddress() in a loop and store each function inside that array:

for(int i=0; i<DLL_FUNCTIONS_N; i++)
{
  func_ptr[i] = GetProcAddress(hinst_mydll, DLL_FUNCTION_NAMES[i]);

  if(func_ptr[i] == NULL)
  {
    // error handling, most likely you have to terminate the program here
  }
}

If the loop was successful, the only problem we have now is calling the functions. The function pointer typedef from earlier isn't helpful, because each function will have its own signature. This can be solved by creating a struct with all the function types:

typedef struct
{
  int  (__stdcall* dll_add_ptr)(int, int);
  int  (__stdcall* dll_subtract_ptr)(int, int);
  void (__stdcall* dll_do_stuff_ptr)(something);
  ...
} functions_struct;

And finally, to connect these to the array from before, create a union:

typedef union
{
  functions_struct  by_type;
  func_ptr_t        func_ptr [DLL_FUNCTIONS_N];
} functions_union;

Now you can load all the functions from the DLL with the convenient loop, but call them through the by_type union member.

But of course, it is a bit burdensome to type out something like

functions.by_type.dll_add_ptr(1, 1); whenever you want to call a function.

As it turns out, this is the reason why I added the "ptr" postfix to the names: I wanted to keep them different from the actual function names. We can now smooth out the icky struct syntax and get the desired names, by using some macros:

#define dll_add (functions.by_type.dll_add_ptr)
#define dll_subtract (functions.by_type.dll_subtract_ptr)
#define dll_do_stuff (functions.by_type.dll_do_stuff_ptr)

And voilà, you can now use the function names, with the correct type and parameters, as if they were statically linked to your project:

int result = dll_add(1, 1);

Disclaimer: Strictly speaking, conversions between different function pointers are not defined by the C standard and not safe. So formally, what I'm doing here is undefined behavior. However, in the Windows world, function pointers are always of the same size no matter their type and the conversions between them are predictable on any version of Windows I've used.

Also, there might in theory be padding inserted in the union/struct, which would cause everything to fail. However, pointers happen to be of the same size as the alignment requirement in Windows. A static_assert to ensure that the struct/union has no padding might be in order still.

Combine two columns of text in pandas dataframe

more efficient is

def concat_df_str1(df):
    """ run time: 1.3416s """
    return pd.Series([''.join(row.astype(str)) for row in df.values], index=df.index)

and here is a time test:

import numpy as np
import pandas as pd

from time import time


def concat_df_str1(df):
    """ run time: 1.3416s """
    return pd.Series([''.join(row.astype(str)) for row in df.values], index=df.index)


def concat_df_str2(df):
    """ run time: 5.2758s """
    return df.astype(str).sum(axis=1)


def concat_df_str3(df):
    """ run time: 5.0076s """
    df = df.astype(str)
    return df[0] + df[1] + df[2] + df[3] + df[4] + \
           df[5] + df[6] + df[7] + df[8] + df[9]


def concat_df_str4(df):
    """ run time: 7.8624s """
    return df.astype(str).apply(lambda x: ''.join(x), axis=1)


def main():
    df = pd.DataFrame(np.zeros(1000000).reshape(100000, 10))
    df = df.astype(int)

    time1 = time()
    df_en = concat_df_str4(df)
    print('run time: %.4fs' % (time() - time1))
    print(df_en.head(10))


if __name__ == '__main__':
    main()

final, when sum(concat_df_str2) is used, the result is not simply concat, it will trans to integer.

How to Execute SQL Script File in Java?

You cannot do using JDBC as it does not support . Work around would be including iBatis iBATIS is a persistence framework and call the Scriptrunner constructor as shown in iBatis documentation .

Its not good to include a heavy weight persistence framework like ibatis in order to run a simple sql scripts any ways which you can do using command line

$ mysql -u root -p db_name < test.sql

PHP sessions default timeout

Yes, that's usually happens after 1440s (24 minutes)

How to get the current loop index when using Iterator?

I had the same question and found using a ListIterator worked. Similar to the test above:

List<String> list = Arrays.asList("zero", "one", "two");

ListIterator iter = list.listIterator();
    
while (iter.hasNext()) {
    System.out.println("index: " + iter.nextIndex() + " value: " + iter.next());
}

Make sure you call the nextIndex() before you actually get the next().

How to install PIP on Python 3.6?

pip is included in Python installation. If you can't call pip.exe try calling python -m pip [args] from cmd

How to customize message box

MessageBox::Show uses function from user32.dll, and its style is dependent on Windows, so you cannot change it like that, you have to create your own form

Finding Number of Cores in Java

int cores = Runtime.getRuntime().availableProcessors();

If cores is less than one, either your processor is about to die, or your JVM has a serious bug in it, or the universe is about to blow up.

SQL JOIN, GROUP BY on three tables to get totals

I am not sure I got you but this might be what you are looking for:

SELECT i.invoiceid, sum(case when i.amount is not null then i.amount else 0 end), sum(case when i.amount is not null then i.amount else 0 end) - sum(case when p.amount is not null then p.amount else 0 end) AS amountdue
FROM invoices i
LEFT JOIN invoicepayments ip ON i.invoiceid = ip.invoiceid
LEFT JOIN payments p ON ip.paymentid = p.paymentid
LEFT JOIN customers c ON p.customerid = c.customerid
WHERE c.customernumber = '100'
GROUP BY i.invoiceid

This would get you the amounts sums in case there are multiple payment rows for each invoice

How to round double to nearest whole number and then convert to a float?

Here is a quick example:

public class One {

    /**
     * @param args
     */
    public static void main(String[] args) {

        double a = 4.56777;
        System.out.println( new Float( Math.round(a)) );

    }

}

the result and output will be: 5.0
the closest upper bound Float to the starting value of double a = 4.56777
in this case the use of round is recommended since it takes in double values and provides whole long values

Regards

Changing the default icon in a Windows Forms application

You can change the app icon under project properties. Individual form icons under form properties.

How do I compile with -Xlint:unchecked?

A cleaner way to specify the Gradle compiler arguments follow:

compileJava.options.compilerArgs = ['-Xlint:unchecked','-Xlint:deprecation']

C# Linq Group By on multiple columns

var consolidatedChildren =
    from c in children
    group c by new
    {
        c.School,
        c.Friend,
        c.FavoriteColor,
    } into gcs
    select new ConsolidatedChild()
    {
        School = gcs.Key.School,
        Friend = gcs.Key.Friend,
        FavoriteColor = gcs.Key.FavoriteColor,
        Children = gcs.ToList(),
    };

var consolidatedChildren =
    children
        .GroupBy(c => new
        {
            c.School,
            c.Friend,
            c.FavoriteColor,
        })
        .Select(gcs => new ConsolidatedChild()
        {
            School = gcs.Key.School,
            Friend = gcs.Key.Friend,
            FavoriteColor = gcs.Key.FavoriteColor,
            Children = gcs.ToList(),
        });

Is it bad to have my virtualenv directory inside my git repository?

I think one of the main problems which occur is that the virtualenv might not be usable by other people. Reason is that it always uses absolute paths. So if you virtualenv was for example in /home/lyle/myenv/ it will assume the same for all other people using this repository (it must be exactly the same absolute path). You can't presume people using the same directory structure as you.

Better practice is that everybody is setting up their own environment (be it with or without virtualenv) and installing libraries there. That also makes you code more usable over different platforms (Linux/Windows/Mac), also because virtualenv is installed different in each of them.

ARG or ENV, which one to use in this case?

So if want to set the value of an environment variable to something different for every build then we can pass these values during build time and we don't need to change our docker file every time.

While ENV, once set cannot be overwritten through command line values. So, if we want to have our environment variable to have different values for different builds then we could use ARG and set default values in our docker file. And when we want to overwrite these values then we can do so using --build-args at every build without changing our docker file.

For more details, you can refer this.

Is there Unicode glyph Symbol to represent "Search"

There is U+1F50D LEFT-POINTING MAGNIFYING GLASS () and U+1F50E RIGHT-POINTING MAGNIFYING GLASS ().

You should use (in HTML) &#x1F50D; or &#x1F50E;

They are, however not supported by many fonts (fileformat.info only lists a few fonts as supporting the Codepoint with a proper glyph).

Also note that they are outside of the BMP, so some Unicode-capable software might have problems rendering them, even if they have fonts that support them.

Generally Unicode Glyphs can be searched using a site such as fileformat.info. This searches "only" in the names and properties of the Unicode glyphs, but they usually contain enough metadata to allow for good search results (for this answer I searched for "glass" and browsed the resulting list, for example)

opening html from google drive

Now you can use https://sites.google.com

Build internal project hubs, team sites, public-facing websites, and more—all without designer, programmer, or IT help. With the new Google Sites, building websites is easy. Just drag content where you need it.

How to get current value of RxJS Subject or Observable?

Although it may sound overkill, this is just another "possible" solution to keep Observable type and reduce boilerplate...

You could always create an extension getter to get the current value of an Observable.

To do this you would need to extend the Observable<T> interface in a global.d.ts typings declaration file. Then implement the extension getter in a observable.extension.ts file and finally include both typings and extension file to your application.

You can refer to this StackOverflow Answer to know how to include the extensions into your Angular application.

// global.d.ts
declare module 'rxjs' {
  interface Observable<T> {
    /**
     * _Extension Method_ - Returns current value of an Observable.
     * Value is retrieved using _first()_ operator to avoid the need to unsubscribe.
     */
    value: Observable<T>;
  }
}

// observable.extension.ts
Object.defineProperty(Observable.prototype, 'value', {
  get <T>(this: Observable<T>): Observable<T> {
    return this.pipe(
      filter(value => value !== null && value !== undefined),
      first());
  },
});

// using the extension getter example
this.myObservable$.value
  .subscribe(value => {
    // whatever code you need...
  });

What Content-Type value should I send for my XML sitemap?

both are fine.

text/xxx means that in case the program does not understand xxx it makes sense to show the file to the user as plain text. application/xxx means that it is pointless to show it.

Please note that those content-types were originally defined for E-Mail attachment before they got later used in Web world.

How can I hide or encrypt JavaScript code?

One of the best compressors (not specifically an obfuscator) is the YUI Compressor.

How to securely save username/password (local)?

I have used this before and I think in order to make sure credential persist and in a best secure way is

  1. you can write them to the app config file using the ConfigurationManager class
  2. securing the password using the SecureString class
  3. then encrypting it using tools in the Cryptography namespace.

This link will be of great help I hope : Click here

@angular/material/index.d.ts' is not a module

I was also facing the same issue with the latest version of @angular/material i.e. "^9.2.3" So I found out a solution of this. If you go to the folder of @angular/material inside node_modules, you can find a file naming index.d.ts, in that file paste the below code. With this change in the index file you will be able to import the modules using import statements from @angular/material directly. (P.S. If you face error in any of the below statements please comment that.)

export * from '@angular/material/core';
export * from '@angular/material/icon';
export * from '@angular/material/autocomplete';
export * from '@angular/material/badge';
export * from '@angular/material/bottom-sheet';
export * from '@angular/material/button';
export * from '@angular/material/button-toggle';
export * from '@angular/material/card';
export * from '@angular/material/checkbox';
export * from '@angular/material/chips';
export * from '@angular/material/stepper';
export * from '@angular/material/datepicker'
export * from '@angular/material/dialog';
export * from '@angular/material/divider';
export * from '@angular/material/esm2015';
export * from '@angular/material/form-field';
export * from '@angular/material/esm5';
export * from '@angular/material/expansion';
export * from '@angular/material/grid-list';
export * from '@angular/material/icon';
export * from '@angular/material/input';
export * from '@angular/material/list';
export * from '@angular/material/menu';
export * from '@angular/material/paginator';
export * from '@angular/material/progress-bar';
export * from '@angular/material/progress-spinner';
export * from '@angular/material/radio';
export * from '@angular/material/stepper';
export * from '@angular/material/select';
export * from '@angular/material/sidenav';
export * from '@angular/material/slider';
export * from '@angular/material/slide-toggle';
export * from '@angular/material/snack-bar';
export * from '@angular/material/sort';
export * from '@angular/material/table';
export * from '@angular/material/tabs';
export * from '@angular/material/toolbar';
export * from '@angular/material/tooltip';
export * from '@angular/material/tree';

Bootstrap Responsive Text Size

Simplest way is to use dimensions in % or em. Just change the base font size everything will change.

Less

@media (max-width: @screen-xs) {
    body{font-size: 10px;}
}

@media (max-width: @screen-sm) {
    body{font-size: 14px;}
}


h5{
    font-size: 1.4rem;
}       

Look at all the ways at https://stackoverflow.com/a/21981859/406659

You could use viewport units (vh,vw...) but they dont work on Android < 4.4

Invert match with regexp

It's indeed almost a duplicate. I guess the regex you're looking for is

(?!foo).*

Concatenate two char* strings in a C program

The way it works is to:

  1. Malloc memory large enough to hold copies of str1 and str2
  2. Then it copies str1 into str3
  3. Then it appends str2 onto the end of str3
  4. When you're using str3 you'd normally free it free (str3);

Here's an example for you play with. It's very simple and has no hard-coded lengths. You can try it here: http://ideone.com/d3g1xs

See this post for information about size of char

#include <stdio.h>
#include <memory.h>

int main(int argc, char** argv) {

      char* str1;
      char* str2;
      str1 = "sssss";
      str2 = "kkkk";
      char * str3 = (char *) malloc(1 + strlen(str1)+ strlen(str2) );
      strcpy(str3, str1);
      strcat(str3, str2);
      printf("%s", str3);

      return 0;
 }

How do I rewrite URLs in a proxy response in NGINX

You can use the following nginx configuration example:

upstream adminhost {
  server adminhostname:8080;
}

server {
  listen 80;

  location ~ ^/admin/(.*)$ {
    proxy_pass http://adminhost/$1$is_args$args;
    proxy_redirect off;
    proxy_set_header Host $host;
    proxy_set_header X-Real-IP $remote_addr;
    proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
    proxy_set_header X-Forwarded-Host $server_name;
  }
}

"unable to locate adb" using Android Studio

  1. on your android studio at the top right corner beside the search icon you can find the SDK Manager.
  2. view android SDK location (this will show you your sdk path)
  3. navigate to file explorer on your system, and locate the file path, this should be found something like Windows=> c://Users/johndoe/AppData/local/android (you can now see the sdk.) Mac=>/Users/johndoe/Library/Android/sdk
  4. check the platform tools folder and see if you would see anything like adb.exe (it should be missing probably because it was corrupted and your antivirus or windows defender has quarantined it)
  5. delete the platform tools folder
  6. go back to android studio and from where you left off navigate to sdk tools (this should be right under android sdk location)
  7. uncheck android sdk platform-tools and select ok. (this will uninstall the platform tools from your ide) wait till it is done and then your gradle will sync.
  8. after sync is complete, go back and check the box of android sdk platform-tools (this will install a fresh one with new adb.exe) wait till it is done and sync project and then you are good to go.

I hope this saves someone some hours of pain.

How can I turn a JSONArray into a JSONObject?

Typically, a Json object would contain your values (including arrays) as named fields within. So, something like:

JSONObject jo = new JSONObject();
JSONArray ja = new JSONArray();
// populate the array
jo.put("arrayName",ja);

Which in JSON will be {"arrayName":[...]}.

How to retrieve current workspace using Jenkins Pipeline Groovy script?

A quick note for anyone who is using bat in the job and needs to access Workspace:

It won't work.

$WORKSPACE https://issues.jenkins-ci.org/browse/JENKINS-33511 as mentioned here only works with PowerShell. So your code should have powershell for execution

 stage('Verifying Workspace') {
  powershell label: '', script: 'dir $WORKSPACE'
}

How to pass parameters using ui-sref in ui-router to controller

You don't necessarily need to have the parameters inside the URL.

For instance, with:

$stateProvider
.state('home', {
  url: '/',
  views: {
    '': {
      templateUrl: 'home.html',
      controller: 'MainRootCtrl'

    },
  },
  params: {
    foo: null,
    bar: null
  }
})

You will be able to send parameters to the state, using either:

$state.go('home', {foo: true, bar: 1});
// or
<a ui-sref="home({foo: true, bar: 1})">Go!</a>

Of course, if you reload the page once on the home state, you will loose the state parameters, as they are not stored anywhere.

A full description of this behavior is documented here, under the params row in the state(name, stateConfig) section.

Positioning background image, adding padding

Updated Answer:

It's been commented multiple times that this is not the correct answer to this question, and I agree. Back when this answer was written, IE 9 was still new (about 8 months old) and many developers including myself needed a solution for <= IE 9. IE 9 is when IE started supporting background-origin. However, it's been over six and a half years, so here's the updated solution which I highly recommend over using an actual border. In case < IE 9 support is needed. My original answer can be found below the demo snippet. It uses an opaque border to simulate padding for background images.

_x000D_
_x000D_
#hello {
  padding-right: 10px;
  background-color:green;
  background: url("https://placehold.it/15/5C5/FFF") no-repeat scroll right center #e8e8e8;
  background-origin: content-box;
}
_x000D_
<p id="hello">I want the background icon to have padding to it too!I want the background icon twant the background icon to have padding to it too!I want the background icon to have padding to it too!I want the background icon to have padding to it too!</p>
_x000D_
_x000D_
_x000D_

Original Answer:

you can fake it with a 10px border of the same color as the background:

http://jsbin.com/eparad/edit#javascript,html,live

#hello {
   border: 10px solid #e8e8e8;
   background-color: green;
   background: url("http://www.costascuisine.com/images/buttons/collapseIcon.gif")
               no-repeat scroll right center #e8e8e8;
}

How do the PHP equality (== double equals) and identity (=== triple equals) comparison operators differ?

You would use === to test whether a function or variable is false rather than just equating to false (zero or an empty string).

$needle = 'a';
$haystack = 'abc';
$pos = strpos($haystack, $needle);
if ($pos === false) {
    echo $needle . ' was not found in ' . $haystack;
} else {
    echo $needle . ' was found in ' . $haystack . ' at location ' . $pos;
}

In this case strpos would return 0 which would equate to false in the test

if ($pos == false)

or

if (!$pos)

which is not what you want here.

How to send json data in POST request using C#

You can use either HttpClient or RestSharp. Since I do not know what your code is, here is an example using HttpClient:

using (var client = new HttpClient())
{
    // This would be the like http://www.uber.com
    client.BaseAddress = new Uri("Base Address/URL Address");

    // serialize your json using newtonsoft json serializer then add it to the StringContent
    var content = new StringContent(YourJson, Encoding.UTF8, "application/json") 

    // method address would be like api/callUber:SomePort for example
    var result = await client.PostAsync("Method Address", content);
    string resultContent = await result.Content.ReadAsStringAsync();   
}

How to set min-font-size in CSS

Use a media query. Example: This is something im using the original size is 1.0vw but when it hits 1000 the letter gets too small so I scale it up

@media(max-width:600px){
    body,input,textarea{
         font-size:2.0vw !important;
    }
}

This site I m working on is not responsive for >500px but you might need more. The pro,benefit for this solution is you keep font size scaling without having super mini letters and you can keep it js free.

Specified cast is not valid?

htmlStr is string then You need to Date and Time variables to string

while (reader.Read())
                {
                    DateTime Date = reader.GetDateTime(0);
                    DateTime Time = reader.GetDateTime(1);
                    htmlStr += "<tr><td>" + Date.ToString() + "</td><td>"  + 
                    Time.ToString() + "</td></tr>";                  
                }

PHP - Get key name of array value

Here is another option

$array = [1=>'one', 2=>'two', 3=>'there'];
$array = array_flip($array);
echo $array['one']; 

Constructors in JavaScript objects

So what is the point of "constructor" property? Cannot figure out where it could be useful, any ideas?

The point of the constructor property is to provide some way of pretending JavaScript has classes. One of the things you cannot usefully do is change an object's constructor after it's been created. It's complicated.

I wrote a fairly comprehensive piece on it a few years ago: http://joost.zeekat.nl/constructors-considered-mildly-confusing.html

Get content of a cell given the row and column numbers

Try =index(ARRAY, ROW, COLUMN)

where: Array: select the whole sheet Row, Column: Your row and column references

That should be easier to understand to those looking at the formula.

TypeError: got multiple values for argument

My issue was similar to Q---ten's, but in my case it was that I had forgotten to provide the self argument to a class function:

class A:
    def fn(a, b, c=True):
        pass

Should become

class A:
    def fn(self, a, b, c=True):
        pass

This faulty implementation is hard to see when calling the class method as:

a_obj = A()
a.fn(a_val, b_val, c=False)

Which will yield a TypeError: got multiple values for argument. Hopefully, the rest of the answers here are clear enough for anyone to be able to quickly understand and fix the error. If not, hope this answer helps you!

How do I change the default index page in Apache?

I recommend using .htaccess. You only need to add:

DirectoryIndex home.php

or whatever page name you want to have for it.

EDIT: basic htaccess tutorial.

1) Create .htaccess file in the directory where you want to change the index file.

  • no extension
  • . in front, to ensure it is a "hidden" file

Enter the line above in there. There will likely be many, many other things you will add to this (AddTypes for webfonts / media files, caching for headers, gzip declaration for compression, etc.), but that one line declares your new "home" page.

2) Set server to allow reading of .htaccess files (may only be needed on your localhost, if your hosting servce defaults to allow it as most do)

Assuming you have access, go to your server's enabled site location. I run a Debian server for development, and the default site setup is at /etc/apache2/sites-available/default for Debian / Ubuntu. Not sure what server you run, but just search for "sites-available" and go into the "default" document. In there you will see an entry for Directory. Modify it to look like this:

<Directory /var/www/>
    Options Indexes FollowSymLinks MultiViews
    AllowOverride None
    Order allow,deny
    allow from all
</Directory>

Then restart your apache server. Again, not sure about your server, but the command on Debian / Ubuntu is:

sudo service apache2 restart

Technically you only need to reload, but I restart just because I feel safer with a full refresh like that.

Once that is done, your site should be reading from your .htaccess file, and you should have a new default home page! A side note, if you have a sub-directory that runs a site (like an admin section or something) and you want to have a different "home page" for that directory, you can just plop another .htaccess file in that sub-site's root and it will overwrite the declaration in the parent.

In C++ check if std::vector<string> contains a certain value

it's in <algorithm> and called std::find.

GridLayout (not GridView) how to stretch all children evenly

Starting in API 21 without v7 support library with ScrollView:

enter image description here

XML:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    >

    <GridLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:columnCount="2"
            >

        <TextView
            android:layout_width="0dp"
            android:layout_height="100dp"
            android:layout_columnWeight="1"
            android:gravity="center"
            android:layout_gravity="fill_horizontal"
            android:background="@color/colorAccent"
            android:text="Tile1" />

        <TextView
            android:layout_width="0dp"
            android:layout_height="100dp"
            android:layout_columnWeight="1"
            android:gravity="center"
            android:layout_gravity="fill_horizontal"
            android:background="@color/colorPrimaryDark"
            android:text="Tile2" />

        <TextView
            android:layout_width="0dp"
            android:layout_height="100dp"
            android:layout_columnWeight="1"
            android:gravity="center"
            android:layout_gravity="fill_horizontal"
            android:background="@color/colorPrimary"
            android:text="Tile3" />

        <TextView
            android:layout_width="0dp"
            android:layout_height="100dp"
            android:layout_columnWeight="1"
            android:gravity="center"
            android:layout_gravity="fill_horizontal"
            android:background="@color/colorAccent"
            android:text="Tile4" />

    </GridLayout>
</ScrollView>

MySQL query to select events between start/end date

I am assuming that active events in a time period means at least one day of the event falls inside the time period. This is a simple "find overlapping dates" problem and there is a generic solution:

-- [@d1, @d2] is the date range to check against
SELECT * FROM events WHERE @d2 >= start AND end >= @d1

Some tests:

-- list of events
SELECT * FROM events;
+------+------------+------------+
| id   | start      | end        |
+------+------------+------------+
|    1 | 2013-06-14 | 2013-06-14 |
|    2 | 2013-06-15 | 2013-08-21 |
|    3 | 2013-06-22 | 2013-06-25 |
|    4 | 2013-07-01 | 2013-07-10 |
|    5 | 2013-07-30 | 2013-07-31 |
+------+------------+------------+

-- events between [2013-06-01, 2013-06-15]
SELECT * FROM events WHERE '2013-06-15' >= start AND end >= '2013-06-01';
+------+------------+------------+
| id   | start      | end        |
+------+------------+------------+
|    1 | 2013-06-14 | 2013-06-14 |
|    2 | 2013-06-15 | 2013-08-21 |
+------+------------+------------+

-- events between [2013-06-16, 2013-06-30]
SELECT * FROM events WHERE '2013-06-30' >= start AND end >= '2013-06-16';
+------+------------+------------+
| id   | start      | end        |
+------+------------+------------+
|    2 | 2013-06-15 | 2013-08-21 |
|    3 | 2013-06-22 | 2013-06-25 |
+------+------------+------------+

-- events between [2013-07-01, 2013-07-01]
SELECT * FROM events WHERE '2013-07-01' >= start AND end >= '2013-07-01';
+------+------------+------------+
| id   | start      | end        |
+------+------------+------------+
|    2 | 2013-06-15 | 2013-08-21 |
|    4 | 2013-07-01 | 2013-07-10 |
+------+------------+------------+

-- events between [2013-07-11, 2013-07-29]
SELECT * FROM events WHERE '2013-07-29' >= start AND end >= '2013-07-11';
+------+------------+------------+
| id   | start      | end        |
+------+------------+------------+
|    2 | 2013-06-15 | 2013-08-21 |
+------+------------+------------+

127 Return code from $?

This error is also at times deceiving. It says file is not found even though the files is indeed present. It could be because of invalid unreadable special characters present in the files that could be caused by the editor you are using. This link might help you in such cases.

-bash: ./my_script: /bin/bash^M: bad interpreter: No such file or directory

The best way to find out if it is this issue is to simple place an echo statement in the entire file and verify if the same error is thrown.

Summing radio input values

Your javascript is executed before the HTML is generated, so it doesn't "see" the ungenerated INPUT elements. For jQuery, you would either stick the Javascript at the end of the HTML or wrap it like this:

<script type="text/javascript">   $(function() { //jQuery trick to say after all the HTML is parsed.     $("input[type=radio]").click(function() {       var total = 0;       $("input[type=radio]:checked").each(function() {         total += parseFloat($(this).val());       });        $("#totalSum").val(total);     });   }); </script> 

EDIT: This code works for me

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> </head> <body>   <strong>Choose a base package:</strong>   <input id="item_0" type="radio" name="pkg" value="1942" />Base Package 1 - $1942   <input id="item_1" type="radio" name="pkg" value="2313" />Base Package 2 - $2313   <input id="item_2" type="radio" name="pkg" value="2829" />Base Package 3 - $2829   <strong>Choose an add on:</strong>   <input id="item_10" type="radio" name="ext" value="0" />No add-on - +$0   <input id="item_12" type="radio" name="ext" value="2146" />Add-on 1 - (+$2146)   <input id="item_13" type="radio" name="ext" value="2455" />Add-on 2 - (+$2455)   <input id="item_14" type="radio" name="ext" value="2764" />Add-on 3 - (+$2764)   <input id="item_15" type="radio" name="ext" value="3073" />Add-on 4 - (+$3073)   <input id="item_16" type="radio" name="ext" value="3382" />Add-on 5 - (+$3382)   <input id="item_17" type="radio" name="ext" value="3691" />Add-on 6 - (+$3691)   <strong>Your total is:</strong>   <input id="totalSum" type="text" name="totalSum" readonly="readonly" size="5" value="" />   <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>   <script type="text/javascript">       $("input[type=radio]").click(function() {         var total = 0;         $("input[type=radio]:checked").each(function() {           total += parseFloat($(this).val());         });          $("#totalSum").val(total);       });     </script> </body> </html> 

Get list of Excel files in a folder using VBA

Regarding the upvoted answer, I liked it except that if the resulting "listfiles" array is used in an array formula {CSE}, the list values come out all in a horizontal row. To make them come out in a vertical column, I simply made the array two dimensional as follows:

ReDim vaArray(1 To oFiles.Count, 0)
i = 1
For Each oFile In oFiles
    vaArray(i, 0) = oFile.Name
    i = i + 1
Next

Python 3 - ValueError: not enough values to unpack (expected 3, got 2)

1. First should understand the error meaning

Error not enough values to unpack (expected 3, got 2) means:

a 2 part tuple, but assign to 3 values

and I have written demo code to show for you:


#!/usr/bin/python
# -*- coding: utf-8 -*-
# Function: Showing how to understand ValueError 'not enough values to unpack (expected 3, got 2)'
# Author: Crifan Li
# Update: 20191212

def notEnoughUnpack():
    """Showing how to understand python error `not enough values to unpack (expected 3, got 2)`"""
    # a dict, which single key's value is two part tuple
    valueIsTwoPartTupleDict = {
        "name1": ("lastname1", "email1"),
        "name2": ("lastname2", "email2"),
    }

    # Test case 1: got value from key
    gotLastname, gotEmail = valueIsTwoPartTupleDict["name1"] # OK
    print("gotLastname=%s, gotEmail=%s" % (gotLastname, gotEmail))
    # gotLastname, gotEmail, gotOtherSomeValue = valueIsTwoPartTupleDict["name1"] # -> ValueError not enough values to unpack (expected 3, got 2)

    # Test case 2: got from dict.items()
    for eachKey, eachValues in valueIsTwoPartTupleDict.items():
        print("eachKey=%s, eachValues=%s" % (eachKey, eachValues))
    # same as following:
    # Background knowledge: each of dict.items() return (key, values)
    # here above eachValues is a tuple of two parts
    for eachKey, (eachValuePart1, eachValuePart2) in valueIsTwoPartTupleDict.items():
        print("eachKey=%s, eachValuePart1=%s, eachValuePart2=%s" % (eachKey, eachValuePart1, eachValuePart2))
    # but following:
    for eachKey, (eachValuePart1, eachValuePart2, eachValuePart3) in valueIsTwoPartTupleDict.items(): # will -> ValueError not enough values to unpack (expected 3, got 2)
        pass

if __name__ == "__main__":
    notEnoughUnpack()

using VSCode debug effect:

notEnoughUnpack CrifanLi

2. For your code

for name, email, lastname in unpaidMembers.items():

but error ValueError: not enough values to unpack (expected 3, got 2)

means each item(a tuple value) in unpaidMembers, only have 1 parts:email, which corresponding above code

    unpaidMembers[name] = email

so should change code to:

for name, email in unpaidMembers.items():

to avoid error.

But obviously you expect extra lastname, so should change your above code to

    unpaidMembers[name] = (email, lastname)

and better change to better syntax:

for name, (email, lastname) in unpaidMembers.items():

then everything is OK and clear.

How to set delay in vbscript

if it is VBScript, it should be

WScript.Sleep 100

If it is JavaScript

WScript.Sleep(100);

Time in milliseconds. WScript.Sleep 1000 results in a 1 second sleep.

AngularJS format JSON string output

I guess you want to use to edit the json text. Then you can use ivarni's way:

{{data | json}}
and add an adition attribute to make
 editable

<pre contenteditable="true">{{data | json}}</pre>

Hope this can help you.

How to get the home directory in Python?

I know this is an old thread, but I recently needed this for a large scale project (Python 3.8). It had to work on any mainstream OS, so therefore I went with the solution @Max wrote in the comments.

Code:

import os
print(os.path.expanduser("~"))

Output Windows:

PS C:\Python> & C:/Python38/python.exe c:/Python/test.py
C:\Users\mXXXXX

Output Linux (Ubuntu):

rxxx@xx:/mnt/c/Python$ python3 test.py
/home/rxxx

I also tested it on Python 2.7.17 and that works too.

jQuery .val change doesn't change input value

This is just a possible scenario which happened to me. Well if it helps someone then great: I wrote a complicated app which somewhere along the code I used a function to clear all textboxes values before showing them. Sometime later I tried to set a textbox value using jquery val('value') but I did'nt notice that right after that I invoked the ClearAllInputs method.. so, this could also happen.

file.delete() returns false even though file.exists(), file.canRead(), file.canWrite(), file.canExecute() all return true

if file.delete() is sending false then in most of the cases your Bufferedreader handle will not be closed. Just close and it seems to work for me normally.