Programs & Examples On #Ajaxpro

select2 onchange event only works once

This is what I am using:

$("#search_code").live('change', function(){
  alert(this.value)
});

For latest jQuery users, this one should work:

$(document.body).on("change","#search_code",function(){
 alert(this.value);
});

Expected response code 250 but got code "535", with message "535-5.7.8 Username and Password not accepted

I had the same problem, then I did this two steps:

  • Enable "Allow less secure apps" on your google account security policy.
  • Restart your local servers.

What is the difference between =Empty and IsEmpty() in VBA (Excel)?

Empty refers to a variable being at its default value. So if you check if a cell with a value of 0 = Empty then it would return true.

IsEmpty refers to no value being initialized.

In a nutshell, if you want to see if a cell is empty (as in nothing exists in its value) then use IsEmpty. If you want to see if something is currently in its default value then use Empty.

Nested lists python

You can do this. Adapt it to your situation:

  for l in Nlist:
      for item in l:
        print item

In Perl, how can I concisely check if a $variable is defined and contains a non zero length string?

It isn't always possible to do repetitive things in a simple and elegant way.

Just do what you always do when you have common code that gets replicated across many projects:

Search CPAN, someone may have already the code for you. For this issue I found Scalar::MoreUtils.

If you don't find something you like on CPAN, make a module and put the code in a subroutine:

package My::String::Util;
use strict;
use warnings;
our @ISA = qw( Exporter );
our @EXPORT = ();
our @EXPORT_OK = qw( is_nonempty);

use Carp  qw(croak);

sub is_nonempty ($) {
    croak "is_nonempty() requires an argument" 
        unless @_ == 1;

    no warnings 'uninitialized';

    return( defined $_[0] and length $_[0] != 0 );
}

1;

=head1 BOILERPLATE POD

blah blah blah

=head3 is_nonempty

Returns true if the argument is defined and has non-zero length.    

More boilerplate POD.

=cut

Then in your code call it:

use My::String::Util qw( is_nonempty );

if ( is_nonempty $name ) {
    # do something with $name
}

Or if you object to prototypes and don't object to the extra parens, skip the prototype in the module, and call it like: is_nonempty($name).

Concatenate multiple result rows of one column into one, group by another column

You can use array_agg function for that:

SELECT "Movie",
array_to_string(array_agg(distinct "Actor"),',') AS Actor
FROM Table1
GROUP BY "Movie";

Result:

MOVIE ACTOR
A 1,2,3
B 4

See this SQLFiddle

For more See 9.18. Aggregate Functions

Differences between SP initiated SSO and IDP initiated SSO

In IDP Init SSO (Unsolicited Web SSO) the Federation process is initiated by the IDP sending an unsolicited SAML Response to the SP. In SP-Init, the SP generates an AuthnRequest that is sent to the IDP as the first step in the Federation process and the IDP then responds with a SAML Response. IMHO ADFSv2 support for SAML2.0 Web SSO SP-Init is stronger than its IDP-Init support re: integration with 3rd Party Fed products (mostly revolving around support for RelayState) so if you have a choice you'll want to use SP-Init as it'll probably make life easier with ADFSv2.

Here are some simple SSO descriptions from the PingFederate 8.0 Getting Started Guide that you can poke through that may help as well -- https://documentation.pingidentity.com/pingfederate/pf80/index.shtml#gettingStartedGuide/task/idpInitiatedSsoPOST.html

Setting up and using environment variables in IntelliJ Idea

It is possible to reference an intellij 'Path Variable' in an intellij 'Run Configuration'.

In 'Path Variables' create a variable for example ANALYTICS_VERSION.

In a 'Run Configuration' under 'Environment Variables' add for example the following:

ANALYTICS_LOAD_LOCATION=$MAVEN_REPOSITORY$\com\my\company\analytics\$ANALYTICS_VERSION$\bin

To answer the original question you would need to add an APP_HOME environment variable to your run configuration which references the path variable:

APP_HOME=$APP_HOME$

Calculating and printing the nth prime number

I just added the missing lines in your own thought process.

static int nthPrimeFinder(int n) {

        int counter = 1; // For 1 and 2. assuming n is not 1 or 2.
        int i = 2;
        int x = 2;
        int tempLength = n;

        while (counter <= n) {
            for (; i <= tempLength; i++) {
                for (x = 2; x < i; x++) {
                    if (i % x == 0) {
                        break;
                    }
                }
                if (x == i && counter < n) {
                    //System.out.printf("\n%d is prime", x);
                    counter++;
                    if (counter == n) {
                        System.out.printf("\n%d is prime", x);
                        return counter;
                    }
                }
            }
            tempLength = tempLength+n;
        }
        return 0;
    }

How do I calculate square root in Python?

What you're seeing is integer division. To get floating point division by default,

from __future__ import division

Or, you could convert 1 or 2 of 1/2 into a floating point value.

sqrt = x**(1.0/2)

Enabling/installing GD extension? --without-gd

I've PHP 7.3 and Nginx 1.14 on Ubuntu 18.

# it installs php7.3-gd for the moment
# and restarts PHP 7.3 FastCGI Process Manager: php-fpm7.3.
sudo apt-get install php-gd

# after I've restarted Nginx
sudo /etc/init.d/nginx restart

Works!

tell pip to install the dependencies of packages listed in a requirement file

simplifily, use:

pip install -r requirement.txt

it can install all listed in requirement file.

The SELECT permission was denied on the object 'Users', database 'XXX', schema 'dbo'

This is how I was able to solve the problem when I faced it

  1. Start SQL Management Studio.
  2. Expand the Server Node (in the 'Object Explorer').
  3. Expand the Databases Node and then expand the specific Database which you are trying to access using the specific user.
  4. Expand the Users node under the Security node for the database.
  5. Right click the specific user and click 'properties'. You will get a dialog box.
  6. Make sure the user is a member of the db_owner group (please read the comments below before you use go this path) and other required changes using the view. (I used this for 2016. Not sure how the specific dialog look like in other version and hence not being specific)

Angular 2 Unit Tests: Cannot find name 'describe'

With [email protected] or later you can install types with npm install

npm install --save-dev @types/jasmine

then import the types automatically using the typeRoots option in tsconfig.json.

"typeRoots": [
      "node_modules/@types"
    ],

This solution does not require import {} from 'jasmine'; in each spec file.

How do I open a Visual Studio project in design view?

You can double click directly on the .cs file representing your form in the Solution Explorer :

Solution explorer with Design View circled

This will open Form1.cs [Design], which contains the drag&drop controls.

If you are directly in the code behind (The file named Form1.cs, without "[Design]"), you can press Shift + F7 (or only F7 depending on the project type) instead to open it.

From the design view, you can switch back to the Code Behind by pressing F7.

Case insensitive string as HashMap key

You can use a HashingStrategy based Map from Eclipse Collections

HashingStrategy<String> hashingStrategy =
    HashingStrategies.fromFunction(String::toUpperCase);
MutableMap<String, String> node = HashingStrategyMaps.mutable.of(hashingStrategy);

Note: I am a contributor to Eclipse Collections.

What is a NullPointerException, and how do I fix it?

A null pointer exception is an indicator that you are using an object without initializing it.

For example, below is a student class which will use it in our code.

public class Student {

    private int id;

    public int getId() {
        return this.id;
    }

    public setId(int newId) {
        this.id = newId;
    }
}

The below code gives you a null pointer exception.

public class School {

    Student student;

    public School() {
        try {
            student.getId();
        }
        catch(Exception e) {
            System.out.println("Null pointer exception");
        }
    }
}

Because you are using student, but you forgot to initialize it like in the correct code shown below:

public class School {

    Student student;

    public School() {
        try {
            student = new Student();
            student.setId(12);
            student.getId();
        }
        catch(Exception e) {
            System.out.println("Null pointer exception");
        }
    }
}

How do I see all foreign keys to a table or column?

A quick way to list your FKs (Foreign Key references) using the

KEY_COLUMN_USAGE view:

SELECT CONCAT( table_name, '.',
column_name, ' -> ',
referenced_table_name, '.',
referenced_column_name ) AS list_of_fks
FROM information_schema.KEY_COLUMN_USAGE
WHERE REFERENCED_TABLE_SCHEMA = (your schema name here)
AND REFERENCED_TABLE_NAME is not null
ORDER BY TABLE_NAME, COLUMN_NAME;

This query does assume that the constraints and all referenced and referencing tables are in the same schema.

Add your own comment.

Source: the official mysql manual.

How do I revert back to an OpenWrt router configuration?

Those who are facing this problem: Don't panic.

Short answer:

Restart your router, and this problem will be fixed. (But if your restart button is not working, you need to do a nine-step process to do the restart. Hitting the restart button is just one of them.)

Long answer: Let's learn how to restart the router.

  1. Set your PC's IP address: 192.168.1.2 and subnetmask 255.255.255.0 and gateway 192.168.1.1
  2. Power off the router
  3. Disconnect the WAN cable
  4. Only connect your PC Ethernet cable to ETH0
  5. Power on the router
  6. Wait for the router to start the boot sequence (SYS LED starts blinking)
  7. When the SYS LED is blinking, hit the restart button (the SYS LED will be blinking at a faster rate means your router is in failsafe mode). (You have to hit the button before the router boots.)
  8. telnet 192.168.1.1
  9. Run these commands:

    mount_root ## this remounts your partitions from read-only to read/write mode
    
    firstboot  ## This will reset your router after reboot
    
    reboot -f ## And force reboot
    
  10. Log in the web interface using web browser.

link to see the official failsafe mode.

Looping through the content of a file in Bash

cat peptides.txt | while read line 
do
   # do something with $line here
done

and the one-liner variant:

cat peptides.txt | while read line; do something_with_$line_here; done

These options will skip the last line of the file if there is no trailing line feed.

You can avoid this by the following:

cat peptides.txt | while read line || [[ -n $line ]];
do
   # do something with $line here
done

entity object cannot be referenced by multiple instances of IEntityChangeTracker. while adding related objects to entity in Entity Framework 4.1

In my case, I was using the ASP.NET Identity Framework. I had used the built in UserManager.FindByNameAsync method to retrieve an ApplicationUser entity. I then tried to reference this entity on a newly created entity on a different DbContext. This resulted in the exception you originally saw.

I solved this by creating a new ApplicationUser entity with only the Id from the UserManager method and referencing that new entity.

Check variable equality against a list of values

var a = [1,2,3];

if ( a.indexOf( 1 ) !== -1 ) { }

Note that indexOf is not in the core ECMAScript. You'll need to have a snippet for IE and possibly other browsers that dont support Array.prototype.indexOf.

if (!Array.prototype.indexOf)
{
  Array.prototype.indexOf = function(searchElement /*, fromIndex */)
  {
    "use strict";

    if (this === void 0 || this === null)
      throw new TypeError();

    var t = Object(this);
    var len = t.length >>> 0;
    if (len === 0)
      return -1;

    var n = 0;
    if (arguments.length > 0)
    {
      n = Number(arguments[1]);
      if (n !== n)
        n = 0;
      else if (n !== 0 && n !== (1 / 0) && n !== -(1 / 0))
        n = (n > 0 || -1) * Math.floor(Math.abs(n));
    }

    if (n >= len)
      return -1;

    var k = n >= 0
          ? n
          : Math.max(len - Math.abs(n), 0);

    for (; k < len; k++)
    {
      if (k in t && t[k] === searchElement)
        return k;
    }
    return -1;
  };
}

What are the aspect ratios for all Android phone and tablet devices?

I researched the same thing several months ago looking at dozens of the most popular Android devices. I found that every Android device had one of the following aspect ratios (from most square to most rectangular):

  • 4:3
  • 3:2
  • 8:5
  • 5:3
  • 16:9

And if you consider portrait devices separate from landscape devices you'll also find the inverse of those ratios (3:4, 2:3, 5:8, 3:5, and 9:16)


More complete answer here: stackoverflow community spreadsheet of Android device resolutions and DPIs

Returning data from Axios API

axiosTest() is firing asynchronously and not being waited for.

A then() function needs to be hooked up afterwards in order to capture the response variable (axiosTestData).

See Promise for more info.

See Async to level up.

_x000D_
_x000D_
// Dummy Url._x000D_
const url = 'https://jsonplaceholder.typicode.com/posts/1'_x000D_
_x000D_
// Axios Test._x000D_
const axiosTest = axios.get_x000D_
_x000D_
// Axios Test Data._x000D_
axiosTest(url).then(function(axiosTestResult) {_x000D_
  console.log('response.JSON:', {_x000D_
    message: 'Request received',_x000D_
    data: axiosTestResult.data_x000D_
  })_x000D_
})
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/axios/0.18.0/axios.js"></script>
_x000D_
_x000D_
_x000D_

How can I use std::maps with user-defined types as key?

You don't have to define operator< for your class, actually. You can also make a comparator function object class for it, and use that to specialize std::map. To extend your example:

struct Class1Compare
{
   bool operator() (const Class1& lhs, const Class1& rhs) const
   {
       return lhs.id < rhs.id;
   }
};

std::map<Class1, int, Class1Compare> c2int;

It just so happens that the default for the third template parameter of std::map is std::less, which will delegate to operator< defined for your class (and fail if there is none). But sometimes you want objects to be usable as map keys, but you do not actually have any meaningful comparison semantics, and so you don't want to confuse people by providing operator< on your class just for that. If that's the case, you can use the above trick.

Yet another way to achieve the same is to specialize std::less:

namespace std
{
    template<> struct less<Class1>
    {
       bool operator() (const Class1& lhs, const Class1& rhs) const
       {
           return lhs.id < rhs.id;
       }
    };
}

The advantage of this is that it will be picked by std::map "by default", and yet you do not expose operator< to client code otherwise.

Can I force a UITableView to hide the separator between empty cells?

You can achieve what you want by defining a footer for the tableview. See this answer for more details:Eliminate Extra separators below UITableView

How to "select distinct" across multiple data frame columns in pandas?

You can take the sets of the columns and just subtract the smaller set from the larger set:

distinct_values = set(df['a'])-set(df['b'])

Regex for string contains?

Assuming regular PCRE-style regex flavors:

If you want to check for it as a single, full word, it's \bTest\b, with appropriate flags for case insensitivity if desired and delimiters for your programming language. \b represents a "word boundary", that is, a point between characters where a word can be considered to start or end. For example, since spaces are used to separate words, there will be a word boundary on either side of a space.

If you want to check for it as part of the word, it's just Test, again with appropriate flags for case insensitivity. Note that usually, dedicated "substring" methods tend to be faster in this case, because it removes the overhead of parsing the regex.

Replace Fragment inside a ViewPager

after research i found solution with short code. first of all create a public instance on fragment and just remove your fragment on onSaveInstanceState if fragment not recreating on orientation change.

 @Override
public void onSaveInstanceState(Bundle outState) {
    if (null != mCalFragment) {
        FragmentTransaction bt = getChildFragmentManager().beginTransaction();
        bt.remove(mFragment);
        bt.commit();
    }
    super.onSaveInstanceState(outState);
}

Regex Named Groups in Java

For people coming to this late: Java 7 adds named groups. Matcher.group(String groupName) documentation.

Difference Between $.getJSON() and $.ajax() in jQuery

There is lots of confusion in some of the function of jquery like $.ajax, $.get, $.post, $.getScript, $.getJSON that what is the difference among them which is the best, which is the fast, which to use and when so below is the description of them to make them clear and to get rid of this type of confusions.

$.getJSON() function is a shorthand Ajax function (internally use $.get() with data type script), which is equivalent to below expression, Uses some limited criteria like Request type is GET and data Type is json.

Read More .. jquery-post-vs-get-vs-ajax

Select rows with same id but different value in another column

You can simply achieve it by

SELECT *
FROM test
WHERE ARIDNR IN
    (SELECT ARIDNR FROM test
     GROUP BY ARIDNR
     HAVING COUNT(*) > 1)
GROUP BY ARIDNR, LIEFNR;

Thanks.

Run Batch File On Start-up

RunOnce

RunOnce is an option and have a few keys that can be used for pointing a command to start on startup (depending if it concerns a user or the whole system):

HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\Run
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run
HKEY_LOCAL_MACHINE\Software\Microsoft\Windows\CurrentVersion\RunOnce
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunOnce

