Programs & Examples On #Launch condition

Create ArrayList from array

Given Object Array:

Element[] array = {new Element(1), new Element(2), new Element(3) , new Element(2)};

Convert Array to List:

    List<Element> list = Arrays.stream(array).collect(Collectors.toList());

Convert Array to ArrayList

    ArrayList<Element> arrayList = Arrays.stream(array)
                                       .collect(Collectors.toCollection(ArrayList::new));

Convert Array to LinkedList

    LinkedList<Element> linkedList = Arrays.stream(array)
                     .collect(Collectors.toCollection(LinkedList::new));

Print List:

    list.forEach(element -> {
        System.out.println(element.i);
    });

OUTPUT

1

2

3

force line break in html table cell

You could put the text into a div (or other container) with a width of 50%.

http://jsfiddle.net/6gjsd/

Add missing dates to pandas dataframe

A quicker workaround is to use .asfreq(). This doesn't require creation of a new index to call within .reindex().

# "broken" (staggered) dates
dates = pd.Index([pd.Timestamp('2012-05-01'), 
                  pd.Timestamp('2012-05-04'), 
                  pd.Timestamp('2012-05-06')])
s = pd.Series([1, 2, 3], dates)

print(s.asfreq('D'))
2012-05-01    1.0
2012-05-02    NaN
2012-05-03    NaN
2012-05-04    2.0
2012-05-05    NaN
2012-05-06    3.0
Freq: D, dtype: float64

"R cannot be resolved to a variable"?

I just had this error on my first hello world android application (3-Nov-2013).

Along with a few pointers from other users, this is what I had to do:

Control+Shift+O

Delete the import *.R from the top of the main activity .java file

Save the file, clean and compile the project (usually build is automatic)

Run SDK Manager, enable the build tools if not already checked, and hit Update regardless

Close and reopen Eclipse and the problem was gone

How do I navigate to a parent route from a child route?

This seems to work for me as of Spring 2017:

goBack(): void {
  this.router.navigate(['../'], { relativeTo: this.route });
}

Where your component ctor accepts ActivatedRoute and Router, imported as follows:

import { ActivatedRoute, Router } from '@angular/router';

HTML table: keep the same width for columns

give this style to td: width: 1%;

How to output MySQL query results in CSV format?

How about:

mysql your_database -p < my_requests.sql | awk '{print $1","$2}' > out.csv

Purpose of returning by const value?

It makes sure that the returned object (which is an RValue at that point) can't be modified. This makes sure the user can't do thinks like this:

myFunc() = Object(...);

That would work nicely if myFunc returned by reference, but is almost certainly a bug when returned by value (and probably won't be caught by the compiler). Of course in C++11 with its rvalues this convention doesn't make as much sense as it did earlier, since a const object can't be moved from, so this can have pretty heavy effects on performance.

How can I remove text within parentheses with a regex?

>>> import re
>>> filename = "Example_file_(extra_descriptor).ext"
>>> p = re.compile(r'\([^)]*\)')
>>> re.sub(p, '', filename)
'Example_file_.ext'

Column order manipulation using col-lg-push and col-lg-pull in Twitter Bootstrap 3

Misconception Common misconception with column ordering is that, I should (or could) do the pushing and pulling on mobile devices, and that the desktop views should render in the natural order of the markup. This is wrong.

Reality Bootstrap is a mobile first framework. This means that the order of the columns in your HTML markup should represent the order in which you want them displayed on mobile devices. This mean that the pushing and pulling is done on the larger desktop views. not on mobile devices view..

Brandon Schmalz - Full Stack Web Developer Have a look at full description here

How do I get only directories using Get-ChildItem?

For PowerShell versions less than 3.0:

The FileInfo object returned by Get-ChildItem has a "base" property, PSIsContainer. You want to select only those items.

Get-ChildItem -Recurse | ?{ $_.PSIsContainer }

If you want the raw string names of the directories, you can do

Get-ChildItem -Recurse | ?{ $_.PSIsContainer } | Select-Object FullName

For PowerShell 3.0 and greater:

Get-ChildItem -Directory

You can also use the aliases dir, ls, and gci

How to get a list of user accounts using the command line in MySQL?

MySQL stores the user information in its own database. The name of the database is MySQL. Inside that database, the user information is in a table, a dataset, named user. If you want to see what users are set up in the MySQL user table, run the following command:

SELECT User, Host FROM mysql.user;

+------------------+-----------+
| User             | Host      |
+------------------+-----------+
| root             | localhost |
| root             | demohost  |
| root             | 127.0.0.1 |
| debian-sys-maint | localhost |
|                  | %         |
+------------------+-----------+

git am error: "patch does not apply"

I had this error, was able to overcome it by using : patch -p1 < example.patch

I took it from here: https://www.drupal.org/node/1129120

Error in launching AVD with AMD processor

First, you must enable Intel virtualization technology from the BIOS:

Enter image description here

Second, navigate to your SDK ...\extras\intel\Hardware_Accelerated_Execution_Manager:

Enter image description here

Then install intelhaxm-android.exe.

Note that if you can't find this file in the directory, make sure you install the package from your SDK manager:

Enter image description here

How to print variables without spaces between values

>>> value=42

>>> print "Value is %s"%('"'+str(value)+'"') 

Value is "42"

Spring - @Transactional - What happens in background?

When Spring loads your bean definitions, and has been configured to look for @Transactional annotations, it will create these proxy objects around your actual bean. These proxy objects are instances of classes that are auto-generated at runtime. The default behaviour of these proxy objects when a method is invoked is just to invoke the same method on the "target" bean (i.e. your bean).

However, the proxies can also be supplied with interceptors, and when present these interceptors will be invoked by the proxy before it invokes your target bean's method. For target beans annotated with @Transactional, Spring will create a TransactionInterceptor, and pass it to the generated proxy object. So when you call the method from client code, you're calling the method on the proxy object, which first invokes the TransactionInterceptor (which begins a transaction), which in turn invokes the method on your target bean. When the invocation finishes, the TransactionInterceptor commits/rolls back the transaction. It's transparent to the client code.

As for the "external method" thing, if your bean invokes one of its own methods, then it will not be doing so via the proxy. Remember, Spring wraps your bean in the proxy, your bean has no knowledge of it. Only calls from "outside" your bean go through the proxy.

Does that help?

Do we need type="text/css" for <link> in HTML5

Don’t need to specify a type value of “text/css”

Every time you link to a CSS file:

<link rel="stylesheet" type="text/css" href="file.css">

You can simply write:

<link rel="stylesheet" href="file.css">

How can I test a Windows DLL file to determine if it is 32 bit or 64 bit?

Gory details

A DLL uses the PE executable format, and it's not too tricky to read that information out of the file.

See this MSDN article on the PE File Format for an overview. You need to read the MS-DOS header, then read the IMAGE_NT_HEADERS structure. This contains the IMAGE_FILE_HEADER structure which contains the info you need in the Machine member which contains one of the following values

  • IMAGE_FILE_MACHINE_I386 (0x014c)
  • IMAGE_FILE_MACHINE_IA64 (0x0200)
  • IMAGE_FILE_MACHINE_AMD64 (0x8664)

This information should be at a fixed offset in the file, but I'd still recommend traversing the file and checking the signature of the MS-DOS header and the IMAGE_NT_HEADERS to be sure you cope with any future changes.

Use ImageHelp to read the headers...

You can also use the ImageHelp API to do this - load the DLL with LoadImage and you'll get a LOADED_IMAGE structure which will contain a pointer to an IMAGE_NT_HEADERS structure. Deallocate the LOADED_IMAGE with ImageUnload.

...or adapt this rough Perl script

Here's rough Perl script which gets the job done. It checks the file has a DOS header, then reads the PE offset from the IMAGE_DOS_HEADER 60 bytes into the file.

It then seeks to the start of the PE part, reads the signature and checks it, and then extracts the value we're interested in.

#!/usr/bin/perl
#
# usage: petype <exefile>
#
$exe = $ARGV[0];

open(EXE, $exe) or die "can't open $exe: $!";
binmode(EXE);
if (read(EXE, $doshdr, 64)) {

   ($magic,$skip,$offset)=unpack('a2a58l', $doshdr);
   die("Not an executable") if ($magic ne 'MZ');

   seek(EXE,$offset,SEEK_SET);
   if (read(EXE, $pehdr, 6)){
       ($sig,$skip,$machine)=unpack('a2a2v', $pehdr);
       die("No a PE Executable") if ($sig ne 'PE');

       if ($machine == 0x014c){
            print "i386\n";
       }
       elsif ($machine == 0x0200){
            print "IA64\n";
       }
       elsif ($machine == 0x8664){
            print "AMD64\n";
       }
       else{
            printf("Unknown machine type 0x%lx\n", $machine);
       }
   }
}

close(EXE);

Java converting Image to BufferedImage

One way to handle this is to create a new BufferedImage, and tell it's graphics object to draw your scaled image into the new BufferedImage:

final float FACTOR  = 4f;
BufferedImage img = ImageIO.read(new File("graphic.png"));
int scaleX = (int) (img.getWidth() * FACTOR);
int scaleY = (int) (img.getHeight() * FACTOR);
Image image = img.getScaledInstance(scaleX, scaleY, Image.SCALE_SMOOTH);
BufferedImage buffered = new BufferedImage(scaleX, scaleY, TYPE);
buffered.getGraphics().drawImage(image, 0, 0 , null);

That should do the trick without casting.

Allowing the "Enter" key to press the submit button, as opposed to only using MouseClick

I know this isn't the best way to do it, but right click the button in question, events, key, key typed. This is a simple way to do it, but reacts to any key

How do I use extern to share variables between source files?

The correct interpretation of extern is that you tell something to the compiler. You tell the compiler that, despite not being present right now, the variable declared will somehow be found by the linker (typically in another object (file)). The linker will then be the lucky guy to find everything and put it together, whether you had some extern declarations or not.

deleting folder from java

You should delete the file in the folder first , then the folder.This way you will recursively call the method.

How to read user input into a variable in Bash?

Use read -p:

# fullname="USER INPUT"
read -p "Enter fullname: " fullname
# user="USER INPUT"
read -p "Enter user: " user

If you like to confirm:

read -p "Continue? (Y/N): " confirm && [[ $confirm == [yY] || $confirm == [yY][eE][sS] ]] || exit 1

You should also quote your variables to prevent pathname expansion and word splitting with spaces:

# passwd "$user"
# mkdir "$home"
# chown "$user:$group" "$home"

Color text in discord

Discord doesn't allow colored text. Though, currently, you have two options to "mimic" colored text.

Option #1 (Markdown code-blocks)

Discord supports Markdown and uses highlight.js to highlight code-blocks. Some programming languages have specific color outputs from highlight.js and can be used to mimic colored output.

To use code-blocks, send a normal message in this format (Which follows Markdown's standard format).

```language
message
```

Languages that currently reproduce nice colors: prolog (red/orange), css (yellow).

Option #2 (Embeds)

Discord now supports Embeds and Webhooks, which can be used to display colored blocks, they also support markdown. For documentation on how to use Embeds, please read your lib's documentation.

(Embed Cheat-sheet)
Embed Cheat-sheet

Edit Crystal report file without Crystal Report software

My dad moved his office after 30 year and they need to update the address in the header of their Crystal Reports 7 (1997!) based billing system.

After buying old copies of Access 97 and Visual Studio 2003 Pro, I found out that both programs were too new - they could open the RPT files, but they saved them with an updated version that would not open in the billing system.

I ended up being able to make the changes using this life-saver program...

http://www.softwareforces.com/Products/rpt-inspector-professional-suite-for-crystal-reports

It was available with a 10 day free trial, and I only needed about 10 minutes to make my changes. That said, I would have happily paid whatever they asked for it. :)

Some hints:

  1. When I opened my RPT files, I got an error saving the database could not be found. I ignored this error and everything worked fine.
  2. Because my RPT files were Crystal Reports version 7, I had to go into Options->Misc and tell the program to save in the old format...

enter image description here

How to center icon and text in a android button with width set to "fill parent"

Had similar issue but wanted to have center drawable with no text and no wrapped layouts. Solution was to create custom button and add one more drawable in addition to LEFT, RIGHT, TOP, BOTTOM. One can easily modify drawable placement and have it in desired position relative to text.

CenterDrawableButton.java

public class CenterDrawableButton extends Button {
    private Drawable mDrawableCenter;

    public CenterDrawableButton(Context context) {
        super(context);
        init(context, null);
    }

    public CenterDrawableButton(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs);
    }

    public CenterDrawableButton(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init(context, attrs);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public CenterDrawableButton(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        init(context, attrs);
    }


    private void init(Context context, AttributeSet attrs){
        //if (isInEditMode()) return;
        if(attrs!=null){
            TypedArray a = context.getTheme().obtainStyledAttributes(
                    attrs, R.styleable.CenterDrawableButton, 0, 0);

            try {
                setCenterDrawable(a.getDrawable(R.styleable.CenterDrawableButton_drawableCenter));

            } finally {
                a.recycle();
            }

        }
    }

    public void setCenterDrawable(int center) {
        if(center==0){
            setCenterDrawable(null);
        }else
        setCenterDrawable(getContext().getResources().getDrawable(center));
    }
    public void setCenterDrawable(@Nullable Drawable center) {
        int[] state;
        state = getDrawableState();
        if (center != null) {
            center.setState(state);
            center.setBounds(0, 0, center.getIntrinsicWidth(), center.getIntrinsicHeight());
            center.setCallback(this);
        }
        mDrawableCenter = center;
        invalidate();
        requestLayout();
    }
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        if(mDrawableCenter!=null) {
            setMeasuredDimension(Math.max(getMeasuredWidth(), mDrawableCenter.getIntrinsicWidth()),
                    Math.max(getMeasuredHeight(), mDrawableCenter.getIntrinsicHeight()));
        }
    }
    @Override
    protected void drawableStateChanged() {
        super.drawableStateChanged();
        if (mDrawableCenter != null) {
            int[] state = getDrawableState();
            mDrawableCenter.setState(state);
            mDrawableCenter.setBounds(0, 0, mDrawableCenter.getIntrinsicWidth(),
                    mDrawableCenter.getIntrinsicHeight());
        }
        invalidate();
    }

    @Override
    protected void onDraw(@NonNull Canvas canvas) {
        super.onDraw(canvas);

        if (mDrawableCenter != null) {
            Rect rect = mDrawableCenter.getBounds();
            canvas.save();
            canvas.translate(getWidth() / 2 - rect.right / 2, getHeight() / 2 - rect.bottom / 2);
            mDrawableCenter.draw(canvas);
            canvas.restore();
        }
    }
}

attrs.xml

<resources>
    <attr name="drawableCenter" format="reference"/>
    <declare-styleable name="CenterDrawableButton">
        <attr name="drawableCenter"/>
    </declare-styleable>
</resources>

usage

<com.virtoos.android.view.custom.CenterDrawableButton
            android:id="@id/centerDrawableButton"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            app:drawableCenter="@android:drawable/ic_menu_info_details"/>

Getting the minimum of two values in SQL

Use a temp table to insert the range of values, then select the min/max of the temp table from within a stored procedure or UDF. This is a basic construct, so feel free to revise as needed.

For example:

CREATE PROCEDURE GetMinSpeed() AS
BEGIN

    CREATE TABLE #speed (Driver NVARCHAR(10), SPEED INT);
    '
    ' Insert any number of data you need to sort and pull from
    '
    INSERT INTO #speed (N'Petty', 165)
    INSERT INTO #speed (N'Earnhardt', 172)
    INSERT INTO #speed (N'Patrick', 174)

    SELECT MIN(SPEED) FROM #speed

    DROP TABLE #speed

END

std::queue iteration

Why not just make a copy of the queue that you want to iterate over, and remove items one at a time, printing them as you go? If you want to do more with the elements as you iterate, then a queue is the wrong data structure.

Rails: How can I rename a database column in a Ruby on Rails migration?

I'm on rails 5.2, and trying to rename a column on a devise User.

the rename_column bit worked for me, but the singular :table_name threw a "User table not found" error. Plural worked for me.

rails g RenameAgentinUser

Then change migration file to this:

rename_column :users, :agent?, :agent

Where :agent? is the old column name.

How to deserialize a JObject to .NET object

Too late, just in case some one is looking for another way:

void Main()
{
    string jsonString = @"{
  'Stores': [
    'Lambton Quay',
    'Willis Street'
  ],
  'Manufacturers': [
    {
      'Name': 'Acme Co',
      'Products': [
        {
          'Name': 'Anvil',
          'Price': 50
        }
      ]
    },
    {
      'Name': 'Contoso',
      'Products': [
        {
          'Name': 'Elbow Grease',
          'Price': 99.95
        },
        {
          'Name': 'Headlight Fluid',
          'Price': 4
        }
      ]
    }
  ]
}";

    Product product = new Product();
    //Serializing to Object
    Product obj = JObject.Parse(jsonString).SelectToken("$.Manufacturers[?(@.Name == 'Acme Co' && @.Name != 'Contoso')]").ToObject<Product>();

    Console.WriteLine(obj);
}


public class Product
{
    public string Name { get; set; }
    public decimal Price { get; set; }
}

Passing by reference in C

In C, Pass-by-reference is simulated by passing the address of a variable (a pointer) and dereferencing that address within the function to read or write the actual variable. This will be referred to as "C style pass-by-reference."

Source: www-cs-students.stanford.edu

Recommended way to get hostname in Java

hostName == null;
Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
{
    while (interfaces.hasMoreElements()) {
        NetworkInterface nic = interfaces.nextElement();
        Enumeration<InetAddress> addresses = nic.getInetAddresses();
        while (hostName == null && addresses.hasMoreElements()) {
            InetAddress address = addresses.nextElement();
            if (!address.isLoopbackAddress()) {
                hostName = address.getHostName();
            }
        }
    }
}

IIS: Display all sites and bindings in PowerShell