setting the value:

reg add "HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\RunOnce" /v MyBat /D "!C:\mybat.bat"

With setting and exclamation mark at the beginning and if the script exist with a value different than 0 the registry key wont be deleted and the script will be executed every time on startup

SCHTASKS

You can use SCHTASKS and a triggering event:

SCHTASKS /Create /SC ONEVENT /MO ONLOGON /TN ON_LOGON /tr "c:\some.bat" 

or

SCHTASKS /Create /SC ONEVENT /MO ONSTART/TN ON_START /tr "c:\some.bat"

Startup Folder

You also have two startup folders - one for the current user and one global. There you can copy your scripts (or shortcuts) in order to start a file on startup

::the global one
C:\ProgramData\Microsoft\Windows\Start Menu\Programs\StartUp
::for the current user
%USERPROFILE%\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup

Regex: Remove lines containing "help", etc

Easy task with grep:

grep -v help filename

Append > newFileName to redirect output to a new file.


Update

To clarify it, the normal behavior will be printing the lines on screen. To pipe it to a file, the > can be used. Thus, in this command:

grep -v help filename > newFileName
  1. grep calls the grep program, obviously
  2. -v is a flag to inverse the output. By defaulf, grep prints the lines that match the given pattern. With this flag, it will print the lines that don't match the pattern.
  3. help is the pattern to match
  4. filename is the name of the input file
  5. > redirects the output to the following item
  6. newFileName the new file where output will be saved.

As you may noticed, you will not be deleting things in your file. grep will read it and another file will be saved, modified accordingly.

Return generated pdf using spring MVC

You were on the right track with response.getOutputStream(), but you're not using its output anywhere in your code. Essentially what you need to do is to stream the PDF file's bytes directly to the output stream and flush the response. In Spring you can do it like this:

@RequestMapping(value="/getpdf", method=RequestMethod.POST)
public ResponseEntity<byte[]> getPDF(@RequestBody String json) {
    // convert JSON to Employee 
    Employee emp = convertSomehow(json);

    // generate the file
    PdfUtil.showHelp(emp);

    // retrieve contents of "C:/tmp/report.pdf" that were written in showHelp
    byte[] contents = (...);

    HttpHeaders headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_PDF);
    // Here you have to set the actual filename of your pdf
    String filename = "output.pdf";
    headers.setContentDispositionFormData(filename, filename);
    headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
    ResponseEntity<byte[]> response = new ResponseEntity<>(contents, headers, HttpStatus.OK);
    return response;
}

Notes:

  • use meaningful names for your methods: naming a method that writes a PDF document showHelp is not a good idea
  • reading a file into a byte[]: example here
  • I'd suggest adding a random string to the temporary PDF file name inside showHelp() to avoid overwriting the file if two users send a request at the same time

display: inline-block extra margin

Can you post a link to the HTML in question?

Ultimately you should be able to do:

div {
    margin:0;
    padding: 0;
}

to remove the spacing. Is this just in one particular browser or all of them?

Cannot open include file with Visual Studio

By default, Visual Studio searches for headers in the folder where your project is ($ProjectDir) and in the default standard libraries directories. If you need to include something that is not placed in your project directory, you need to add the path to the folder to include:

Go to your Project properties (Project -> Properties -> Configuration Properties -> C/C++ -> General) and in the field Additional Include Directories add the path to your .h file.

You can, also, as suggested by Chris Olen, add the path to VC++ Directories field.

In android how to set navigation drawer header image and name programmatically in class file?

EDIT : Works with design library upto 23.0.1 but doesn't work on 23.1.0

In main layout xml you will have NavigationView defined, in that use app:headerLayout to set the header view.

<android.support.design.widget.NavigationView
        android:id="@+id/navigation_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:headerLayout="@layout/nav_drawer_header"
        app:menu="@menu/navigation_drawer_menu" />

And the @layout/nav_drawer_header will be the place holder of the image and texts.

nav_drawer_header.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="170dp"
android:orientation="vertical">

<RelativeLayout
    android:id="@+id/headerRelativeLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:scaleType="fitXY"
        android:src="@drawable/background" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="@dimen/action_bar_size"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:background="#40000000"
        android:gravity="center"
        android:orientation="horizontal"
        android:paddingBottom="5dp"
        android:paddingLeft="16dp"
        android:paddingRight="10dp"
        android:paddingTop="5dp">

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_marginLeft="35dp"
            android:orientation="vertical"
            android:weightSum="2">


            <TextView
                android:id="@+id/navHeaderTitle"
                android:layout_width="wrap_content"
                android:layout_height="0dp"
                android:layout_weight="1"
                android:textAppearance="?android:attr/textAppearanceMedium"
                android:textColor="@android:color/white" />

            <TextView
                android:id="@+id/navHeaderSubTitle"
                android:layout_width="wrap_content"
                android:layout_height="0dp"
                android:layout_weight="1"
                android:textAppearance="?android:attr/textAppearanceSmall"
                android:textColor="@android:color/white" />

        </LinearLayout>

    </LinearLayout>
</RelativeLayout>
</LinearLayout>

And in your main class, you can take handle of Imageview and TextView as like normal other views.

TextView navHeaderTitle = (TextView) findViewById(R.id.navHeaderTitle);
navHeaderTitle.setText("Application Name");

TextView navHeaderSubTitle = (TextView) findViewById(R.id.navHeaderSubTitle);
navHeaderSubTitle.setText("Application Caption");

Hope this helps.

How to change TextField's height and width?

You can simply wrap Text field widget in padding widget..... Like this,

Padding(
         padding: EdgeInsets.only(left: 5.0, right: 5.0),
          child: TextField(
            cursorColor: Colors.blue,

            decoration: InputDecoration(
                labelText: 'Email',
                hintText: '[email protected]',
                //labelStyle: textStyle,
              border: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(5),
                  borderSide: BorderSide(width: 2, color: Colors.blue,)),
              focusedBorder: OutlineInputBorder(
                  borderRadius: BorderRadius.circular(10),
                  borderSide: BorderSide(width: 2, color: Colors.green)),
                )

            ),
          ),

manage.py runserver

I had the same problem and here was my way to solve it:

First, You must know your IP address. On my Windows PC, in the cmd windows i run ipconfig and select my IP V4 address. In my case 192.168.0.13

Second as mention above: runserver 192.168.0.13:8000

It worked for me. The error i did to get the message was the use of the gateway address not my PC address.

Removing Java 8 JDK from Mac

Two ways you can do that:

  1. Removing JDK directly from Users-> Library -> Java -> VirtualMachines -> then delete the jdk folder directly to uninstall the java.

  2. By following the command: (uninstall java 1.8 version )

make sure you are in home directory by using below command, before you write the command:

cd ~/

sudo rm -rf /Library/Java/JavaVirtualMachines/jdk1.8.jdk
sudo rm -rf /Library/PreferencePanes/JavaControlPanel.prefPane
sudo rm -rf /Library/Internet\ Plug-Ins/JavaAppletPlugin.plugin
sudo rm -rf /Library/Application\ Support/Oracle/Java

Cannot catch toolbar home button click event

Try this code

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if(id == android.R.id.home){
        //You can get 
    }
    return super.onOptionsItemSelected(item);
}

Add below code to your onCreate() metod

ActionBar ab = getSupportActionBar();
    ab.setDisplayHomeAsUpEnabled(true);

Android open camera from button

For me this worked perfectly fine .

 Intent intent=new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
 startActivity(intent);

and add this permission to mainfest file:

<uses-permission android:name="android.permission.CAMERA">

It opens the camera,after capturing the image it saves the image to gallery with a new image set.

Get all column names of a DataTable into string array using (LINQ/Predicate)

I'd suggest using such extension method:

public static class DataColumnCollectionExtensions
{
    public static IEnumerable<DataColumn> AsEnumerable(this DataColumnCollection source)
    {
        return source.Cast<DataColumn>();
    }
}

And therefore:

string[] columnNames = dataTable.Columns.AsEnumerable().Select(column => column.Name).ToArray();

You may also implement one more extension method for DataTable class to reduce code:

public static class DataTableExtensions
{
    public static IEnumerable<DataColumn> GetColumns(this DataTable source)
    {
        return source.Columns.AsEnumerable();
    }
}

And use it as follows:

string[] columnNames = dataTable.GetColumns().Select(column => column.Name).ToArray();

How to run TestNG from command line

Below command works for me. Provided that all required jars including testng jar kept inside lib.

java -cp "lib/*" org.testng.TestNG testng.xml

How to find index of all occurrences of element in array?

const indexes = cars
    .map((car, i) => car === "Nano" ? i : null)
    .filter(i => i !== null)

Decode UTF-8 with Javascript

You should take decodeURI for it.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/decodeURI

As simple as this:

decodeURI('https://developer.mozilla.org/ru/docs/JavaScript_%D1%88%D0%B5%D0%BB%D0%BB%D1%8B');
// "https://developer.mozilla.org/ru/docs/JavaScript_?????"

Consider to use it inside try catch block for not missing an URIError.

Also it has full browsers support.

Android: show soft keyboard automatically when focus is on an EditText

This is good sample for you :

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

    <ScrollView
        android:id="@+id/scrollID"
        android:layout_width="fill_parent"
        android:layout_height="0dip"
        android:layout_weight="1" >

        <LinearLayout
            android:id="@+id/test"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:orientation="vertical" >
        </LinearLayout>
    </ScrollView>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:baselineAligned="true"
        android:orientation="horizontal"
        android:paddingBottom="5dp"
        android:paddingLeft="5dp"
        android:paddingRight="5dp"
        android:weightSum="1" >

        <EditText
            android:id="@+id/txtInpuConversation"
            android:layout_width="0dip"
            android:layout_height="wrap_content"
            android:layout_weight="0.5"
            android:hint="@string/edt_Conversation" >

            <requestFocus />
        </EditText>

        <Button
            android:id="@+id/btnSend"
            android:layout_width="0dip"
            android:layout_height="wrap_content"
            android:layout_weight="0.5"
            android:text="@string/btn_Conversation" />
    </LinearLayout>

</LinearLayout>

Add a new element to an array without specifying the index in Bash

Yes there is:

ARRAY=()
ARRAY+=('foo')
ARRAY+=('bar')

Bash Reference Manual:

In the context where an assignment statement is assigning a value to a shell variable or array index (see Arrays), the ‘+=’ operator can be used to append to or add to the variable's previous value.

What Vim command(s) can be used to quote/unquote words?

VIM for vscode does it awsomely. It's based one vim-surround if you don't use vscode.

Some examples:

"test" with cursor inside quotes type cs"' to end up with 'test'

"test" with cursor inside quotes type ds" to end up with test

"test" with cursor inside quotes type cs"t and enter 123> to end up with <123>test

test with cursor on word test type ysaw) to end up with (test)

What is pluginManagement in Maven's pom.xml?

pluginManagement: is an element that is seen along side plugins. Plugin Management contains plugin elements in much the same way, except that rather than configuring plugin information for this particular project build, it is intended to configure project builds that inherit from this one. However, this only configures plugins that are actually referenced within the plugins element in the children. The children have every right to override pluginManagement definitions.

From http://maven.apache.org/pom.html#Plugin%5FManagement

Copied from :

Maven2 - problem with pluginManagement and parent-child relationship

IllegalArgumentException or NullPointerException for a null parameter?

NullPointerException thrown when attempting to access an object with a reference variable whose current value is null.

IllegalArgumentException thrown when a method receives an argument formatted differently than the method expects.

Regular Expression to select everything before and up to a particular text

((\n.*){0,3})(.*)\W*\.txt

This will select all the content before the particular word ".txt" including any context in different lines up to 3 lines

The declared package does not match the expected package ""

In my case I selected the error marker in the Problems tab and deleted it since the Java's file main method was being executed correctly. That is some glitch in Eclipse Neon with the multitude of plugins it has installed.

Android REST client, Sample?

EDIT 2 (October 2017):

It is 2017. Just use Retrofit. There is almost no reason to use anything else.

EDIT:

The original answer is more than a year and a half old at the time of this edit. Although the concepts presented in original answer still hold, as other answers point out, there are now libraries out there that make this task easier for you. More importantly, some of these libraries handle device configuration changes for you.

The original answer is retained below for reference. But please also take the time to examine some of the Rest client libraries for Android to see if they fit your use cases. The following is a list of some of the libraries I've evaluated. It is by no means intended to be an exhaustive list.


Original Answer:

Presenting my approach to having REST clients on Android. I do not claim it is the best though :) Also, note that this is what I came up with in response to my requirement. You might need to have more layers/add more complexity if your use case demands it. For example, I do not have local storage at all; because my app can tolerate loss of a few REST responses.

My approach uses just AsyncTasks under the covers. In my case, I "call" these Tasks from my Activity instance; but to fully account for cases like screen rotation, you might choose to call them from a Service or such.

I consciously chose my REST client itself to be an API. This means, that the app which uses my REST client need not even be aware of the actual REST URL's and the data format used.

The client would have 2 layers:

  1. Top layer: The purpose of this layer is to provide methods which mirror the functionality of the REST API. For example, you could have one Java method corresponding to every URL in your REST API (or even two - one for GETs and one for POSTs).
    This is the entry point into the REST client API. This is the layer the app would use normally. It could be a singleton, but not necessarily.
    The response of the REST call is parsed by this layer into a POJO and returned to the app.

  2. This is the lower level AsyncTask layer, which uses HTTP client methods to actually go out and make that REST call.

In addition, I chose to use a Callback mechanism to communicate the result of the AsyncTasks back to the app.

Enough of text. Let's see some code now. Lets take a hypothetical REST API URL - http://myhypotheticalapi.com/user/profile

The top layer might look like this:

   /**
 * Entry point into the API.
 */
public class HypotheticalApi{   
    public static HypotheticalApi getInstance(){
        //Choose an appropriate creation strategy.
    }
    
    /**
     * Request a User Profile from the REST server.
     * @param userName The user name for which the profile is to be requested.
     * @param callback Callback to execute when the profile is available.
     */
    public void getUserProfile(String userName, final GetResponseCallback callback){
        String restUrl = Utils.constructRestUrlForProfile(userName);
        new GetTask(restUrl, new RestTaskCallback (){
            @Override
            public void onTaskComplete(String response){
                Profile profile = Utils.parseResponseAsProfile(response);
                callback.onDataReceived(profile);
            }
        }).execute();
    }
    
    /**
     * Submit a user profile to the server.
     * @param profile The profile to submit
     * @param callback The callback to execute when submission status is available.
     */
    public void postUserProfile(Profile profile, final PostCallback callback){
        String restUrl = Utils.constructRestUrlForProfile(profile);
        String requestBody = Utils.serializeProfileAsString(profile);
        new PostTask(restUrl, requestBody, new RestTaskCallback(){
            public void onTaskComplete(String response){
                callback.onPostSuccess();
            }
        }).execute();
    }
}


/**
 * Class definition for a callback to be invoked when the response data for the
 * GET call is available.
 */
public abstract class GetResponseCallback{
    
    /**
     * Called when the response data for the REST call is ready. <br/>
     * This method is guaranteed to execute on the UI thread.
     * 
     * @param profile The {@code Profile} that was received from the server.
     */
    abstract void onDataReceived(Profile profile);
    
    /*
     * Additional methods like onPreGet() or onFailure() can be added with default implementations.
     * This is why this has been made and abstract class rather than Interface.
     */
}

/**
 * 
 * Class definition for a callback to be invoked when the response for the data 
 * submission is available.
 * 
 */
public abstract class PostCallback{
    /**
     * Called when a POST success response is received. <br/>
     * This method is guaranteed to execute on the UI thread.
     */
    public abstract void onPostSuccess();

}

Note that the app doesn't use the JSON or XML (or whatever other format) returned by the REST API directly. Instead, the app only sees the bean Profile.

Then, the lower layer (AsyncTask layer) might look like this:

/**
 * An AsyncTask implementation for performing GETs on the Hypothetical REST APIs.
 */
public class GetTask extends AsyncTask<String, String, String>{
    
    private String mRestUrl;
    private RestTaskCallback mCallback;
    