I found this question because I wanted to generate a web page with links to all the websites running on my IIS instance. I used Alexander Shapkin's answer to come up with the following to generate a bunch of links.

$hostname = "localhost"

Foreach ($Site in get-website) {
    Foreach ($Bind in $Site.bindings.collection) {
        $data = [PSCustomObject]@{
            name=$Site.name;
            Protocol=$Bind.Protocol;
            Bindings=$Bind.BindingInformation
        }
        $data.Bindings = $data.Bindings -replace '(:$)', ''
        $html = "<a href=""" + $data.Protocol + "://" + $data.Bindings + """>" + $data.name + "</a>"
        $html.Replace("*", $hostname);
    }
}

Then I paste the results into this hastily written HTML:

<html>
<style>
    a { display: block; }
</style>
{paste PowerShell results here}
</body>
</html>

How to define a default value for "input type=text" without using attribute 'value'?

You can use Javascript.

For example, using jQuery:

$(':text').val('1000');

However, this won't be any different from using the value attribute.

HTML text input allow only numeric input

Remember the regional differences (Euros use periods and commas in the reverse way as Americans), plus the minus sign (or the convention of wrapping a number in parentheses to indicate negative), plus exponential notation (I'm reaching on that one).

How can I update a single row in a ListView?

int wantedPosition = 25; // Whatever position you're looking for
int firstPosition = linearLayoutManager.findFirstVisibleItemPosition(); // This is the same as child #0
int wantedChild = wantedPosition - firstPosition;

if (wantedChild < 0 || wantedChild >= linearLayoutManager.getChildCount()) {
    Log.w(TAG, "Unable to get view for desired position, because it's not being displayed on screen.");
    return;
}

View wantedView = linearLayoutManager.getChildAt(wantedChild);
mlayoutOver =(LinearLayout)wantedView.findViewById(R.id.layout_over);
mlayoutPopup = (LinearLayout)wantedView.findViewById(R.id.layout_popup);

mlayoutOver.setVisibility(View.INVISIBLE);
mlayoutPopup.setVisibility(View.VISIBLE);

For RecycleView please use this code

jQuery: set selected value of dropdown list?

You need to select jQuery in the dropdown on the left and you have a syntax error because the $(document).ready should end with }); not )}; Check this link.

Form Submit Execute JavaScript Best Practice?

Attach an event handler to the submit event of the form. Make sure it cancels the default action.

Quirks Mode has a guide to event handlers, but you would probably be better off using a library to simplify the code and iron out the differences between browsers. All the major ones (such as YUI and jQuery) include event handling features, and there is a large collection of tiny event libraries.

Here is how you would do it in YUI 3:

<script src="http://yui.yahooapis.com/3.4.1/build/yui/yui-min.js"></script>
<script>
    YUI().use('event', function (Y) {
        Y.one('form').on('submit', function (e) {
            // Whatever else you want to do goes here
            e.preventDefault();
        });
    });
</script>

Make sure that the server will pick up the slack if the JavaScript fails for any reason.

CronJob not running

I found useful debugging information on an Ubuntu 16.04 server by running:

systemctl status cron.service

In my case I was kindly informed I had left a comment '#' off of a remark line:

Aug 18 19:12:01 is-feb19 cron[14307]: Error: bad minute; while reading /etc/crontab
Aug 18 19:12:01 is-feb19 cron[14307]: (*system*) ERROR (Syntax error, this crontab file will be ignored)

How to read strings from a Scanner in a Java console application?

Scanner scanner = new Scanner(System.in);
int employeeId, supervisorId;
String name;
System.out.println("Enter employee ID:");
employeeId = scanner.nextInt();
scanner.nextLine(); //This is needed to pick up the new line
System.out.println("Enter employee name:");
name = scanner.nextLine();
System.out.println("Enter supervisor ID:");
supervisorId = scanner.nextInt();

Calling nextInt() was a problem as it didn't pick up the new line (when you hit enter). So, calling scanner.nextLine() after that does the work.

Error parsing yaml file: mapping values are not allowed here

Another cause is wrong indentation which means trying to create the wrong objects. I've just fixed one in a Kubernetes Ingress definition:

Wrong

- path: / 
    backend: 
      serviceName: <service_name> 
      servicePort: <port> 

Correct

- path: /
  backend:
    serviceName: <service_name>
    servicePort: <port>

Using Gulp to Concatenate and Uglify files

we are using below configuration to do something similar

    var gulp = require('gulp'),
    async = require("async"),
    less = require('gulp-less'),
    minifyCSS = require('gulp-minify-css'),
    uglify = require('gulp-uglify'),
    concat = require('gulp-concat'),
    gulpDS = require("./gulpDS"),
    del = require('del');

// CSS & Less
var jsarr = [gulpDS.jsbundle.mobile, gulpDS.jsbundle.desktop, gulpDS.jsbundle.common];
var cssarr = [gulpDS.cssbundle];

var generateJS = function() {

    jsarr.forEach(function(gulpDSObject) {
        async.map(Object.keys(gulpDSObject), function(key) {
            var val = gulpDSObject[key]
            execGulp(val, key);
        });

    })
}

var generateCSS = function() {
    cssarr.forEach(function(gulpDSObject) {
        async.map(Object.keys(gulpDSObject), function(key) {
            var val = gulpDSObject[key];
            execCSSGulp(val, key);
        })
    })
}

var execGulp = function(arrayOfItems, dest) {
    var destSplit = dest.split("/");
    var file = destSplit.pop();
    del.sync([dest])
    gulp.src(arrayOfItems)
        .pipe(concat(file))
        .pipe(uglify())
        .pipe(gulp.dest(destSplit.join("/")));
}

var execCSSGulp = function(arrayOfItems, dest) {
    var destSplit = dest.split("/");
    var file = destSplit.pop();
    del.sync([dest])
    gulp.src(arrayOfItems)
        .pipe(less())
        .pipe(concat(file))
        .pipe(minifyCSS())
        .pipe(gulp.dest(destSplit.join("/")));
}

gulp.task('css', generateCSS);
gulp.task('js', generateJS);

gulp.task('default', ['css', 'js']);

sample GulpDS file is below:

{

    jsbundle: {
        "mobile": {
            "public/javascripts/sample.min.js": ["public/javascripts/a.js", "public/javascripts/mobile/b.js"]
           },
        "desktop": {
            'public/javascripts/sample1.js': ["public/javascripts/c.js", "public/javascripts/d.js"]},
        "common": {
            'public/javascripts/responsive/sample2.js': ['public/javascripts/n.js']
           }
    },
    cssbundle: {
        "public/stylesheets/a.css": "public/stylesheets/less/a.less",
        }
}

How to send email in ASP.NET C#

This is the easiest script to test.

<%@ Import Namespace="System.Net" %> 
<%@ Import Namespace="System.Net.Mail" %> 

<script language="C#" runat="server"> 
    protected void Page_Load(object sender, EventArgs e) 
    { 
       //create the mail message 
        MailMessage mail = new MailMessage(); 

        //set the addresses 
        mail.From = new MailAddress("From email account"); 
        mail.To.Add("To email account"); 

        //set the content 
        mail.Subject = "This is a test email from C# script"; 
        mail.Body = "This is a test email from C# script"; 
        //send the message 
         SmtpClient smtp = new SmtpClient("mail.domainname.com"); 

         NetworkCredential Credentials = new NetworkCredential("to email account", "Password"); 
         smtp.Credentials = Credentials;
         smtp.Send(mail); 
         lblMessage.Text = "Mail Sent"; 
    } 
</script> 
<html> 
<body> 
    <form runat="server"> 
        <asp:Label id="lblMessage" runat="server"></asp:Label> 
    </form> 
</body>

How to get the width and height of an android.widget.ImageView?

I could get image width and height by its drawable;

int width = imgView.getDrawable().getIntrinsicWidth();
int height = imgView.getDrawable().getIntrinsicHeight();

How to do URL decoding in Java?

%3A and %2F are URL encoded characters. Use this java code to convert them back into : and /

String decoded = java.net.URLDecoder.decode(url, "UTF-8");

Remap values in pandas column with a dict

As an extension to what have been proposed by Nico Coallier (apply to multiple columns) and U10-Forward(using apply style of methods), and summarising it into a one-liner I propose:

df.loc[:,['col1','col2']].transform(lambda x: x.map(lambda x: {1: "A", 2: "B"}.get(x,x))

The .transform() processes each column as a series. Contrary to .apply()which passes the columns aggregated in a DataFrame.

Consequently you can apply the Series method map().

Finally, and I discovered this behaviour thanks to U10, you can use the whole Series in the .get() expression. Unless I have misunderstood its behaviour and it processes sequentially the series instead of bitwisely.
The .get(x,x)accounts for the values you did not mention in your mapping dictionary which would be considered as Nan otherwise by the .map() method

VBA, if a string contains a certain letter

Try:

If myString like "*A*" Then

Adding values to Arraylist

The second form is preferred:

ArrayList<Object> arr = new ArrayList<Object>();
arr.add(3);
arr.add("ss");

Always specify generic arguments when using generic types (such as ArrayList<T>). This rules out the first form.

As to the last form, it is more verbose and does extra work for no benefit.

How to create helper file full of functions in react native?

An alternative is to create a helper file where you have a const object with functions as properties of the object. This way you only export and import one object.

helpers.js

const helpers = {
    helper1: function(){

    },
    helper2: function(param1){

    },
    helper3: function(param1, param2){

    }
}

export default helpers;

Then, import like this:

import helpers from './helpers';

and use like this:

helpers.helper1();
helpers.helper2('value1');
helpers.helper3('value1', 'value2');

How to open a txt file and read numbers in Java

import java.io.*;  
public class DataStreamExample {  
     public static void main(String args[]){    
          try{    
            FileWriter  fin=new FileWriter("testout.txt");    
            BufferedWriter d = new BufferedWriter(fin);
            int a[] = new int[3];
            a[0]=1;
            a[1]=22;
            a[2]=3;
            String s="";
            for(int i=0;i<3;i++)
            {
                s=Integer.toString(a[i]);
                d.write(s);
                d.newLine();
            }

            System.out.println("Success");
            d.close();
            fin.close();    



            FileReader in=new FileReader("testout.txt");
            BufferedReader br=new BufferedReader(in);
            String i="";
            int sum=0;
            while ((i=br.readLine())!= null)
            {
                sum += Integer.parseInt(i);
            }
            System.out.println(sum);
          }catch(Exception e){System.out.println(e);}    
         }    
        }  

OUTPUT:: Success 26

Also, I used array to make it simple.... you can directly take integer input and convert it into string and send it to file. input-convert-Write-Process... its that simple.

HTML email with Javascript

Here's what you CAN do:

You can attach (to the email) an html document that contains javascript.

Then, when the recipient opens the attachment, their web browser will facilitate the dynamic features you've implemented.

React Native: Getting the position of an element

You can use onLayout to get the width, height, and relative-to-parent position of a component at the earliest moment that they're available:

<View
  onLayout={event => {
    const layout = event.nativeEvent.layout;
    console.log('height:', layout.height);
    console.log('width:', layout.width);
    console.log('x:', layout.x);
    console.log('y:', layout.y);
  }}
>

Compared to using .measure() as shown in the accepted answer, this has the advantage that you'll never have to fiddle around deferring your .measure() calls with setTimeout to make sure that the measurements are available, but the disadvantage that it doesn't give you offsets relative to the entire page, only ones relative to the element's parent.

How to avoid the need to specify the WSDL location in a CXF or JAX-WS generated webservice client?

For those using org.jvnet.jax-ws-commons:jaxws-maven-plugin to generate a client from WSDL at build-time:

  • Place the WSDL somewhere in your src/main/resources
  • Do not prefix the wsdlLocation with classpath:
  • Do prefix the wsdlLocation with /

Example:

  • WSDL is stored in /src/main/resources/foo/bar.wsdl
  • Configure jaxws-maven-plugin with <wsdlDirectory>${basedir}/src/main/resources/foo</wsdlDirectory> and <wsdlLocation>/foo/bar.wsdl</wsdlLocation>

How to request Google to re-crawl my website?

There are two options. The first (and better) one is using the Fetch as Google option in Webmaster Tools that Mike Flynn commented about. Here are detailed instructions:

  1. Go to: https://www.google.com/webmasters/tools/ and log in
  2. If you haven't already, add and verify the site with the "Add a Site" button
  3. Click on the site name for the one you want to manage
  4. Click Crawl -> Fetch as Google
  5. Optional: if you want to do a specific page only, type in the URL
  6. Click Fetch
  7. Click Submit to Index
  8. Select either "URL" or "URL and its direct links"
  9. Click OK and you're done.

With the option above, as long as every page can be reached from some link on the initial page or a page that it links to, Google should recrawl the whole thing. If you want to explicitly tell it a list of pages to crawl on the domain, you can follow the directions to submit a sitemap.

Your second (and generally slower) option is, as seanbreeden pointed out, submitting here: http://www.google.com/addurl/

Update 2019:

  1. Login to - Google Search Console
  2. Add a site and verify it with the available methods.
  3. After verification from the console, click on URL Inspection.
  4. In the Search bar on top, enter your website URL or custom URLs for inspection and enter.
  5. After Inspection, it'll show an option to Request Indexing
  6. Click on it and GoogleBot will add your website in a Queue for crawling.

Connect to network drive with user name and password

Use this code for Impersonation its tested in MVC.NET maybe for dot net core it required some change, If you want to dot net core let me know I will share.

 public static class ImpersonationAuthenticationNew
    {
        [DllImport("advapi32.dll", SetLastError = true)]
        private static extern bool LogonUser(string usernamee, string domain, string password, LogonType dwLogonType, LogonProvider dwLogonProvider, ref IntPtr phToken);
        [DllImport("kernel32.dll")]
        private static extern bool CloseHandle(IntPtr hObject);
        public static bool Login(string domain,string username, string password)
        {                
            IntPtr token = IntPtr.Zero;
            var IsSuccess = LogonUser(username, domain, password, LogonType.LOGON32_LOGON_NEW_CREDENTIALS, LogonProvider.LOGON32_PROVIDER_WINNT50, ref token);
            if (IsSuccess)
            {
                using (WindowsImpersonationContext person = new WindowsIdentity(token).Impersonate())
                {
                    var xIdentity = WindowsIdentity.GetCurrent();
                    #region Start ImpersonationContext  Scope
                    try
                    {

                        // TYPE YOUR CODE HERE 
                      return true;
                    }
                    catch (Exception ex) { throw (ex); }
                    finally {
                        person.Undo();
                        CloseHandle(token);
                       
                    }
                    #endregion
                }
            }
            return false;
        }
    }

    #region Enums
    public enum LogonType
    {
        /// <summary>
        /// This logon type is intended for users who will be interactively using the computer, such as a user being logged on  
        /// by a terminal server, remote shell, or similar process.
        /// This logon type has the additional expense of caching logon information for disconnected operations;
        /// therefore, it is inappropriate for some client/server applications,
        /// such as a mail server.
        /// </summary>
        LOGON32_LOGON_INTERACTIVE = 2,

        /// <summary>
        /// This logon type is intended for high performance servers to authenticate plaintext passwords.

        /// The LogonUser function does not cache credentials for this logon type.
        /// </summary>
        LOGON32_LOGON_NETWORK = 3,

        /// <summary>
        /// This logon type is intended for batch servers, where processes may be executing on behalf of a user without
        /// their direct intervention. This type is also for higher performance servers that process many plaintext
        /// authentication attempts at a time, such as mail or Web servers.
        /// The LogonUser function does not cache credentials for this logon type.
        /// </summary>
        LOGON32_LOGON_BATCH = 4,

        /// <summary>
        /// Indicates a service-type logon. The account provided must have the service privilege enabled.
        /// </summary>
        LOGON32_LOGON_SERVICE = 5,

        /// <summary>
        /// This logon type is for GINA DLLs that log on users who will be interactively using the computer.
        /// This logon type can generate a unique audit record that shows when the workstation was unlocked.
        /// </summary>
        LOGON32_LOGON_UNLOCK = 7,

        /// <summary>
        /// This logon type preserves the name and password in the authentication package, which allows the server to make
        /// connections to other network servers while impersonating the client. A server can accept plaintext credentials
        /// from a client, call LogonUser, verify that the user can access the system across the network, and still
        /// communicate with other servers.
        /// NOTE: Windows NT:  This value is not supported.
        /// </summary>
        LOGON32_LOGON_NETWORK_CLEARTEXT = 8,

        /// <summary>
        /// This logon type allows the caller to clone its current token and specify new credentials for outbound connections.
        /// The new logon session has the same local identifier but uses different credentials for other network connections.
        /// NOTE: This logon type is supported only by the LOGON32_PROVIDER_WINNT50 logon provider.
        /// NOTE: Windows NT:  This value is not supported.
        /// </summary>
        LOGON32_LOGON_NEW_CREDENTIALS = 9,
    }
    public enum LogonProvider
    {
        /// <summary>
        /// Use the standard logon provider for the system.
        /// The default security provider is negotiate, unless you pass NULL for the domain name and the user name
        /// is not in UPN format. In this case, the default provider is NTLM.
        /// NOTE: Windows 2000/NT:   The default security provider is NTLM.
        /// </summary>
        LOGON32_PROVIDER_DEFAULT = 0,
        LOGON32_PROVIDER_WINNT35 = 1,
        LOGON32_PROVIDER_WINNT40 = 2,
        LOGON32_PROVIDER_WINNT50 = 3
    }
    #endregion

Compare two files and write it to "match" and "nomatch" files

I had used JCL about 2 years back so cannot write a code for you but here is the idea;

  1. Have 2 steps
  2. First step will have ICETOOl where you can write the matching records to matched file.
  3. Second you can write a file for mismatched by using SORT/ICETOOl or by just file operations.

again i apologize for solution without code, but i am out of touch by 2 yrs+

file_get_contents("php://input") or $HTTP_RAW_POST_DATA, which one is better to get the body of JSON request?

Your second question is easy, GET has a size limitation of 1-2 kilobytes on both the server and browser side, so any kind of larger amounts of data you'd have to send through POST.

MySQL connection not working: 2002 No such file or directory

Digital Ocean MySql 2002-no-such-file-or-directory

Add this end of file /etc/mysql/my.cnf

[mysqld]
innodb_force_recovery = 1

Restart MySql

service mysql restart

Can we call the function written in one JavaScript in another JS file?

As long as both are referenced by the web page, yes.

You simply call the functions as if they are in the same JS file.

How to find Control in TemplateField of GridView?

If your GridView is databond, make an index column in the resultset you retrive like this:

select row_number() over(order by YourIdentityColumn asc)-1 as RowIndex, * from YourTable where [Expresion]

In the command control you want to use make the value of CommandArgument property equal to the row index of the DataSet table RowIndex like this:

<asp:LinkButton ID="lbnMsgSubj" runat="server" Text='<%# Eval("MsgSubj") %>' Font-Underline="false" CommandArgument='<%#Eval("RowIndex") %>' />

Use the OnRowCommand event to fire on clicking the link button like this:

<asp:GridView ID="gvwStuMsgBoard" runat="server" AutoGenerateColumns="false" GridLines="Horizontal" BorderColor="Transparent" Width="100%" OnRowCommand="gvwStuMsgBoard_RowCommand">

Finally the code behind you can then do whatever you like when the event is triggered like this:

protected void gvwStuMsgBoard_RowCommand(object sender, GridViewCommandEventArgs e)
{
    Panel pnlMsgBody = (Panel)gvwStuMsgBoard.Rows[Convert.ToInt32(e.CommandArgument)].FindControl("pnlMsgBody");
    if(pnlMsgBody.Visible == false)
    {
        pnlMsgBody.Visible = true;
    }
    else
    {
        pnlMsgBody.Visible = false;
    }
}

Mac OS X - EnvironmentError: mysql_config not found

brew install mysql added mysql to /usr/local/Cellar/..., so I needed to add :/usr/local/Cellar/ to my $PATH and then which mysql_config worked!

MySQL InnoDB not releasing disk space after deleting data rows from table

Year back i also faced same problem on mysql5.7 version and ibdata1 occupied 150 Gb. so i added undo tablespaces

Take Mysqldump backup
Stop mysql service
Remove all data from data dir
Add below undo tablespace parameter in current my.cnf

 #undo tablespace
  innodb_undo_directory =  /var/lib/mysql/
  innodb_rollback_segments = 128 
  innodb_undo_tablespaces = 3
  innodb_undo_logs = 128  
  innodb_max_undo_log_size=1G
  innodb_undo_log_truncate = ON

Start mysql service
store mysqldump backup

Problem resolved !!

How can I run multiple curl requests processed sequentially?

You can specify any amount of URLs on the command line. They will be fetched in a sequential manner in the specified order.

What is a raw type and why shouldn't we use it?

What are raw types in Java, and why do I often hear that they shouldn't be used in new code?

Raw-types are ancient history of the Java language. In the beginning there were Collections and they held Objects nothing more and nothing less. Every operation on Collections required casts from Object to the desired type.

List aList = new ArrayList();
String s = "Hello World!";
aList.add(s);
String c = (String)aList.get(0);

While this worked most of the time, errors did happen

List aNumberList = new ArrayList();
String one = "1";//Number one
aNumberList.add(one);
Integer iOne = (Integer)aNumberList.get(0);//Insert ClassCastException here

The old typeless collections could not enforce type-safety so the programmer had to remember what he stored within a collection.
Generics where invented to get around this limitation, the developer would declare the stored type once and the compiler would do it instead.

List<String> aNumberList = new ArrayList<String>();
aNumberList.add("one");
Integer iOne = aNumberList.get(0);//Compile time error
String sOne = aNumberList.get(0);//works fine

For Comparison:

// Old style collections now known as raw types
List aList = new ArrayList(); //Could contain anything
// New style collections with Generics
List<String> aList = new ArrayList<String>(); //Contains only Strings

More complex the Compareable interface:

//raw, not type save can compare with Other classes
class MyCompareAble implements CompareAble
{
   int id;
   public int compareTo(Object other)
   {return this.id - ((MyCompareAble)other).id;}
}
//Generic
class MyCompareAble implements CompareAble<MyCompareAble>
{
   int id;
   public int compareTo(MyCompareAble other)
   {return this.id - other.id;}
}

Note that it is impossible to implement the CompareAble interface with compareTo(MyCompareAble) with raw types. Why you should not use them:

  • Any Object stored in a Collection has to be cast before it can be used
  • Using generics enables compile time checks
  • Using raw types is the same as storing each value as Object

What the compiler does: Generics are backward compatible, they use the same java classes as the raw types do. The magic happens mostly at compile time.

List<String> someStrings = new ArrayList<String>();
someStrings.add("one");
String one = someStrings.get(0);

Will be compiled as:

List someStrings = new ArrayList();
someStrings.add("one"); 
String one = (String)someStrings.get(0);

This is the same code you would write if you used the raw types directly. Thought I'm not sure what happens with the CompareAble interface, I guess that it creates two compareTo functions, one taking a MyCompareAble and the other taking an Object and passing it to the first after casting it.

What are the alternatives to raw types: Use generics

Add a property to a JavaScript object using a variable as the name?

If you have object, you can make array of keys, than map through, and create new object from previous object keys, and values.

Object.keys(myObject)
.map(el =>{
 const obj = {};
 obj[el]=myObject[el].code;
 console.log(obj);
});

Remove the complete styling of an HTML button/submit

I'm assuming that when you say 'click the button, it moves to the top a little' you're talking about the mouse down click state for the button, and that when you release the mouse click, it returns to its normal state? And that you're disabling the default rendering of the button by using:

input, button, submit { border:none; } 

If so..

Personally, I've found that you can't actually stop/override/disable this IE native action, which led me to change my markup a little to allow for this movement and not affect the overall look of the button for the various states.

This is my final mark-up:

_x000D_
_x000D_
<span class="your-button-class">_x000D_
    <span>_x000D_
        <input type="Submit" value="View Person">_x000D_
    </span>_x000D_
</span>
_x000D_
_x000D_
_x000D_

How to download and save an image in Android

Edit as of 30.12.2015 - The Ultimate Guide to image downloading


last major update: Mar 31 2016


TL;DR a.k.a. stop talking, just give me the code!!

Skip to the bottom of this post, copy the BasicImageDownloader (javadoc version here) into your project, implement the OnImageLoaderListener interface and you're done.

Note: though the BasicImageDownloader handles possible errors and will prevent your app from crashing in case anything goes wrong, it will not perform any post-processing (e.g. downsizing) on the downloaded Bitmaps.


Since this post has received quite a lot of attention, I have decided to completely rework it to prevent the folks from using deprecated technologies, bad programming practices or just doing silly things - like looking for "hacks" to run network on the main thread or accept all SSL certs.

I've created a demo project named "Image Downloader" that demonstrates how to download (and save) an image using my own downloader implementation, the Android's built-in DownloadManager as well as some popular open-source libraries. You can view the complete source code or download the project on GitHub.

Note: I have not adjusted the permission management for SDK 23+ (Marshmallow) yet, thus the project is targeting SDK 22 (Lollipop).

In my conclusion at the end of this post I will share my humble opinion about the proper use-case for each particular way of image downloading I've mentioned.

Let's start with an own implementation (you can find the code at the end of the post). First of all, this is a BasicImageDownloader and that's it. All it does is connecting to the given url, reading the data and trying to decode it as a Bitmap, triggering the OnImageLoaderListener interface callbacks when appropriate. The advantage of this approach - it is simple and you have a clear overview of what's going on. A good way to go if all you need is downloading/displaying and saving some images, whilst you don't care about maintaining a memory/disk cache.

Note: in case of large images, you might need to scale them down.

--

Android DownloadManager is a way to let the system handle the download for you. It's actually capable of downloading any kind of files, not just images. You may let your download happen silently and invisible to the user, or you can enable the user to see the download in the notification area. You can also register a BroadcastReceiver to get notified after you download is complete. The setup is pretty much straightforward, refer to the linked project for sample code.

Using the DownloadManager is generally not a good idea if you also want to display the image, since you'd need to read and decode the saved file instead of just setting the downloaded Bitmap into an ImageView. The DownloadManager also does not provide any API for you app to track the download progress.

--

Now the introduction of the great stuff - the libraries. They can do much more than just downloading and displaying images, including: creating and managing the memory/disk cache, resizing images, transforming them and more.

I will start with Volley, a powerful library created by Google and covered by the official documentation. While being a general-purpose networking library not specializing on images, Volley features quite a powerful API for managing images.

You will need to implement a Singleton class for managing Volley requests and you are good to go.

You might want to replace your ImageView with Volley's NetworkImageView, so the download basically becomes a one-liner:

((NetworkImageView) findViewById(R.id.myNIV)).setImageUrl(url, MySingleton.getInstance(this).getImageLoader());

If you need more control, this is what it looks like to create an ImageRequest with Volley:

     ImageRequest imgRequest = new ImageRequest(url, new Response.Listener<Bitmap>() {
             @Override
             public void onResponse(Bitmap response) {
                    //do stuff
                }
            }, 0, 0, ImageView.ScaleType.CENTER_CROP, Bitmap.Config.ARGB_8888, 
             new Response.ErrorListener() {
             @Override
             public void onErrorResponse(VolleyError error) {
                   //do stuff
                }
            });

It is worth mentioning that Volley features an excellent error handling mechanism by providing the VolleyError class that helps you to determine the exact cause of an error. If your app does a lot of networking and managing images isn't its main purpose, then Volley it a perfect fit for you.

--

Square's Picasso is a well-known library which will do all of the image loading stuff for you. Just displaying an image using Picasso is as simple as:

 Picasso.with(myContext)
       .load(url)
       .into(myImageView); 

By default, Picasso manages the disk/memory cache so you don't need to worry about that. For more control you can implement the Target interface and use it to load your image into - this will provide callbacks similar to the Volley example. Check the demo project for examples.

Picasso also lets you apply transformations to the downloaded image and there are even other libraries around that extend those API. Also works very well in a RecyclerView/ListView/GridView.

--

Universal Image Loader is an another very popular library serving the purpose of image management. It uses its own ImageLoader that (once initialized) has a global instance which can be used to download images in a single line of code:

  ImageLoader.getInstance().displayImage(url, myImageView);

If you want to track the download progress or access the downloaded Bitmap:

 ImageLoader.getInstance().displayImage(url, myImageView, opts, 
 new ImageLoadingListener() {
     @Override
     public void onLoadingStarted(String imageUri, View view) {
                     //do stuff
                }

      @Override
      public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
                   //do stuff
                }

      @Override
      public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
                   //do stuff
                }

      @Override
      public void onLoadingCancelled(String imageUri, View view) {
                   //do stuff
                }
            }, new ImageLoadingProgressListener() {
      @Override
      public void onProgressUpdate(String imageUri, View view, int current, int total) {
                   //do stuff
                }
            });

The opts argument in this example is a DisplayImageOptions object. Refer to the demo project to learn more.

Similar to Volley, UIL provides the FailReason class that enables you to check what went wrong on download failure. By default, UIL maintains a memory/disk cache if you don't explicitly tell it not to do so.

Note: the author has mentioned that he is no longer maintaining the project as of Nov 27th, 2015. But since there are many contributors, we can hope that the Universal Image Loader will live on.

--

Facebook's Fresco is the newest and (IMO) the most advanced library that takes image management to a new level: from keeping Bitmaps off the java heap (prior to Lollipop) to supporting animated formats and progressive JPEG streaming.

To learn more about ideas and techniques behind Fresco, refer to this post.

The basic usage is quite simple. Note that you'll need to call Fresco.initialize(Context); only once, preferable in the Application class. Initializing Fresco more than once may lead to unpredictable behavior and OOM errors.

Fresco uses Drawees to display images, you can think of them as of ImageViews:

    <com.facebook.drawee.view.SimpleDraweeView
    android:id="@+id/drawee"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    fresco:fadeDuration="500"
    fresco:actualImageScaleType="centerCrop"
    fresco:placeholderImage="@drawable/placeholder_grey"
    fresco:failureImage="@drawable/error_orange"
    fresco:placeholderImageScaleType="fitCenter"
    fresco:failureImageScaleType="centerInside"
    fresco:retryImageScaleType="centerCrop"
    fresco:progressBarImageScaleType="centerInside"
    fresco:progressBarAutoRotateInterval="1000"
    fresco:roundAsCircle="false" />

As you can see, a lot of stuff (including transformation options) gets already defined in XML, so all you need to do to display an image is a one-liner:

 mDrawee.setImageURI(Uri.parse(url));

Fresco provides an extended customization API, which, under circumstances, can be quite complex and requires the user to read the docs carefully (yes, sometimes you need to RTFM).

I have included examples for progressive JPEG's and animated images into the sample project.


Conclusion - "I have learned about the great stuff, what should I use now?"

Note that the following text reflects my personal opinion and should not be taken as a postulate.

  • If you only need to download/save/display some images, don't plan to use them in a Recycler-/Grid-/ListView and don't need a whole bunch of images to be display-ready, the BasicImageDownloader should fit your needs.
  • If your app saves images (or other files) as a result of a user or an automated action and you don't need the images to be displayed often, use the Android DownloadManager.
  • In case your app does a lot of networking, transmits/receives JSON data, works with images, but those are not the main purpose of the app, go with Volley.
  • Your app is image/media-focused, you'd like to apply some transformations to images and don't want to bother with complex API: use Picasso (Note: does not provide any API to track the intermediate download status) or Universal Image Loader
  • If your app is all about images, you need advanced features like displaying animated formats and you are ready to read the docs, go with Fresco.

In case you missed that, the Github link for the demo project.


And here's the BasicImageDownloader.java

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.support.annotation.NonNull;
import android.util.Log;
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashSet;
import java.util.Set;

public class BasicImageDownloader {

    private OnImageLoaderListener mImageLoaderListener;
    private Set<String> mUrlsInProgress = new HashSet<>();
    private final String TAG = this.getClass().getSimpleName();

    public BasicImageDownloader(@NonNull OnImageLoaderListener listener) {
        this.mImageLoaderListener = listener;
    }

    public interface OnImageLoaderListener {
        void onError(ImageError error);      
        void onProgressChange(int percent);
        void onComplete(Bitmap result);
    }


    public void download(@NonNull final String imageUrl, final boolean displayProgress) {
        if (mUrlsInProgress.contains(imageUrl)) {
            Log.w(TAG, "a download for this url is already running, " +
                    "no further download will be started");
            return;
        }

        new AsyncTask<Void, Integer, Bitmap>() {

            private ImageError error;

            @Override
            protected void onPreExecute() {
                mUrlsInProgress.add(imageUrl);
                Log.d(TAG, "starting download");
            }

            @Override
            protected void onCancelled() {
                mUrlsInProgress.remove(imageUrl);
                mImageLoaderListener.onError(error);
            }

            @Override
            protected void onProgressUpdate(Integer... values) {
                mImageLoaderListener.onProgressChange(values[0]);
            }

        @Override
        protected Bitmap doInBackground(Void... params) {
            Bitmap bitmap = null;
            HttpURLConnection connection = null;
            InputStream is = null;
            ByteArrayOutputStream out = null;
            try {
                connection = (HttpURLConnection) new URL(imageUrl).openConnection();
                if (displayProgress) {
                    connection.connect();
                    final int length = connection.getContentLength();
                    if (length <= 0) {
                        error = new ImageError("Invalid content length. The URL is probably not pointing to a file")
                                .setErrorCode(ImageError.ERROR_INVALID_FILE);
                        this.cancel(true);
                    }
                    is = new BufferedInputStream(connection.getInputStream(), 8192);
                    out = new ByteArrayOutputStream();
                    byte bytes[] = new byte[8192];
                    int count;
                    long read = 0;
                    while ((count = is.read(bytes)) != -1) {
                        read += count;
                        out.write(bytes, 0, count);
                        publishProgress((int) ((read * 100) / length));
                    }
                    bitmap = BitmapFactory.decodeByteArray(out.toByteArray(), 0, out.size());
                } else {
                    is = connection.getInputStream();
                    bitmap = BitmapFactory.decodeStream(is);
                }
            } catch (Throwable e) {
                if (!this.isCancelled()) {
                    error = new ImageError(e).setErrorCode(ImageError.ERROR_GENERAL_EXCEPTION);
                    this.cancel(true);
                }
            } finally {
                try {
                    if (connection != null)
                        connection.disconnect();
                    if (out != null) {
                        out.flush();
                        out.close();
                    }
                    if (is != null)
                        is.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return bitmap;
        }

            @Override
            protected void onPostExecute(Bitmap result) {
                if (result == null) {
                    Log.e(TAG, "factory returned a null result");
                    mImageLoaderListener.onError(new ImageError("downloaded file could not be decoded as bitmap")
                            .setErrorCode(ImageError.ERROR_DECODE_FAILED));
                } else {
                    Log.d(TAG, "download complete, " + result.getByteCount() +
                            " bytes transferred");
                    mImageLoaderListener.onComplete(result);
                }
                mUrlsInProgress.remove(imageUrl);
                System.gc();
            }
        }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
    }

    public interface OnBitmapSaveListener {
        void onBitmapSaved();
        void onBitmapSaveError(ImageError error);
    }


    public static void writeToDisk(@NonNull final File imageFile, @NonNull final Bitmap image,
                               @NonNull final OnBitmapSaveListener listener,
                               @NonNull final Bitmap.CompressFormat format, boolean shouldOverwrite) {

    if (imageFile.isDirectory()) {
        listener.onBitmapSaveError(new ImageError("the specified path points to a directory, " +
                "should be a file").setErrorCode(ImageError.ERROR_IS_DIRECTORY));
        return;
    }

    if (imageFile.exists()) {
        if (!shouldOverwrite) {
            listener.onBitmapSaveError(new ImageError("file already exists, " +
                    "write operation cancelled").setErrorCode(ImageError.ERROR_FILE_EXISTS));
            return;
        } else if (!imageFile.delete()) {
            listener.onBitmapSaveError(new ImageError("could not delete existing file, " +
                    "most likely the write permission was denied")
                    .setErrorCode(ImageError.ERROR_PERMISSION_DENIED));
            return;
        }
    }

    File parent = imageFile.getParentFile();
    if (!parent.exists() && !parent.mkdirs()) {
        listener.onBitmapSaveError(new ImageError("could not create parent directory")
                .setErrorCode(ImageError.ERROR_PERMISSION_DENIED));
        return;
    }

    try {
        if (!imageFile.createNewFile()) {
            listener.onBitmapSaveError(new ImageError("could not create file")
                    .setErrorCode(ImageError.ERROR_PERMISSION_DENIED));
            return;
        }
    } catch (IOException e) {
        listener.onBitmapSaveError(new ImageError(e).setErrorCode(ImageError.ERROR_GENERAL_EXCEPTION));
        return;
    }

    new AsyncTask<Void, Void, Void>() {

        private ImageError error;

        @Override
        protected Void doInBackground(Void... params) {
            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream(imageFile);
                image.compress(format, 100, fos);
            } catch (IOException e) {
                error = new ImageError(e).setErrorCode(ImageError.ERROR_GENERAL_EXCEPTION);
                this.cancel(true);
            } finally {
                if (fos != null) {
                    try {
                        fos.flush();
                        fos.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
            return null;
        }

        @Override
        protected void onCancelled() {
            listener.onBitmapSaveError(error);
        }

        @Override
        protected void onPostExecute(Void result) {
            listener.onBitmapSaved();
        }
    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
  }

public static Bitmap readFromDisk(@NonNull File imageFile) {
    if (!imageFile.exists() || imageFile.isDirectory()) return null;
    return BitmapFactory.decodeFile(imageFile.getAbsolutePath());
}

public interface OnImageReadListener {
    void onImageRead(Bitmap bitmap);
    void onReadFailed();
}

public static void readFromDiskAsync(@NonNull File imageFile, @NonNull final OnImageReadListener listener) {
    new AsyncTask<String, Void, Bitmap>() {
        @Override
        protected Bitmap doInBackground(String... params) {
            return BitmapFactory.decodeFile(params[0]);
        }

        @Override
        protected void onPostExecute(Bitmap bitmap) {
            if (bitmap != null)
                listener.onImageRead(bitmap);
            else
                listener.onReadFailed();
        }
    }.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR, imageFile.getAbsolutePath());
}

    public static final class ImageError extends Throwable {

        private int errorCode;
        public static final int ERROR_GENERAL_EXCEPTION = -1;
        public static final int ERROR_INVALID_FILE = 0;
        public static final int ERROR_DECODE_FAILED = 1;
        public static final int ERROR_FILE_EXISTS = 2;
        public static final int ERROR_PERMISSION_DENIED = 3;
        public static final int ERROR_IS_DIRECTORY = 4;


        public ImageError(@NonNull String message) {
            super(message);
        }

        public ImageError(@NonNull Throwable error) {
            super(error.getMessage(), error.getCause());
            this.setStackTrace(error.getStackTrace());
        }

        public ImageError setErrorCode(int code) {
            this.errorCode = code;
            return this;
        }

        public int getErrorCode() {
            return errorCode;
        }
      }
   }

How can I style even and odd elements?

but it's not working in IE. recommend using :nth-child(2n+1) :nth-child(2n+2)

_x000D_
_x000D_
li {_x000D_
    color: black;_x000D_
}_x000D_
li:nth-child(odd) {_x000D_
    color: #777;_x000D_
}_x000D_
li:nth-child(even) {_x000D_
    color: blue;_x000D_
}
_x000D_
<ul>_x000D_
    <li>ho</li>_x000D_
    <li>ho</li>_x000D_
    <li>ho</li>_x000D_
    <li>ho</li>_x000D_
    <li>ho</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

CSS blur on background image but not on content

jsfiddle.

<div> 
    <img class="class" src="http://i0.kym-cdn.com/photos/images/original/000/051/726/17-i-lol.jpg?1318992465">
    </img>
    <span>
        Hello World!
    </span>
</div>

What about this? No absolute positioning on div, but instead on img and span.

Specifying content of an iframe instead of the src attribute to a page

You can .write() the content into the iframe document. Example:

<iframe id="FileFrame" src="about:blank"></iframe>

<script type="text/javascript">
   var doc = document.getElementById('FileFrame').contentWindow.document;
   doc.open();
   doc.write('<html><head><title></title></head><body>Hello world.</body></html>');
   doc.close();
</script>

Excel add one hour

This may help you as well. This is a conditional statement that will fill the cell with a default date if it is empty but will subtract one hour if it is a valid date/time and put it into the cell.

=IF((Sheet1!C4)="",DATE(1999,1,1),Sheet1!C4-TIME(1,0,0))

You can also substitute TIME with DATE to add or subtract a date or time.

Insert, on duplicate update in PostgreSQL?

CREATE OR REPLACE FUNCTION save_user(_id integer, _name character varying)
  RETURNS boolean AS
$BODY$
BEGIN
    UPDATE users SET name = _name WHERE id = _id;
    IF FOUND THEN
        RETURN true;
    END IF;
    BEGIN
        INSERT INTO users (id, name) VALUES (_id, _name);
    EXCEPTION WHEN OTHERS THEN
            UPDATE users SET name = _name WHERE id = _id;
        END;
    RETURN TRUE;
END;

$BODY$
  LANGUAGE plpgsql VOLATILE STRICT

Add objects to an array of objects in Powershell

To append to an array, just use the += operator.

$Target += $TargetObject

Also, you need to declare $Target = @() before your loop because otherwise, it will empty the array every loop.

Detect page change on DataTable

If you handle the draw.dt event after page.dt, you can detect exactly after moving the page. After work, draw.dt must be unbind

    $(document).on("page.dt", () => {
        $(document).on("draw.dt", changePage);
    });

    const changePage = () => {
        // TODO
        $(document).unbind("draw.dt", changePage);
    } 

Is there a way to get a textarea to stretch to fit its content without using PHP or JavaScript?

one line only

<textarea name="text" oninput='this.style.height = "";this.style.height = this.scrollHeight + "px"'></textarea>

How do I install Eclipse Marketplace in Eclipse Classic?

With Eclipse 3.7 Indigo, I found the link at http://www.eclipse.org/mpc/ which told me the download location and plugin was http://download.eclipse.org/mpc/indigo/ Which made the "Eclipse Marketplace Client" available in my Software updates after I added that address as a repository. Didn't seem to be in the core list on a fresh install.

Nodejs cannot find installed module on Windows

For windows, everybody said you should set environment variables for nodejs and npm modules, but do you know why? For some modules, they have command line tool, after installed the module, there'are [module].cmd file in C:\Program Files\nodejs, and it's used for launch in window command. So if you don't add the path containing the cmd file to environment variables %PATH% , you won't launch them successfully through command window.

rails 3 validation on uniqueness on multiple attributes

Dont work for me, need to put scope in plural

validates_uniqueness_of :teacher_id, :scopes => [:semester_id, :class_id]

store return json value in input hidden field

It looks like the return value is in an array? That's somewhat strange... and also be aware that certain browsers will allow that to be parsed from a cross-domain request (which isn't true when you have a top-level JSON object).

Anyway, if that is an array wrapper, you'll want something like this:

$('#my-hidden-field').val(theObject[0].id);

You can later retrieve it through a simple .val() call on the same field. This honestly looks kind of strange though. The hidden field won't persist across page requests, so why don't you just keep it in your own (pseudo-namespaced) value bucket? E.g.,

$MyNamespace = $MyNamespace || {};
$MyNamespace.myKey = theObject;

This will make it available to you from anywhere, without any hacky input field management. It's also a lot more efficient than doing DOM modification for simple value storage.

How to inherit constructors?

Too bad we're kind of forced to tell the compiler the obvious:

Subclass(): base() {}
Subclass(int x): base(x) {}
Subclass(int x,y): base(x,y) {}

I only need to do 3 constructors in 12 subclasses, so it's no big deal, but I'm not too fond of repeating that on every subclass, after being used to not having to write it for so long. I'm sure there's a valid reason for it, but I don't think I've ever encountered a problem that requires this kind of restriction.

select a value where it doesn't exist in another table

This would select 4 in your case

SELECT ID FROM TableA WHERE ID NOT IN (SELECT ID FROM TableB)

This would delete them

DELETE FROM TableA WHERE ID NOT IN (SELECT ID FROM TableB)

How to make div's percentage width relative to parent div and not viewport

Use position: relative on the parent element.

Also note that had you not added any position attributes to any of the divs you wouldn't have seen this behavior. Juan explains further.

How to resize image (Bitmap) to a given size?

The other answers are correct as to "how" to resize them, but I would also thrown in the recommendation to just grab the resolution you are interested in, to begin with. Most Android devices offer a range of resolutions and you should pick one that gives you a file size that you're comfortable with. The biggest reason for this is that the native Android scaling algorithm (as detailed by Jin35 and Padma Kumar) produces pretty crappy results. It's not going to give you Photoshop quality resizing, even downscaling (to say nothing of upscaling, which I know you're not asking about, but that's just a non-starter).

So, you should try their solution and if you're happy with the outcome, great. But if not, I'd write a function that offers a range of width that you're happy with, and looks for that dimension (or whatever's closest) in the device's available picture size array and just set it and use it.

How can I check for NaN values?

With python < 2.6 I ended up with

def isNaN(x):
    return str(float(x)).lower() == 'nan'

This works for me with python 2.5.1 on a Solaris 5.9 box and with python 2.6.5 on Ubuntu 10

how to delete installed library form react native project

If you want to unlink already installed packages in react native

  1. $ react-native unlink package_name
  2. $ yarn remove package_name (if it is npm then npm uninstall --save)

If you execute 2nd step before 1st step you need to install relevant package back and execute 2nd step

Angular 5 - Copy to clipboard

Use navigator.clipboard.writeText to copy the content to clipboard

navigator.clipboard.writeText(content).then().catch(e => console.error(e));

jQuery UI Dialog - missing close icon

I had the same exact issue, Maybe you already chececked this but got it solved just by placing the "images" folder in the same location as the jquery-ui.css

How can I make a weak protocol reference in 'pure' Swift (without @objc)

You need to declare the type of the protocol as AnyObject.

protocol ProtocolNameDelegate: AnyObject {
    // Protocol stuff goes here
}

class SomeClass {
    weak var delegate: ProtocolNameDelegate?
}

Using AnyObject you say that only classes can conform to this protocol, whereas structs or enums can't.

What is the difference between Trap and Interrupt?

A Trap can be identified as a transfer of control, which is initiated by the programmer. The term Trap is used interchangeably with the term Exception (which is an automatically occurring software interrupt). But some may argue that a trap is simply a special subroutine call. So they fall in to the category of software-invoked interrupts. For example, in 80×86 machines, a programmer can use the int instruction to initiate a trap. Because a trap is always unconditional the control will always be transferred to the subroutine associated with the trap. The exact instruction, which invokes the routine for handling the trap is easily identified because an explicit instruction is used to specify a trap.

how to make a countdown timer in java

You can create a countdown timer using applet, below is the code,

   import java.applet.*;
   import java.awt.*;
   import java.awt.event.*;
   import javax.swing.*;
   import javax.swing.Timer; // not java.util.Timer
   import java.text.NumberFormat;
   import java.net.*;



/**
    * An applet that counts down from a specified time. When it reaches 00:00,
    * it optionally plays a sound and optionally moves the browser to a new page.
    * Place the mouse over the applet to pause the count; move it off to resume.
    * This class demonstrates most applet methods and features.
    **/

public class Countdown extends JApplet implements ActionListener, MouseListener
{
long remaining; // How many milliseconds remain in the countdown.
long lastUpdate; // When count was last updated
JLabel label; // Displays the count
Timer timer; // Updates the count every second
NumberFormat format; // Format minutes:seconds with leading zeros
Image image; // Image to display along with the time
AudioClip sound; // Sound to play when we reach 00:00

// Called when the applet is first loaded
public void init() {
    // Figure out how long to count for by reading the "minutes" parameter
    // defined in a <param> tag inside the <applet> tag. Convert to ms.
    String minutes = getParameter("minutes");
    if (minutes != null) remaining = Integer.parseInt(minutes) * 60000;
    else remaining = 600000; // 10 minutes by default

    // Create a JLabel to display remaining time, and set some properties.
    label = new JLabel();
    label.setHorizontalAlignment(SwingConstants.CENTER );
    label.setOpaque(true); // So label draws the background color

    // Read some parameters for this JLabel object
    String font = getParameter("font");
    String foreground = getParameter("foreground");
    String background = getParameter("background");
    String imageURL = getParameter("image");

    // Set label properties based on those parameters
    if (font != null) label.setFont(Font.decode(font));
    if (foreground != null) label.setForeground(Color.decode(foreground));
    if (background != null) label.setBackground(Color.decode(background));
    if (imageURL != null) {
        // Load the image, and save it so we can release it later
        image = getImage(getDocumentBase(), imageURL);
        // Now display the image in the JLabel.
        label.setIcon(new ImageIcon(image));
    }

    // Now add the label to the applet. Like JFrame and JDialog, JApplet
    // has a content pane that you add children to
    getContentPane().add(label, BorderLayout.CENTER);

    // Get an optional AudioClip to play when the count expires
    String soundURL = getParameter("sound");
    if (soundURL != null) sound=getAudioClip(getDocumentBase(), soundURL);

    // Obtain a NumberFormat object to convert number of minutes and
    // seconds to strings. Set it up to produce a leading 0 if necessary
    format = NumberFormat.getNumberInstance();
    format.setMinimumIntegerDigits(2); // pad with 0 if necessary

    // Specify a MouseListener to handle mouse events in the applet.
    // Note that the applet implements this interface itself
    addMouseListener(this);

    // Create a timer to call the actionPerformed() method immediately,
    // and then every 1000 milliseconds. Note we don't start the timer yet.
    timer = new Timer(1000, this);
    timer.setInitialDelay(0); // First timer is immediate.
}

// Free up any resources we hold; called when the applet is done
public void destroy() { if (image != null) image.flush(); }

// The browser calls this to start the applet running
// The resume() method is defined below.
public void start() { resume(); } // Start displaying updates

// The browser calls this to stop the applet. It may be restarted later.
// The pause() method is defined below
public void stop() { pause(); } // Stop displaying updates

// Return information about the applet
public String getAppletInfo() {
    return "Countdown applet Copyright (c) 2003 by David Flanagan";
}

// Return information about the applet parameters
public String[][] getParameterInfo() { return parameterInfo; }

// This is the parameter information. One array of strings for each
// parameter. The elements are parameter name, type, and description.
static String[][] parameterInfo = {
    {"minutes", "number", "time, in minutes, to countdown from"},
    {"font", "font", "optional font for the time display"},
    {"foreground", "color", "optional foreground color for the time"},
    {"background", "color", "optional background color"},
    {"image", "image URL", "optional image to display next to countdown"},
    {"sound", "sound URL", "optional sound to play when we reach 00:00"},
    {"newpage", "document URL", "URL to load when timer expires"},
};

// Start or resume the countdown
void resume() {
    // Restore the time we're counting down from and restart the timer.
    lastUpdate = System.currentTimeMillis();
    timer.start(); // Start the timer
}

// Pause the countdown
void pause() {
    // Subtract elapsed time from the remaining time and stop timing
    long now = System.currentTimeMillis();
    remaining -= (now - lastUpdate);
    timer.stop(); // Stop the timer
}

// Update the displayed time. This method is called from actionPerformed()
// which is itself invoked by the timer.
void updateDisplay() {
    long now = System.currentTimeMillis(); // current time in ms
    long elapsed = now - lastUpdate; // ms elapsed since last update
    remaining -= elapsed; // adjust remaining time
    lastUpdate = now; // remember this update time

    // Convert remaining milliseconds to mm:ss format and display
    if (remaining < 0) remaining = 0;
    int minutes = (int)(remaining/60000);
    int seconds = (int)((remaining)/1000);
    label.setText(format.format(minutes) + ":" + format.format(seconds));

    // If we've completed the countdown beep and display new page
    if (remaining == 0) {
        // Stop updating now.
        timer.stop();
        // If we have an alarm sound clip, play it now.
        if (sound != null) sound.play();
        // If there is a newpage URL specified, make the browser
        // load that page now.
        String newpage = getParameter("newpage");
        if (newpage != null) {
            try {
                URL url = new URL(getDocumentBase(), newpage);
                getAppletContext().showDocument(url);
            }
            catch(MalformedURLException ex) {      showStatus(ex.toString()); }
        }
    }
}

// This method implements the ActionListener interface.
// It is invoked once a second by the Timer object
// and updates the JLabel to display minutes and seconds remaining.
public void actionPerformed(ActionEvent e) { updateDisplay(); }

// The methods below implement the MouseListener interface. We use
// two of them to pause the countdown when the mouse hovers over the timer.
// Note that we also display a message in the statusline
public void mouseEntered(MouseEvent e) {
    pause(); // pause countdown
    showStatus("Paused"); // display statusline message
}
public void mouseExited(MouseEvent e) {
    resume(); // resume countdown
    showStatus(""); // clear statusline
}
// These MouseListener methods are unused.
public void mouseClicked(MouseEvent e) {}
public void mousePressed(MouseEvent e) {}
public void mouseReleased(MouseEvent e) {}
} 

XmlWriter to Write to a String Instead of to a File

You need to create a StringWriter, and pass that to the XmlWriter.

The string overload of the XmlWriter.Create is for a filename.

E.g.

using (var sw = new StringWriter()) {
  using (var xw = XmlWriter.Create(sw)) {
    // Build Xml with xw.


  }
  return sw.ToString();
}

Is there a way to rollback my last push to Git?

First you need to determine the revision ID of the last known commit. You can use HEAD^ or HEAD~{1} if you know you need to reverse exactly one commit.

git reset --hard <revision_id_of_last_known_good_commit>
git push --force

Is there a splice method for strings?

It is faster to slice the string twice, like this:

function spliceSlice(str, index, count, add) {
  // We cannot pass negative indexes directly to the 2nd slicing operation.
  if (index < 0) {
    index = str.length + index;
    if (index < 0) {
      index = 0;
    }
  }

  return str.slice(0, index) + (add || "") + str.slice(index + count);
}

than using a split followed by a join (Kumar Harsh's method), like this:

function spliceSplit(str, index, count, add) {
  var ar = str.split('');
  ar.splice(index, count, add);
  return ar.join('');
}

Here's a jsperf that compares the two and a couple other methods. (jsperf has been down for a few months now. Please suggest alternatives in comments.)

Although the code above implements functions that reproduce the general functionality of splice, optimizing the code for the case presented by the asker (that is, adding nothing to the modified string) does not change the relative performance of the various methods.

Python 3 TypeError: must be str, not bytes with sys.stdout.write()

Python 3 handles strings a bit different. Originally there was just one type for strings: str. When unicode gained traction in the '90s the new unicode type was added to handle Unicode without breaking pre-existing code1. This is effectively the same as str but with multibyte support.

In Python 3 there are two different types:

  • The bytes type. This is just a sequence of bytes, Python doesn't know anything about how to interpret this as characters.
  • The str type. This is also a sequence of bytes, but Python knows how to interpret those bytes as characters.
  • The separate unicode type was dropped. str now supports unicode.

In Python 2 implicitly assuming an encoding could cause a lot of problems; you could end up using the wrong encoding, or the data may not have an encoding at all (e.g. it’s a PNG image).
Explicitly telling Python which encoding to use (or explicitly telling it to guess) is often a lot better and much more in line with the "Python philosophy" of "explicit is better than implicit".

This change is incompatible with Python 2 as many return values have changed, leading to subtle problems like this one; it's probably the main reason why Python 3 adoption has been so slow. Since Python doesn't have static typing2 it's impossible to change this automatically with a script (such as the bundled 2to3).

  • You can convert str to bytes with bytes('h€llo', 'utf-8'); this should produce b'H\xe2\x82\xacllo'. Note how one character was converted to three bytes.
  • You can convert bytes to str with b'H\xe2\x82\xacllo'.decode('utf-8').

Of course, UTF-8 may not be the correct character set in your case, so be sure to use the correct one.

In your specific piece of code, nextline is of type bytes, not str, reading stdout and stdin from subprocess changed in Python 3 from str to bytes. This is because Python can't be sure which encoding this uses. It probably uses the same as sys.stdin.encoding (the encoding of your system), but it can't be sure.

You need to replace:

sys.stdout.write(nextline)

with:

sys.stdout.write(nextline.decode('utf-8'))

or maybe:

sys.stdout.write(nextline.decode(sys.stdout.encoding))

You will also need to modify if nextline == '' to if nextline == b'' since:

>>> '' == b''
False

Also see the Python 3 ChangeLog, PEP 358, and PEP 3112.


1 There are some neat tricks you can do with ASCII that you can't do with multibyte character sets; the most famous example is the "xor with space to switch case" (e.g. chr(ord('a') ^ ord(' ')) == 'A') and "set 6th bit to make a control character" (e.g. ord('\t') + ord('@') == ord('I')). ASCII was designed in a time when manipulating individual bits was an operation with a non-negligible performance impact.

2 Yes, you can use function annotations, but it's a comparatively new feature and little used.

Java for loop syntax: "for (T obj : objects)"

Yes, It is called the for-each loop. Objects in the collectionName will be assigned one after one from the beginning of that collection, to the created object reference, 'objectName'. So in each iteration of the loop, the 'objectName' will be assigned an object from the 'collectionName' collection. The loop will terminate once when all the items(objects) of the 'collectionName' Collection have finished been assigning or simply the objects to get are over.

for (ObjectType objectName : collectionName.getObjects()){ //loop body> //You can use the 'objectName' here as needed and different objects will be //reepresented by it in each iteration. }

In Ruby on Rails, what's the difference between DateTime, Timestamp, Time and Date?

  1. :datetime (8 bytes)

    • Stores Date and Time formatted YYYY-MM-DD HH:MM:SS
    • Useful for columns like birth_date
  2. :timestamp (4 bytes)

    • Stores number of seconds since 1970-01-01
    • Useful for columns like updated_at, created_at
  3. :date (3 bytes)
    • Stores Date
  4. :time (3 bytes)
    • Stores Time

How to set up Automapper in ASP.NET Core

about theutz answer , there is no need to specify the IMapper mapper parrameter at the controllers constructor.

you can use the Mapper as it is a static member at any place of the code.

public class UserController : Controller {
   public someMethod()
   {
      Mapper.Map<User, UserDto>(user);
   }
}

How to display image from database using php

If you want to show images from database then first you have to insert the images in database then you can show that image on page. Follow the below code to show or display or fetch the image.

Here I am showing image and name from database.

Note: I am only storing the path of image in database but actual image i am storing in photo folder.

PHP Complete Code with design: show-code.php

   <!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, intial-scale=1.0"/>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<title>Show Image in PHP - Campuslife</title>
<style>
    body{background-color: #f2f2f2; color: #333;}
    .main{box-shadow: 0 .125rem .25rem rgba(0,0,0,.075)!important; margin-top: 10px;}
    h3{background-color: #4294D1; color: #f7f7f7; padding: 15px; border-radius: 4px; box-shadow: 0 1px 6px rgba(57,73,76,0.35);}
    .img-box{margin-top: 20px;}
    .img-block{float: left; margin-right: 5px; text-align: center;}
    p{margin-top: 0;}
    img{width: 375px; min-height: 250px; margin-bottom: 10px; box-shadow: 0 .125rem .25rem rgba(0,0,0,.075)!important; border:6px solid #f7f7f7;}
</style>
</head>
    <body>
    <!-------------------Main Content------------------------------>
    <div class="container main">
        <h3>Showing Images from database</h3>
        <div class="img-box">
    <?php
        $host ="localhost";
        $uname = "root";
        $pwd = '123456';
        $db_name = "master";

        $file_path = 'photo/';
        $result = mysqli_connect($host,$uname,$pwd) or die("Could not connect to database." .mysqli_error());
        mysqli_select_db($result,$db_name) or die("Could not select the databse." .mysqli_error());
        $image_query = mysqli_query($result,"select img_name,img_path from image_table");
        while($rows = mysqli_fetch_array($image_query))
        {
            $img_name = $rows['img_name'];
            $img_src = $rows['img_path'];
        ?>

        <div class="img-block">
        <img src="<?php echo $img_src; ?>" alt="" title="<?php echo $img_name; ?>" width="300" height="200" class="img-responsive" />
        <p><strong><?php echo $img_name; ?></strong></p>
        </div>

        <?php
        }
    ?>
        </div>
    </div>
    </body>
</body>
</html>

If you found any mistake then you can directly follow the tutorial which is i found from where. You can see the live tutorial step by step on this website.

I hope may be you like my answer.

Thank You

https://www.campuslife.co.in/Php/how-to-show-image-from-database-using-php-mysql.php

Output

[Showing Images from Database][1]

https://www.campuslife.co.in/Php/image/show-image1.png

What do I need to do to get Internet Explorer 8 to accept a self signed certificate?

As everyone else has mentioned, the first task is to add the certificate to the Trusted Root Authority.

There is a custom exe (selfssl.exe) which will create a certificate and allow you to specify the Issued to: value (the URL). This means Internet explorer will validate the issued to url with the custom intranet url.

Make sure you restart Internet Explorer to refresh changes.

Current time in microseconds in java

tl;dr

Java 9 and later: Up to nanoseconds resolution when capturing the current moment. That’s 9 digits of decimal fraction.

Instant.now()   

2017-12-23T12:34:56.123456789Z

To limit to microseconds, truncate.

Instant                // Represent a moment in UTC. 
.now()                 // Capture the current moment. Returns a `Instant` object. 
.truncatedTo(          // Lop off the finer part of this moment. 
    ChronoUnit.MICROS  // Granularity to which we are truncating. 
)                      // Returns another `Instant` object rather than changing the original, per the immutable objects pattern. 

2017-12-23T12:34:56.123456Z

In practice, you will see only microseconds captured with .now as contemporary conventional computer hardware clocks are not accurate in nanoseconds.

Details

The other Answers are somewhat outdated as of Java 8.

java.time

Java 8 and later comes with the java.time framework. These new classes supplant the flawed troublesome date-time classes shipped with the earliest versions of Java such as java.util.Date/.Calendar and java.text.SimpleDateFormat. The framework is defined by JSR 310, inspired by Joda-Time, extended by the ThreeTen-Extra project.

The classes in java.time resolve to nanoseconds, much finer than the milliseconds used by both the old date-time classes and by Joda-Time. And finer than the microseconds asked in the Question.

enter image description here

Clock Implementation

While the java.time classes support data representing values in nanoseconds, the classes do not yet generate values in nanoseconds. The now() methods use the same old clock implementation as the old date-time classes, System.currentTimeMillis(). We have the new Clock interface in java.time but the implementation for that interface is the same old milliseconds clock.

So you could format the textual representation of the result of ZonedDateTime.now( ZoneId.of( "America/Montreal" ) ) to see nine digits of a fractional second but only the first three digits will have numbers like this:

2017-12-23T12:34:56.789000000Z

New Clock In Java 9

The OpenJDK and Oracle implementations of Java 9 have a new default Clock implementation with finer granularity, up to the full nanosecond capability of the java.time classes.

See the OpenJDK issue, Increase the precision of the implementation of java.time.Clock.systemUTC(). That issue has been successfully implemented.

2017-12-23T12:34:56.123456789Z

On a MacBook Pro (Retina, 15-inch, Late 2013) with macOS Sierra, I get the current moment in microseconds (up to six digits of decimal fraction).

2017-12-23T12:34:56.123456Z

Hardware Clock

Remember that even with a new finer Clock implementation, your results may vary by computer. Java depends on the underlying computer hardware’s clock to know the current moment.

  • The resolution of the hardware clocks vary widely. For example, if a particular computer’s hardware clock supports only microseconds granularity, any generated date-time values will have only six digits of fractional second with the last three digits being zeros.
  • The accuracy of the hardware clocks vary widely. Just because a clock generates a value with several digits of decimal fraction of a second, those digits may be inaccurate, just approximations, adrift from actual time as might be read from an atomic clock. In other words, just because you see a bunch of digits to the right of the decimal mark does not mean you can trust the elapsed time between such readings to be true to that minute degree.

Spring Boot application as a Service

Following up on Chad's excellent answer, if you get an error of "Error: Could not find or load main class" - and you spend a couple hours trying to troubleshoot it, whether your executing a shell script that starts your java app or starting it from systemd itself - and you know your classpath is 100% correct, e.g. manually running the shell script works as well as running what you have in systemd execstart. Be sure you're running things as the correct user! In my case, I had tried different users, after quite a while of troubleshooting - i finally had a hunch, put root as the user - voila, the app started correctly. After determining it was a wrong user issue, I chown -R user:user the folder and subfolders and the app ran correctly as the specified user and group so no longer needed to run it as root (bad security).

Regex: Remove lines containing "help", etc

This is also possible with Notepad++:

  • Go to the search menu, Ctrl + F, and open the Mark tab.
  • Check Bookmark line (if there is no Mark tab update to the current version).

  • Enter your search term and click Mark All

    • All lines containing the search term are bookmarked.
  • Now go to the menu SearchBookmarkRemove Bookmarked lines

  • Done.

The type or namespace name 'Entity' does not exist in the namespace 'System.Data'

I had just updated my Entity framework to version 6 in my Visual studio 2013 through NugetPackage and add following References:

System.Data.Entity,
System.Data.Entity.Design,
System.Data.Linq

by right clicking on references->Add references in my project. Now delete my previously created Entity model and recreate it again,Built solution. Now It works fine for me.

How to target the href to div

Put for div same name as in href target.

ex: <div name="link"> and <a href="#link">

conversion of a varchar data type to a datetime data type resulted in an out-of-range value

It's a date format issue. In Ireland the standard date format for the 28th of March would be "28-03-2011", whereas "03/28/2011" is the standard for the USA (among many others).

JavaScript: client-side vs. server-side validation

Client side should use a basic validation via HTML5 input types and pattern attributes and as these are only used for progressive enhancements for better user experience (Even if they are not supported on < IE9 and safari, but we don't rely on them). But the main validation should happen on the server side..

Byte array to image conversion

try (UPDATE)

MemoryStream ms = new MemoryStream(byteArrayIn,0,byteArrayIn.Length);
ms.Position = 0; // this is important
returnImage = Image.FromStream(ms,true);

AWS : The config profile (MyName) could not be found

Make sure you are in the correct VirtualEnvironment. I updated PyCharm and for some reason had to point my project at my VE again. Opening the terminal, I was not in my VE when attempting zappa update (and got this error). Restarting PyCharm, all back to normal.

How to add a new row to an empty numpy array

The way to "start" the array that you want is:

arr = np.empty((0,3), int)

Which is an empty array but it has the proper dimensionality.

>>> arr
array([], shape=(0, 3), dtype=int64)

Then be sure to append along axis 0:

arr = np.append(arr, np.array([[1,2,3]]), axis=0)
arr = np.append(arr, np.array([[4,5,6]]), axis=0)

But, @jonrsharpe is right. In fact, if you're going to be appending in a loop, it would be much faster to append to a list as in your first example, then convert to a numpy array at the end, since you're really not using numpy as intended during the loop:

In [210]: %%timeit
   .....: l = []
   .....: for i in xrange(1000):
   .....:     l.append([3*i+1,3*i+2,3*i+3])
   .....: l = np.asarray(l)
   .....: 
1000 loops, best of 3: 1.18 ms per loop

In [211]: %%timeit
   .....: a = np.empty((0,3), int)
   .....: for i in xrange(1000):
   .....:     a = np.append(a, 3*i+np.array([[1,2,3]]), 0)
   .....: 
100 loops, best of 3: 18.5 ms per loop

In [214]: np.allclose(a, l)
Out[214]: True

The numpythonic way to do it depends on your application, but it would be more like:

In [220]: timeit n = np.arange(1,3001).reshape(1000,3)
100000 loops, best of 3: 5.93 µs per loop

In [221]: np.allclose(a, n)
Out[221]: True

PHP how to get local IP of system

If you are in a dev environment on OS X, connected via Wifi:

echo exec("/sbin/ifconfig en1 | grep 'inet ' | cut -d ' ' -f2");

jQuery: Get height of hidden element in jQuery

Here's a script I wrote to handle all of jQuery's dimension methods for hidden elements, even descendants of hidden parents. Note that, of course, there's a performance hit using this.

// Correctly calculate dimensions of hidden elements
(function($) {
    var originals = {},
        keys = [
            'width',
            'height',
            'innerWidth',
            'innerHeight',
            'outerWidth',
            'outerHeight',
            'offset',
            'scrollTop',
            'scrollLeft'
        ],
        isVisible = function(el) {
            el = $(el);
            el.data('hidden', []);

            var visible = true,
                parents = el.parents(),
                hiddenData = el.data('hidden');

            if(!el.is(':visible')) {
                visible = false;
                hiddenData[hiddenData.length] = el;
            }

            parents.each(function(i, parent) {
                parent = $(parent);
                if(!parent.is(':visible')) {
                    visible = false;
                    hiddenData[hiddenData.length] = parent;
                }
            });
            return visible;
        };

    $.each(keys, function(i, dimension) {
        originals[dimension] = $.fn[dimension];

        $.fn[dimension] = function(size) {
            var el = $(this[0]);

            if(
                (
                    size !== undefined &&
                    !(
                        (dimension == 'outerHeight' || 
                            dimension == 'outerWidth') &&
                        (size === true || size === false)
                    )
                ) ||
                isVisible(el)
            ) {
                return originals[dimension].call(this, size);
            }

            var hiddenData = el.data('hidden'),
                topHidden = hiddenData[hiddenData.length - 1],
                topHiddenClone = topHidden.clone(true),
                topHiddenDescendants = topHidden.find('*').andSelf(),
                topHiddenCloneDescendants = topHiddenClone.find('*').andSelf(),
                elIndex = topHiddenDescendants.index(el[0]),
                clone = topHiddenCloneDescendants[elIndex],
                ret;

            $.each(hiddenData, function(i, hidden) {
                var index = topHiddenDescendants.index(hidden);
                $(topHiddenCloneDescendants[index]).show();
            });
            topHidden.before(topHiddenClone);

            if(dimension == 'outerHeight' || dimension == 'outerWidth') {
                ret = $(clone)[dimension](size ? true : false);
            } else {
                ret = $(clone)[dimension]();
            }

            topHiddenClone.remove();
            return ret;
        };
    });
})(jQuery);

How do I find ' % ' with the LIKE operator in SQL Server?

Try this:

declare @var char(3)
set @var='[%]'
select Address from Accomodation where Address like '%'+@var+'%' 

You must use [] cancels the effect of wildcard, so you read % as a normal character, idem about character _

Regex: Specify "space or start of string" and "space or end of string"

Here's what I would use:

 (?<!\S)stackoverflow(?!\S)

In other words, match "stackoverflow" if it's not preceded by a non-whitespace character and not followed by a non-whitespace character.

This is neater (IMO) than the "space-or-anchor" approach, and it doesn't assume the string starts and ends with word characters like the \b approach does.

How to convert a timezone aware string to datetime in Python without dateutil?

Here is the Python Doc for datetime object using dateutil package..

from dateutil.parser import parse

get_date_obj = parse("2012-11-01T04:16:13-04:00")
print get_date_obj

How to create a new figure in MATLAB?

The other thing to be careful about, is to use the clf (clear figure) command when you are starting a fresh plot. Otherwise you may be plotting on a pre-existing figure (not possible with the figure command by itself, but if you do figure(2) there may already be a figure #2), with more than one axis, or an axis that is placed kinda funny. Use clf to ensure that you're starting from scratch:

figure(N);
clf;
plot(something);
...

How to use null in switch

Just consider how the SWITCH might work,

  • in case of primitives we know it can fail with NPE for auto-boxing
  • but for String or enum, it might be invoking equals method, which obviously needs a LHS value on which equals is being invoked. So, given no method can be invoked on a null, switch cant handle null.

Installing PIL with pip

These days, everyone uses Pillow, a friendly PIL fork, over PIL.

Instead of: sudo pip install pil

Do: sudo pip install pillow

$ sudo apt-get install python-imaging
$ sudo -H pip install pillow

Failed to load resource: the server responded with a status of 404 (Not Found) css

you have defined the public dir in app root/public

app.use(express.static(__dirname + '/public')); 

so you have to use:

./css/main.css

How to delete zero components in a vector in Matlab?

Why not just, a=a(~~a) or a(~a)=[]. It's equivalent to the other approaches but certainly less key strokes.

How do I get first name and last name as whole name in a MYSQL query?

You can use a query to get the same:

SELECT CONCAT(FirstName , ' ' , MiddleName , ' ' , Lastname) AS Name FROM TableName;

Note: This query return if all columns have some value if anyone is null or empty then it will return null for all, means Name will return "NULL"

To avoid above we can use the IsNull keyword to get the same.

SELECT Concat(Ifnull(FirstName,' ') ,' ', Ifnull(MiddleName,' '),' ', Ifnull(Lastname,' ')) FROM TableName;

If anyone containing null value the ' ' (space) will add with next value.

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

It can be useful to someone that uses a different system that does not have that library readily available. If that is not declared and you have some functions in your script that are not supported by that system, you should declare #/bin/bash. I've ran into this problem before at work and now I just include it as a practice.

Best approach to real time http streaming to HTML5 video client

Take a look at JSMPEG project. There is a great idea implemented there — to decode MPEG in the browser using JavaScript. Bytes from encoder (FFMPEG, for example) can be transfered to browser using WebSockets or Flash, for example. If community will catch up, I think, it will be the best HTML5 live video streaming solution for now.

How to Export Private / Secret ASC Key to Decrypt GPG Files

All the above replies are correct, but might be missing one crucial step, you need to edit the imported key and "ultimately trust" that key

gpg --edit-key (keyIDNumber)
gpg> trust

Please decide how far you trust this user to correctly verify other users' keys
(by looking at passports, checking fingerprints from different sources, etc.)

  1 = I don't know or won't say
  2 = I do NOT trust
  3 = I trust marginally
  4 = I trust fully
  5 = I trust ultimately
  m = back to the main menu

and select 5 to enable that imported private key as one of your keys

How to check the version before installing a package using apt-get?

As posted somewhere else, this works, too:

apt-cache madison <package_name>

Simple way to repeat a string

Java 8's String.join provides a tidy way to do this in conjunction with Collections.nCopies:

// say hello 100 times
System.out.println(String.join("", Collections.nCopies(100, "hello")));

How to maximize a plt.show() window using Python

import matplotlib.pyplot as plt
def maximize():
    plot_backend = plt.get_backend()
    mng = plt.get_current_fig_manager()
    if plot_backend == 'TkAgg':
        mng.resize(*mng.window.maxsize())
    elif plot_backend == 'wxAgg':
        mng.frame.Maximize(True)
    elif plot_backend == 'Qt4Agg':
        mng.window.showMaximized()

Then call function maximize() before plt.show()

How to check if Thread finished execution

I use IsAlive extensively, unless I want to block the current execution (of the calling thread), in which case I just call Join() without a parameter. Now, be aware that IsAlive may return false if the target thread has not actually started execution yet for any reason.

Carlos Merighe.

How to set environment variables from within package.json?

Set the environment variable in the script command:

...
"scripts": {
  "start": "node app.js",
  "test": "NODE_ENV=test mocha --reporter spec"
},
...

Then use process.env.NODE_ENV in your app.

Note: This is for Mac & Linux only. For Windows refer to the comments.

How to convert a plain object into an ES6 Map?

The answer by Nils describes how to convert objects to maps, which I found very useful. However, the OP was also wondering where this information is in the MDN docs. While it may not have been there when the question was originally asked, it is now on the MDN page for Object.entries() under the heading Converting an Object to a Map which states:

Converting an Object to a Map

The new Map() constructor accepts an iterable of entries. With Object.entries, you can easily convert from Object to Map:

const obj = { foo: 'bar', baz: 42 }; 
const map = new Map(Object.entries(obj));
console.log(map); // Map { foo: "bar", baz: 42 }

Javascript change font color

Html code

<div id="coloredBy">
    Colored By Santa
</div>

javascript code

document.getElementById("coloredBy").style.color = colorCode; // red or #ffffff

I think this is very easy to use

Example: Communication between Activity and Service using Messaging

Great tutorial, fantastic presentation. Neat, simple, short and very explanatory. Although, notification.setLatestEventInfo(this, getText(R.string.service_label), text, contentIntent); method is no more. As trante stated here, good approach would be:

private static final int NOTIFICATION_ID = 45349;

private void showNotification() {
    NotificationCompat.Builder builder =
            new NotificationCompat.Builder(this)
                    .setSmallIcon(R.mipmap.ic_launcher)
                    .setContentTitle("My Notification Title")
                    .setContentText("Something interesting happened");

    Intent targetIntent = new Intent(this, MainActivity.class);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, targetIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setContentIntent(contentIntent);
    _nManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    _nManager.notify(NOTIFICATION_ID, builder.build());
}

@Override
public void onDestroy() {
    super.onDestroy();
    if (_timer != null) {_timer.cancel();}
    _counter=0;
    _nManager.cancel(NOTIFICATION_ID); // Cancel the persistent notification.
    Log.i("PlaybackService", "Service Stopped.");
    _isRunning = false;
}

Checked myself, everything works like a charm (activity and service names may differ from original).

Moving Average Pandas

The rolling mean returns a Series you only have to add it as a new column of your DataFrame (MA) as described below.

For information, the rolling_mean function has been deprecated in pandas newer versions. I have used the new method in my example, see below a quote from the pandas documentation.

Warning Prior to version 0.18.0, pd.rolling_*, pd.expanding_*, and pd.ewm* were module level functions and are now deprecated. These are replaced by using the Rolling, Expanding and EWM. objects and a corresponding method call.

df['MA'] = df.rolling(window=5).mean()

print(df)
#             Value    MA
# Date                   
# 1989-01-02   6.11   NaN
# 1989-01-03   6.08   NaN
# 1989-01-04   6.11   NaN
# 1989-01-05   6.15   NaN
# 1989-01-09   6.25  6.14
# 1989-01-10   6.24  6.17
# 1989-01-11   6.26  6.20
# 1989-01-12   6.23  6.23
# 1989-01-13   6.28  6.25
# 1989-01-16   6.31  6.27

Wi-Fi Direct and iOS Support

The official list of current iOS Wi-Fi Management APIs

There is no Wi-Fi Direct type of connection available. The primary issue being that Apple does not allow programmatic setting of the Wi-Fi network SSID and password. However, this improves substantially in iOS 11 where you can at least prompt the user to switch to another WiFi network.

QA1942 - iOS Wi-Fi Management APIs

Entitlement option

This technology is useful if you want to provide a list of Wi-Fi networks that a user might want to connect to in a manager type app. It requires that you apply for this entitlement with Apple and the email address is in the documentation.

MFi Program options

These technologies allow the accessory connect to the same network as the iPhone and are not for setting up a peer-to-peer connection.

  • Wireless Accessory Configuration (WAC)
  • HomeKit

Peer-to-peer between Apple devices

These APIs come close to what you want, but they're Apple-to-Apple only.

WiTap Example Code

iOS 11 NEHotspotConfiguration

Brought up at WWDC 2017 Advances in Networking, Part 1 is NEHotspotConfiguration which allows the app to specify and prompt to connect to a specific network.

How to do exponential and logarithmic curve fitting in Python? I found only polynomial fitting

We demonstrate features of lmfit while solving both problems.

Given

import lmfit

import numpy as np

import matplotlib.pyplot as plt


%matplotlib inline
np.random.seed(123)
# General Functions
def func_log(x, a, b, c):
    """Return values from a general log function."""
    return a * np.log(b * x) + c


# Data
x_samp = np.linspace(1, 5, 50)
_noise = np.random.normal(size=len(x_samp), scale=0.06)
y_samp = 2.5 * np.exp(1.2 * x_samp) + 0.7 + _noise
y_samp2 = 2.5 * np.log(1.2 * x_samp) + 0.7 + _noise

Code

Approach 1 - lmfit Model

Fit exponential data

regressor = lmfit.models.ExponentialModel()                # 1    
initial_guess = dict(amplitude=1, decay=-1)                # 2
results = regressor.fit(y_samp, x=x_samp, **initial_guess)
y_fit = results.best_fit    

plt.plot(x_samp, y_samp, "o", label="Data")
plt.plot(x_samp, y_fit, "k--", label="Fit")
plt.legend()

enter image description here

Approach 2 - Custom Model

Fit log data

regressor = lmfit.Model(func_log)                          # 1
initial_guess = dict(a=1, b=.1, c=.1)                      # 2
results = regressor.fit(y_samp2, x=x_samp, **initial_guess)
y_fit = results.best_fit

plt.plot(x_samp, y_samp2, "o", label="Data")
plt.plot(x_samp, y_fit, "k--", label="Fit")
plt.legend()

enter image description here


Details

  1. Choose a regression class
  2. Supply named, initial guesses that respect the function's domain

You can determine the inferred parameters from the regressor object. Example:

regressor.param_names
# ['decay', 'amplitude']

To make predictions, use the ModelResult.eval() method.

model = results.eval
y_pred = model(x=np.array([1.5]))

Note: the ExponentialModel() follows a decay function, which accepts two parameters, one of which is negative.

enter image description here

See also ExponentialGaussianModel(), which accepts more parameters.

Install the library via > pip install lmfit.

Facebook database design?

It's most likely a many to many relationship:

FriendList (table)

user_id -> users.user_id
friend_id -> users.user_id
friendVisibilityLevel

EDIT

The user table probably doesn't have user_email as a PK, possibly as a unique key though.

users (table)

user_id PK
user_email
password

Cannot execute RUN mkdir in a Dockerfile

Apart from the previous use cases, you can also use Docker Compose to create directories in case you want to make new dummy folders on docker-compose up:

    volumes:
  - .:/ftp/
  - /ftp/node_modules
  - /ftp/files

'this' implicitly has type 'any' because it does not have a type annotation

The error is indeed fixed by inserting this with a type annotation as the first callback parameter. My attempt to do that was botched by simultaneously changing the callback into an arrow-function:

foo.on('error', (this: Foo, err: any) => { // DON'T DO THIS

It should've been this:

foo.on('error', function(this: Foo, err: any) {

or this:

foo.on('error', function(this: typeof foo, err: any) {

A GitHub issue was created to improve the compiler's error message and highlight the actual grammar error with this and arrow-functions.

Running multiple commands with xargs

With GNU Parallel you can do:

cat a.txt | parallel 'command1 {}; command2 {}; ...; '

Watch the intro videos to learn more: https://www.youtube.com/playlist?list=PL284C9FF2488BC6D1

For security reasons it is recommended you use your package manager to install. But if you cannot do that then you can use this 10 seconds installation.

The 10 seconds installation will try to do a full installation; if that fails, a personal installation; if that fails, a minimal installation.

$ (wget -O - pi.dk/3 || lynx -source pi.dk/3 || curl pi.dk/3/ || \
   fetch -o - http://pi.dk/3 ) > install.sh
$ sha1sum install.sh | grep 67bd7bc7dc20aff99eb8f1266574dadb
12345678 67bd7bc7 dc20aff9 9eb8f126 6574dadb
$ md5sum install.sh | grep b7a15cdbb07fb6e11b0338577bc1780f
b7a15cdb b07fb6e1 1b033857 7bc1780f
$ sha512sum install.sh | grep 186000b62b66969d7506ca4f885e0c80e02a22444
6f25960b d4b90cf6 ba5b76de c1acdf39 f3d24249 72930394 a4164351 93a7668d
21ff9839 6f920be5 186000b6 2b66969d 7506ca4f 885e0c80 e02a2244 40e8a43f
$ bash install.sh

Playing m3u8 Files with HTML Video Tag

In normally html5 video player will support mp4, WebM, 3gp and OGV format directly.

    <video controls>
      <source src=http://techslides.com/demos/sample-videos/small.webm type=video/webm>
      <source src=http://techslides.com/demos/sample-videos/small.ogv type=video/ogg>
      <source src=http://techslides.com/demos/sample-videos/small.mp4 type=video/mp4>
      <source src=http://techslides.com/demos/sample-videos/small.3gp type=video/3gp>
    </video>

We can add an external HLS js script in web application.

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset=utf-8 />
    <title>Your title</title>
      
    
      <link href="https://unpkg.com/video.js/dist/video-js.css" rel="stylesheet">
      <script src="https://unpkg.com/video.js/dist/video.js"></script>
      <script src="https://unpkg.com/videojs-contrib-hls/dist/videojs-contrib-hls.js"></script>
       
    </head>
    <body>
      <video id="my_video_1" class="video-js vjs-fluid vjs-default-skin" controls preload="auto"
      data-setup='{}'>
        <source src="https://cdn3.wowza.com/1/ejBGVnFIOW9yNlZv/cithRSsv/hls/live/playlist.m3u8" type="application/x-mpegURL">
      </video>
      
    <script>
    var player = videojs('my_video_1');
    player.play();
    </script>
      
    </body>
    </html>

What is the best way to parse html in C#?

You could use TidyNet.Tidy to convert the HTML to XHTML, and then use an XML parser.

Another alternative would be to use the builtin engine mshtml:

using mshtml;
...
object[] oPageText = { html };
HTMLDocument doc = new HTMLDocumentClass();
IHTMLDocument2 doc2 = (IHTMLDocument2)doc;
doc2.write(oPageText);

This allows you to use javascript-like functions like getElementById()

Is there a stopwatch in Java?

use : com.google.common.base.Stopwatch, its simple and easy.

<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>23.0</version>
</dependency>

example:

Stopwatch stopwatch = new Stopwatch();
stopwatch.start();

"Do something"

logger.debug("this task took " + stopwatch.stop().elapsedTime(TimeUnit.MILLISECONDS) + " mills");

this task took 112 mills

How to analyse the heap dump using jmap in java

If you just run jmap -histo:live or jmap -histo, it outputs the contents on the console!

SQL Server - find nth occurrence in a string

You can use the same function inside for the position +1

charindex('_', [TEXT], (charindex('_', [TEXT], 1))+1)

in where +1 is the nth time you will want to find.

Timestamp conversion in Oracle for YYYY-MM-DD HH:MM:SS format

Use TO_TIMESTAMP function

TO_TIMESTAMP(date_string,'YYYY-MM-DD HH24:MI:SS')

How can I get the named parameters from a URL using Flask?

It's really simple. Let me divide this process into two simple steps.

  1. On the html template you will declare name attribute for username and password like this:
<form method="POST">
<input type="text" name="user_name"></input>
<input type="text" name="password"></input>
</form>
  1. Then, modify your code like this:
from flask import request

@app.route('/my-route', methods=['POST'])
# you should always parse username and 
# password in a POST method not GET
def my_route():
    username = request.form.get("user_name")
    print(username)
    password = request.form.get("password")
    print(password)
    #now manipulate the username and password variables as you wish
    #Tip: define another method instead of methods=['GET','POST'], if you want to  
    # render the same template with a GET request too

jQuery SVG vs. Raphael

Since it's not mentioned here yet: You should also take a look at Dojox.drawing, which also provides good SVG drawing capabilities. It has a pretty impressive set of features. I'm just starting a project with it, but it seems to me that it's far superior (at least in terms of features) to Raphael and JQuerySVG.

This presentation convinced me to use it instead of Raphael/JQuerySVG: http://www.slideshare.net/elazutkin/dojo-gfx-svg-in-the-real-world-2114082

Reference: http://dojotoolkit.org/reference-guide/dojox/index.html

Reference on Dojocampus: http://docs.dojocampus.org/dojox/drawing

Download Dojo (including Dojox): http://dojotoolkit.org/download/

Image is not showing in browser?

Another random reason for why your images might not show up is because of something called base href="http://..." this can make it so that the images file doesn't work the way it should. Delete that line and you should be good.

How do you sort a dictionary by value?

Use LINQ:

Dictionary<string, int> myDict = new Dictionary<string, int>();
myDict.Add("one", 1);
myDict.Add("four", 4);
myDict.Add("two", 2);
myDict.Add("three", 3);

var sortedDict = from entry in myDict orderby entry.Value ascending select entry;

This would also allow for great flexibility in that you can select the top 10, 20 10%, etc. Or if you are using your word frequency index for type-ahead, you could also include StartsWith clause as well.

How can I schedule a job to run a SQL query daily?

To do this in t-sql, you can use the following system stored procedures to schedule a daily job. This example schedules daily at 1:00 AM. See Microsoft help for details on syntax of the individual stored procedures and valid range of parameters.

DECLARE @job_name NVARCHAR(128), @description NVARCHAR(512), @owner_login_name NVARCHAR(128), @database_name NVARCHAR(128);

SET @job_name = N'Some Title';
SET @description = N'Periodically do something';
SET @owner_login_name = N'login';
SET @database_name = N'Database_Name';

-- Delete job if it already exists:
IF EXISTS(SELECT job_id FROM msdb.dbo.sysjobs WHERE (name = @job_name))
BEGIN
    EXEC msdb.dbo.sp_delete_job
        @job_name = @job_name;
END

-- Create the job:
EXEC  msdb.dbo.sp_add_job
    @job_name=@job_name, 
    @enabled=1, 
    @notify_level_eventlog=0, 
    @notify_level_email=2, 
    @notify_level_netsend=2, 
    @notify_level_page=2, 
    @delete_level=0, 
    @description=@description, 
    @category_name=N'[Uncategorized (Local)]', 
    @owner_login_name=@owner_login_name;

-- Add server:
EXEC msdb.dbo.sp_add_jobserver @job_name=@job_name;

-- Add step to execute SQL:
EXEC msdb.dbo.sp_add_jobstep
    @job_name=@job_name,
    @step_name=N'Execute SQL', 
    @step_id=1, 
    @cmdexec_success_code=0, 
    @on_success_action=1, 
    @on_fail_action=2, 
    @retry_attempts=0, 
    @retry_interval=0, 
    @os_run_priority=0, 
    @subsystem=N'TSQL', 
    @command=N'EXEC my_stored_procedure; -- OR ANY SQL STATEMENT', 
    @database_name=@database_name, 
    @flags=0;

-- Update job to set start step:
EXEC msdb.dbo.sp_update_job
    @job_name=@job_name, 
    @enabled=1, 
    @start_step_id=1, 
    @notify_level_eventlog=0, 
    @notify_level_email=2, 
    @notify_level_netsend=2, 
    @notify_level_page=2, 
    @delete_level=0, 
    @description=@description, 
    @category_name=N'[Uncategorized (Local)]', 
    @owner_login_name=@owner_login_name, 
    @notify_email_operator_name=N'', 
    @notify_netsend_operator_name=N'', 
    @notify_page_operator_name=N'';

-- Schedule job:
EXEC msdb.dbo.sp_add_jobschedule
    @job_name=@job_name,
    @name=N'Daily',
    @enabled=1,
    @freq_type=4,
    @freq_interval=1, 
    @freq_subday_type=1, 
    @freq_subday_interval=0, 
    @freq_relative_interval=0, 
    @freq_recurrence_factor=1, 
    @active_start_date=20170101, --YYYYMMDD
    @active_end_date=99991231, --YYYYMMDD (this represents no end date)
    @active_start_time=010000, --HHMMSS
    @active_end_time=235959; --HHMMSS

onclick open window and specific size

Just add them to the parameter string.

window.open(this.href,'targetWindow','toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=350,height=250')

Merge data frames based on rownames in R

See ?merge:

the name "row.names" or the number 0 specifies the row names.

Example:

R> de <- merge(d, e, by=0, all=TRUE)  # merge by row names (by=0 or by="row.names")
R> de[is.na(de)] <- 0                 # replace NA values
R> de
  Row.names   a   b   c   d   e   f   g   h   i  j  k  l  m  n  o  p  q  r  s
1         1 1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 10 11 12 13 14 15 16 17 18 19
2         2 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 0.9  1  0  0  0  0  0  0  0  0  0
3         3 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0 0.0  0 21 22 23 24 25 26 27 28 29
   t
1 20
2  0
3 30

What is LD_LIBRARY_PATH and how to use it?

Well, the error message tells you what to do: add the path where Jacob.dll resides to java.library.path. You can do that on the command line like this:

java -Djava.library.path="dlls" ...

(assuming Jacob.dll is in the "dlls" folder)

Also see java.lang.UnsatisfiedLinkError no *****.dll in java.library.path

How can I generate a random number in a certain range?

Random Number Generator in Android If you want to know about random number generator in android then you should read this article till end. Here you can get all information about random number generator in android. Random Number Generator in Android

You should use this code in your java file.

Random r = new Random();
                    int randomNumber = r.nextInt(100);
                    tv.setText(String.valueOf(randomNumber));

I hope this answer may helpful for you. If you want to read more about this article then you should read this article. Random Number Generator

How to mount a host directory in a Docker container

How do I link the main_folder to the test_container folder present inside the docker container?

Your command below is correct, unless your on a mac using boot2docker(depending on future updates) in which case you may find the folder empty. See mattes answer for a tutorial on correcting this.

docker run -d -v /Users/kishore/main_folder:/test_container k3_s3:latest

I need to make this run automatically, how to do that without really using the run -d -v command.

You can't really get away from using these commands, they are intrinsic to the way docker works. You would be best off putting them into a shell script to save you writing them out repeatedly.

What happens if boot2docker crashes? Where are the docker files stored?

If you manage to use the -v arg and reference your host machine then the files will be safe on your host.

If you've used 'docker build -t myimage .' with a Dockerfile then your files will be baked into the image.

Your docker images, i believe, are stored in the boot2docker-vm. I found this out when my images disappeared when i delete the vm from VirtualBox. (Note, i don't know how Virtualbox works, so the images might be still hidden somewhere else, just not visible to docker).

Cleaning up old remote git branches

Consider to run :

git fetch --prune

On a regular basis in each repo to remove local branches that have been tracking a remote branch that is deleted (no longer exists in remote GIT repo).

This can be further simplified by

git config remote.origin.prune true

this is a per-repo setting that will make any future git fetch or git pull to automatically prune.

To set this up for your user, you may also edit the global .gitconfig and add

[fetch]
    prune = true

However, it's recommended that this is done using the following command:

git config --global fetch.prune true

or to apply it system wide (not just for the user)

git config --system fetch.prune true

Highlight Bash/shell code in Markdown files

Using the knitr package:

```{r, engine='bash', code_block_name} ...

E.g.:

```{r, engine='bash', count_lines}
wc -l en_US.twitter.txt
```

You can also use:

  • engine='sh' for shell
  • engine='python' for Python
  • engine='perl', engine='haskell' and a bunch of other C-like languages and even gawk, AWK, etc.

what do these symbolic strings mean: %02d %01d?

They are formatting String. The Java specific syntax is given in java.util.Formatter.

The general syntax is as follows:

   %[argument_index$][flags][width][.precision]conversion

%02d performs decimal integer conversion d, formatted with zero padding (0 flag), with width 2. Thus, an int argument whose value is say 7, will be formatted into "07" as a String.

You may also see this formatting string in e.g. String.format.


Commonly used formats

These are just some commonly used formats and doesn't cover the syntax exhaustively.

Zero padding for numbers

System.out.printf("Agent %03d to the rescue!", 7);
// Agent 007 to the rescue!

Width for justification

You can use the - flag for left justification; otherwise it'll be right justification.

for (Map.Entry<Object,Object> prop : System.getProperties().entrySet()) {
    System.out.printf("%-30s : %50s%n", prop.getKey(), prop.getValue());
}

This prints something like:

java.version                   :                                 1.6.0_07
java.vm.name                   :               Java HotSpot(TM) Client VM
java.vm.vendor                 :                    Sun Microsystems Inc.
java.vm.specification.name     :       Java Virtual Machine Specification
java.runtime.name              :          Java(TM) SE Runtime Environment
java.vendor.url                :                     http://java.sun.com/

For more powerful message formatting, you can use java.text.MessageFormat. %n is the newline conversion (see below).

Hexadecimal conversion

System.out.println(Integer.toHexString(255));
// ff

System.out.printf("%d is %<08X", 255);
// 255 is 000000FF

Note that this also uses the < relative indexing (see below).

Floating point formatting

System.out.printf("%+,010.2f%n", 1234.567);
System.out.printf("%+,010.2f%n", -66.6666);
// +01,234.57
// -000066.67

For more powerful floating point formatting, use DecimalFormat instead.

%n for platform-specific line separator

System.out.printf("%s,%n%s%n", "Hello", "World");
// Hello,
// World

%% for an actual %-sign

System.out.printf("It's %s%% guaranteed!", 99.99);
// It's 99.99% guaranteed!

Note that the double literal 99.99 is autoboxed to Double, on which a string conversion using toString() is defined.

n$ for explicit argument indexing

System.out.printf("%1$s! %1$s %2$s! %1$s %2$s %3$s!",
    "Du", "hast", "mich"
);
// Du! Du hast! Du hast mich!

< for relative indexing

System.out.format("%s?! %<S?!?!?", "Who's your daddy");
// Who's your daddy?! WHO'S YOUR DADDY?!?!?

Related questions

ASP.NET Button to redirect to another page

You can either do a Response.Redirect("YourPage.aspx"); or a Server.Transfer("YourPage.aspx"); on your button click event. So it's gonna be like the following:

protected void btnConfirm_Click(object sender, EventArgs e)
{
    Response.Redirect("YourPage.aspx");
    //or
    Server.Transfer("YourPage.aspx");
}

Convert date from String to Date format in Dataframes

Since your main aim was to convert the type of a column in a DataFrame from String to Timestamp, I think this approach would be better.

import org.apache.spark.sql.functions.{to_date, to_timestamp}
val modifiedDF = DF.withColumn("Date", to_date($"Date", "MM/dd/yyyy"))

You could also use to_timestamp (I think this is available from Spark 2.x) if you require fine grained timestamp.

Convert XML String to Object

Another way with an Advanced xsd to c# classes generation Tools : xsd2code.com. This tool is very handy and powerfull. It has a lot more customisation than the xsd.exe tool from Visual Studio. Xsd2Code++ can be customised to use Lists or Arrays and supports large schemas with a lot of Import statements.

Note of some features,

  • Generates business objects from XSD Schema or XML file to flexible C# or Visual Basic code.
  • Support Framework 2.0 to 4.x
  • Support strong typed collection (List, ObservableCollection, MyCustomCollection).
  • Support automatic properties.
  • Generate XML read and write methods (serialization/deserialization).
  • Databinding support (WPF, Xamarin).
  • WCF (DataMember attribute).
  • XML Encoding support (UTF-8/32, ASCII, Unicode, Custom).
  • Camel case / Pascal Case support.
  • restriction support ([StringLengthAttribute=true/false], [RegularExpressionAttribute=true/false], [RangeAttribute=true/false]).
  • Support large and complex XSD file.
  • Support of DotNet Core & standard

Error when checking model input: expected convolution2d_input_1 to have 4 dimensions, but got array with shape (32, 32, 3)

It is as simple as to Add one dimension, so I was going through the tutorial taught by Siraj Rawal on CNN Code Deployment tutorial, it was working on his terminal, but the same code was not working on my terminal, so I did some research about it and solved, I don't know if that works for you all. Here I have come up with solution;

Unsolved code lines which gives you problem:

if K.image_data_format() == 'channels_first':
    x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
    x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
    print(x_train.shape)
    input_shape = (1, img_rows, img_cols)
else:
    x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols)
    x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols)
    input_shape = (img_rows, img_cols, 1)

Solved Code:

if K.image_data_format() == 'channels_first':
    x_train = x_train.reshape(x_train.shape[0], 1, img_rows, img_cols)
    x_test = x_test.reshape(x_test.shape[0], 1, img_rows, img_cols)
    print(x_train.shape)
    input_shape = (1, img_rows, img_cols)
else:
    x_train = x_train.reshape(x_train.shape[0], img_rows, img_cols, 1)
    x_test = x_test.reshape(x_test.shape[0], img_rows, img_cols, 1)
    input_shape = (img_rows, img_cols, 1)

Please share the feedback here if that worked for you.

How to make a drop down list in yii2?

There are some good solutions above, and mine is just a combination of two (I came here looking for a solution).

@Sarvar Nishonboyev's solution is good because it maintains the creation of the form input label and help-block for error messages.

I went with:

<?php
use yii\helpers\ArrayHelper;
use app\models\Product;
?>
<?=
$form->field($model, 'parent_id')
     ->dropDownList(
            ArrayHelper::map(Product::find()->asArray()->all(), 'parent_id', 'name')
            )
?>

Again, full credit to: @Sarvar Nishonboyev's and @ippi

Resize height with Highcharts

According to the API Reference:

By default the height is calculated from the offset height of the containing element. Defaults to null.

So, you can control it's height according to the parent div using redraw event, which is called when it changes it's size.

References

Javascript to set hidden form value on drop down change

Just to be different, changed my answer so that this question doesn't have 5 answers with the same code.

<html>
<head>
   <title>Page</title>  
   <script src="jquery-1.3.2.min.js"></script>
   <script>
       $(function() {
           var select = $("body").append('<form></form>').children('form')
                .append('<input type="hidden" value="" />').children('input[type=hidden]')
                .attr('id', 'hiddenValue').end()
                .append('<select></select>').children('select')
                .attr('id', 'dropdown')
                .change(function() {
                    alert($(this).val());
                });

           $.each({ one: 1, two: 2, three: 3, four: 4, five: 5 }, function(txt, val) {
               select.append('<option value="' + val + '">' + txt + '</option>');
           });
       });
</script>
</head>
   <body></body>
</html>

jQuery Keypress Arrow Keys

left = 37,up = 38, right = 39,down = 40

$(document).keydown(function(e) {
switch(e.which) {
    case 37:
    $( "#prev" ).click();
    break;

    case 38:
    $( "#prev" ).click();
    break;

    case 39:
    $( "#next" ).click();
    break;

    case 40:
    $( "#next" ).click();
    break;

    default: return;
}
e.preventDefault();

});

Store images in a MongoDB database

install below libraries

var express = require(‘express’);
var fs = require(‘fs’);
var mongoose = require(‘mongoose’);
var Schema = mongoose.Schema;
var multer = require('multer');

connect ur mongo db :

mongoose.connect(‘url_here’);

Define database Schema

var Item = new ItemSchema({ 
    img: { 
       data: Buffer, 
       contentType: String 
    }
 }
);
var Item = mongoose.model('Clothes',ItemSchema);

using the middleware Multer to upload the photo on the server side.

app.use(multer({ dest: ‘./uploads/’,
  rename: function (fieldname, filename) {
    return filename;
  },
}));

post req to our db

app.post(‘/api/photo’,function(req,res){
  var newItem = new Item();
  newItem.img.data = fs.readFileSync(req.files.userPhoto.path)
  newItem.img.contentType = ‘image/png’;
  newItem.save();
});

Using Cookie in Asp.Net Mvc 4

userCookie.Expires.AddDays(365); 

This line of code doesn't do anything. It is the equivalent of:

DateTime temp = userCookie.Expires.AddDays(365); 
//do nothing with temp

You probably want

userCookie.Expires = DateTime.Now.AddDays(365); 

Excel SUMIF between dates

I found another way to work around this issue that I thought I would share.

In my case I had a years worth of daily columns (i.e. Jan-1, Jan-2... Dec-31), and I had to extract totals for each month. I went about it this way: Sum the entire year, Subtract out the totals for the dates prior and the dates after. It looks like this for February's totals:

=SUM($P3:$NP3)-(SUMIF($P$2:$NP$2, ">2/28/2014",$P3:$NP3)+SUMIF($P$2:$NP$2, "<2/1/2014",$P3:$NP3))

Where $P$2:$NP$2 contained my date values and $P3:$NP3 was the first row of data I am totaling. So SUM($P3:$NP3) is my entire year's total and I subtract (the sum of two sumifs):

SUMIF($P$2:$NP$2, ">2/28/2014",$P3:$NP3), which totals all the months after February and SUMIF($P$2:$NP$2, "<2/1/2014",$P3:$NP3), which totals all the months before February.

How to fix Invalid AES key length?

You can use this code, this code is for AES-256-CBC or you can use it for other AES encryption. Key length error mainly comes in 256-bit encryption.

This error comes due to the encoding or charset name we pass in the SecretKeySpec. Suppose, in my case, I have a key length of 44, but I am not able to encrypt my text using this long key; Java throws me an error of invalid key length. Therefore I pass my key as a BASE64 in the function, and it converts my 44 length key in the 32 bytes, which is must for the 256-bit encryption.

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.MessageDigest;
import java.security.Security;
import java.util.Base64;

public class Encrypt {

    static byte [] arr = {1,2,3,4,5,6,7,8,9};

    // static byte [] arr = new byte[16];

      public static void main(String...args) {
        try {
         //   System.out.println(Cipher.getMaxAllowedKeyLength("AES"));
            Base64.Decoder decoder = Base64.getDecoder();
            // static byte [] arr = new byte[16];
            Security.setProperty("crypto.policy", "unlimited");
            String key = "Your key";
       //     System.out.println("-------" + key);

            String value = "Hey, i am adnan";
            String IV = "0123456789abcdef";
       //     System.out.println(value);
            // log.info(value);
          IvParameterSpec iv = new IvParameterSpec(IV.getBytes());
            //    IvParameterSpec iv = new IvParameterSpec(arr);

        //    System.out.println(key);
            SecretKeySpec skeySpec = new SecretKeySpec(decoder.decode(key), "AES");
         //   System.out.println(skeySpec);
            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        //    System.out.println("ddddddddd"+IV);
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);
       //     System.out.println(cipher.getIV());

            byte[] encrypted = cipher.doFinal(value.getBytes());
            String encryptedString = Base64.getEncoder().encodeToString(encrypted);

            System.out.println("encrypted string,,,,,,,,,,,,,,,,,,,: " + encryptedString);
            // vars.put("input-1",encryptedString);
            //  log.info("beanshell");
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
    }
}

Selecting multiple columns with linq query and lambda expression

Not sure what you table structure is like but see below.

public NamePriceModel[] AllProducts()
{
    try
    {
        using (UserDataDataContext db = new UserDataDataContext())
        {
            return db.mrobProducts
                .Where(x => x.Status == 1)
                .Select(x => new NamePriceModel { 
                    Name = x.Name, 
                    Id = x.Id, 
                    Price = x.Price
                })
                .OrderBy(x => x.Id)
                .ToArray();
         }
     }
     catch
     {
         return null;
     }
 }

This would return an array of type anonymous with the members you require.

Update:

Create a new class.

public class NamePriceModel 
{
    public string Name {get; set;}
    public decimal? Price {get; set;}
    public int Id {get; set;}
}

I've modified the query above to return this as well and you should change your method from returning string[] to returning NamePriceModel[].

Most common C# bitwise operations on enums

In .NET 4 you can now write:

flags.HasFlag(FlagsEnum.Bit4)

How can a query multiply 2 cell for each row MySQL?

Use this:

SELECT 
    Pieces, Price, 
    Pieces * Price as 'Total' 
FROM myTable

Java String to Date object of the format "yyyy-mm-dd HH:mm:ss"

its work for me SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); sdf.format(new Date));

How do I check if file exists in jQuery or pure JavaScript?

I was getting a cross domain permissions issue when trying to run the answer to this question so I went with:

function UrlExists(url) {
$('<img src="'+ url +'">').load(function() {
    return true;
}).bind('error', function() {
    return false;
});
}

It seems to work great, hope this helps someone!

How to style the parent element when hovering a child element?

This solution depends fully on the design, but if you have a parent div that you want to change the background on when hovering a child you can try to mimic the parent with a ::after / ::before.

<div class="item">
    design <span class="icon-cross">x</span>
</div>

CSS:

.item {
    background: blue;
    border-radius: 10px;
    position: relative;
    z-index: 1;
}
.item span.icon-cross:hover::after {
    background: DodgerBlue;
    border-radius: 10px;
    display: block;
    position: absolute;
    z-index: -1;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    content: "";
}

See a full fiddle example here

Could not load file or assembly 'EntityFramework' after downgrading EF 5.0.0.0 --> 4.3.1.0

I have this issue, and all I did was make sure that I was referencing the right .Net framework in all the projects then just change the web.config from

From

<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false"/>

To

<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework" requirePermission="false"/>

All works..

How to check if ping responded or not in a batch file

Here's something I found:

:pingtheserver
ping %input% | find "Reply" > nul
if not errorlevel 1 (
    echo server is online, up and running.
) else (
    echo host has been taken down wait 3 seconds to refresh
    ping 1.1.1.1 -n 1 -w 3000 >NUL
    goto :pingtheserver
) 

Note that ping 1.1.1.1 -n -w 1000 >NUL will wait 1 second but only works when connected to a network

"The operation is not valid for the state of the transaction" error and transaction scope

I've encountered this error when my Transaction is nested within another. Is it possible that the stored procedure declares its own transaction or that the calling function declares one?

Easy way to pull latest of all git submodules

The following worked for me on Windows.

git submodule init
git submodule update

Xcode 'CodeSign error: code signing is required'

It happens when Xcode doesn't recognize your certificate.

It's just a pain in the ass to solve it, there are a lot of possibilities to help you.

But the first thing you should try is removing in the "Window" tab => Organizer, the provisioning that is in your device. Then re-add them (download them again on the apple website). And try to compile again.

By the way, did you check in the Project Info Window the "code signing identity" ?

Good Luck.

com.google.android.gms:play-services-measurement-base is being requested by various other libraries

If the message is:

The library com.google.android.gms:play-services-measurement-base is being requested by various other libraries at [[15.0.4,15.0.4]], but resolves to 15.0.2. Disable the plugin and check your dependencies tree using ./gradlew :app:dependencies.

Change the version of all the play services libraries you are using to the one you need (15.0.2 in this case) could solve the problem.

In my case, I've changed:

implementation 'com.google.android.gms:play-services-base:+' -> implementation 'com.google.android.gms:play-services-base:15.0.2'
implementation 'com.google.android.gms:play-services-location:+' -> implementation 'com.google.android.gms:play-services-location:15.0.2'
implementation 'com.google.android.gms:play-services-maps:+' -> implementation 'com.google.android.gms:play-services-maps:15.0.2'
implementation 'com.google.android.gms:play-services-auth:+' -> implementation 'com.google.android.gms:play-services-auth:15.0.2'
implementation 'com.google.android.gms:play-services-places:+' -> implementation 'com.google.android.gms:play-services-places:15.0.2'

How to pass params with history.push/Link/Redirect in react-router v4?

First of all, you need not do var r = this; as this in if statement refers to the context of the callback itself which since you are using arrow function refers to the React component context.

According to the docs:

history objects typically have the following properties and methods:

  • length - (number) The number of entries in the history stack
  • action - (string) The current action (PUSH, REPLACE, or POP)
  • location - (object) The current location. May have the following properties:

    • pathname - (string) The path of the URL
    • search - (string) The URL query string
    • hash - (string) The URL hash fragment
    • state - (string) location-specific state that was provided to e.g. push(path, state) when this location was pushed onto the stack. Only available in browser and memory history.
  • push(path, [state]) - (function) Pushes a new entry onto the history stack
  • replace(path, [state]) - (function) Replaces the current entry on the history stack
  • go(n) - (function) Moves the pointer in the history stack by n entries
  • goBack() - (function) Equivalent to go(-1)
  • goForward() - (function) Equivalent to go(1)
  • block(prompt) - (function) Prevents navigation

So while navigating you can pass props to the history object like

this.props.history.push({
  pathname: '/template',
  search: '?query=abc',
  state: { detail: response.data }
})

or similarly for the Link component or the Redirect component

<Link to={{
      pathname: '/template',
      search: '?query=abc',
      state: { detail: response.data }
    }}> My Link </Link>

and then in the component which is rendered with /template route, you can access the props passed like

this.props.location.state.detail

Also keep in mind that, when using history or location objects from props you need to connect the component with withRouter.

As per the Docs:

withRouter

You can get access to the history object’s properties and the closest <Route>'s match via the withRouter higher-order component. withRouter will re-render its component every time the route changes with the same props as <Route> render props: { match, location, history }.

How to set up subdomains on IIS 7

As DotNetMensch said but you DO NOT need to add another site in IIS as this can also cause further problems and make things more complicated because you then have a website within a website so the file paths, masterpage paths and web.config paths may need changing. You just need to edit teh bindings of the existing site and add the new subdomain there.

So:

  1. Add sub-domain to DNS records. My host (RackSpace) uses a web portal to do this so you just log in and go to Network->Domains(DNS)->Actions->Create Zone, and enter your subdomain as mysubdomain.domain.com etc, leave the other settings as default

  2. Go to your domain in IIS, right-click->Edit Bindings->Add, and add your new subdomain leaving everything else the same e.g. mysubdomain.domain.com

You may need to wait 5-10 mins for the DNS records to update but that's all you need.

Python list sort in descending order

You can simply do this:

timestamps.sort(reverse=True)

Twitter - How to embed native video from someone else's tweet into a New Tweet or a DM

I found a faster way of embedding:

  • Just copy the link.
  • Paste the link and remove the "?s=19" part and add "/video/1"
  • That's it.

Are "while(true)" loops so bad?

Maybe I am unlucky. Or maybe I just lack an experience. But every time I recall dealing with while(true) having break inside, it was possible to improve the code applying Extract Method to while-block, which kept the while(true) but (by coincidence?) transformed all the breaks into returns.

In my experience while(true) without breaks (ie with returns or throws) are quite comfortable and easy to understand.


  void handleInput() {
      while (true) {
          final Input input = getSomeInput();
          if (input == null) {
              throw new BadInputException("can't handle null input");
          }
          if (input.isPoisonPill()) {
              return;
          }
          doSomething(input);
      }
  }

See full command of running/stopped container in Docker

TL-DR

docker ps --no-trunc and docker inspect CONTAINER provide the entrypoint executed to start the container, along the command passed to, but that may miss some parts such as ${ANY_VAR} because container environment variables are not printed as resolved.

To overcome that, docker inspect CONTAINER has an advantage because it also allow to retrieve separately env variables and their values defined in the container from the Config.Env property.

docker ps and docker inspect provide information about the executed entrypoint and its command. Often, that is a wrapper entrypoint script (.sh) and not the "real" program started by the container. To get information on that, requesting process information with ps or /proc/1/cmdline help.


1) docker ps --no-trunc

It prints the entrypoint and the command executed for all running containers. While it prints the command passed to the entrypoint (if we pass that), it doesn't show value of docker env variables (such as $FOO or ${FOO}).
If our containers use env variables, it may be not enough.

For example, run an alpine container :

docker run --name alpine-example -e MY_VAR=/var alpine:latest sh -c 'ls $MY_VAR'

When use docker -ps such as :

docker ps -a --filter name=alpine-example --no-trunc

It prints :

CONTAINER ID           IMAGE               COMMAND                CREATED             STATUS                     PORTS               NAMES
5b064a6de6d8417...   alpine:latest       "sh -c 'ls $MY_VAR'"   2 minutes ago       Exited (0) 2 minutes ago                       alpine-example

We see the command passed to the entrypoint : sh -c 'ls $MY_VAR' but $MY_VAR is indeed not resolved.

2) docker inspect CONTAINER

When we inspect the alpine-example container :

docker inspect alpine-example | grep -4 Cmd

The command is also there but we don't still see the env variable value :

        "Cmd": [
            "sh",
            "-c",
            "ls $MY_VAR"
        ],

In fact, we could not see interpolated variables with these docker commands.
While as a trade-off, we could display separately both command and env variables for a container with docker inspect :

docker inspect  alpine-example  | grep -4 -E "Cmd|Env"

That prints :

        "Env": [
            "MY_VAR=/var",
            "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
        ],
        "Cmd": [
            "sh",
            "-c",
            "ls $MY_VAR"
        ]

A more docker way would be to use the --format flag of docker inspect that allows to specify JSON attributes to render :

docker inspect --format '{{.Name}} {{.Config.Cmd}}  {{ (.Config.Env) }}'  alpine-example

That outputs :

/alpine-example [sh -c ls $MY_VAR]  [MY_VAR=/var PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin]

3) Retrieve the started process from the container itself for running containers

The entrypoint and command executed by docker may be helpful but in some cases, it is not enough because that is "only" a wrapper entrypoint script (.sh) that is responsible to start the real/core process.
For example when I run a Nexus container, the command executed and shown to run the container is "sh -c ${SONATYPE_DIR}/start-nexus-repository-manager.sh".
For PostgreSQL that is "docker-entrypoint.sh postgres".

To get more information, we could execute on a running container docker exec CONTAINER ps aux.
It may print other processes that may not interest us.
To narrow to the initial process launched by the entrypoint, we could do :

docker exec CONTAINER ps -1

I specify 1 because the process executed by the entrypoint is generally the one with the 1 id.

Without ps, we could still find the information in /proc/1/cmdline (in most of Linux distros but not all). For example :

docker exec CONTAINER cat /proc/1/cmdline | sed -e "s/\x00/ /g"; echo    

If we have access to the docker host that started the container, another alternative to get the full command of the process executed by the entrypoint is : : execute ps -PID where PID is the local process created by the Docker daemon to run the container such as :

ps -$(docker container inspect --format '{{.State.Pid}}'  CONTAINER)

User-friendly formatting with docker ps

docker ps --no-trunc is not always easy to read.
Specifying columns to print and in a tabular format may make it better :

docker ps   --no-trunc  --format "table{{.Names}}\t{{.CreatedAt}}\t{{.Command}}"

Create an alias may help :

alias dps='docker ps   --no-trunc  --format "table{{.Names}}\t{{.CreatedAt}}\t{{.Command}}"'

How to create and write to a txt file using VBA

Open ThisWorkbook.Path & "\template.txt" For Output As #1
Print #1, strContent
Close #1

More Information:

The type is defined in an assembly that is not referenced, how to find the cause?

In my case this was because I used

Implicit Operator

between BLL and DAL classes.when I want to use BLL Layer In Application Layer I got this error. I changed

implicit operator

to

explicit operator

it be OK. Thanks

Oracle query to fetch column names

The below query worked for me in Oracle database.

select COLUMN_NAME from ALL_TAB_COLUMNS where TABLE_NAME='MyTableName';

Get battery level and state in Android

Other answers didn't mention how to access battery status (chraging or not).

IntentFilter ifilter = new IntentFilter(Intent.ACTION_BATTERY_CHANGED);
Intent batteryStatus = context.registerReceiver(null, ifilter);

// Are we charging / charged?
int status = batteryStatus.getIntExtra(BatteryManager.EXTRA_STATUS, -1);
boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
                     status == BatteryManager.BATTERY_STATUS_FULL;

// How are we charging?
int chargePlug = batteryStatus.getIntExtra(BatteryManager.EXTRA_PLUGGED, -1);
boolean usbCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_USB;
boolean acCharge = chargePlug == BatteryManager.BATTERY_PLUGGED_AC;

jQuery move to anchor location on page load

Did you tried JQuery's scrollTo method? http://demos.flesler.com/jquery/scrollTo/

Or you can extend JQuery and add your custom mentod:

jQuery.fn.extend({
 scrollToMe: function () {
   var x = jQuery(this).offset().top - 100;
   jQuery('html,body').animate({scrollTop: x}, 400);
}});

Then you can call this method like:

$("#header").scrollToMe();

UIScrollView scroll to bottom programmatically

It looks like all of the answers here didn't take the safe area into consideration. Since iOS 11, iPhone X had a safe area introduced. This may affect the scrollView's contentInset.

For iOS 11 and above, to properly scroll to the bottom with the content inset included. You should use adjustedContentInset instead of contentInset. Check this code:

  • Swift:
let bottomOffset = CGPoint(x: 0, y: scrollView.contentSize.height - scrollView.bounds.height + scrollView.adjustedContentInset.bottom)
scrollView.setContentOffset(bottomOffset, animated: true)
  • Objective-C
CGPoint bottomOffset = CGPointMake(0, self.scrollView.contentSize.height - self.scrollView.bounds.size.height + self.scrollView.adjustedContentInset.bottom);
[self.scrollView setContentOffset:bottomOffset animated:YES];
  • Swift extension (this keeps the original contentOffset.x):
extension UIScrollView {
    func scrollsToBottom(animated: Bool) {
        let bottomOffset = CGPoint(x: contentOffset.x,
                                   y: contentSize.height - bounds.height + adjustedContentInset.bottom)
        setContentOffset(bottomOffset, animated: animated)
    }
}

References:

How to send a compressed archive that contains executables so that Google's attachment filter won't reject it

Try this:

tar -czf my.tar.gz dir/

But are you sure you are not compressing some .exe file or something? Maybe the problem is not with te compression, but with the files you are compressing?

AngularJS dynamic routing

In the $routeProvider URI patters, you can specify variable parameters, like so: $routeProvider.when('/page/:pageNumber' ... , and access it in your controller via $routeParams.

There is a good example at the end of the $route page: http://docs.angularjs.org/api/ng.$route

EDIT (for the edited question):

The routing system is unfortunately very limited - there is a lot of discussion on this topic, and some solutions have been proposed, namely via creating multiple named views, etc.. But right now, the ngView directive serves only ONE view per route, on a one-to-one basis. You can go about this in multiple ways - the simpler one would be to use the view's template as a loader, with a <ng-include src="myTemplateUrl"></ng-include> tag in it ($scope.myTemplateUrl would be created in the controller).

I use a more complex (but cleaner, for larger and more complicated problems) solution, basically skipping the $route service altogether, that is detailed here:

http://www.bennadel.com/blog/2420-Mapping-AngularJS-Routes-Onto-URL-Parameters-And-Client-Side-Events.htm

Adb over wireless without usb cable at all for not rooted phones

For your question

Adb over wireless without USB cable at all for not rooted phones

 You can't do it for now without USB cable.

But you have an option:

Note: You need put USB at least once to achieve the following:

You need to connect your device to your computer via USB cable. Make sure USB debugging is working. You can check if it shows up when running adb devices.

Open cmd in ...\AppData\Local\Android\sdk\platform-tools

Step1: Run adb devices

Ex: C:\pathToSDK\platform-tools>adb devices

You can check if it shows up when running adb devices.

Step2: Run adb tcpip 5555

Ex: C:\pathToSDK\platform-tools>adb tcpip 5555

Disconnect your device (remove the USB cable).

Step3: Go to the Settings -> About phone -> Status to view the IP address of your phone.

.

Step4: Run `adb connect

Ex: C:\pathToSDK\platform-tools>adb connect 192.168.0.2

Step5: Run adb devices again, you should see your device.

Now you can execute adb commands or use your favourite IDE for android development - wireless!

Now you might ask, what do I have to do when I move into a different work space and change WiFi networks? You do not have to repeat steps 1 to 3 (these set your phone into WiFi-debug mode). You do have to connect to your phone again by executing steps 4 to 6.

Unfortunately, the android phones lose the WiFi-debug mode when restarting. Thus, if your battery died, you have to start over. Otherwise, if you keep an eye on your battery and do not restart your phone, you can live without a cable for weeks!

See here for more

Happy wireless coding!

Ref: https://futurestud.io/tutorials/how-to-debug-your-android-app-over-wifi-without-root

UPDATE:

If you set C:\pathToSDK\platform-tools this path in Environment variables then there is no need to repeat all steps, you can simply use only Step 4 that's it, it will connect to your device.

To set path : My Computer-> Right click--> properties -> Advanced system settings -> Environment variables -> edit path in System variables -> paste the platform-tools path in variable value -> ok -> ok -> ok

Select from one table matching criteria in another?

The simplest solution would be a correlated sub select:

select
    A.*
from
    table_A A
where
    A.id in (
        select B.id from table_B B where B.tag = 'chair'
)

Alternatively you could join the tables and filter the rows you want:

select
    A.*
from
    table_A A
inner join table_B B
    on A.id = B.id
where
    B.tag = 'chair'

You should profile both and see which is faster on your dataset.

ssh : Permission denied (publickey,gssapi-with-mic)

I try

rm ~/.ssh/id_rsa.pub

then it work!