    /**
     * Creates a new instance of GetTask with the specified URL and callback.
     * 
     * @param restUrl The URL for the REST API.
     * @param callback The callback to be invoked when the HTTP request
     *            completes.
     * 
     */
    public GetTask(String restUrl, RestTaskCallback callback){
        this.mRestUrl = restUrl;
        this.mCallback = callback;
    }
    
    @Override
    protected String doInBackground(String... params) {
        String response = null;
        //Use HTTP Client APIs to make the call.
        //Return the HTTP Response body here.
        return response;
    }
    
    @Override
    protected void onPostExecute(String result) {
        mCallback.onTaskComplete(result);
        super.onPostExecute(result);
    }
}

    /**
     * An AsyncTask implementation for performing POSTs on the Hypothetical REST APIs.
     */
    public class PostTask extends AsyncTask<String, String, String>{
        private String mRestUrl;
        private RestTaskCallback mCallback;
        private String mRequestBody;
        
        /**
         * Creates a new instance of PostTask with the specified URL, callback, and
         * request body.
         * 
         * @param restUrl The URL for the REST API.
         * @param callback The callback to be invoked when the HTTP request
         *            completes.
         * @param requestBody The body of the POST request.
         * 
         */
        public PostTask(String restUrl, String requestBody, RestTaskCallback callback){
            this.mRestUrl = restUrl;
            this.mRequestBody = requestBody;
            this.mCallback = callback;
        }
        
        @Override
        protected String doInBackground(String... arg0) {
            //Use HTTP client API's to do the POST
            //Return response.
        }
        
        @Override
        protected void onPostExecute(String result) {
            mCallback.onTaskComplete(result);
            super.onPostExecute(result);
        }
    }
    
    /**
     * Class definition for a callback to be invoked when the HTTP request
     * representing the REST API Call completes.
     */
    public abstract class RestTaskCallback{
        /**
         * Called when the HTTP request completes.
         * 
         * @param result The result of the HTTP request.
         */
        public abstract void onTaskComplete(String result);
    }

Here's how an app might use the API (in an Activity or Service):

HypotheticalApi myApi = HypotheticalApi.getInstance();
        myApi.getUserProfile("techie.curious", new GetResponseCallback() {

            @Override
            void onDataReceived(Profile profile) {
                //Use the profile to display it on screen, etc.
            }
            
        });
        
        Profile newProfile = new Profile();
        myApi.postUserProfile(newProfile, new PostCallback() {
            
            @Override
            public void onPostSuccess() {
                //Display Success
            }
        });

I hope the comments are sufficient to explain the design; but I'd be glad to provide more info.

How do I change the ID of a HTML element with JavaScript?

That seems to work for me:

<html>
<head><style>
#monkey {color:blue}
#ape {color:purple}
</style></head>
<body>
<span id="monkey" onclick="changeid()">
fruit
</span>
<script>
function changeid ()
{
var e = document.getElementById("monkey");
e.id = "ape";
}
</script>
</body>
</html>

The expected behaviour is to change the colour of the word "fruit".

Perhaps your document was not fully loaded when you called the routine?

What is the format specifier for unsigned short int?

Here is a good table for printf specifiers. So it should be %hu for unsigned short int.

And link to Wikipedia "C data types" too.

Entity Framework rollback and remove bad migration

First, Update your last perfect migration via this command :

Update-Database –TargetMigration

Example:

Update-Database -20180906131107_xxxx_xxxx

And, then delete your unused migration manually.

How can I merge two commits into one if I already started rebase?

First you should check how many commits you have:

git log

There are two status:

One is that there are only two commits:

For example:

commit A
commit B

(In this case, you can't use git rebase to do) you need to do following.

$ git reset --soft HEAD^1

$ git commit --amend

Another is that there are more than two commits; you want to merge commit C and D.

For example:

commit A
commit B
commit C
commit D

(under this condition, you can use git rebase)

git rebase -i B

And than use "squash" to do. The rest thins is very easy. If you still don't know, please read http://zerodie.github.io/blog/2012/01/19/git-rebase-i/

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

Remove old Fragment from fragment manager

I had the same issue. I came up with a simple solution. Use fragment .replace instead of fragment .add. Replacing fragment doing the same thing as adding fragment and then removing it manually.

getFragmentManager().beginTransaction().replace(fragment).commit();

instead of

getFragmentManager().beginTransaction().add(fragment).commit();

Get json value from response

If the response is in json then it would be like:

alert(response.id);

Otherwise

var str='{"id":"2231f87c-a62c-4c2c-8f5d-b76d11942301"}';

How to remove the default arrow icon from a dropdown list (select element)?

Try this :

select {
    -webkit-appearance: none;
    -moz-appearance: none;
    appearance: none;
    padding: 2px 30px 2px 2px;
    border: none;
}

JS Bin : http://jsbin.com/aniyu4/2/edit

If you use Internet Explorer :

select {
    overflow:hidden;
    width: 120%;
}

Or you can use Choosen : http://harvesthq.github.io/chosen/

Adding rows to dataset

To add rows to existing DataTable in Dataset:

DataRow drPartMtl = DSPartMtl.Tables[0].NewRow();
drPartMtl["Group"] = "Group";
drPartMtl["BOMPart"] = "BOMPart";
DSPartMtl.Tables[0].Rows.Add(drPartMtl);

Get current URL from IFRAME

For security reasons, you can only get the url for as long as the contents of the iframe, and the referencing javascript, are served from the same domain. As long as that is true, something like this will work:

document.getElementById("iframe_id").contentWindow.location.href

If the two domains are mismatched, you'll run into cross site reference scripting security restrictions.

See also answers to a similar question.

How can I convert a Timestamp into either Date or DateTime object?

You can also get DateTime object from timestamp, including your current daylight saving time:

public DateTime getDateTimeFromTimestamp(Long value) {
    TimeZone timeZone = TimeZone.getDefault();
    long offset = timeZone.getOffset(value);
    if (offset < 0) {
        value -= offset;
    } else {
        value += offset;
    }
    return new DateTime(value);
}    

System.Net.WebException HTTP status code

this works only if WebResponse is a HttpWebResponse.

try
{
    ...
}
catch (System.Net.WebException exc)
{
    var webResponse = exc.Response as System.Net.HttpWebResponse;
    if (webResponse != null && 
        webResponse.StatusCode == System.Net.HttpStatusCode.Unauthorized)
    {
        MessageBox.Show("401");
    }
    else
        throw;
}

generating variable names on fly in python

I got your problem , and here is my answer:

prices = [5, 12, 45]
list=['1','2','3']

for i in range(1,3):
  vars()["prices"+list[0]]=prices[0]
print ("prices[i]=" +prices[i])

so while printing:

price1 = 5 
price2 = 12
price3 = 45

How can I set focus on an element in an HTML form using JavaScript?

If your code is:

<input type="text" id="mytext"/>

And If you are using JQuery, You can use this too:

<script>
function setFocusToTextBox(){
    $("#mytext").focus();
}
</script>

Keep in mind that you must draw the input first $(document).ready()

Python import csv to list

Pandas is pretty good at dealing with data. Here is one example how to use it:

import pandas as pd

# Read the CSV into a pandas data frame (df)
#   With a df you can do many things
#   most important: visualize data with Seaborn
df = pd.read_csv('filename.csv', delimiter=',')

# Or export it in many ways, e.g. a list of tuples
tuples = [tuple(x) for x in df.values]

# or export it as a list of dicts
dicts = df.to_dict().values()

One big advantage is that pandas deals automatically with header rows.

If you haven't heard of Seaborn, I recommend having a look at it.

See also: How do I read and write CSV files with Python?

Pandas #2

import pandas as pd

# Get data - reading the CSV file
import mpu.pd
df = mpu.pd.example_df()

# Convert
dicts = df.to_dict('records')

The content of df is:

     country   population population_time    EUR
0    Germany   82521653.0      2016-12-01   True
1     France   66991000.0      2017-01-01   True
2  Indonesia  255461700.0      2017-01-01  False
3    Ireland    4761865.0             NaT   True
4      Spain   46549045.0      2017-06-01   True
5    Vatican          NaN             NaT   True

The content of dicts is

[{'country': 'Germany', 'population': 82521653.0, 'population_time': Timestamp('2016-12-01 00:00:00'), 'EUR': True},
 {'country': 'France', 'population': 66991000.0, 'population_time': Timestamp('2017-01-01 00:00:00'), 'EUR': True},
 {'country': 'Indonesia', 'population': 255461700.0, 'population_time': Timestamp('2017-01-01 00:00:00'), 'EUR': False},
 {'country': 'Ireland', 'population': 4761865.0, 'population_time': NaT, 'EUR': True},
 {'country': 'Spain', 'population': 46549045.0, 'population_time': Timestamp('2017-06-01 00:00:00'), 'EUR': True},
 {'country': 'Vatican', 'population': nan, 'population_time': NaT, 'EUR': True}]

Pandas #3

import pandas as pd

# Get data - reading the CSV file
import mpu.pd
df = mpu.pd.example_df()

# Convert
lists = [[row[col] for col in df.columns] for row in df.to_dict('records')]

The content of lists is:

[['Germany', 82521653.0, Timestamp('2016-12-01 00:00:00'), True],
 ['France', 66991000.0, Timestamp('2017-01-01 00:00:00'), True],
 ['Indonesia', 255461700.0, Timestamp('2017-01-01 00:00:00'), False],
 ['Ireland', 4761865.0, NaT, True],
 ['Spain', 46549045.0, Timestamp('2017-06-01 00:00:00'), True],
 ['Vatican', nan, NaT, True]]

How to reference Microsoft.Office.Interop.Excel dll?

Building off of Mulfix's answer, if you have Visual Studio Community 2015, try Add Reference... -> COM -> Type Libraries -> 'Microsoft Excel 15.0 Object Library'.

Convert base class to derived class

No, there's no built-in way to convert a class like you say. The simplest way to do this would be to do what you suggested: create a DerivedClass(BaseClass) constructor. Other options would basically come out to automate the copying of properties from the base to the derived instance, e.g. using reflection.

The code you posted using as will compile, as I'm sure you've seen, but will throw a null reference exception when you run it, because myBaseObject as DerivedClass will evaluate to null, since it's not an instance of DerivedClass.

How to sort a NSArray alphabetically?

The other answers provided here mention using @selector(localizedCaseInsensitiveCompare:) This works great for an array of NSString, however if you want to extend this to another type of object, and sort those objects according to a 'name' property, you should do this instead:

NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES];
sortedArray=[anArray sortedArrayUsingDescriptors:@[sort]];

Your objects will be sorted according to the name property of those objects.

If you want the sorting to be case insensitive, you would need to set the descriptor like this

NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES selector:@selector(caseInsensitiveCompare:)];

Cannot open database "test" requested by the login. The login failed. Login failed for user 'xyz\ASPNET'

The best option would be to use Windows integrated authentication as it is more secure than sql authentication. Create a new windows user in sql server with necessary permissions and change IIS user in the application pool security settings.

How can I trim leading and trailing white space?

The best method is trimws().

The following code will apply this function to the entire dataframe.

mydataframe<- data.frame(lapply(mydataframe, trimws),stringsAsFactors = FALSE)

INSERT IF NOT EXISTS ELSE UPDATE?

If you have no primary key, You can insert if not exist, then do an update. The table must contain at least one entry before using this.

INSERT INTO Test 
   (id, name)
   SELECT 
      101 as id, 
      'Bob' as name
   FROM Test
       WHERE NOT EXISTS(SELECT * FROM Test WHERE id = 101 and name = 'Bob') LIMIT 1;

Update Test SET id='101' WHERE name='Bob';

How can I disable ARC for a single file in a project?

Note: if you want to disable ARC for many files, you have to:

  1. open "Build phases" -> "Compile sources"
  2. select files with "left_mouse" + "cmd" (for separated files) or + "shift" (for grouped files - select first and last)
  3. press "enter"
  4. paste -fno-objc-arc
  5. press "enter" again
  6. profit!

Change value of input placeholder via model?

The accepted answer still threw a Javascript error in IE for me (for Angular 1.2 at least). It is a bug but the workaround is to use ngAttr detailed on https://docs.angularjs.org/guide/interpolation

<input type="text" ng-model="inputText" ng-attr-placeholder="{{somePlaceholder}}" />

Issue: https://github.com/angular/angular.js/issues/5025

Change class on mouseover in directive

In general I fully agree with Jason's use of css selector, but in some cases you may not want to change the css, e.g. when using a 3rd party css-template, and rather prefer to add/remove a class on the element.

The following sample shows a simple way of adding/removing a class on ng-mouseenter/mouseleave:

<div ng-app>
  <div 
    class="italic" 
    ng-class="{red: hover}"
    ng-init="hover = false"
    ng-mouseenter="hover = true"
    ng-mouseleave="hover = false">
      Test 1 2 3.
  </div>
</div>

with some styling:

.red {
  background-color: red;
}

.italic {
  font-style: italic;
  color: black;
}

See running example here: jsfiddle sample

Styling on hovering is a view concern. Although the solution above sets a "hover" property in the current scope, the controller does not need to be concerned about this.

Understanding Bootstrap's clearfix class

The :before pseudo element isn't needed for the clearfix hack itself.

It's just an additional nice feature helping to prevent margin-collapsing of the first child element. Thus the top margin of an child block element of the "clearfixed" element is guaranteed to be positioned below the top border of the clearfixed element.

display:table is being used because display:block doesn't do the trick. Using display:block margins will collapse even with a :before element.

There is one caveat: if vertical-align:baseline is used in table cells with clearfixed <div> elements, Firefox won't align well. Then you might prefer using display:block despite loosing the anti-collapsing feature. In case of further interest read this article: Clearfix interfering with vertical-align.

How to set Toolbar text and back arrow color

Try a lot of methods, in the low version of the API,a feasible method is <item name="actionMenuTextColor">@color/your_color</item> and don't use the Android namespace

ps:

  <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>

    <!-- change the textColor -->
    <item name="actionMenuTextColor">@color/actionMenuTextColor</item>
</style>

Proper MIME type for .woff2 fonts

Apache

In Apache, you can add the woff2 mime type via your .htaccess file as stated by this link.

AddType  application/font-woff2  .woff2

IIS

In IIS, simply add the following mimeMap tag into your web.config file inside the staticContent tag.

<configuration>
  <system.webServer>
    <staticContent>
      <mimeMap fileExtension=".woff2" mimeType="application/font-woff2" />

How to remove index.php from URLs?

I tried everything on the post but nothing had worked. I then changed the .htaccess snippet that ErJab put up to read:

RewriteRule ^(.*)$ 'folder_name'/index.php/$1 [L]

The above line fixed it for me. where *folder_name* is the magento root folder.

Hope this helps!

Using filesystem in node.js with async / await

Native support for async await fs functions since Node 11

Since Node.JS 11.0.0 (stable), and version 10.0.0 (experimental), you have access to file system methods that are already promisify'd and you can use them with try catch exception handling rather than checking if the callback's returned value contains an error.

The API is very clean and elegant! Simply use .promises member of fs object:

import fs from 'fs';
const fsPromises = fs.promises;

async function listDir() {
  try {
    return fsPromises.readdir('path/to/dir');
  } catch (err) {
    console.error('Error occured while reading directory!', err);
  }
}

listDir();

Response Content type as CSV

Try one of these other mime-types (from here: http://filext.com/file-extension/CSV )

  • text/comma-separated-values
  • text/csv
  • application/csv
  • application/excel
  • application/vnd.ms-excel
  • application/vnd.msexcel

Also, the mime-type might be case sensitive...

C# Clear all items in ListView

I would suggest to remove the rows from the underlying DataTable, or if you don't need the datatable anymore, set the datasource to null.

C/C++ switch case with string

The best way is to use source generation, so that you could use

if (hash(str) == HASH("some string") ..

in your main source, and an pre-build step would convert the HASH(const char*) expression to an integer value.

Code for Greatest Common Divisor in Python

#This program will find the hcf of a given list of numbers.

A = [65, 20, 100, 85, 125]     #creates and initializes the list of numbers

def greatest_common_divisor(_A):
  iterator = 1
  factor = 1
  a_length = len(_A)
  smallest = 99999

#get the smallest number
for number in _A: #iterate through array
  if number < smallest: #if current not the smallest number
    smallest = number #set to highest

while iterator <= smallest: #iterate from 1 ... smallest number
for index in range(0, a_length): #loop through array
  if _A[index] % iterator != 0: #if the element is not equally divisible by 0
    break #stop and go to next element
  if index == (a_length - 1): #if we reach the last element of array
    factor = iterator #it means that all of them are divisibe by 0
iterator += 1 #let's increment to check if array divisible by next iterator
#print the factor
print factor

print "The highest common factor of: ",
for element in A:
  print element,
print " is: ",

greatest_common_devisor(A)

Add common prefix to all cells in Excel

  1. Enter the function of = CONCATENATE("X",A1) in one cell other than A say D
  2. Click the Cell D1, and drag the fill handle across the range that you want to fill.All the cells should have been added the specific prefix text.

You can see the changes made to the repective cells.

Configuring RollingFileAppender in log4j

Regarding error: log4j:ERROR Element type "rollingPolicy" must be declared

  1. Use a log4j.jar version newer than log4j-1.2.14.jar, which has a log4j.dtd defining rollingPolicy.
  2. of course you also need apache-log4j-extras-1.1.jar
  3. Check if any other third party jars you are using perhaps have an older version of log4j.jar packed inside. If so, make sure your log4j.jar comes first in the order before the third party containing the older log4j.jar.

What are ODEX files in Android?

The blog article is mostly right, but not complete. To have a full understanding of what an odex file does, you have to understand a little about how application files (APK) work.

Applications are basically glorified ZIP archives. The java code is stored in a file called classes.dex and this file is parsed by the Dalvik JVM and a cache of the processed classes.dex file is stored in the phone's Dalvik cache.

An odex is basically a pre-processed version of an application's classes.dex that is execution-ready for Dalvik. When an application is odexed, the classes.dex is removed from the APK archive and it does not write anything to the Dalvik cache. An application that is not odexed ends up with 2 copies of the classes.dex file--the packaged one in the APK, and the processed one in the Dalvik cache. It also takes a little longer to launch the first time since Dalvik has to extract and process the classes.dex file.

If you are building a custom ROM, it's a really good idea to odex both your framework JAR files and the stock apps in order to maximize the internal storage space for user-installed apps. If you want to theme, then simply deodex -> apply your theme -> reodex -> release.

To actually deodex, use small and baksmali:

https://github.com/JesusFreke/smali/wiki/DeodexInstructions

jQuery .val change doesn't change input value

$('#link').prop('value', 'new value');

Explanation: Attr will work on jQuery 1.6 but as of jQuery 1.6.1 things have changed. In the majority of cases, prop() does what attr() used to do. Replacing calls to attr() with prop() in your code will generally work. Attr will give you the value of element as it was defined in the html on page load and prop gives the updated values of elements which are modified via jQuery.

Struct like objects in Java

Do not use public fields

Don't use public fields when you really want to wrap the internal behavior of a class. Take java.io.BufferedReader for example. It has the following field:

private boolean skipLF = false; // If the next character is a line feed, skip it

skipLF is read and written in all read methods. What if an external class running in a separate thread maliciously modified the state of skipLF in the middle of a read? BufferedReader will definitely go haywire.

Do use public fields

Take this Point class for example:

class Point {
    private double x;
    private double y;

    public Point(double x, double y) {
        this.x = x;
        this.y = y;
    }

    public double getX() {
        return this.x;
    }

    public double getY() {
        return this.y;
    }

    public void setX(double x) {
        this.x = x;
    }

    public void setY(double y) {
        this.y = y;
    }
}

This would make calculating the distance between two points very painful to write.

Point a = new Point(5.0, 4.0);
Point b = new Point(4.0, 9.0);
double distance = Math.sqrt(Math.pow(b.getX() - a.getX(), 2) + Math.pow(b.getY() - a.getY(), 2));

The class does not have any behavior other than plain getters and setters. It is acceptable to use public fields when the class represents just a data structure, and does not have, and never will have behavior (thin getters and setters is not considered behavior here). It can be written better this way:

class Point {
    public double x;
    public double y;

    public Point(double x, double y) {
        this.x = x;
        this.y = y;
    }
}

Point a = new Point(5.0, 4.0);
Point b = new Point(4.0, 9.0);
double distance = Math.sqrt(Math.pow(b.x - a.x, 2) + Math.pow(b.y - a.y, 2));

Clean!

But remember: Not only your class must be absent of behavior, but it should also have no reason to have behavior in the future as well.


(This is exactly what this answer describes. To quote "Code Conventions for the Java Programming Language: 10. Programming Practices":

One example of appropriate public instance variables is the case where the class is essentially a data structure, with no behavior. In other words, if you would have used a struct instead of a class (if Java supported struct), then it's appropriate to make the class's instance variables public.

So the official documentation also accepts this practice.)


Also, if you're extra sure that members of above Point class should be immutable, then you could add final keyword to enforce it:

public final double x;
public final double y;

Input type "number" won't resize

Use an on onkeypress event. Example for a zip code box. It allows a maximum of 5 characters, and checks to make sure input is only numbers.

Nothing beats a server side validation of course, but this is a nifty way to go.

_x000D_
_x000D_
function validInput(e) {_x000D_
  e = (e) ? e : window.event;_x000D_
  a = document.getElementById('zip-code');_x000D_
  cPress = (e.which) ? e.which : e.keyCode;_x000D_
_x000D_
  if (cPress > 31 && (cPress < 48 || cPress > 57)) {_x000D_
    return false;_x000D_
  } else if (a.value.length >= 5) {_x000D_
    return false;_x000D_
  }_x000D_
_x000D_
  return true;_x000D_
}
_x000D_
#zip-code {_x000D_
  overflow: hidden;_x000D_
  width: 60px;_x000D_
}
_x000D_
<label for="zip-code">Zip Code:</label>_x000D_
<input type="number" id="zip-code" name="zip-code" onkeypress="return validInput(event);" required="required">
_x000D_
_x000D_
_x000D_

Explicitly select items from a list or tuple

Another possible solution:

sek=[]
L=[1,2,3,4,5,6,7,8,9,0]
for i in [2, 4, 7, 0, 3]:
   a=[L[i]]
   sek=sek+a
print (sek)

How to Select a substring in Oracle SQL up to a specific character?

You need to get the position of the first underscore (using INSTR) and then get the part of the string from 1st charecter to (pos-1) using substr.

  1  select 'ABC_blahblahblah' test_string,
  2         instr('ABC_blahblahblah','_',1,1) position_underscore,
  3         substr('ABC_blahblahblah',1,instr('ABC_blahblahblah','_',1,1)-1) result
  4*   from dual
SQL> /

TEST_STRING      POSITION_UNDERSCORE RES
---------------- ------------------  ---
ABC_blahblahblah                  4  ABC

Instr documentation

Susbtr Documentation

How to find out client ID of component for ajax update/render? Cannot find component with expression "foo" referenced from "bar"

It's because the tab is a naming container aswell... your update should be update="Search:insTable:display" What you can do aswell is just place your dialog outside the form and still inside the tab then it would be: update="Search:display"

Correct way to remove plugin from Eclipse

I would like to propose my solution,that worked for me.

It's reverting Eclipse and its plugins versions, to the version just before the plugin was installed.

Most concise way to convert a Set<T> to a List<T>

Try this for Set:

Set<String> listOfTopicAuthors = .....
List<String> setList = new ArrayList<String>(listOfTopicAuthors); 

Try this for Map:

Map<String, String> listOfTopicAuthors = .....
// List of values:
List<String> mapValueList = new ArrayList<String>(listOfTopicAuthors.values());
// List of keys:
List<String> mapKeyList = new ArrayList<String>(listOfTopicAuthors.KeySet());

How do you append an int to a string in C++?

These work for general strings (in case you do not want to output to file/console, but store for later use or something).

boost.lexical_cast

MyStr += boost::lexical_cast<std::string>(MyInt);

String streams

//sstream.h
std::stringstream Stream;
Stream.str(MyStr);
Stream << MyInt;
MyStr = Stream.str();

// If you're using a stream (for example, cout), rather than std::string
someStream << MyInt;

Sort a list of lists with a custom compare function

>>> l = [list(range(i, i+4)) for i in range(10,1,-1)]
>>> l
[[10, 11, 12, 13], [9, 10, 11, 12], [8, 9, 10, 11], [7, 8, 9, 10], [6, 7, 8, 9], [5, 6, 7, 8], [4, 5, 6, 7], [3, 4, 5, 6], [2, 3, 4, 5]]
>>> sorted(l, key=sum)
[[2, 3, 4, 5], [3, 4, 5, 6], [4, 5, 6, 7], [5, 6, 7, 8], [6, 7, 8, 9], [7, 8, 9, 10], [8, 9, 10, 11], [9, 10, 11, 12], [10, 11, 12, 13]]

The above works. Are you doing something different?

Notice that your key function is just sum; there's no need to write it explicitly.

Returning a pointer to a vector element in c++

Return the address of the thing pointed to by the iterator:

&(*iterator)

Edit: To clear up some confusion:

vector <int> vec;          // a global vector of ints

void f() {
   vec.push_back( 1 );    // add to the global vector
   vector <int>::iterator it = vec.begin();
   * it = 2;              // change what was 1 to 2
   int * p = &(*it);      // get pointer to first element
   * p = 3;               // change what was 2 to 3
}

No need for vectors of pointers or dynamic allocation.

PDO error message?

Maybe this post is too old but it may help as a suggestion for someone looking around on this : Instead of using:

 print_r($this->pdo->errorInfo());

Use PHP implode() function:

 echo 'Error occurred:'.implode(":",$this->pdo->errorInfo());

This should print the error code, detailed error information etc. that you would usually get if you were using some SQL User interface.

Hope it helps

How to declare and use 1D and 2D byte arrays in Verilog?

In addition to Marty's excellent Answer, the SystemVerilog specification offers the byte data type. The following declares a 4x8-bit variable (4 bytes), assigns each byte a value, then displays all values:

module tb;

byte b [4];

initial begin
    foreach (b[i]) b[i] = 1 << i;
    foreach (b[i]) $display("Address = %0d, Data = %b", i, b[i]);
    $finish;
end

endmodule

This prints out:

Address = 0, Data = 00000001
Address = 1, Data = 00000010
Address = 2, Data = 00000100
Address = 3, Data = 00001000

This is similar in concept to Marty's reg [7:0] a [0:3];. However, byte is a 2-state data type (0 and 1), but reg is 4-state (01xz). Using byte also requires your tool chain (simulator, synthesizer, etc.) to support this SystemVerilog syntax. Note also the more compact foreach (b[i]) loop syntax.

The SystemVerilog specification supports a wide variety of multi-dimensional array types. The LRM can explain them better than I can; refer to IEEE Std 1800-2005, chapter 5.

How can I check what version/edition of Visual Studio is installed programmatically?

Run the path in cmd C:\Program Files (x86)\Microsoft Visual Studio\Installer>vswhere.exe

Extract every nth element of a vector

To select every nth element from any starting position in the vector

nth_element <- function(vector, starting_position, n) { 
  vector[seq(starting_position, length(vector), n)] 
  }

# E.g.
vec <- 1:12

nth_element(vec, 1, 3)
# [1]  1  4  7 10

nth_element(vec, 2, 3)
# [1]  2  5  8 11

Get most recent row for given ID

Building on @xQbert's answer's, you can avoid the subquery AND make it generic enough to filter by any ID

SELECT id, signin, signout
FROM dTable
INNER JOIN(
  SELECT id, MAX(signin) AS signin
  FROM dTable
  GROUP BY id
) AS t1 USING(id, signin)

Difference between Constructor and ngOnInit

To test this, I wrote this code, borrowing from the NativeScript Tutorial:

user.ts

export class User {
    email: string;
    password: string;
    lastLogin: Date;

    constructor(msg:string) {        
        this.email = "";
        this.password = "";
        this.lastLogin = new Date();
        console.log("*** User class constructor " + msg + " ***");
    }

    Login() {
    }
}

login.component.ts

import {Component} from "@angular/core";
import {User} from "./../../shared/user/user"

@Component({
  selector: "login-component",
  templateUrl: "pages/login/login.html",
  styleUrls: ["pages/login/login-common.css", "pages/login/login.css"]
})
export class LoginComponent {

  user: User = new User("property");  // ONE
  isLoggingIn:boolean;

  constructor() {    
    this.user = new User("constructor");   // TWO
    console.log("*** Login Component Constructor ***");
  }

  ngOnInit() {
    this.user = new User("ngOnInit");   // THREE
    this.user.Login();
    this.isLoggingIn = true;
    console.log("*** Login Component ngOnInit ***");
  }

  submit() {
    alert("You’re using: " + this.user.email + " " + this.user.lastLogin);
  }

  toggleDisplay() {
    this.isLoggingIn = !this.isLoggingIn;
  }

}

Console output

JS: *** User class constructor property ***  
JS: *** User class constructor constructor ***  
JS: *** Login Component Constructor ***  
JS: *** User class constructor ngOnInit ***  
JS: *** Login Component ngOnInit ***  

Delete worksheet in Excel using VBA

Try this code:

For Each aSheet In Worksheets

    Select Case aSheet.Name

        Case "ID Sheet", "Summary"
            Application.DisplayAlerts = False
            aSheet.Delete
            Application.DisplayAlerts = True

    End Select

Next aSheet

Does document.body.innerHTML = "" clear the web page?

To expound on Douwem's answer, in your script tag, put your code in an onload:

<script type="text/javascript">
    window.onload=function(){
       document.body.innerHTML = "";
    }
</script>

Laravel eloquent update record without loading from database

Use property exists:

$post = new Post();
$post->exists = true;
$post->id = 3; //already exists in database.
$post->title = "Updated title";
$post->save();

Here is the API documentation: http://laravel.com/api/5.0/Illuminate/Database/Eloquent/Model.html

Efficiently finding the last line in a text file

Could you load the file into a mmap, then use mmap.rfind(string[, start[, end]]) to find the second last EOL character in the file? A seek to that point in the file should point you to the last line I would think.

EditText non editable

android:editable="false" should work, but it is deprecated, you should be using android:inputType="none" instead.

Alternatively, if you want to do it in the code you could do this :

EditText mEdit = (EditText) findViewById(R.id.yourid);
mEdit.setEnabled(false);

This is also a viable alternative :

EditText mEdit = (EditText) findViewById(R.id.yourid);
mEdit.setKeyListener(null);

If you're going to make your EditText non-editable, may I suggest using the TextView widget instead of the EditText, since using a EditText seems kind of pointless in that case.

EDIT: Altered some information since I've found that android:editable is deprecated, and you should use android:inputType="none", but there is a bug about it on android code; So please check this.

How to give environmental variable path for file appender in configuration file in log4j

I got this working.

  1. In my log4j.properties. I specified

log4j.appender.file.File=${LogFilePath}

  1. in eclipse - JVM arguments

-DLogFilePath=C:\work\MyLogFile.log

Is there an advantage to use a Synchronized Method instead of a Synchronized Block?

The only real difference is that a synchronized block can choose which object it synchronizes on. A synchronized method can only use 'this' (or the corresponding Class instance for a synchronized class method). For example, these are semantically equivalent:

synchronized void foo() {
  ...
}

void foo() {
    synchronized (this) {
      ...
    }
}

The latter is more flexible since it can compete for the associated lock of any object, often a member variable. It's also more granular because you could have concurrent code executing before and after the block but still within the method. Of course, you could just as easily use a synchronized method by refactoring the concurrent code into separate non-synchronized methods. Use whichever makes the code more comprehensible.

JFrame Maximize window

I've tried the solutions in this thread and the ones here, but simply calling setExtendedState(getExtendedState()|Frame.MAXIMIZED_BOTH); right after calling setVisible(true); apparently does not work for my environment (Windows 10, JDK 1.8, my taskbar is on the right side of my screen). Doing it this way still leaves a tiny space on the left, right and bottom .

What did work for me however, is calling setExtendedState(... when the window is activated, like so:

public class SomeFrame extends JFrame {

    public SomeFrame() {
        // ...
        setVisible(true);
        setResizable(true);
        // if you are calling setSize() for fallback size, do that here
        addWindowListener (
            new WindowAdapter() {
                private boolean shown = false;
                @Override
                public void windowActivated(WindowEvent we) {
                    if(shown) return;
                    shown = true;
                    setExtendedState(getExtendedState()|JFrame.MAXIMIZED_BOTH);
                }
            }
        );
    }
}

How can I URL encode a string in Excel VBA?

The VBA-tools library has a function for that:

http://vba-tools.github.io/VBA-Web/docs/#/WebHelpers/UrlEncode

It seems to work similar to encodeURIComponent() in JavaScript.

Access a function variable outside the function without using "global"

The problem is you were calling print x.bye after you set x as a string. When you run x = hi() it runs hi() and sets the value of x to 5 (the value of bye; it does NOT set the value of x as a reference to the bye variable itself). EX: bye = 5; x = bye; bye = 4; print x; prints 5, not 4

Also, you don't have to run hi() twice, just run x = hi(), not hi();x=hi() (the way you had it it was running hi(), not doing anything with the resulting value of 5, and then rerunning the same hi() and saving the value of 5 to the x variable.

So full code should be

def hi():
    something
    something
    bye = 5
    return bye 
x = hi()
print x

If you wanted to return multiple variables, one option would be to use a list, or dictionary, depending on what you need.

ex:

def hi():
    something
    xyz = { 'bye': 7, 'foobar': 8}
    return xyz
x = hi()
print x['bye']

more on python dictionaries at http://docs.python.org/2/tutorial/datastructures.html#dictionaries

Babel 6 regeneratorRuntime is not defined

  1. Install @babel-polyfill and save it in your dev dependencies

_x000D_
_x000D_
npm install --save-dev @babel/polyfill
_x000D_
_x000D_
_x000D_

  1. Copy and Paste require("@babel/polyfill"); at the top your entry file

Entry.js

require("@babel/polyfill"); // this should be include at the top
  1. Add @babel/polyfill in the entry array

  2. You need preset-env in your preset array

webpack.config.js

_x000D_
_x000D_
const path =  require('path');
require("@babel/polyfill"); // necesarry

module.exports = {
  entry: ['@babel/polyfill','./src/js/index.js'],
  output: {
    path: path.resolve(__dirname, 'to_be_deployed/js'),
    filename: 'main.js'
  },
  module: {
    rules: [
      {
        test: /\.m?js$/,
        exclude: /node_modules/,
        use: {
          loader: "babel-loader",
          options: {
            presets: ['@babel/preset-env']
          }
        }
      }
    ]
  },

  mode: 'development'
}
_x000D_
_x000D_
_x000D_

Align printf output in Java

A simple solution that springs to mind is to have a String block of spaces:

String indent = "                  "; // 20 spaces.

When printing out a string, compute the actual indent and add it to the end:

String output = "Newspaper";
output += indent.substring(0, indent.length - output.length);

This will mediate the number of spaces to the string, and put them all in the same column.

How to send a “multipart/form-data” POST in Android with Volley

This is my way of doing it. It may be useful to others :

private void updateType(){
    // Log.i(TAG,"updateType");
     StringRequest request = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {

         @Override
         public void onResponse(String response) {
             // running on main thread-------
             try {
                 JSONObject res = new JSONObject(response);
                 res.getString("result");
                 System.out.println("Response:" + res.getString("result"));

                 }else{
                     CustomTast ct=new CustomTast(context);
                     ct.showCustomAlert("Network/Server Disconnected",R.drawable.disconnect);
                 }

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

                 //Log.e("Response", "==> " + e.getMessage());
             }
         }
     }, new Response.ErrorListener() {
         @Override
         public void onErrorResponse(VolleyError volleyError) {
             // running on main thread-------
             VolleyLog.d(TAG, "Error: " + volleyError.getMessage());

         }
     }) {
         protected Map<String, String> getParams() {
             HashMap<String, String> hashMapParams = new HashMap<String, String>();
             hashMapParams.put("key", "value");
             hashMapParams.put("key", "value");
             hashMapParams.put("key", "value"));
             hashMapParams.put("key", "value");
             System.out.println("Hashmap:" + hashMapParams);
             return hashMapParams;
         }
     };
     AppController.getInstance().addToRequestQueue(request);

 }

"git rm --cached x" vs "git reset head --? x"?

git rm --cached file will remove the file from the stage. That is, when you commit the file will be removed. git reset HEAD -- file will simply reset file in the staging area to the state where it was on the HEAD commit, i.e. will undo any changes you did to it since last commiting. If that change happens to be newly adding the file, then they will be equivalent.

REST API - file (ie images) processing - best practices

There's no easy solution. Each way has their pros and cons . But the canonical way is using the first option: multipart/form-data. As W3 recommendation guide says

The content type "multipart/form-data" should be used for submitting forms that contain files, non-ASCII data, and binary data.

We aren't sending forms,really, but the implicit principle still applies. Using base64 as a binary representation, is incorrect because you're using the incorrect tool for accomplish your goal, in other hand, the second option forces your API clients to do more job in order to consume your API service. You should do the hard work in the server side in order to supply an easy-to-consume API. The first option is not easy to debug, but when you do it, it probably never changes.

Using multipart/form-data you're sticked with the REST/http philosophy. You can view an answer to similar question here.

Another option if mixing the alternatives, you can use multipart/form-data but instead of send every value separate, you can send a value named payload with the json payload inside it. (I tried this approach using ASP.NET WebAPI 2 and works fine).

Getting msbuild.exe without installing Visual Studio

It used to be installed with the .NET framework. MsBuild v12.0 (2013) is now bundled as a stand-alone utility and has it's own installer.

http://www.microsoft.com/en-us/download/confirmation.aspx?id=40760

To reference the location of MsBuild.exe from within an MsBuild script, use the default $(MsBuildToolsPath) property.

Disable click outside of bootstrap modal area to close modal

If you are using @ng-bootstrap use the following:

Component

import { Component, OnInit } from '@angular/core';
import { NgbModal } from '@ng-bootstrap/ng-bootstrap';

@Component({
  selector: 'example',
  templateUrl: './example.component.html',
  styleUrls: ['./example.component.scss'],
})
export class ExampleComponent implements OnInit {

  constructor(
    private ngbModal: NgbModal
  ) {}

  ngOnInit(): void {
  }

  openModal(exampleModal: any, $event: any) {
    this.ngbModal.open(exampleModal, {
      size: 'lg', // set modal size
      backdrop: 'static', // disable modal from closing on click outside
      keyboard: false, // disable modal closing by keyboard esc
    });
  }
}

Template

<div (click)="openModal(exampleModal, $event)"> </div>
    <ng-template #exampleModal let-modal>
        <div class="modal-header">
            <h5 class="modal-title">Test modal</h5>
        </div>
        <div class="modal-body p-3">
            <form action="">
                <div class="form-row">
                    <div class="form-group col-md-6">
                        <label for="">Test field 1</label>
                        <input type="text" class="form-control">
                    </div>
                    <div class="form-group col-md-6">
                        <label for="">Test field 2</label>
                        <input type="text" class="form-control">
                    </div>

                    <div class="text-right pt-4">
                        <button type="button" class="btn btn-light" (click)="modal.dismiss('Close')">Close</button>
                        <button class="btn btn-primary ml-1">Save</button>
                    </div>
            </form>
        </div>
    </ng-template>

This code was tested on angular 9 using:

  1. "@ng-bootstrap/ng-bootstrap": "^6.1.0",

  2. "bootstrap": "^4.4.1",

Youtube - downloading a playlist - youtube-dl

I found the best solution after many attempts for this problem.

youtube-dl --ignore-errors --format bestaudio --extract-audio --audio-format mp3 --audio-quality 160K --output "%(title)s.%(ext)s" --yes-playlist https://www.youtube.com/playlist?list={your-youtube-playlist-id}

Array initialization syntax when not in a declaration

I'll try to answer the why question: The Java array is very simple and rudimentary compared to classes like ArrayList, that are more dynamic. Java wants to know at declaration time how much memory should be allocated for the array. An ArrayList is much more dynamic and the size of it can vary over time.

If you initialize your array with the length of two, and later on it turns out you need a length of three, you have to throw away what you've got, and create a whole new array. Therefore the 'new' keyword.

In your first two examples, you tell at declaration time how much memory to allocate. In your third example, the array name becomes a pointer to nothing at all, and therefore, when it's initialized, you have to explicitly create a new array to allocate the right amount of memory.

I would say that (and if someone knows better, please correct me) the first example

AClass[] array = {object1, object2}

actually means

AClass[] array = new AClass[]{object1, object2};

but what the Java designers did, was to make quicker way to write it if you create the array at declaration time.

The suggested workarounds are good. If the time or memory usage is critical at runtime, use arrays. If it's not critical, and you want code that is easier to understand and to work with, use ArrayList.

Equivalent of jQuery .hide() to set visibility: hidden

There isn't one built in but you could write your own quite easily:

(function($) {
    $.fn.invisible = function() {
        return this.each(function() {
            $(this).css("visibility", "hidden");
        });
    };
    $.fn.visible = function() {
        return this.each(function() {
            $(this).css("visibility", "visible");
        });
    };
}(jQuery));

You can then call this like so:

$("#someElem").invisible();
$("#someOther").visible();

Here's a working example.

How do I activate C++ 11 in CMake?

This is another way of enabling C++11 support,

ADD_DEFINITIONS(
    -std=c++11 # Or -std=c++0x
    # Other flags
)

I have encountered instances where only this method works and other methods fail. Maybe it has something to do with the latest version of CMake.

How can you print a variable name in python?

To answer your original question:

def namestr(obj, namespace):
    return [name for name in namespace if namespace[name] is obj]

Example:

>>> a = 'some var'
>>> namestr(a, globals())
['a']

As @rbright already pointed out whatever you do there are probably better ways to do it.

Can (a== 1 && a ==2 && a==3) ever evaluate to true?

Okay, another hack with generators:

_x000D_
_x000D_
const value = function* () {_x000D_
  let i = 0;_x000D_
  while(true) yield ++i;_x000D_
}();_x000D_
_x000D_
Object.defineProperty(this, 'a', {_x000D_
  get() {_x000D_
    return value.next().value;_x000D_
  }_x000D_
});_x000D_
_x000D_
if (a === 1 && a === 2 && a === 3) {_x000D_
  console.log('yo!');_x000D_
}
_x000D_
_x000D_
_x000D_

HttpClient.GetAsync(...) never returns when using await/async

These two schools are not really excluding.

Here is the scenario where you simply have to use

   Task.Run(() => AsyncOperation()).Wait(); 

or something like

   AsyncContext.Run(AsyncOperation);

I have a MVC action that is under database transaction attribute. The idea was (probably) to roll back everything done in the action if something goes wrong. This does not allow context switching, otherwise transaction rollback or commit is going to fail itself.

The library I need is async as it is expected to run async.

The only option. Run it as a normal sync call.

I am just saying to each its own.

angular.min.js.map not found, what is it exactly?

As eaon21 and monkey said, source map files basically turn minified code into its unminified version for debugging.

You can find the .map files here. Just add them into the same directory as the minified js files and it'll stop complaining. The reason they get fetched is the

/*
//@ sourceMappingURL=angular.min.js.map
*/

at the end of angular.min.js. If you don't want to add the .map files you can remove those lines and it'll stop the fetch attempt, but if you plan on debugging it's always good to keep the source maps linked.

Is there a timeout for idle PostgreSQL connections?

In PostgreSQL 9.6, there's a new option idle_in_transaction_session_timeout which should accomplish what you describe. You can set it using the SET command, e.g.:

SET SESSION idle_in_transaction_session_timeout = '5min';

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

An immediately-invoked function expression (IIFE) immediately calls a function. This simply means that the function is executed immediately after the completion of the definition.

Three more common wordings:

// Crockford's preference - parens on the inside
(function() {
  console.log('Welcome to the Internet. Please follow me.');
}());

//The OPs example, parentheses on the outside
(function() {
  console.log('Welcome to the Internet. Please follow me.');
})();

//Using the exclamation mark operator
//https://stackoverflow.com/a/5654929/1175496
!function() {
  console.log('Welcome to the Internet. Please follow me.');
}();

If there are no special requirements for its return value, then we can write:

!function(){}();  // => true
~function(){}(); // => -1
+function(){}(); // => NaN
-function(){}();  // => NaN

Alternatively, it can be:

~(function(){})();
void function(){}();
true && function(){ /* code */ }();
15.0, function(){ /* code */ }();

You can even write:

new function(){ /* code */ }
31.new function(){ /* code */ }() //If no parameters, the last () is not required

How to pass multiple values to single parameter in stored procedure

USE THIS

I have had this exact issue for almost 2 weeks, extremely frustrating but I FINALLY found this site and it was a clear walk-through of what to do.

http://blog.summitcloud.com/2010/01/multivalue-parameters-with-stored-procedures-in-ssrs-sql/

I hope this helps people because it was exactly what I was looking for

How to set DateTime to null

You can write DateTime? newdate = null;

Excel: last character/string match in a string

Very late to the party, but A simple solution is using VBA to create a custom function.

Add the function to VBA in the WorkBook, Worksheet, or a VBA Module

Function LastSegment(S, C)
    LastSegment = Right(S, Len(S) - InStrRev(S, C))
End Function

Then the cell formula

=lastsegment(B1,"/")

in a cell and the string to be searched in cell B1 will populate the cell with the text trailing the last "/" from cell B1. No length limit, no obscure formulas. Only downside I can think is the need for a macro-enabled workbook.

Any user VBA Function can be called this way to return a value to a cell formula, including as a parameter to a builtin Excel function.

If you are going to use the function heavily you'll want to check for the case when the character is not in the string, then string is blank, etc.

How to run ssh-add on windows?

The Git GUI for Windows has a window-based application that allows you to paste in locations for ssh keys and repo url etc:

https://gitforwindows.org/

Which is a better way to check if an array has more than one element?

Use this

if (sizeof($arr) > 1) {
     ....
}

Or

if (count($arr) > 1) {
     ....
}

sizeof() is an alias for count(), they work the same.

Edit: Answering the second part of the question: The two lines of codes in the question are not alternative methods, they perform different functions. The first checks if the value at $arr['1'] is set, while the second returns the number of elements in the array.

ping: google.com: Temporary failure in name resolution

If you get the IP address from a DHCP server, you can also set the server to send a DNS server. Or add the nameserver 8.8.8.8 into /etc/resolvconf/resolv.conf.d/base file. The information in this file is included in the resolver configuration file even when no interfaces are configured.

AngularJS $http, CORS and http authentication

No you don't have to put credentials, You have to put headers on client side eg:

 $http({
        url: 'url of service',
        method: "POST",
        data: {test :  name },
        withCredentials: true,
        headers: {
                    'Content-Type': 'application/json; charset=utf-8'
        }
    });

And and on server side you have to put headers to this is example for nodejs:

/**
 * On all requests add headers
 */
app.all('*', function(req, res,next) {


    /**
     * Response settings
     * @type {Object}
     */
    var responseSettings = {
        "AccessControlAllowOrigin": req.headers.origin,
        "AccessControlAllowHeaders": "Content-Type,X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5,  Date, X-Api-Version, X-File-Name",
        "AccessControlAllowMethods": "POST, GET, PUT, DELETE, OPTIONS",
        "AccessControlAllowCredentials": true
    };

    /**
     * Headers
     */
    res.header("Access-Control-Allow-Credentials", responseSettings.AccessControlAllowCredentials);
    res.header("Access-Control-Allow-Origin",  responseSettings.AccessControlAllowOrigin);
    res.header("Access-Control-Allow-Headers", (req.headers['access-control-request-headers']) ? req.headers['access-control-request-headers'] : "x-requested-with");
    res.header("Access-Control-Allow-Methods", (req.headers['access-control-request-method']) ? req.headers['access-control-request-method'] : responseSettings.AccessControlAllowMethods);

    if ('OPTIONS' == req.method) {
        res.send(200);
    }
    else {
        next();
    }


});

Force flex item to span full row width

When you want a flex item to occupy an entire row, set it to width: 100% or flex-basis: 100%, and enable wrap on the container.

The item now consumes all available space. Siblings are forced on to other rows.

_x000D_
_x000D_
.parent {
  display: flex;
  flex-wrap: wrap;
}

#range, #text {
  flex: 1;
}

.error {
  flex: 0 0 100%; /* flex-grow, flex-shrink, flex-basis */
  border: 1px dashed black;
}
_x000D_
<div class="parent">
  <input type="range" id="range">
  <input type="text" id="text">
  <label class="error">Error message (takes full width)</label>
</div>
_x000D_
_x000D_
_x000D_

More info: The initial value of the flex-wrap property is nowrap, which means that all items will line up in a row. MDN

fatal: This operation must be run in a work tree

You repository is bare, i.e. it does not have a working tree attached to it. You can clone it locally to create a working tree for it, or you could use one of several other options to tell Git where the working tree is, e.g. the --work-tree option for single commands, or the GIT_WORK_TREE environment variable. There is also the core.worktree configuration option but it will not work in a bare repository (check the man page for what it does).

# git --work-tree=/path/to/work/tree checkout master
# GIT_WORK_TREE=/path/to/work/tree git status

Eclipse reports rendering library more recent than ADT plug-in

Change the Target version to new updates you have. Otherwise, change what SDK version you have in the Android manifest file.

android:minSdkVersion="8"
android:targetSdkVersion="18"

Python's equivalent of && (logical-and) in an if-statement

You use and and or to perform logical operations like in C, C++. Like literally and is && and or is ||.


Take a look at this fun example,

Say you want to build Logic Gates in Python:

def AND(a,b):
    return (a and b) #using and operator

def OR(a,b):
    return (a or b)  #using or operator

Now try calling them:

print AND(False, False)
print OR(True, False)

This will output:

False
True

Hope this helps!

powerpoint loop a series of animation

Unfortunately you're probably done with the animation and presentation already. In the hopes this answer can help future questioners, however, this blog post has a walkthrough of steps that can loop a single slide as a sort of sub-presentation.

First, click Slide Show > Set Up Show.

Put a checkmark to Loop continuously until 'Esc'.

Click Ok. Now, Click Slide Show > Custom Shows. Click New.

Select the slide you are looping, click Add. Click Ok and Close.

Click on the slide you are looping. Click Slide Show > Slide Transition. Under Advance slide, put a checkmark to Automatically After. This will allow the slide to loop automatically. Do NOT Apply to all slides.

Right click on the thumbnail of the current slide, select Hide Slide.

Now, you will need to insert a new slide just before the slide you are looping. On the new slide, insert an action button. Set the hyperlink to the custom show you have created. Put a checkmark on "Show and Return"

This has worked for me.

new Date() is working in Chrome but not Firefox

I was having a similar issue in both Firefox and Safari when working with AngularJS. For example, if a date returned from Angular looked like this:

2014-06-02 10:28:00

using this code:

new Date('2014-06-02 10:28:00').toISOString();

returns an invalid date error in Firefox and Safari. However in Chrome it works fine. As another answer stated, Chrome is most likely just more flexible with parsing date strings.

My eventual goal was to format the date a certain way. I found an excellent library that handled both the cross browser compatibility issue and the date formatting issue. The library is called moment.js.

Using this library the following code works correctly across all browsers I tested:

moment('2014-06-02 10:28:00').format('MMM d YY')

If you are willing to include this extra library into your app you can more easily build your date string while avoiding possible browser compatibility issues. As a bonus you will have a good way to easily format, add, subtract, etc dates if needed.

Best way to resolve file path too long exception

this may be also possibly solution.It some times also occurs when you keep your Development project into too deep, means may be possible project directory may have too many directories so please don't make too many directories keep it in a simple folder inside the drives. For Example- I was also getting this error when my project was kept like this-

D:\Sharad\LatestWorkings\GenericSurveyApplication020120\GenericSurveyApplication\GenericSurveyApplication

then I simply Pasted my project inside

D:\Sharad\LatestWorkings\GenericSurveyApplication

And Problem was solved.

Loop until a specific user input

Your code won't work because you haven't assigned anything to n before you first use it. Try this:

def oracle():
    n = None
    while n != 'Correct':
        # etc...

A more readable approach is to move the test until later and use a break:

def oracle():
    guess = 50

    while True:
        print 'Current number = {0}'.format(guess)
        n = raw_input("lower, higher or stop?: ")
        if n == 'stop':
            break
        # etc...

Also input in Python 2.x reads a line of input and then evaluates it. You want to use raw_input.

Note: In Python 3.x, raw_input has been renamed to input and the old input method no longer exists.

Can I map a hostname *and* a port with /etc/hosts?

If you really need to do this, use reverse proxy.

For example, with nginx as reverse proxy

server {
  listen       api.mydomain.com:80;
  server_name  api.mydomain.com;
  location / {
    proxy_pass http://127.0.0.1:8000;
  }
}

How to clear cache in Yarn?

Ok I found out the answer myself. Much like npm cache clean, Yarn also has its own

yarn cache clean

Reference - What does this error mean in PHP?

Parse error: syntax error, unexpected T_PAAMAYIM_NEKUDOTAYIM

The scope resolution operator is also called "Paamayim Nekudotayim" from the Hebrew ?????? ?????????. which means "double colon".

This error typically happens if you inadvertently put :: in your code.

Related Questions:

Documentation:

ASP.NET postback with JavaScript

You can't call _doPostBack() because it forces submition of the form. Why don't you disable the PostBack on the UpdatePanel?

How to Specify "Vary: Accept-Encoding" header in .htaccess

if anyone needs this for NGINX configuration file here is the snippet:

location ~* \.(js|css|xml|gz)$ {
    add_header Vary "Accept-Encoding";
    (... other headers or rules ...)
}

Laravel 5.2 - pluck() method returns array

laravel pluck returns an array

if your query is:

 $name = DB::table('users')->where('name', 'John')->pluck('name');

then the array is like this (key is the index of the item. auto incremented value):

[
    1 => "name1",
    2 => "name2",
    .
    .
    .
    100 => "name100"
]

but if you do like this:

$name = DB::table('users')->where('name', 'John')->pluck('name','id');

then the key is actual index in the database.

key||value
[
    1 => "name1",
    2 => "name2",
    .
    .
    .
    100 => "name100"
]

you can set any value as key.

VBA Go to last empty row

If you are certain that you only need column A, then you can use an End function in VBA to get that result.

If all the cells A1:A100 are filled, then to select the next empty cell use:

Range("A1").End(xlDown).Offset(1, 0).Select

Here, End(xlDown) is the equivalent of selecting A1 and pressing Ctrl + Down Arrow.

If there are blank cells in A1:A100, then you need to start at the bottom and work your way up. You can do this by combining the use of Rows.Count and End(xlUp), like so:

Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Select

Going on even further, this can be generalized to selecting a range of cells, starting at a point of your choice (not just in column A). In the following code, assume you have values in cells C10:C100, with blank cells interspersed in between. You wish to select all the cells C10:C100, not knowing that the column ends at row 100, starting by manually selecting C10.

Range(Selection, Cells(Rows.Count, Selection.Column).End(xlUp)).Select

The above line is perhaps one of the more important lines to know as a VBA programmer, as it allows you to dynamically select ranges based on very few criteria, and not be bothered with blank cells in the middle.

How to write data with FileOutputStream without losing old data?

Use the constructor for appending material to the file:

FileOutputStream(File file, boolean append)
Creates a file output stream to write to the file represented by the specified File object.

So to append to a file say "abc.txt" use

FileOutputStream fos=new FileOutputStream(new File("abc.txt"),true);

Algorithm to find all Latitude Longitude locations within a certain distance from a given Lat Lng location

PostgreSQL GIS extensions might be helpful - as in, it may already implement much of the functionality you are thinking of implementing.

Check if value exists in enum in TypeScript

If you want to use the variable as enum, just add the function:

Enum EVehicle {
    Car = 'car',
    Bike = 'bike',
    Truck = 'truck'
}

const getVehicleAsEnum = (vehicleStr:string) => vehicleStr === 'car' ? EVehicle.Car : vehicleStr === 'bike' ? EVehicle.Bike : vehicleStr === 'truck' ? EVehicle.Truck : undefined

And then test:

const vehicleEnum = getVecicleAsEnum(str)
if(vehicleEnum) {
   // do something
}

How to save DataFrame directly to Hive?

For Hive external tables I use this function in PySpark:

def save_table(sparkSession, dataframe, database, table_name, save_format="PARQUET"):
    print("Saving result in {}.{}".format(database, table_name))
    output_schema = "," \
        .join(["{} {}".format(x.name.lower(), x.dataType) for x in list(dataframe.schema)]) \
        .replace("StringType", "STRING") \
        .replace("IntegerType", "INT") \
        .replace("DateType", "DATE") \
        .replace("LongType", "INT") \
        .replace("TimestampType", "INT") \
        .replace("BooleanType", "BOOLEAN") \
        .replace("FloatType", "FLOAT")\
        .replace("DoubleType","FLOAT")
    output_schema = re.sub(r'DecimalType[(][0-9]+,[0-9]+[)]', 'FLOAT', output_schema)

    sparkSession.sql("DROP TABLE IF EXISTS {}.{}".format(database, table_name))

    query = "CREATE EXTERNAL TABLE IF NOT EXISTS {}.{} ({}) STORED AS {} LOCATION '/user/hive/{}/{}'" \
        .format(database, table_name, output_schema, save_format, database, table_name)
    sparkSession.sql(query)
    dataframe.write.insertInto('{}.{}'.format(database, table_name),overwrite = True)

How can I remove non-ASCII characters but leave periods and spaces using Python?

Working my way through Fluent Python (Ramalho) - highly recommended. List comprehension one-ish-liners inspired by Chapter 2:

onlyascii = ''.join([s for s in data if ord(s) < 127])
onlymatch = ''.join([s for s in data if s in
              'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz'])

How to reload a page using Angularjs?

Be sure to include the $route service into your scope and do this:

$route.reload();

See this:

How to reload or re-render the entire page using AngularJS

PHP page redirect

As metioned by nixxx adding ob_start() before adding any php code will prevent the headers already sent error.

It worked for me

The code below also works. But it first loads the page and then redirects when I use it.

echo '<META HTTP-EQUIV=REFRESH CONTENT="1; '.$redirect_url.'">';

How to copy Outlook mail message into excel using VBA or Macros

New introduction 2

In the previous version of macro "SaveEmailDetails" I used this statement to find Inbox:

Set FolderTgt = CreateObject("Outlook.Application"). _
              GetNamespace("MAPI").GetDefaultFolder(olFolderInbox)

I have since installed a newer version of Outlook and I have discovered that it does not use the default Inbox. For each of my email accounts, it created a separate store (named for the email address) each with its own Inbox. None of those Inboxes is the default.

This macro, outputs the name of the store holding the default Inbox to the Immediate Window:

Sub DsplUsernameOfDefaultStore()

  Dim NS As Outlook.NameSpace
  Dim DefaultInboxFldr As MAPIFolder

  Set NS = CreateObject("Outlook.Application").GetNamespace("MAPI")
  Set DefaultInboxFldr = NS.GetDefaultFolder(olFolderInbox)

  Debug.Print DefaultInboxFldr.Parent.Name

End Sub

On my installation, this outputs: "Outlook Data File".

I have added an extra statement to macro "SaveEmailDetails" that shows how to access the Inbox of any store.

New introduction 1

A number of people have picked up the macro below, found it useful and have contacted me directly for further advice. Following these contacts I have made a few improvements to the macro so I have posted the revised version below. I have also added a pair of macros which together will return the MAPIFolder object for any folder with the Outlook hierarchy. These are useful if you wish to access other than a default folder.

The original text referenced one question by date which linked to an earlier question. The first question has been deleted so the link has been lost. That link was to Update excel sheet based on outlook mail (closed)

Original text

There are a surprising number of variations of the question: "How do I extract data from Outlook emails to Excel workbooks?" For example, two questions up on [outlook-vba] the same question was asked on 13 August. That question references a variation from December that I attempted to answer.

For the December question, I went overboard with a two part answer. The first part was a series of teaching macros that explored the Outlook folder structure and wrote data to text files or Excel workbooks. The second part discussed how to design the extraction process. For this question Siddarth has provided an excellent, succinct answer and then a follow-up to help with the next stage.

What the questioner of every variation appears unable to understand is that showing us what the data looks like on the screen does not tell us what the text or html body looks like. This answer is an attempt to get past that problem.

The macro below is more complicated than Siddarth’s but a lot simpler that those I included in my December answer. There is more that could be added but I think this is enough to start with.

The macro creates a new Excel workbook and outputs selected properties of every email in Inbox to create this worksheet:

Example of worksheet created by macro

Near the top of the macro there is a comment containing eight hashes (#). The statement below that comment must be changed because it identifies the folder in which the Excel workbook will be created.

All other comments containing hashes suggest amendments to adapt the macro to your requirements.

How are the emails from which data is to be extracted identified? Is it the sender, the subject, a string within the body or all of these? The comments provide some help in eliminating uninteresting emails. If I understand the question correctly, an interesting email will have Subject = "Task Completed".

The comments provide no help in extracting data from interesting emails but the worksheet shows both the text and html versions of the email body if they are present. My idea is that you can see what the macro will see and start designing the extraction process.

This is not shown in the screen image above but the macro outputs two versions on the text body. The first version is unchanged which means tab, carriage return, line feed are obeyed and any non-break spaces look like spaces. In the second version, I have replaced these codes with the strings [TB], [CR], [LF] and [NBSP] so they are visible. If my understanding is correct, I would expect to see the following within the second text body:

Activity[TAB]Count[CR][LF]Open[TAB]35[CR][LF]HCQA[TAB]42[CR][LF]HCQC[TAB]60[CR][LF]HAbst[TAB]50 45 5 2 2 1[CR][LF] and so on

Extracting the values from the original of this string should not be difficult.

I would try amending my macro to output the extracted values in addition to the email’s properties. Only when I have successfully achieved this change would I attempt to write the extracted data to an existing workbook. I would also move processed emails to a different folder. I have shown where these changes must be made but give no further help. I will respond to a supplementary question if you get to the point where you need this information.

Good luck.

Latest version of macro included within the original text

Option Explicit
Public Sub SaveEmailDetails()

  ' This macro creates a new Excel workbook and writes to it details
  ' of every email in the Inbox.

  ' Lines starting with hashes either MUST be changed before running the
  ' macro or suggest changes you might consider appropriate.

  Dim AttachCount As Long
  Dim AttachDtl() As String
  Dim ExcelWkBk As Excel.Workbook
  Dim FileName As String
  Dim FolderTgt As MAPIFolder
  Dim HtmlBody As String
  Dim InterestingItem As Boolean
  Dim InxAttach As Long
  Dim InxItemCrnt As Long
  Dim PathName As String
  Dim ReceivedTime As Date
  Dim RowCrnt As Long
  Dim SenderEmailAddress As String
  Dim SenderName As String
  Dim Subject As String
  Dim TextBody As String
  Dim xlApp As Excel.Application

  ' The Excel workbook will be created in this folder.
  ' ######## Replace "C:\DataArea\SO" with the name of a folder on your disc.
  PathName = "C:\DataArea\SO"

  ' This creates a unique filename.
  ' #### If you use a version of Excel 2003, change the extension to "xls".
  FileName = Format(Now(), "yymmdd hhmmss") & ".xlsx"

  ' Open own copy of Excel
  Set xlApp = Application.CreateObject("Excel.Application")
  With xlApp
    ' .Visible = True         ' This slows your macro but helps during debugging
    .ScreenUpdating = False ' Reduces flash and increases speed
    ' Create a new workbook
    ' #### If updating an existing workbook, replace with an
    ' #### Open workbook statement.
    Set ExcelWkBk = xlApp.Workbooks.Add
    With ExcelWkBk
      ' #### None of this code will be useful if you are adding
      ' #### to an existing workbook.  However, it demonstrates a
      ' #### variety of useful statements.
      .Worksheets("Sheet1").Name = "Inbox"    ' Rename first worksheet
      With .Worksheets("Inbox")
        ' Create header line
        With .Cells(1, "A")
          .Value = "Field"
          .Font.Bold = True
        End With
        With .Cells(1, "B")
          .Value = "Value"
          .Font.Bold = True
        End With
        .Columns("A").ColumnWidth = 18
        .Columns("B").ColumnWidth = 150
      End With
    End With
    RowCrnt = 2
  End With

  ' FolderTgt is the folder I am going to search.  This statement says
  ' I want to seach the Inbox.  The value "olFolderInbox" can be replaced
  ' to allow any of the standard folders to be searched.
  ' See FindSelectedFolder() for a routine that will search for any folder.
  Set FolderTgt = CreateObject("Outlook.Application"). _
              GetNamespace("MAPI").GetDefaultFolder(olFolderInbox)
  ' #### Use the following the access a non-default Inbox.
  ' #### Change "Xxxx" to name of one of your store you want to access.
  Set FolderTgt = Session.Folders("Xxxx").Folders("Inbox")

  ' This examines the emails in reverse order. I will explain why later.
  For InxItemCrnt = FolderTgt.Items.Count To 1 Step -1
    With FolderTgt.Items.Item(InxItemCrnt)
      ' A folder can contain several types of item: mail items, meeting items,
      ' contacts, etc.  I am only interested in mail items.
      If .Class = olMail Then
        ' Save selected properties to variables
        ReceivedTime = .ReceivedTime
        Subject = .Subject
        SenderName = .SenderName
        SenderEmailAddress = .SenderEmailAddress
        TextBody = .Body
        HtmlBody = .HtmlBody
        AttachCount = .Attachments.Count
        If AttachCount > 0 Then
          ReDim AttachDtl(1 To 7, 1 To AttachCount)
          For InxAttach = 1 To AttachCount
            ' There are four types of attachment:
            '  *   olByValue       1
            '  *   olByReference   4
            '  *   olEmbeddedItem  5
            '  *   olOLE           6
            Select Case .Attachments(InxAttach).Type
              Case olByValue
            AttachDtl(1, InxAttach) = "Val"
              Case olEmbeddeditem
            AttachDtl(1, InxAttach) = "Ebd"
              Case olByReference
            AttachDtl(1, InxAttach) = "Ref"
              Case olOLE
            AttachDtl(1, InxAttach) = "OLE"
              Case Else
            AttachDtl(1, InxAttach) = "Unk"
            End Select
            ' Not all types have all properties.  This code handles
            ' those missing properties of which I am aware.  However,
            ' I have never found an attachment of type Reference or OLE.
            ' Additional code may be required for them.
            Select Case .Attachments(InxAttach).Type
              Case olEmbeddeditem
                AttachDtl(2, InxAttach) = ""
              Case Else
                AttachDtl(2, InxAttach) = .Attachments(InxAttach).PathName
            End Select
            AttachDtl(3, InxAttach) = .Attachments(InxAttach).FileName
            AttachDtl(4, InxAttach) = .Attachments(InxAttach).DisplayName
            AttachDtl(5, InxAttach) = "--"
            ' I suspect Attachment had a parent property in early versions
            ' of Outlook. It is missing from Outlook 2016.
            On Error Resume Next
            AttachDtl(5, InxAttach) = .Attachments(InxAttach).Parent
            On Error GoTo 0
            AttachDtl(6, InxAttach) = .Attachments(InxAttach).Position
            ' Class 5 is attachment.  I have never seen an attachment with
            ' a different class and do not see the purpose of this property.
            ' The code will stop here if a different class is found.
            Debug.Assert .Attachments(InxAttach).Class = 5
            AttachDtl(7, InxAttach) = .Attachments(InxAttach).Class
          Next
        End If
        InterestingItem = True
      Else
        InterestingItem = False
      End If
    End With
    ' The most used properties of the email have been loaded to variables but
    ' there are many more properies.  Press F2.  Scroll down classes until
    ' you find MailItem.  Look through the members and note the name of
    ' any properties that look useful.  Look them up using VB Help.

    ' #### You need to add code here to eliminate uninteresting items.
    ' #### For example:
    'If SenderEmailAddress <> "[email protected]" Then
    '  InterestingItem = False
    'End If
    'If InStr(Subject, "Accounts payable") = 0 Then
    '  InterestingItem = False
    'End If
    'If AttachCount = 0 Then
    '  InterestingItem = False
    'End If

    ' #### If the item is still thought to be interesting I
    ' #### suggest extracting the required data to variables here.

    ' #### You should consider moving processed emails to another
    ' #### folder.  The emails are being processed in reverse order
    ' #### to allow this removal of an email from the Inbox without
    ' #### effecting the index numbers of unprocessed emails.

    If InterestingItem Then
      With ExcelWkBk
        With .Worksheets("Inbox")
          ' #### This code creates a dividing row and then
          ' #### outputs a property per row.  Again it demonstrates
          ' #### statements that are likely to be useful in the final
          ' #### version
          ' Create dividing row between emails
          .Rows(RowCrnt).RowHeight = 5
          .Range(.Cells(RowCrnt, "A"), .Cells(RowCrnt, "B")) _
                                      .Interior.Color = RGB(0, 255, 0)
          RowCrnt = RowCrnt + 1
          .Cells(RowCrnt, "A").Value = "Sender name"
          .Cells(RowCrnt, "B").Value = SenderName
          RowCrnt = RowCrnt + 1
          .Cells(RowCrnt, "A").Value = "Sender email address"
          .Cells(RowCrnt, "B").Value = SenderEmailAddress
          RowCrnt = RowCrnt + 1
          .Cells(RowCrnt, "A").Value = "Received time"
          With .Cells(RowCrnt, "B")
            .NumberFormat = "@"
            .Value = Format(ReceivedTime, "mmmm d, yyyy h:mm")
          End With
          RowCrnt = RowCrnt + 1
          .Cells(RowCrnt, "A").Value = "Subject"
          .Cells(RowCrnt, "B").Value = Subject
          RowCrnt = RowCrnt + 1
          If AttachCount > 0 Then
            .Cells(RowCrnt, "A").Value = "Attachments"
            .Cells(RowCrnt, "B").Value = "Inx|Type|Path name|File name|Display name|Parent|Position|Class"
            RowCrnt = RowCrnt + 1
            For InxAttach = 1 To AttachCount
              .Cells(RowCrnt, "B").Value = InxAttach & "|" & _
                                           AttachDtl(1, InxAttach) & "|" & _
                                           AttachDtl(2, InxAttach) & "|" & _
                                           AttachDtl(3, InxAttach) & "|" & _
                                           AttachDtl(4, InxAttach) & "|" & _
                                           AttachDtl(5, InxAttach) & "|" & _
                                           AttachDtl(6, InxAttach) & "|" & _
                                           AttachDtl(7, InxAttach)
              RowCrnt = RowCrnt + 1
            Next
          End If
          If TextBody <> "" Then

            ' ##### This code was in the original version of the macro
            ' ##### but I did not find it as useful as the other version of
            ' ##### the text body.  See below
            ' This outputs the text body with CR, LF and TB obeyed
            'With .Cells(RowCrnt, "A")
            '  .Value = "text body"
            '  .VerticalAlignment = xlTop
            'End With
            'With .Cells(RowCrnt, "B")
            '  ' The maximum size of a cell 32,767
            '  .Value = Mid(TextBody, 1, 32700)
            '  .WrapText = True
            'End With
            'RowCrnt = RowCrnt + 1

            ' This outputs the text body with NBSP, CR, LF and TB
            ' replaced by strings.
            With .Cells(RowCrnt, "A")
              .Value = "text body"
              .VerticalAlignment = xlTop
            End With
            TextBody = Replace(TextBody, Chr(160), "[NBSP]")
            TextBody = Replace(TextBody, vbCr, "[CR]")
            TextBody = Replace(TextBody, vbLf, "[LF]")
            TextBody = Replace(TextBody, vbTab, "[TB]")
            With .Cells(RowCrnt, "B")
              ' The maximum size of a cell 32,767
              .Value = Mid(TextBody, 1, 32700)
              .WrapText = True
            End With
            RowCrnt = RowCrnt + 1
          End If

          If HtmlBody <> "" Then

            ' ##### This code was in the original version of the macro
            ' ##### but I did not find it as useful as the other version of
            ' ##### the html body.  See below
            ' This outputs the html body with CR, LF and TB obeyed
            'With .Cells(RowCrnt, "A")
            '  .Value = "Html body"
            '  .VerticalAlignment = xlTop
            'End With
            'With .Cells(RowCrnt, "B")
            '  .Value = Mid(HtmlBody, 1, 32700)
            '  .WrapText = True
            'End With
            'RowCrnt = RowCrnt + 1

            ' This outputs the html body with NBSP, CR, LF and TB
            ' replaced by strings.
            With .Cells(RowCrnt, "A")
              .Value = "Html body"
              .VerticalAlignment = xlTop
            End With
            HtmlBody = Replace(HtmlBody, Chr(160), "[NBSP]")
            HtmlBody = Replace(HtmlBody, vbCr, "[CR]")
            HtmlBody = Replace(HtmlBody, vbLf, "[LF]")
            HtmlBody = Replace(HtmlBody, vbTab, "[TB]")
            With .Cells(RowCrnt, "B")
              .Value = Mid(HtmlBody, 1, 32700)
              .WrapText = True
            End With
            RowCrnt = RowCrnt + 1

          End If
        End With
      End With
    End If
  Next

  With xlApp
    With ExcelWkBk
      ' Write new workbook to disc
      If Right(PathName, 1) <> "\" Then
        PathName = PathName & "\"
      End If
      .SaveAs FileName:=PathName & FileName
      .Close
    End With
    .Quit   ' Close our copy of Excel
  End With

  Set xlApp = Nothing       ' Clear reference to Excel

End Sub

Macros not included in original post but which some users of above macro have found useful.

Public Sub FindSelectedFolder(ByRef FolderTgt As MAPIFolder, _
                              ByVal NameTgt As String, ByVal NameSep As String)

  ' This routine (and its sub-routine) locate a folder within the hierarchy and
  ' returns it as an object of type MAPIFolder

  ' NameTgt   The name of the required folder in the format:
  '              FolderName1 NameSep FolderName2 [ NameSep FolderName3 ] ...
  '           If NameSep is "|", an example value is "Personal Folders|Inbox"
  '           FolderName1 must be an outer folder name such as
  '           "Personal Folders". The outer folder names are typically the names
  '           of PST files.  FolderName2 must be the name of a folder within
  '           Folder1; in the example "Inbox".  FolderName2 is compulsory.  This
  '           routine cannot return a PST file; only a folder within a PST file.
  '           FolderName3, FolderName4 and so on are optional and allow a folder
  '           at any depth with the hierarchy to be specified.
  ' NameSep   A character or string used to separate the folder names within
  '           NameTgt.
  ' FolderTgt On exit, the required folder.  Set to Nothing if not found.

  ' This routine initialises the search and finds the top level folder.
  ' FindSelectedSubFolder() is used to find the target folder within the
  ' top level folder.

  Dim InxFolderCrnt As Long
  Dim NameChild As String
  Dim NameCrnt As String
  Dim Pos As Long
  Dim TopLvlFolderList As Folders

  Set FolderTgt = Nothing   ' Target folder not found

  Set TopLvlFolderList = _
          CreateObject("Outlook.Application").GetNamespace("MAPI").Folders

  ' Split NameTgt into the name of folder at current level
  ' and the name of its children
  Pos = InStr(NameTgt, NameSep)
  If Pos = 0 Then
    ' I need at least a level 2 name
    Exit Sub
  End If
  NameCrnt = Mid(NameTgt, 1, Pos - 1)
  NameChild = Mid(NameTgt, Pos + 1)

  ' Look for current name.  Drop through and return nothing if name not found.
  For InxFolderCrnt = 1 To TopLvlFolderList.Count
    If NameCrnt = TopLvlFolderList(InxFolderCrnt).Name Then
      ' Have found current name. Call FindSelectedSubFolder() to
      ' look for its children
      Call FindSelectedSubFolder(TopLvlFolderList.Item(InxFolderCrnt), _
                                            FolderTgt, NameChild, NameSep)
      Exit For
    End If
  Next

End Sub
Public Sub FindSelectedSubFolder(FolderCrnt As MAPIFolder, _
                      ByRef FolderTgt As MAPIFolder, _
                      ByVal NameTgt As String, ByVal NameSep As String)

  ' See FindSelectedFolder() for an introduction to the purpose of this routine.
  ' This routine finds all folders below the top level

  ' FolderCrnt The folder to be seached for the target folder.
  ' NameTgt    The NameTgt passed to FindSelectedFolder will be of the form:
  '               A|B|C|D|E
  '            A is the name of outer folder which represents a PST file.
  '            FindSelectedFolder() removes "A|" from NameTgt and calls this
  '            routine with FolderCrnt set to folder A to search for B.
  '            When this routine finds B, it calls itself with FolderCrnt set to
  '            folder B to search for C.  Calls are nested to whatever depth are
  '            necessary.
  ' NameSep    As for FindSelectedSubFolder
  ' FolderTgt  As for FindSelectedSubFolder

  Dim InxFolderCrnt As Long
  Dim NameChild As String
  Dim NameCrnt As String
  Dim Pos As Long

  ' Split NameTgt into the name of folder at current level
  ' and the name of its children
  Pos = InStr(NameTgt, NameSep)
  If Pos = 0 Then
    NameCrnt = NameTgt
    NameChild = ""
  Else
    NameCrnt = Mid(NameTgt, 1, Pos - 1)
    NameChild = Mid(NameTgt, Pos + 1)
  End If

  ' Look for current name.  Drop through and return nothing if name not found.
  For InxFolderCrnt = 1 To FolderCrnt.Folders.Count
    If NameCrnt = FolderCrnt.Folders(InxFolderCrnt).Name Then
      ' Have found current name.
      If NameChild = "" Then
        ' Have found target folder
        Set FolderTgt = FolderCrnt.Folders(InxFolderCrnt)
      Else
        'Recurse to look for children
        Call FindSelectedSubFolder(FolderCrnt.Folders(InxFolderCrnt), _
                                            FolderTgt, NameChild, NameSep)
      End If
      Exit For
    End If
  Next

  ' If NameCrnt not found, FolderTgt will be returned unchanged.  Since it is
  ' initialised to Nothing at the beginning, that will be the returned value.

End Sub

Equivalent of *Nix 'which' command in PowerShell?

The very first alias I made once I started customizing my profile in PowerShell was 'which'.

New-Alias which get-command

To add this to your profile, type this:

"`nNew-Alias which get-command" | add-content $profile

The `n at the start of the last line is to ensure it will start as a new line.

'too many values to unpack', iterating over a dict. key=>string, value=>list

In Python3 iteritems() is no longer supported

Use .items

for field, possible_values in fields.items():
    print(field, possible_values)

React-Native Button style not work

The React Native Button is very limited in what you can do, see; Button

It does not have a style prop, and you don't set text the "web-way" like <Button>txt</Button> but via the title property <Button title="txt" />

If you want to have more control over the appearance you should use one of the TouchableXXXX' components like TouchableOpacity They are really easy to use :-)

enum Values to NSString (iOS)

This is an old question, but if you have a non contiguous enum use a dictionary literal instead of an array:

typedef enum {
    value1 = 0,
    value2 = 1,
    value3 = 2,

    // beyond value3
    value1000 = 1000,
    value1001
} MyType;

#define NSStringFromMyType( value ) \
( \
    @{ \
        @( value1 )    : @"value1", \
        @( value2 )    : @"value2", \
        @( value3 )    : @"value3", \
        @( value1000 ) : @"value1000", \
        @( value1001 ) : @"value1001", \
    } \
    [ @( value ) ] \
)

force client disconnect from server with socket.io and nodejs

socket.disconnect() can be used only on the client side, not on the server side.

Client.emit('disconnect') triggers the disconnection event on the server, but does not effectively disconnect the client. The client is not aware of the disconnection.

So the question remain : how to force a client to disconnect from server side ?

Is it possible to implement a Python for range loop without an iterator variable?

I generally agree with solutions given above. Namely with:

  1. Using underscore in for-loop (2 and more lines)
  2. Defining a normal while counter (3 and more lines)
  3. Declaring a custom class with __nonzero__ implementation (many more lines)

If one is to define an object as in #3 I would recommend implementing protocol for with keyword or apply contextlib.

Further I propose yet another solution. It is a 3 liner and is not of supreme elegance, but it uses itertools package and thus might be of an interest.

from itertools import (chain, repeat)

times = chain(repeat(True, 2), repeat(False))
while next(times):
    print 'do stuff!'

In these example 2 is the number of times to iterate the loop. chain is wrapping two repeat iterators, the first being limited but the second is infinite. Remember that these are true iterator objects, hence they do not require infinite memory. Obviously this is much slower then solution #1. Unless written as a part of a function it might require a clean up for times variable.

Python requests - print entire http request (raw)?

An even better idea is to use the requests_toolbelt library, which can dump out both requests and responses as strings for you to print to the console. It handles all the tricky cases with files and encodings which the above solution does not handle well.

It's as easy as this:

import requests
from requests_toolbelt.utils import dump

resp = requests.get('https://httpbin.org/redirect/5')
data = dump.dump_all(resp)
print(data.decode('utf-8'))

Source: https://toolbelt.readthedocs.org/en/latest/dumputils.html

You can simply install it by typing:

pip install requests_toolbelt

Remove HTML tags from a String

To get formateed plain html text you can do that:

String BR_ESCAPED = "&lt;br/&gt;";
Element el=Jsoup.parse(html).select("body");
el.select("br").append(BR_ESCAPED);
el.select("p").append(BR_ESCAPED+BR_ESCAPED);
el.select("h1").append(BR_ESCAPED+BR_ESCAPED);
el.select("h2").append(BR_ESCAPED+BR_ESCAPED);
el.select("h3").append(BR_ESCAPED+BR_ESCAPED);
el.select("h4").append(BR_ESCAPED+BR_ESCAPED);
el.select("h5").append(BR_ESCAPED+BR_ESCAPED);
String nodeValue=el.text();
nodeValue=nodeValue.replaceAll(BR_ESCAPED, "<br/>");
nodeValue=nodeValue.replaceAll("(\\s*<br[^>]*>){3,}", "<br/><br/>");

To get formateed plain text change <br/> by \n and change last line by:

nodeValue=nodeValue.replaceAll("(\\s*\n){3,}", "<br/><br/>");

Twitter Bootstrap 3 Sticky Footer

_x000D_
_x000D_
#myfooter{_x000D_
height: 3em;_x000D_
  background-color: #f5f5f5;_x000D_
  text-align: center;_x000D_
  padding-top: 1em;_x000D_
}
_x000D_
<footer>_x000D_
    <div class="footer">_x000D_
        <div class="container-fluid"  id="myfooter">_x000D_
            <div class="row">_x000D_
                <div class="col-md-12">_x000D_
                    <p class="copy">Copyright &copy; Your words</p>_x000D_
                </div>_x000D_
            </div>_x000D_
        </div>_x000D_
    </div>_x000D_
</footer>
_x000D_
_x000D_
_x000D_

Using grep to help subset a data frame in R

You may also use the stringr package

library(dplyr)
library(stringr)
My.Data %>% filter(str_detect(x, '^G45'))

You may not use '^' (starts with) in this case, to obtain the results you need

What is the use of "object sender" and "EventArgs e" parameters?

EventArgs e is a parameter called e that contains the event data, see the EventArgs MSDN page for more information.

Object Sender is a parameter called Sender that contains a reference to the control/object that raised the event.

Event Arg Class: http://msdn.microsoft.com/en-us/library/system.eventargs.aspx

Example:

protected void btn_Click (object sender, EventArgs e){
   Button btn = sender as Button;
   btn.Text = "clicked!";
}

Edit: When Button is clicked, the btn_Click event handler will be fired. The "object sender" portion will be a reference to the button which was clicked

Cannot create PoolableConnectionFactory

If you use apache tomcat 8.0 version, instead of it, use tomcat 7.0 I had tried localhost to 127.0.0.1 and power off firewall but not working, but use tomcat 7.0 and now working

How to save an activity state using save instance state?

The savedInstanceState is only for saving state associated with a current instance of an Activity, for example current navigation or selection info, so that if Android destroys and recreates an Activity, it can come back as it was before. See the documentation for onCreate and onSaveInstanceState

For more long lived state, consider using a SQLite database, a file, or preferences. See Saving Persistent State.

How do I use a regular expression to match any string, but at least 3 characters?

You could try with simple 3 dots. refer to the code in perl below

$a =~ m /.../ #where $a is your string

How to add default value for html <textarea>?

Placeholder cannot set the default value for text area. You can use

<textarea rows="10" cols="55" name="description"> /*Enter default value here to display content</textarea>

This is the tag if you are using it for database connection. You may use different syntax if you are using other languages than php.For php :

e.g.:

<textarea rows="10" cols="55" name="description" required><?php echo $description; ?></textarea>

required command minimizes efforts needed to check empty fields using php.

How can I access a hover state in reactjs?

React components expose all the standard Javascript mouse events in their top-level interface. Of course, you can still use :hover in your CSS, and that may be adequate for some of your needs, but for the more advanced behaviors triggered by a hover you'll need to use the Javascript. So to manage hover interactions, you'll want to use onMouseEnter and onMouseLeave. You then attach them to handlers in your component like so:

<ReactComponent
    onMouseEnter={() => this.someHandler}
    onMouseLeave={() => this.someOtherHandler}
/>

You'll then use some combination of state/props to pass changed state or properties down to your child React components.

M_PI works with math.h but not with cmath in Visual Studio

As suggested by user7860670, right-click on the project, select properties, navigate to C/C++ -> Preprocessor and add _USE_MATH_DEFINES to the Preprocessor Definitions.

That's what worked for me.

Send email using java

Here is the working solution bro. It's guranteed.

  1. First of all open your gmail account from which you wanted to send mail, like in you case [email protected]
  2. Open this link below:

    https://support.google.com/accounts/answer/6010255?hl=en

  3. Click on "Go to the "Less secure apps" section in My Account." option
  4. Then turn on it
  5. That's it (:

Here is my code:

import javax.mail.*;
import javax.mail.internet.*;
import java.util.*;

public class SendEmail {

   final String senderEmailID = "Sender Email id";
final String senderPassword = "Sender Pass word";
final String emailSMTPserver = "smtp.gmail.com";
final String emailServerPort = "465";
String receiverEmailID = null;
static String emailSubject = "Test Mail";
static String emailBody = ":)";
public SendEmail(String receiverEmailID, String emailSubject, String emailBody)
{
this.receiverEmailID=receiverEmailID;
this.emailSubject=emailSubject;
this.emailBody=emailBody;
Properties props = new Properties();
props.put("mail.smtp.user",senderEmailID);
props.put("mail.smtp.host", emailSMTPserver);
props.put("mail.smtp.port", emailServerPort);
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.socketFactory.port", emailServerPort);
props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");
SecurityManager security = System.getSecurityManager();
try
{
Authenticator auth = new SMTPAuthenticator();
Session session = Session.getInstance(props, auth);
MimeMessage msg = new MimeMessage(session);
msg.setText(emailBody);
msg.setSubject(emailSubject);
msg.setFrom(new InternetAddress(senderEmailID));
msg.addRecipient(Message.RecipientType.TO,
new InternetAddress(receiverEmailID));
Transport.send(msg);
System.out.println("Message send Successfully:)");
}
catch (Exception mex)
{
mex.printStackTrace();
}
}
public class SMTPAuthenticator extends javax.mail.Authenticator
{
public PasswordAuthentication getPasswordAuthentication()
{
return new PasswordAuthentication(senderEmailID, senderPassword);
}
}
    public static void main(String[] args) {
       SendEmail mailSender;
        mailSender = new SendEmail("Receiver Email id","Testing Code 2 example","Testing Code Body yess");
    }

}

Access multiple viewchildren using @viewchild

Use the @ViewChildren decorator combined with QueryList. Both of these are from "@angular/core"

@ViewChildren(CustomComponent) customComponentChildren: QueryList<CustomComponent>;

Doing something with each child looks like: this.customComponentChildren.forEach((child) => { child.stuff = 'y' })

There is further documentation to be had at angular.io, specifically: https://angular.io/docs/ts/latest/cookbook/component-communication.html#!#sts=Parent%20calls%20a%20ViewChild

Python: finding lowest integer

list1 = [10,-4,5,2,33,4,7,8,2,3,5,8,99,-34]

print(list1)

max_v=list1[0]

min_v=list1[0]

for x in list1:
    if x>max_v:
        max_v=x
        print('X is {0} and max is {1}'.format(x,max_v))
for x in list1:
    if x<min_v:
        min_v=x
        print('X is {0} and min is {1}'.format(x,min_v))

print('Max values is ' + str(max_v))
print('Min values is ' + str(min_v))

onclick or inline script isn't working in extension

I decide to publish my example that I used in my case. I tried to replace content in div using a script. My problem was that Chrome did not recognized / did not run that script.

In more detail What I wanted to do: To click on a link, and that link to "read" an external html file, that it will be loaded in a div section.

  • I found out that by placing the script before the DIV with ID that was called, the script did not work.
  • If the script was in another DIV, also it does not work
  • The script must be coded using document.addEventListener('DOMContentLoaded', function() as it was told

        <body>
        <a id=id_page href ="#loving"   onclick="load_services()"> loving   </a>
    
            <script>
                    // This script MUST BE under the "ID" that is calling
                    // Do not transfer it to a differ DIV than the caller "ID"
                    document.getElementById("id_page").addEventListener("click", function(){
                    document.getElementById("mainbody").innerHTML = '<object data="Services.html" class="loving_css_edit"; ></object>'; });
                </script>
        </body>
    
      <div id="mainbody" class="main_body">
            "here is loaded the external html file when the loving link will 
             be  clicked. "
      </div>
    

How do I get the last day of a month?

You can find the last date of any month by this code:

var now = DateTime.Now;
var startOfMonth = new DateTime(now.Year, now.Month, 1);
var DaysInMonth = DateTime.DaysInMonth(now.Year, now.Month);
var lastDay = new DateTime(now.Year, now.Month, DaysInMonth);

Proper usage of Optional.ifPresent()

Why write complicated code when you could make it simple?

Indeed, if you are absolutely going to use the Optional class, the most simple code is what you have already written ...

if (user.isPresent())
{
    doSomethingWithUser(user.get());
}

This code has the advantages of being

  1. readable
  2. easy to debug (breakpoint)
  3. not tricky

Just because Oracle has added the Optional class in Java 8 doesn't mean that this class must be used in all situation.

Stop jQuery .load response from being cached

Sasha is good idea, i use a mix.

I create a function

LoadWithoutCache: function (url, source) {
    $.ajax({
        url: url,
        cache: false,
        dataType: "html",
        success: function (data) {
            $("#" + source).html(data);
            return false;
        }
    });
}

And invoke for diferents parts of my page for example on init:

Init: function (actionUrl1, actionUrl2, actionUrl3) {

var ExampleJS= {

Init: function (actionUrl1, actionUrl2, actionUrl3)           ExampleJS.LoadWithoutCache(actionUrl1, "div1");

ExampleJS.LoadWithoutCache(actionUrl2, "div2"); ExampleJS.LoadWithoutCache(actionUrl3, "div3"); } },

Parsing HTTP Response in Python

When I printed response.read() I noticed that b was preprended to the string (e.g. b'{"a":1,..). The "b" stands for bytes and serves as a declaration for the type of the object you're handling. Since, I knew that a string could be converted to a dict by using json.loads('string'), I just had to convert the byte type to a string type. I did this by decoding the response to utf-8 decode('utf-8'). Once it was in a string type my problem was solved and I was easily able to iterate over the dict.

I don't know if this is the fastest or most 'pythonic' way of writing this but it works and theres always time later of optimization and improvement! Full code for my solution:

from urllib.request import urlopen
import json

# Get the dataset
url = 'http://www.quandl.com/api/v1/datasets/FRED/GDP.json'
response = urlopen(url)

# Convert bytes to string type and string type to dict
string = response.read().decode('utf-8')
json_obj = json.loads(string)

print(json_obj['source_name']) # prints the string with 'source_name' key

Keep CMD open after BAT file executes

Adding pause in (Windows 7) to the end did not work for me
but adding the cmd /k in front of my command did work.

Example :

cmd /k gradlew cleanEclipse

What do these operators mean (** , ^ , %, //)?

You are correct that ** is the power function.

^ is bitwise XOR.

% is indeed the modulus operation, but note that for positive numbers, x % m = x whenever m > x. This follows from the definition of modulus. (Additionally, Python specifies x % m to have the sign of m.)

// is a division operation that returns an integer by discarding the remainder. This is the standard form of division using the / in most programming languages. However, Python 3 changed the behavior of / to perform floating-point division even if the arguments are integers. The // operator was introduced in Python 2.6 and Python 3 to provide an integer-division operator that would behave consistently between Python 2 and Python 3. This means:

| context                                | `/` behavior   | `//` behavior |
---------------------------------------------------------------------------
| floating-point arguments, Python 2 & 3 | float division | int divison   |
---------------------------------------------------------------------------
| integer arguments, python 2            | int division   | int division  |
---------------------------------------------------------------------------
| integer arguments, python 3            | float division | int division  |

For more details, see this question: Division in Python 2.7. and 3.3

Inserting a blank table row with a smaller height

Just add the CSS rule (and the slightly improved mark-up) posted below and you should get the result that you're after.

CSS

.blank_row
{
    height: 10px !important; /* overwrites any other rules */
    background-color: #FFFFFF;
}

HTML

<tr class="blank_row">
    <td colspan="3"></td>
</tr>

Since I have no idea what your current stylesheet looks like I added the !important property just in case. If possible, though, you should remove it as one rarely wants to rely on !important declarations in a stylesheet considering the big possibility that they will mess it up later on.

Uploading both data and files in one form using Ajax?

In my case I had to make a POST request, which had information sent through the header, and also a file sent using a FormData object.

I made it work using a combination of some of the answers here, so basically what ended up working was having this five lines in my Ajax request:

 contentType: "application/octet-stream",
 enctype: 'multipart/form-data',
 contentType: false,
 processData: false,
 data: formData,

Where formData was a variable created like this:

 var file = document.getElementById('uploadedFile').files[0];
 var form = $('form')[0];
 var formData = new FormData(form);
 formData.append("File", file);

Beautiful Soup and extracting a div and its contents by ID

I think there is a problem when the 'div' tags are too much nested. I am trying to parse some contacts from a facebook html file, and the Beautifulsoup is not able to find tags "div" with class "fcontent".

This happens with other classes as well. When I search for divs in general, it turns only those that are not so much nested.

The html source code can be any page from facebook of the friends list of a friend of you (not the one of your friends). If someone can test it and give some advice I would really appreciate it.

This is my code, where I just try to print the number of tags "div" with class "fcontent":

from BeautifulSoup import BeautifulSoup 
f = open('/Users/myUserName/Desktop/contacts.html')
soup = BeautifulSoup(f) 
list = soup.findAll('div', attrs={'class':'fcontent'})
print len(list)

Retaining file permissions with Git

We can improve on the other answers by changing the format of the .permissions file to be executable chmod statements, and to make use of the -printf parameter to find. Here is the simpler .git/hooks/pre-commit file:

#!/usr/bin/env bash

echo -n "Backing-up file permissions... "

cd "$(git rev-parse --show-toplevel)"

find . -printf 'chmod %m "%p"\n' > .permissions

git add .permissions

echo done.

...and here is the simplified .git/hooks/post-checkout file:

#!/usr/bin/env bash

echo -n "Restoring file permissions... "

cd "$(git rev-parse --show-toplevel)"

. .permissions

echo "done."

Remember that other tools might have already configured these scripts, so you may need to merge them together. For example, here's a post-checkout script that also includes the git-lfs commands:

#!/usr/bin/env bash

echo -n "Restoring file permissions... "

cd "$(git rev-parse --show-toplevel)"

. .permissions

echo "done."

command -v git-lfs >/dev/null 2>&1 || { echo >&2 "\nThis repository is configured for Git LFS but 'git-lfs' was not found on you
r path. If you no longer wish to use Git LFS, remove this hook by deleting .git/hooks/post-checkout.\n"; exit 2; }
git lfs post-checkout "$@"

JavaScript OR (||) variable assignment explanation

See short-circuit evaluation for the explanation. It's a common way of implementing these operators; it is not unique to JavaScript.